View source
<?php
define('USERNAME_MAX_LENGTH', 60);
define('EMAIL_MAX_LENGTH', 254);
define('USER_REGISTER_ADMINISTRATORS_ONLY', 0);
define('USER_REGISTER_VISITORS', 1);
define('USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL', 2);
function user_help($path, $arg) {
global $user;
switch ($path) {
case 'admin/help#user':
$output = '';
$output .= '<h3>' . t('About') . '</h3>';
$output .= '<p>' . 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 <a href="@user">User module</a>.', array(
'@user' => 'http://drupal.org/documentation/modules/user',
)) . '</p>';
$output .= '<h3>' . t('Uses') . '</h3>';
$output .= '<dl>';
$output .= '<dt>' . t('Creating and managing users') . '</dt>';
$output .= '<dd>' . t('The User module allows users with the appropriate <a href="@permissions">permissions</a> to create user accounts through the <a href="@people">People administration page</a>, where they can also assign users to one or more roles, and block or delete user accounts. If allowed, users without accounts (anonymous users) can create their own accounts on the <a href="@register">Create new account</a> page.', array(
'@permissions' => url('admin/people/permissions', array(
'fragment' => 'module-user',
)),
'@people' => url('admin/people'),
'@register' => url('user/register'),
)) . '</dd>';
$output .= '<dt>' . t('User roles and permissions') . '</dt>';
$output .= '<dd>' . t('<em>Roles</em> are used to group and classify users; each user can be assigned one or more roles. By default there are two roles: <em>anonymous user</em> (users that are not logged in) and <em>authenticated user</em> (users that are registered and logged in). Depending on choices you made when you installed Drupal, the installation process may have defined more roles, and you can create additional custom roles on the <a href="@roles">Roles page</a>. After creating roles, you can set permissions for each role on the <a href="@permissions_user">Permissions page</a>. Granting a permission allows users who have been assigned a particular role to perform an action on the site, such as viewing a particular type of content, editing or creating content, administering settings for a particular module, or using a particular function of the site (such as search).', array(
'@permissions_user' => url('admin/people/permissions'),
'@roles' => url('admin/people/permissions/roles'),
)) . '</dd>';
$output .= '<dt>' . t('Account settings') . '</dt>';
$output .= '<dd>' . t('The <a href="@accounts">Account settings page</a> allows you to manage settings for the displayed name of the anonymous user role, personal contact forms, user registration, and account cancellation. On this page you can also manage settings for account personalization (including signatures and user pictures), and adapt the text for the e-mail messages that are sent automatically during the user registration process.', array(
'@accounts' => url('admin/config/people/accounts'),
)) . '</dd>';
$output .= '</dl>';
return $output;
case 'admin/people/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/people/permissions':
return '<p>' . 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 <a href="@role">Roles</a> 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 <a href="@settings">User Settings</a> 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/people/permissions/roles'),
'@settings' => url('admin/config/people/accounts'),
)) . '</p>';
case 'admin/people/permissions/roles':
$output = '<p>' . 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 on the <a href="@permissions">permissions page</a>. Examples of roles include: anonymous user, authenticated user, moderator, administrator and so on. In this area you will define the names and order of the roles on your site. It is recommended to order your roles from least permissive (anonymous user) to most permissive (administrator). To delete a role choose "edit role".', array(
'@permissions' => url('admin/people/permissions'),
)) . '</p>';
$output .= '<p>' . t('By default, Drupal comes with two user roles:') . '</p>';
$output .= '<ul>';
$output .= '<li>' . t("Anonymous user: this role is used for users that don't have a user account or that are not authenticated.") . '</li>';
$output .= '<li>' . t('Authenticated user: this role is automatically granted to all logged in users.') . '</li>';
$output .= '</ul>';
return $output;
case 'admin/config/people/accounts/fields':
return '<p>' . t('This form lets administrators add, edit, and arrange fields for storing user data.') . '</p>';
case 'admin/config/people/accounts/display':
return '<p>' . t('This form lets administrators configure how fields should be displayed when rendering a user profile page.') . '</p>';
case 'admin/people/search':
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>';
}
}
function user_module_invoke($type, &$edit, $account, $category = NULL) {
foreach (module_implements('user_' . $type) as $module) {
$function = $module . '_user_' . $type;
$function($edit, $account, $category);
}
}
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_roles' => array(
'render element' => 'form',
'file' => 'user.admin.inc',
),
'user_permission_description' => array(
'variables' => array(
'permission_item' => NULL,
'hide' => NULL,
),
'file' => 'user.admin.inc',
),
'user_signature' => array(
'variables' => array(
'signature' => NULL,
),
),
);
}
function user_entity_info() {
$return = array(
'user' => array(
'label' => t('User'),
'controller class' => 'UserController',
'base table' => 'users',
'uri callback' => 'user_uri',
'label callback' => 'format_username',
'fieldable' => TRUE,
'entity 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'),
'custom settings' => FALSE,
),
),
),
);
return $return;
}
function user_uri($user) {
return array(
'path' => 'user/' . $user->uid,
);
}
function user_field_info_alter(&$info) {
foreach ($info as $field_type => &$field_type_info) {
$field_type_info += array(
'instance_settings' => array(),
);
$field_type_info['instance_settings'] += array(
'user_register_form' => FALSE,
);
}
}
function user_field_extra_fields() {
$return['user']['user'] = array(
'form' => array(
'account' => array(
'label' => t('User name and password'),
'description' => t('User module account form elements.'),
'weight' => -10,
),
'timezone' => array(
'label' => t('Timezone'),
'description' => t('User module timezone form element.'),
'weight' => 6,
),
),
'display' => array(
'summary' => array(
'label' => t('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;
}
}
function user_load_multiple($uids = array(), $conditions = array(), $reset = FALSE) {
return entity_load('user', $uids, $conditions, $reset);
}
class UserController extends DrupalDefaultEntityController {
function attachLoad(&$queried_users, $revision_id = FALSE) {
$picture_fids = array();
foreach ($queried_users as $key => $record) {
$picture_fids[] = $record->picture;
$queried_users[$key]->data = unserialize($record->data);
$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';
}
}
$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;
}
if (!empty($picture_fids) && variable_get('user_pictures', 0)) {
$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;
}
}
}
parent::attachLoad($queried_users, $revision_id);
}
}
function user_load($uid, $reset = FALSE) {
$users = user_load_multiple(array(
$uid,
), array(), $reset);
return reset($users);
}
function user_load_by_mail($mail) {
$users = user_load_multiple(array(), array(
'mail' => $mail,
));
return reset($users);
}
function user_load_by_name($name) {
$users = user_load_multiple(array(), array(
'name' => $name,
));
return reset($users);
}
function user_save($account, $edit = array(), $category = 'account') {
$transaction = db_transaction();
try {
if (isset($edit['pass']) && strlen(trim($edit['pass'])) > 0) {
require_once DRUPAL_ROOT . '/' . variable_get('password_inc', 'includes/password.inc');
$edit['pass'] = user_hash_password(trim($edit['pass']));
if (!$edit['pass']) {
return FALSE;
}
}
else {
unset($edit['pass']);
}
if (isset($edit['mail'])) {
$edit['mail'] = trim($edit['mail']);
}
if (!empty($account->uid) && !isset($account->original)) {
$account->original = entity_load_unchanged('user', $account->uid);
}
if (empty($account)) {
$account = new stdClass();
}
if (!isset($account->is_new)) {
$account->is_new = empty($account->uid);
}
if (!empty($account->data)) {
$edit['data'] = !empty($edit['data']) ? array_merge($account->data, $edit['data']) : $account->data;
}
user_module_invoke('presave', $edit, $account, $category);
foreach ($edit as $key => $value) {
$account->{$key} = $value;
}
field_attach_presave('user', $account);
module_invoke_all('entity_presave', $account, 'user');
if (is_object($account) && !$account->is_new) {
if (!empty($account->picture->fid) && (!isset($account->original->picture->fid) || $account->picture->fid != $account->original->picture->fid)) {
$picture = $account->picture;
if (!$picture->status) {
$info = image_get_info($picture->uri);
$picture_directory = file_default_scheme() . '://' . variable_get('user_picture_path', 'pictures');
file_prepare_directory($picture_directory, FILE_CREATE_DIRECTORY);
$destination = file_stream_wrapper_uri_normalize($picture_directory . '/picture-' . $account->uid . '-' . REQUEST_TIME . '.' . $info['extension']);
if ($picture = file_move($picture, $destination, FILE_EXISTS_RENAME)) {
$picture->status = FILE_STATUS_PERMANENT;
$account->picture = file_save($picture);
file_usage_add($picture, 'user', 'user', $account->uid);
}
}
if (!empty($account->original->picture->fid)) {
file_usage_delete($account->original->picture, 'user', 'user', $account->uid);
file_delete($account->original->picture);
}
}
elseif (isset($edit['picture_delete']) && $edit['picture_delete']) {
file_usage_delete($account->original->picture, 'user', 'user', $account->uid);
file_delete($account->original->picture);
}
$picture = empty($account->picture) ? NULL : $account->picture;
$account->picture = empty($account->picture->fid) ? 0 : $account->picture->fid;
$account->uid = $account->original->uid;
$success = drupal_write_record('users', $account, 'uid');
$account->picture = $picture;
if ($success === FALSE) {
return FALSE;
}
if ($account->roles != $account->original->roles) {
db_delete('users_roles')
->condition('uid', $account->uid)
->execute();
$query = db_insert('users_roles')
->fields(array(
'uid',
'rid',
));
foreach (array_keys($account->roles) as $rid) {
if (!in_array($rid, array(
DRUPAL_ANONYMOUS_RID,
DRUPAL_AUTHENTICATED_RID,
))) {
$query
->values(array(
'uid' => $account->uid,
'rid' => $rid,
));
}
}
$query
->execute();
}
if ($account->original->status != $account->status && $account->status == 0) {
drupal_session_destroy_uid($account->uid);
}
if ($account->pass != $account->original->pass) {
drupal_session_destroy_uid($account->uid);
if ($account->uid == $GLOBALS['user']->uid) {
drupal_session_regenerate();
}
}
field_attach_update('user', $account);
if ($account->status != $account->original->status) {
$op = $account->status == 1 ? 'status_activated' : 'status_blocked';
_user_mail_notify($op, $account);
}
foreach ($account as $key => $value) {
if (!property_exists($account->original, $key) || $value !== $account->original->{$key}) {
$edit[$key] = $value;
}
}
user_module_invoke('update', $edit, $account, $category);
module_invoke_all('entity_update', $account, 'user');
}
else {
if (empty($account->uid)) {
$account->uid = db_next_id(db_query('SELECT MAX(uid) FROM {users}')
->fetchField());
}
if (!isset($account->created)) {
$account->created = REQUEST_TIME;
}
$success = drupal_write_record('users', $account);
if ($success === FALSE) {
return FALSE;
}
$account->roles[DRUPAL_AUTHENTICATED_RID] = 'authenticated user';
field_attach_insert('user', $account);
$edit = (array) $account;
user_module_invoke('insert', $edit, $account, $category);
module_invoke_all('entity_insert', $account, 'user');
$rids_to_skip = array_merge(array(
DRUPAL_ANONYMOUS_RID,
DRUPAL_AUTHENTICATED_RID,
), db_query('SELECT rid FROM {users_roles} WHERE uid = :uid', array(
':uid' => $account->uid,
))
->fetchCol());
if ($rids_to_save = array_diff(array_keys($account->roles), $rids_to_skip)) {
$query = db_insert('users_roles')
->fields(array(
'uid',
'rid',
));
foreach ($rids_to_save as $rid) {
$query
->values(array(
'uid' => $account->uid,
'rid' => $rid,
));
}
$query
->execute();
}
}
unset($account->is_new);
unset($account->original);
entity_get_controller('user')
->resetCache(array(
$account->uid,
));
return $account;
} catch (Exception $e) {
$transaction
->rollback();
watchdog_exception('user', $e);
throw $e;
}
}
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}' . '\\x{AD}' . '\\x{2000}-\\x{200F}' . '\\x{2028}-\\x{202F}' . '\\x{205F}-\\x{206F}' . '\\x{FEFF}' . '\\x{FF01}-\\x{FF60}' . '\\x{FFF9}-\\x{FFFD}' . '\\x{0}-\\x{1F}]/u', $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) {
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) {
$validators = array(
'file_validate_is_image' => array(),
'file_validate_image_resolution' => array(
variable_get('user_picture_dimensions', '85x85'),
),
'file_validate_size' => array(
(int) variable_get('user_picture_file_size', '30') * 1024,
),
);
$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;
}
}
function user_password($length = 10) {
$allowable_characters = 'abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789';
$len = strlen($allowable_characters) - 1;
$pass = '';
for ($i = 0; $i < $length; $i++) {
do {
$index = ord(drupal_random_bytes(1));
} while ($index > $len);
$pass .= $allowable_characters[$index];
}
return $pass;
}
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 {
$fetch[] = $rid;
$cache[$rid] = array();
}
}
if ($fetch) {
$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) {
$role_permissions[$rid] = $cache[$rid];
}
}
}
return $role_permissions;
}
function user_access($string, $account = NULL) {
global $user;
if (!isset($account)) {
$account = $user;
}
if ($account->uid == 1) {
return TRUE;
}
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]);
}
function user_is_blocked($name) {
return db_select('users')
->fields('users', array(
'name',
))
->condition('name', db_like($name), 'LIKE')
->condition('status', 0)
->execute()
->fetchObject();
}
function user_has_role($rid, $account = NULL) {
if (!$account) {
$account = $GLOBALS['user'];
}
return isset($account->roles[$rid]);
}
function user_permission() {
return array(
'administer permissions' => array(
'title' => t('Administer permissions'),
'restrict access' => TRUE,
),
'administer users' => array(
'title' => t('Administer users'),
'restrict access' => TRUE,
),
'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 transferred to the %anonymous-name user depending on the configured <a href="@user-settings-url">user settings</a>.', 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'),
'restrict access' => TRUE,
),
);
}
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'],
);
}
}
function user_file_move($file, $source) {
if (isset($file->fid) && isset($source->fid) && $file->fid != $source->fid) {
db_update('users')
->fields(array(
'picture' => $file->fid,
))
->condition('picture', $source->fid)
->execute();
}
}
function user_file_delete($file) {
db_update('users')
->fields(array(
'picture' => 0,
))
->condition('picture', $file->fid)
->execute();
}
function user_search_info() {
return array(
'title' => 'Users',
);
}
function user_search_access() {
return user_access('access user profiles');
}
function user_search_execute($keys = NULL, $conditions = NULL) {
$find = array();
$keys = db_like($keys);
$keys = preg_replace('!\\*+!', '%', $keys);
$query = db_select('users')
->extend('PagerDefault');
$query
->fields('users', array(
'uid',
));
if (user_access('administer users')) {
$query
->fields('users', array(
'mail',
));
$query
->condition(db_or()
->condition('name', '%' . $keys . '%', 'LIKE')
->condition('mail', '%' . $keys . '%', 'LIKE'));
}
else {
$query
->condition('name', '%' . $keys . '%', 'LIKE')
->condition('status', 1);
}
$uids = $query
->limit(15)
->execute()
->fetchCol();
$accounts = user_load_multiple($uids);
$results = array();
foreach ($accounts as $account) {
$result = array(
'title' => format_username($account),
'link' => url('user/' . $account->uid, array(
'absolute' => TRUE,
)),
);
if (user_access('administer users')) {
$result['title'] .= ' (' . $account->mail . ')';
}
$results[] = $result;
}
return $results;
}
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;
}
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),
);
}
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';
$form['account'] = array(
'#type' => 'container',
'#weight' => -10,
);
$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,
'#weight' => -10,
);
$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 : '',
);
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.'),
);
if (!isset($form_state['user_pass_reset'])) {
$form_state['user_pass_reset'] = isset($_SESSION['pass_reset_' . $account->uid]) && isset($_GET['pass-reset-token']) && $_GET['pass-reset-token'] == $_SESSION['pass_reset_' . $account->uid];
}
$protected_values = array();
$current_pass_description = '';
if (!$form_state['user_pass_reset']) {
$protected_values['mail'] = $form['account']['mail']['#title'];
$protected_values['pass'] = t('Password');
$request_new = l(t('Request new password'), 'user/password', array(
'attributes' => array(
'title' => t('Request new password via e-mail.'),
),
));
$current_pass_description = t('Enter your current password to change the %mail or %pass. !request_new.', array(
'%mail' => $protected_values['mail'],
'%pass' => $protected_values['pass'],
'!request_new' => $request_new,
));
}
if ($user->uid == $account->uid) {
$form['account']['current_pass_required_values'] = array(
'#type' => 'value',
'#value' => $protected_values,
);
$form['account']['current_pass'] = array(
'#type' => 'password',
'#title' => t('Current password'),
'#size' => 25,
'#access' => !empty($protected_values),
'#description' => $current_pass_description,
'#weight' => -5,
'#attributes' => array(
'autocomplete' => 'off',
),
);
$form['#validate'][] = 'user_validate_current_pass';
}
}
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 = $register ? variable_get('user_register', USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL) == USER_REGISTER_VISITORS : $account->status;
}
$form['account']['status'] = array(
'#type' => 'radios',
'#title' => t('Status'),
'#default_value' => $status,
'#options' => array(
t('Blocked'),
t('Active'),
),
'#access' => $admin,
);
$roles = array_map('check_plain', user_roles(TRUE));
$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 && !empty($account->roles) ? array_keys(array_filter($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,
);
$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' => 'text_format',
'#title' => t('Signature'),
'#default_value' => isset($account->signature) ? $account->signature : '',
'#description' => t('Your signature will be publicly displayed at the end of your comments.'),
'#format' => isset($account->signature_format) ? $account->signature_format : NULL,
);
$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. Pictures larger than @dimensions pixels will be scaled down.', array(
'@dimensions' => variable_get('user_picture_dimensions', '85x85'),
)) . ' ' . filter_xss_admin(variable_get('user_picture_guidelines', '')),
);
$form['#validate'][] = 'user_validate_picture';
}
function user_validate_current_pass(&$form, &$form_state) {
$account = $form['#user'];
foreach ($form_state['values']['current_pass_required_values'] as $key => $name) {
if (strlen(trim($form_state['values'][$key])) > 0 && $form_state['values'][$key] != $account->{$key}) {
require_once DRUPAL_ROOT . '/' . variable_get('password_inc', 'includes/password.inc');
$current_pass_failed = strlen(trim($form_state['values']['current_pass'])) == 0 || !user_check_password($form_state['values']['current_pass'], $account);
if ($current_pass_failed) {
form_set_error('current_pass', t("Your current password is missing or incorrect; it's required to change the %name.", array(
'%name' => $name,
)));
form_set_error($key);
}
break;
}
}
}
function user_account_form_validate($form, &$form_state) {
if ($form['#user_category'] == 'account' || $form['#user_category'] == 'register') {
$account = $form['#user'];
if (isset($form_state['values']['name'])) {
if ($error = user_validate_name($form_state['values']['name'])) {
form_set_error('name', $error);
}
elseif ((bool) db_select('users')
->fields('users', array(
'uid',
))
->condition('uid', $account->uid, '<>')
->condition('name', db_like($form_state['values']['name']), 'LIKE')
->range(0, 1)
->execute()
->fetchField()) {
form_set_error('name', t('The name %name is already taken.', array(
'%name' => $form_state['values']['name'],
)));
}
}
$mail = trim($form_state['values']['mail']);
form_set_value($form['account']['mail'], $mail, $form_state);
if ($error = user_validate_mail($form_state['values']['mail'])) {
form_set_error('mail', $error);
}
elseif ((bool) db_select('users')
->fields('users', array(
'uid',
))
->condition('uid', $account->uid, '<>')
->condition('mail', db_like($form_state['values']['mail']), 'LIKE')
->range(0, 1)
->execute()
->fetchField()) {
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. <a href="@password">Have you forgotten your password?</a>', array(
'%email' => $form_state['values']['mail'],
'@password' => url('user/password'),
)));
}
}
if (isset($form_state['values']['signature'])) {
$form_state['values']['signature_format'] = $form_state['values']['signature']['format'];
$form_state['values']['signature'] = $form_state['values']['signature']['value'];
$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'],
)));
}
}
}
}
function user_user_presave(&$edit, $account, $category) {
if ($category == 'account' || $category == 'register') {
if (!empty($edit['picture_upload'])) {
$edit['picture'] = $edit['picture_upload'];
}
elseif (!empty($edit['picture_delete'])) {
$edit['picture'] = NULL;
}
}
if (isset($edit['roles'])) {
$edit['roles'] = array_filter($edit['roles']);
}
foreach (array(
'user_cancel_method',
'user_cancel_notify',
) as $key) {
if (isset($edit[$key])) {
$edit['data'][$key] = $edit[$key];
}
}
}
function user_user_categories() {
return array(
array(
'name' => 'account',
'title' => t('Account settings'),
'weight' => 1,
),
);
}
function user_login_block($form) {
$form['#action'] = url(current_path(), array(
'query' => drupal_get_destination(),
'external' => FALSE,
));
$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'),
'#size' => 15,
'#required' => TRUE,
);
$form['actions'] = array(
'#type' => 'actions',
);
$form['actions']['submit'] = array(
'#type' => 'submit',
'#value' => t('Log in'),
);
$items = array();
if (variable_get('user_register', USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL)) {
$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;
}
function user_block_info() {
global $user;
$blocks['login']['info'] = t('User login');
$blocks['login']['cache'] = DRUPAL_NO_CACHE;
$blocks['new']['info'] = t('Who\'s new');
$blocks['new']['properties']['administrative'] = TRUE;
$blocks['online']['info'] = t('Who\'s online');
$blocks['online']['cache'] = DRUPAL_NO_CACHE;
$blocks['online']['properties']['administrative'] = TRUE;
return $blocks;
}
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;
}
}
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;
}
}
function user_block_view($delta = '') {
global $user;
$block = array();
switch ($delta) {
case 'login':
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')) {
$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')) {
$interval = REQUEST_TIME - variable_get('user_block_seconds_online', 900);
$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 = '<p>' . format_plural($authenticated_count, 'There is currently 1 user online.', 'There are currently @count users online.') . '</p>';
$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;
}
}
function template_preprocess_user_picture(&$variables) {
$variables['user_picture'] = '';
if (variable_get('user_pictures', 0)) {
$account = $variables['account'];
if (!empty($account->picture)) {
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') && file_valid_uri($filepath) && ($style = variable_get('user_picture_style', ''))) {
$variables['user_picture'] = theme('image_style', array(
'style_name' => $style,
'path' => $filepath,
'alt' => $alt,
'title' => $alt,
));
}
else {
$variables['user_picture'] = theme('image', array(
'path' => $filepath,
'alt' => $alt,
'title' => $alt,
));
}
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);
}
}
}
}
function theme_user_list($variables) {
$users = $variables['users'];
$title = $variables['title'];
$items = array();
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() {
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', USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL);
}
function user_view_access($account) {
$uid = is_object($account) ? $account->uid : (int) $account;
if ($uid) {
if ($GLOBALS['user']->uid == $uid || user_access('administer users')) {
return TRUE;
}
elseif (user_access('access user profiles')) {
if (!is_object($account)) {
$account = user_load($uid);
}
return is_object($account) && $account->status;
}
}
return FALSE;
}
function user_edit_access($account) {
return ($GLOBALS['user']->uid == $account->uid || user_access('administer users')) && $account->uid > 0;
}
function user_cancel_access($account) {
return ($GLOBALS['user']->uid == $account->uid && user_access('cancel account') || user_access('administer users')) && $account->uid > 0;
}
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',
);
$items['user'] = array(
'title' => 'User account',
'title callback' => 'user_menu_title',
'page callback' => 'user_page',
'access callback' => TRUE,
'file' => 'user.pages.inc',
'weight' => -10,
'menu_name' => 'user-menu',
);
$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' => TRUE,
'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',
);
$items['admin/people'] = array(
'title' => 'People',
'description' => 'Manage user accounts, roles, and permissions.',
'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/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',
'type' => MENU_LOCAL_TASK,
);
$items['admin/people/permissions/list'] = array(
'title' => 'Permissions',
'description' => 'Determine access to features by selecting permissions for roles.',
'type' => MENU_DEFAULT_LOCAL_TASK,
'weight' => -8,
);
$items['admin/people/permissions/roles'] = array(
'title' => 'Roles',
'description' => 'List, edit, or add user roles.',
'page callback' => 'drupal_get_form',
'page arguments' => array(
'user_admin_roles',
),
'access arguments' => array(
'administer permissions',
),
'file' => 'user.admin.inc',
'type' => MENU_LOCAL_TASK,
'weight' => -5,
);
$items['admin/people/permissions/roles/edit/%user_role'] = array(
'title' => 'Edit role',
'page arguments' => array(
'user_admin_role',
5,
),
'access callback' => 'user_role_edit_access',
'access arguments' => array(
5,
),
);
$items['admin/people/permissions/roles/delete/%user_role'] = array(
'title' => 'Delete role',
'page callback' => 'drupal_get_form',
'page arguments' => array(
'user_admin_role_delete_confirm',
5,
),
'access callback' => 'user_role_edit_access',
'access arguments' => array(
5,
),
'file' => 'user.admin.inc',
);
$items['admin/people/create'] = array(
'title' => 'Add user',
'page callback' => 'user_admin',
'page arguments' => array(
'create',
),
'access arguments' => array(
'administer users',
),
'type' => MENU_LOCAL_ACTION,
'file' => 'user.admin.inc',
);
$items['admin/config/people'] = array(
'title' => 'People',
'description' => 'Configure user accounts.',
'position' => 'left',
'weight' => -20,
'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, fields, 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,
);
$items['user/%user'] = array(
'title' => 'My account',
'title callback' => 'user_page_title',
'title arguments' => array(
1,
),
'page callback' => 'user_view_page',
'page arguments' => array(
1,
),
'access callback' => 'user_view_access',
'access arguments' => array(
1,
),
'menu_name' => 'navigation',
);
$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,
),
'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,
),
'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) {
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;
}
function user_menu_site_status_alter(&$menu_site_status, $path) {
if ($menu_site_status == MENU_SITE_OFFLINE) {
if (user_is_logged_in() && !user_access('access site in maintenance mode')) {
module_load_include('pages.inc', 'user', 'user');
user_logout();
}
if (user_is_anonymous()) {
switch ($path) {
case 'user':
drupal_goto('user/login');
case 'user/login':
case 'user/password':
$menu_site_status = MENU_SITE_ONLINE;
break;
default:
if (strpos($path, 'user/reset/') === 0) {
$menu_site_status = MENU_SITE_ONLINE;
}
break;
}
}
}
if (user_is_logged_in()) {
if ($path == 'user/login') {
drupal_goto('user');
}
if ($path == 'user/register') {
drupal_goto('user/' . $GLOBALS['user']->uid . '/edit');
}
}
}
function user_menu_link_alter(&$link) {
if ($link['link_path'] == 'user' && isset($link['module']) && $link['module'] == 'system') {
$link['options']['alter'] = TRUE;
}
if ($link['link_path'] == 'user/logout' && isset($link['module']) && $link['module'] == 'system' && empty($link['customized'])) {
$link['plid'] = 0;
}
}
function user_translated_menu_link_alter(&$link) {
if ($link['link_path'] == 'user' && $link['module'] == 'system' && !$GLOBALS['user']->uid) {
$link['hidden'] = 1;
}
}
function user_admin_paths() {
$paths = array(
'user/*/cancel' => TRUE,
'user/*/edit' => TRUE,
'user/*/edit/*' => TRUE,
);
return $paths;
}
function user_uid_only_optional_to_arg($arg) {
return user_uid_optional_to_arg($arg);
}
function user_uid_optional_load($uid = NULL) {
if (!isset($uid)) {
$uid = $GLOBALS['user']->uid;
}
return user_load($uid);
}
function user_category_load($uid, &$map, $index) {
static $user_categories, $accounts;
if (!isset($accounts[$uid])) {
$accounts[$uid] = user_load($uid);
}
$valid = TRUE;
if ($account = $accounts[$uid]) {
$category_index = $index + 2;
$category_path = implode('/', array_slice($map, $category_index));
if ($category_path) {
$valid = FALSE;
if (!isset($user_categories)) {
$user_categories = _user_categories();
}
foreach ($user_categories as $category) {
if ($category['name'] == $category_path) {
$valid = TRUE;
$map = array_slice($map, 0, $category_index);
$map[$category_index] = $category_path;
break;
}
}
}
}
return $valid ? $account : FALSE;
}
function user_uid_optional_to_arg($arg) {
return empty($arg) || $arg == '%' ? $GLOBALS['user']->uid : $arg;
}
function user_menu_title() {
return user_is_logged_in() ? t('My account') : t('User account');
}
function user_page_title($account) {
return is_object($account) ? format_username($account) : '';
}
function user_get_authmaps($authname = NULL) {
$authmaps = db_query("SELECT module, authname FROM {authmap} WHERE authname = :authname", array(
':authname' => $authname,
))
->fetchAllKeyed();
return count($authmaps) ? $authmaps : 0;
}
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();
}
}
}
function user_login($form, &$form_state) {
global $user;
if ($user->uid) {
drupal_goto('user/' . $user->uid);
}
$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['actions'] = array(
'#type' => 'actions',
);
$form['actions']['submit'] = array(
'#type' => 'submit',
'#value' => t('Log in'),
);
return $form;
}
function user_login_default_validators() {
return array(
'user_login_name_validate',
'user_login_authenticate_validate',
'user_login_final_validate',
);
}
function user_login_name_validate($form, &$form_state) {
if (!empty($form_state['values']['name']) && user_is_blocked($form_state['values']['name'])) {
form_set_error('name', t('The username %name has not been activated or is blocked.', array(
'%name' => $form_state['values']['name'],
)));
}
}
function user_login_authenticate_validate($form, &$form_state) {
$password = trim($form_state['values']['pass']);
if (!empty($form_state['values']['name']) && strlen(trim($password)) > 0) {
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)) {
$identifier = $account->uid;
}
else {
$identifier = $account->uid . '-' . ip_address();
}
$form_state['flood_control_user_identifier'] = $identifier;
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;
}
}
$form_state['uid'] = user_authenticate($form_state['values']['name'], $password);
}
}
function user_login_final_validate($form, &$form_state) {
if (empty($form_state['uid'])) {
flood_register_event('failed_login_attempt_ip', variable_get('user_failed_login_ip_window', 3600));
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. Try again later or <a href="@url">request a new password</a>.', 'Sorry, there have been more than @count failed login attempts for this account. It is temporarily blocked. Try again later or <a href="@url">request a new password</a>.', array(
'@url' => url('user/password'),
)));
module_invoke_all('user_flood_control', ip_address(), $form_state['values']['name']);
}
else {
form_set_error('name', t('Sorry, too many failed login attempts from your IP address. This IP address is temporarily blocked. Try again later or <a href="@url">request a new password</a>.', array(
'@url' => url('user/password'),
)));
module_invoke_all('user_flood_control', ip_address());
}
drupal_add_http_header('Status', '403 Forbidden');
}
else {
$query = isset($form_state['input']['name']) ? array(
'name' => $form_state['input']['name'],
) : array();
form_set_error('name', t('Sorry, unrecognized username or password. <a href="@password">Have you forgotten your password?</a>', array(
'@password' => url('user/password', array(
'query' => $query,
)),
)));
watchdog('user', 'Login attempt failed for %user.', array(
'%user' => $form_state['values']['name'],
));
}
}
elseif (isset($form_state['flood_control_user_identifier'])) {
flood_clear_event('failed_login_attempt_user', $form_state['flood_control_user_identifier']);
}
}
function user_user_flood_control($ip, $username = FALSE) {
if (variable_get('log_user_flood_control', TRUE)) {
if (!empty($username)) {
watchdog('user', 'Flood control blocked login attempt for %user from %ip.', array(
'%user' => $username,
'%ip' => $ip,
));
}
else {
watchdog('user', 'Flood control blocked login attempt from %ip.', array(
'%ip' => $ip,
));
}
}
}
function user_authenticate($name, $password) {
$uid = FALSE;
if (!empty($name) && strlen(trim($password)) > 0) {
$account = user_load_by_name($name);
if ($account) {
require_once DRUPAL_ROOT . '/' . variable_get('password_inc', 'includes/password.inc');
if (user_check_password($password, $account)) {
$uid = $account->uid;
if (user_needs_new_hash($account)) {
user_save($account, array(
'pass' => $password,
));
}
}
}
}
return $uid;
}
function user_login_finalize(&$edit = array()) {
global $user;
watchdog('user', 'Session opened for %name.', array(
'%name' => $user->name,
));
$user->login = REQUEST_TIME;
db_update('users')
->fields(array(
'login' => $user->login,
))
->condition('uid', $user->uid)
->execute();
drupal_session_regenerate();
user_module_invoke('login', $edit, $user);
}
function user_login_submit($form, &$form_state) {
global $user;
$user = user_load($form_state['uid']);
$form_state['redirect'] = 'user/' . $user->uid;
user_login_finalize($form_state);
}
function user_external_login_register($name, $module) {
$account = user_external_load($name);
if (!$account) {
$userinfo = array(
'name' => $name,
'pass' => user_password(),
'init' => $name,
'status' => 1,
'access' => REQUEST_TIME,
);
$account = user_save(drupal_anonymous_user(), $userinfo);
if (!$account) {
drupal_set_message(t("Error saving user account."), 'error');
return;
}
user_set_authmaps($account, array(
"authname_{$module}" => $name,
));
}
$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, $account->uid), array(
'absolute' => TRUE,
));
}
function user_cancel_url($account) {
$timestamp = REQUEST_TIME;
return url("user/{$account->uid}/cancel/confirm/{$timestamp}/" . user_pass_rehash($account->pass, $timestamp, $account->login, $account->uid), array(
'absolute' => TRUE,
));
}
function user_pass_rehash($password, $timestamp, $login, $uid) {
if (!isset($uid)) {
$uids = db_query_range('SELECT uid FROM {users} WHERE pass = :password AND login = :login AND uid > 0', 0, 2, array(
':password' => $password,
':login' => $login,
))
->fetchCol();
if (count($uids) == 1) {
$uid = reset($uids);
}
else {
return drupal_random_key();
}
}
return drupal_hmac_base64($timestamp . $login . $uid, drupal_get_hash_salt() . $password);
}
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;
}
$batch = array(
'title' => t('Cancelling account'),
'operations' => array(),
);
batch_set($batch);
if ($method != 'user_cancel_delete') {
module_invoke_all('user_cancel', $edit, $account, $method);
}
$batch = array(
'title' => t('Cancelling user account'),
'operations' => array(
array(
'_user_cancel',
array(
$edit,
$account,
$method,
),
),
),
);
if ($account->uid == $user->uid) {
$batch['finished'] = '_user_cancel_session_regenerate';
}
batch_set($batch);
}
function _user_cancel($edit, $account, $method) {
global $user;
switch ($method) {
case 'user_cancel_block':
case 'user_cancel_block_unpublish':
default:
if (!empty($edit['user_cancel_notify'])) {
_user_mail_notify('status_blocked', $account);
}
user_save($account, array(
'status' => 0,
));
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':
if (!empty($edit['user_cancel_notify'])) {
_user_mail_notify('status_canceled', $account);
}
user_delete($account->uid);
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;
}
if ($account->uid == $user->uid) {
$user = drupal_anonymous_user();
}
cache_clear_all();
}
function _user_cancel_session_regenerate() {
drupal_session_regenerate();
}
function user_delete($uid) {
user_delete_multiple(array(
$uid,
));
}
function user_delete_multiple(array $uids) {
if (!empty($uids)) {
$accounts = user_load_multiple($uids, array());
$transaction = db_transaction();
try {
foreach ($accounts as $uid => $account) {
module_invoke_all('user_delete', $account);
module_invoke_all('entity_delete', $account, 'user');
field_attach_delete('user', $account);
drupal_session_destroy_uid($account->uid);
}
db_delete('users')
->condition('uid', $uids, 'IN')
->execute();
db_delete('users_roles')
->condition('uid', $uids, 'IN')
->execute();
db_delete('authmap')
->condition('uid', $uids, 'IN')
->execute();
} catch (Exception $e) {
$transaction
->rollback();
watchdog_exception('user', $e);
throw $e;
}
entity_get_controller('user')
->resetCache();
}
}
function user_view_page($account) {
return is_object($account) ? user_view($account) : MENU_NOT_FOUND;
}
function user_view($account, $view_mode = 'full', $langcode = NULL) {
if (!isset($langcode)) {
$langcode = $GLOBALS['language_content']->language;
}
user_build_content($account, $view_mode, $langcode);
$build = $account->content;
unset($account->content);
$build += array(
'#theme' => 'user_profile',
'#account' => $account,
'#view_mode' => $view_mode,
'#language' => $langcode,
);
$type = 'user';
drupal_alter(array(
'user_view',
'entity_view',
), $build, $type);
return $build;
}
function user_build_content($account, $view_mode = 'full', $langcode = NULL) {
if (!isset($langcode)) {
$langcode = $GLOBALS['language_content']->language;
}
$account->content = array();
$view_mode = key(entity_view_mode_prepare('user', array(
$account->uid => $account,
), $view_mode, $langcode));
field_attach_prepare_view('user', array(
$account->uid => $account,
), $view_mode, $langcode);
entity_prepare_view('user', array(
$account->uid => $account,
), $langcode);
$account->content += field_attach_view('user', $account, $view_mode, $langcode);
module_invoke_all('user_view', $account, $view_mode, $langcode);
module_invoke_all('entity_view', $account, 'user', $view_mode, $langcode);
$account->content += array(
'#view_mode' => $view_mode,
);
}
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);
}
function _user_mail_text($key, $language = NULL, $variables = array(), $replace = TRUE) {
$langcode = isset($language) ? $language->language : NULL;
if ($admin_setting = variable_get('user_mail_' . $key, FALSE)) {
$text = $admin_setting;
}
else {
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],\n\nThank you for registering at [site:name]. You may now log in by clicking this link or copying and pasting it to your browser:\n\n[user:one-time-login-url]\n\nThis link can only be used once to log in and will lead you to a page where you can set your password.\n\nAfter setting your password, you will be able to log in at [site:login-url] in the future using:\n\nusername: [user:name]\npassword: Your password\n\n-- [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],\n\nA site administrator at [site:name] has created an account for you. You may now log in by clicking this link or copying and pasting it to your browser:\n\n[user:one-time-login-url]\n\nThis link can only be used once to log in and will lead you to a page where you can set your password.\n\nAfter setting your password, you will be able to log in at [site:login-url] in the future using:\n\nusername: [user:name]\npassword: Your password\n\n-- [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],\n\nThank 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.\n\n\n-- [site:name] team", array(), array(
'langcode' => $langcode,
));
break;
case 'register_pending_approval_admin_body':
$text = t("[user:name] has applied for an account.\n\n[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],\n\nA request to reset the password for your account has been made at [site:name].\n\nYou may now log in by clicking this link or copying and pasting it to your browser:\n\n[user:one-time-login-url]\n\nThis link can only be used once to log in and will lead you to a page where you can set your password. It expires after one day and nothing will happen if it's not used.\n\n-- [site:name] team", 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],\n\nYour account at [site:name] has been activated.\n\nYou may now log in by clicking this link or copying and pasting it into your browser:\n\n[user:one-time-login-url]\n\nThis link can only be used once to log in and will lead you to a page where you can set your password.\n\nAfter setting your password, you will be able to log in at [site:login-url] in the future using:\n\nusername: [user:name]\npassword: Your password\n\n-- [site:name] team", 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.\n\n-- [site:name] team", 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],\n\nA request to cancel your account has been made at [site:name].\n\nYou may now cancel your account on [site:url-brief] by clicking this link or copying and pasting it into your browser:\n\n[user:cancel-url]\n\nNOTE: The cancellation of your account is not reversible.\n\nThis link expires in one day and nothing will happen if it is not used.\n\n-- [site:name] team", 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],\n\nYour account on [site:name] has been canceled.\n\n-- [site:name] team", array(), array(
'langcode' => $langcode,
));
break;
}
}
if ($replace) {
return token_replace($text, $variables, array(
'language' => $language,
'callback' => 'user_mail_tokens',
'sanitize' => FALSE,
'clear' => TRUE,
));
}
return $text;
}
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']);
}
}
function user_roles($membersonly = FALSE, $permission = NULL) {
$query = db_select('role', 'r');
$query
->addTag('translatable');
$query
->fields('r', array(
'rid',
'name',
));
$query
->orderBy('weight');
$query
->orderBy('name');
if (!empty($permission)) {
$query
->innerJoin('role_permission', 'p', 'r.rid = p.rid');
$query
->condition('p.permission', $permission);
}
$result = $query
->execute();
$roles = array();
foreach ($result as $role) {
switch ($role->rid) {
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;
}
}
return $roles;
}
function user_role_load($rid) {
return db_select('role', 'r')
->fields('r')
->condition('rid', $rid)
->execute()
->fetchObject();
}
function user_role_load_by_name($role_name) {
return db_select('role', 'r')
->fields('r')
->condition('name', $role_name)
->execute()
->fetchObject();
}
function user_role_save($role) {
if ($role->name) {
$role->name = trim($role->name);
}
if (!isset($role->weight)) {
$query = db_select('role');
$query
->addExpression('MAX(weight)');
$role->weight = $query
->execute()
->fetchField() + 1;
}
module_invoke_all('user_role_presave', $role);
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);
}
drupal_static_reset('user_access');
drupal_static_reset('user_role_permissions');
return $status;
}
function user_role_delete($role) {
if (is_int($role)) {
$role = user_role_load($role);
}
else {
$role = user_role_load_by_name($role);
}
if ($role->rid == variable_get('user_admin_role')) {
variable_del('user_admin_role');
}
db_delete('role')
->condition('rid', $role->rid)
->execute();
db_delete('role_permission')
->condition('rid', $role->rid)
->execute();
db_delete('users_roles')
->condition('rid', $role->rid)
->execute();
module_invoke_all('user_role_delete', $role);
drupal_static_reset('user_access');
drupal_static_reset('user_role_permissions');
}
function user_role_edit_access($role) {
if ($role->rid == DRUPAL_ANONYMOUS_RID || $role->rid == DRUPAL_AUTHENTICATED_RID) {
return FALSE;
}
return user_access('administer permissions');
}
function user_permission_get_modules() {
$permissions = array();
foreach (module_implements('permission') as $module) {
$perms = module_invoke($module, 'permission');
foreach ($perms as $key => $value) {
$permissions[$key] = $module;
}
}
return $permissions;
}
function user_role_change_permissions($rid, array $permissions = array()) {
$grant = array_filter($permissions);
if (!empty($grant)) {
user_role_grant_permissions($rid, array_keys($grant));
}
$revoke = array_diff_assoc($permissions, $grant);
if (!empty($revoke)) {
user_role_revoke_permissions($rid, array_keys($revoke));
}
}
function user_role_grant_permissions($rid, array $permissions = array()) {
$modules = user_permission_get_modules();
foreach ($permissions as $name) {
db_merge('role_permission')
->key(array(
'rid' => $rid,
'permission' => $name,
))
->fields(array(
'module' => $modules[$name],
))
->execute();
}
drupal_static_reset('user_access');
drupal_static_reset('user_role_permissions');
}
function user_role_revoke_permissions($rid, array $permissions = array()) {
db_delete('role_permission')
->condition('rid', $rid)
->condition('permission', $permissions, 'IN')
->execute();
drupal_static_reset('user_access');
drupal_static_reset('user_role_permissions');
}
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]);
$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 (!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;
}
function user_user_operations_unblock($accounts) {
$accounts = user_load_multiple($accounts);
foreach ($accounts as $account) {
if ($account !== FALSE && $account->status == 0) {
user_save($account, array(
'status' => 1,
));
}
}
}
function user_user_operations_block($accounts) {
$accounts = user_load_multiple($accounts);
foreach ($accounts as $account) {
if ($account !== FALSE && $account->status == 1) {
$account->original = clone $account;
user_save($account, array(
'status' => 0,
));
}
}
}
function user_multiple_role_edit($accounts, $operation, $rid) {
$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) {
if ($account !== FALSE && !isset($account->roles[$rid])) {
$roles = $account->roles + array(
$rid => $role_name,
);
$account->original = clone $account;
user_save($account, array(
'roles' => $roles,
));
}
}
break;
case 'remove_role':
$accounts = user_load_multiple($accounts);
foreach ($accounts as $account) {
if ($account !== FALSE && isset($account->roles[$rid])) {
$roles = array_diff($account->roles, array(
$rid => $role_name,
));
$account->original = clone $account;
user_save($account, array(
'roles' => $roles,
));
}
}
break;
}
}
function user_multiple_cancel_confirm($form, &$form_state) {
$edit = $form_state['input'];
$form['accounts'] = array(
'#prefix' => '<ul>',
'#suffix' => '</ul>',
'#tree' => TRUE,
);
$accounts = user_load_multiple(array_keys(array_filter($edit['accounts'])));
foreach ($accounts as $uid => $account) {
if ($uid <= 1) {
continue;
}
$form['accounts'][$uid] = array(
'#type' => 'hidden',
'#value' => $uid,
'#prefix' => '<li>',
'#suffix' => check_plain($account->name) . "</li>\n",
);
}
if (isset($accounts[1])) {
$redirect = count($accounts) == 1;
$message = t('The user account %name cannot be cancelled.', array(
'%name' => $accounts[1]->name,
));
drupal_set_message($message, $redirect ? 'error' : 'warning');
if ($redirect) {
drupal_goto('admin/people');
}
}
$form['operation'] = array(
'#type' => 'hidden',
'#value' => 'cancel',
);
module_load_include('inc', 'user', 'user.pages');
$form['user_cancel_method'] = array(
'#type' => 'item',
'#title' => t('When cancelling these accounts'),
);
$form['user_cancel_method'] += user_cancel_methods();
foreach (element_children($form['user_cancel_method']) as $element) {
unset($form['user_cancel_method'][$element]['#description']);
}
$form['user_cancel_confirm'] = array(
'#type' => 'checkbox',
'#title' => t('Require e-mail confirmation to cancel account.'),
'#default_value' => FALSE,
'#description' => t('When enabled, the user must confirm the account cancellation via e-mail.'),
);
$form['user_cancel_notify'] = array(
'#type' => 'checkbox',
'#title' => t('Notify user when account is canceled.'),
'#default_value' => FALSE,
'#access' => variable_get('user_mail_status_canceled_notify', FALSE),
'#description' => t('When enabled, the user will receive an e-mail notification after the account has been cancelled.'),
);
return confirm_form($form, t('Are you sure you want to cancel these user accounts?'), 'admin/people', t('This action cannot be undone.'), t('Cancel accounts'), t('Cancel'));
}
function user_multiple_cancel_confirm_submit($form, &$form_state) {
global $user;
if ($form_state['values']['confirm']) {
foreach ($form_state['values']['accounts'] as $uid => $value) {
if ($uid <= 1) {
continue;
}
if ($uid == $user->uid) {
$admin_form_state = $form_state;
unset($admin_form_state['values']['user_cancel_confirm']);
$admin_form_state['values']['_account'] = $user;
user_cancel_confirm_form_submit(array(), $admin_form_state);
}
else {
user_cancel($form_state['values'], $uid, $form_state['values']['user_cancel_method']);
}
}
}
$form_state['redirect'] = 'admin/people';
}
function _user_categories() {
$categories = module_invoke_all('user_categories');
usort($categories, '_user_sort');
return $categories;
}
function _user_sort($a, $b) {
$a = (array) $a + array(
'weight' => 0,
'title' => '',
);
$b = (array) $b + array(
'weight' => 0,
'title' => '',
);
return $a['weight'] < $b['weight'] ? -1 : ($a['weight'] > $b['weight'] ? 1 : ($a['title'] < $b['title'] ? -1 : 1));
}
function user_filters() {
$filters = array();
$roles = user_roles(TRUE);
unset($roles[DRUPAL_AUTHENTICATED_RID]);
if (count($roles)) {
$filters['role'] = array(
'title' => t('role'),
'field' => 'ur.rid',
'options' => array(
'[any]' => t('any'),
) + $roles,
);
}
$options = array();
foreach (module_implements('permission') as $module) {
$function = $module . '_permission';
if ($permissions = $function()) {
asort($permissions);
foreach ($permissions as $permission => $description) {
$options[t('@module module', array(
'@module' => $module,
))][$permission] = t($permission);
}
}
}
ksort($options);
$filters['permission'] = array(
'title' => t('permission'),
'options' => array(
'[any]' => t('any'),
) + $options,
);
$filters['status'] = array(
'title' => t('status'),
'field' => 'u.status',
'options' => array(
'[any]' => t('any'),
1 => t('active'),
0 => t('blocked'),
),
);
return $filters;
}
function user_build_filter_query(SelectQuery $query) {
$filters = user_filters();
foreach (isset($_SESSION['user_overview_filter']) ? $_SESSION['user_overview_filter'] : array() as $filter) {
list($key, $value) = $filter;
if ($key == 'permission') {
$account = new stdClass();
$account->uid = 'user_filter';
$account->roles = array(
DRUPAL_AUTHENTICATED_RID => 1,
);
if (user_access($value, $account)) {
continue;
}
$users_roles_alias = $query
->join('users_roles', 'ur', '%alias.uid = u.uid');
$permission_alias = $query
->join('role_permission', 'p', $users_roles_alias . '.rid = %alias.rid');
$query
->condition($permission_alias . '.permission', $value);
}
elseif ($key == 'role') {
$users_roles_alias = $query
->join('users_roles', 'ur', '%alias.uid = u.uid');
$query
->condition($users_roles_alias . '.rid', $value);
}
else {
$query
->condition($filters[$key]['field'], $value);
}
}
}
function user_comment_view($comment) {
if (variable_get('user_signatures', 0) && !empty($comment->signature)) {
$comment->signature = check_markup($comment->signature, $comment->signature_format, '', TRUE);
}
else {
$comment->signature = '';
}
}
function theme_user_signature($variables) {
$signature = $variables['signature'];
$output = '';
if ($signature) {
$output .= '<div class="clear">';
$output .= '<div>—</div>';
$output .= $signature;
$output .= '</div>';
}
return $output;
}
function user_preferred_language($account, $default = NULL) {
$language_list = language_list();
if (!empty($account->language) && isset($language_list[$account->language])) {
return $language_list[$account->language];
}
else {
return $default ? $default : language_default();
}
}
function _user_mail_notify($op, $account, $language = NULL) {
$default_notify = $op != 'status_canceled' && $op != 'status_blocked';
$notify = variable_get('user_mail_' . $op . '_notify', $default_notify);
if ($notify) {
$params['account'] = $account;
$language = $language ? $language : user_preferred_language($account);
$mail = drupal_mail('user', $op, $account->mail, $language, $params);
if ($op == 'register_pending_approval') {
drupal_mail('user', 'register_pending_approval_admin', variable_get('site_mail', ini_get('sendmail_from')), language_default(), $params);
}
}
return empty($mail) ? NULL : $mail['result'];
}
function user_form_process_password_confirm($element) {
global $user;
$js_settings = array(
'password' => array(
'strengthTitle' => t('Password strength:'),
'hasWeaknesses' => t('To make your password stronger:'),
'tooShort' => t('Make it at least 6 characters'),
'addLowerCase' => t('Add lowercase letters'),
'addUpperCase' => t('Add uppercase letters'),
'addNumbers' => t('Add numbers'),
'addPunctuation' => t('Add punctuation'),
'sameAsUsername' => t('Make it different from your username'),
'confirmSuccess' => t('yes'),
'confirmFailure' => t('no'),
'weak' => t('Weak'),
'fair' => t('Fair'),
'good' => t('Good'),
'strong' => t('Strong'),
'confirmTitle' => t('Passwords match:'),
'username' => isset($user->name) ? $user->name : '',
),
);
$element['#attached']['js'][] = drupal_get_path('module', 'user') . '/user.js';
$element['#attached']['js'][] = array(
'data' => $js_settings,
'type' => 'setting',
);
return $element;
}
function user_node_load($nodes, $types) {
$uids = array();
foreach ($nodes as $nid => $node) {
$uids[$nid] = $node->uid;
}
$user_fields = db_query("SELECT uid, name, picture, data FROM {users} WHERE uid IN (:uids)", array(
':uids' => $uids,
))
->fetchAllAssoc('uid');
foreach ($uids as $nid => $uid) {
$nodes[$nid]->name = $user_fields[$uid]->name;
$nodes[$nid]->picture = $user_fields[$uid]->picture;
$nodes[$nid]->data = $user_fields[$uid]->data;
}
}
function user_image_style_delete($style) {
user_image_style_save($style);
}
function user_image_style_save($style) {
if (isset($style['old_name']) && $style['old_name'] == variable_get('user_picture_style', '')) {
variable_set('user_picture_style', $style['name']);
}
}
function user_action_info() {
return array(
'user_block_user_action' => array(
'label' => t('Block current user'),
'type' => 'user',
'configurable' => FALSE,
'triggers' => array(
'any',
),
),
);
}
function user_block_user_action(&$entity, $context = array()) {
if (isset($entity->uid)) {
$uid = $entity->uid;
}
elseif (isset($context['uid'])) {
$uid = $context['uid'];
}
else {
$uid = $GLOBALS['user']->uid;
}
$account = user_load($uid);
$account = user_save($account, array(
'status' => 0,
));
watchdog('action', 'Blocked user %name.', array(
'%name' => $account->name,
));
}
function user_form_field_ui_field_edit_form_alter(&$form, &$form_state, $form_id) {
$instance = $form['#instance'];
if ($instance['entity_type'] == 'user' && !$form['#field']['locked']) {
$form['instance']['settings']['user_register_form'] = array(
'#type' => 'checkbox',
'#title' => t('Display on user registration form.'),
'#description' => t("This is compulsory for 'required' fields."),
'#default_value' => $instance['settings']['user_register_form'] || $instance['required'],
'#weight' => $form['instance']['required']['#weight'] + 0.1,
'#states' => array(
'enabled' => array(
'input[name="instance[required]"]' => array(
'checked' => FALSE,
),
),
),
'#attached' => array(
'js' => array(
drupal_get_path('module', 'user') . '/user.js',
),
),
);
array_unshift($form['#submit'], 'user_form_field_ui_field_edit_form_submit');
}
}
function user_form_field_ui_field_edit_form_submit($form, &$form_state) {
$instance = $form_state['values']['instance'];
if (!empty($instance['required'])) {
form_set_value($form['instance']['settings']['user_register_form'], 1, $form_state);
}
}
function user_register_form($form, &$form_state) {
global $user;
$admin = user_access('administer users');
$form['administer_users'] = array(
'#type' => 'value',
'#value' => $admin,
);
if (!$admin && $user->uid) {
drupal_goto('user/' . $user->uid);
}
$form['#user'] = drupal_anonymous_user();
$form['#user_category'] = 'register';
$form['#attached']['library'][] = array(
'system',
'jquery.cookie',
);
$form['#attributes']['class'][] = 'user-info-from-cookie';
user_account_form($form, $form_state);
$langcode = entity_language('user', $form['#user']);
field_attach_form('user', $form['#user'], $form, $form_state, $langcode);
foreach (field_info_instances('user', 'user') as $field_name => $instance) {
if (empty($instance['settings']['user_register_form'])) {
$form[$field_name]['#access'] = FALSE;
}
}
if ($admin) {
$form_state['redirect'] = $_GET['q'];
}
$form['actions'] = array(
'#type' => 'actions',
);
$form['actions']['submit'] = array(
'#type' => 'submit',
'#value' => t('Create new account'),
);
$form['#validate'][] = 'user_register_validate';
$form['#submit'][] = 'user_register_submit';
return $form;
}
function user_register_validate($form, &$form_state) {
entity_form_field_validate('user', $form, $form_state);
}
function user_register_submit($form, &$form_state) {
$admin = $form_state['values']['administer_users'];
if (!variable_get('user_email_verification', TRUE) || $admin) {
$pass = $form_state['values']['pass'];
}
else {
$pass = user_password();
}
$notify = !empty($form_state['values']['notify']);
form_state_values_clean($form_state);
$form_state['values']['pass'] = $pass;
$form_state['values']['init'] = $form_state['values']['mail'];
$account = $form['#user'];
entity_form_submit_build_entity('user', $account, $form, $form_state);
$edit = array_intersect_key((array) $account, $form_state['values']);
$account = user_save($account, $edit);
if (!$account) {
drupal_set_message(t("Error saving user account."), 'error');
$form_state['redirect'] = '';
return;
}
$form_state['user'] = $account;
$form_state['values']['uid'] = $account->uid;
watchdog('user', 'New user: %name (%email).', array(
'%name' => $form_state['values']['name'],
'%email' => $form_state['values']['mail'],
), WATCHDOG_NOTICE, l(t('edit'), 'user/' . $account->uid . '/edit'));
$account->password = $pass;
$uri = entity_uri('user', $account);
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($uri['path'], $uri['options']),
'%name' => $account->name,
)));
}
elseif (!$admin && !variable_get('user_email_verification', TRUE) && $account->status) {
_user_mail_notify('register_no_approval_required', $account);
$form_state['uid'] = $account->uid;
user_login_submit(array(), $form_state);
drupal_set_message(t('Registration successful. You are now logged in.'));
$form_state['redirect'] = '';
}
elseif ($account->status || $notify) {
$op = $notify ? 'register_admin_created' : 'register_no_approval_required';
_user_mail_notify($op, $account);
if ($notify) {
drupal_set_message(t('A welcome message with further instructions has been e-mailed to the new user <a href="@url">%name</a>.', array(
'@url' => url($uri['path'], $uri['options']),
'%name' => $account->name,
)));
}
else {
drupal_set_message(t('A welcome message with further instructions has been sent to your e-mail address.'));
$form_state['redirect'] = '';
}
}
else {
_user_mail_notify('register_pending_approval', $account);
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'] = '';
}
}
function user_modules_installed($modules) {
$rid = variable_get('user_admin_role', 0);
if ($rid) {
$permissions = array();
foreach ($modules as $module) {
if ($module_permissions = module_invoke($module, 'permission')) {
$permissions = array_merge($permissions, array_keys($module_permissions));
}
}
if (!empty($permissions)) {
user_role_grant_permissions($rid, $permissions);
}
}
}
function user_modules_uninstalled($modules) {
db_delete('role_permission')
->condition('module', $modules, 'IN')
->execute();
}
function user_login_destination() {
$destination = drupal_get_destination();
if ($destination['destination'] == 'user/login') {
$destination['destination'] = 'user';
}
return $destination;
}
function user_cookie_save(array $values) {
foreach ($values as $field => $value) {
setrawcookie('Drupal.visitor.' . $field, rawurlencode($value), REQUEST_TIME + 31536000, '/');
}
}
function user_cookie_delete($cookie_name) {
setrawcookie('Drupal.visitor.' . $cookie_name, '', REQUEST_TIME - 3600, '/');
}
function user_rdf_mapping() {
return array(
array(
'type' => 'user',
'bundle' => RDF_DEFAULT_BUNDLE,
'mapping' => array(
'rdftype' => array(
'sioc:UserAccount',
),
'name' => array(
'predicates' => array(
'foaf:name',
),
),
'homepage' => array(
'predicates' => array(
'foaf:page',
),
'type' => 'rel',
),
),
),
);
}
function user_file_download_access($field, $entity_type, $entity) {
if ($entity_type == 'user') {
return user_view_access($entity);
}
}
function user_system_info_alter(&$info, $file, $type) {
if ($type == 'module' && $file->name == 'profile' && db_table_exists('profile_field')) {
$info['hidden'] = FALSE;
}
}