Newer
Older
use Drupal\Core\Database\Query\SelectInterface;
use Drupal\Core\Entity\EntityInterface;
Angie Byron
committed
use Drupal\file\Plugin\Core\Entity\File;
use Drupal\Core\Template\Attribute;
Dries Buytaert
committed
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
/**
* @file
* Enables the user registration and login system.
*/
/**
* Maximum length of username text field.
*/
const USERNAME_MAX_LENGTH = 60;
/**
* Maximum length of user e-mail text field.
*/
const EMAIL_MAX_LENGTH = 254;
Dries Buytaert
committed
/**
* Only administrators can create user accounts.
*/
Angie Byron
committed
const USER_REGISTER_ADMINISTRATORS_ONLY = 'admin_only';
Dries Buytaert
committed
/**
* Visitors can create their own accounts.
*/
Angie Byron
committed
const USER_REGISTER_VISITORS = 'visitors';
Dries Buytaert
committed
/**
* Visitors can create accounts, but they don't become active without
* administrative approval.
*/
Angie Byron
committed
const USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL = 'visitors_admin_approval';
Dries Buytaert
committed
Angie Byron
committed
/**
* Implement hook_help().
*/
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>';
Angie Byron
committed
$output .= '<h3>' . t('Uses') . '</h3>';
$output .= '<dl>';
$output .= '<dt>' . t('Creating and managing users') . '</dt>';
Angie Byron
committed
$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>';
Angie Byron
committed
$output .= '<dt>' . t('User roles and permissions') . '</dt>';
Dries Buytaert
committed
$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/roles'))) . '</dd>';
Angie Byron
committed
$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 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>';
Angie Byron
committed
$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>';
Angie Byron
committed
case 'admin/people/permissions':
Dries Buytaert
committed
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/roles'), '@settings' => url('admin/config/people/accounts'))) . '</p>';
case 'admin/people/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>';
Dries Buytaert
committed
$output .= '<p>' . t('Drupal has three special user roles:') . '</p>';
Angie Byron
committed
$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>';
Dries Buytaert
committed
$output .= '<li>' . t('Administrator role: this role is automatically granted all new permissions when you install a new module. Configure which role is the administrator role on the <a href="@account_settings">Account settings page</a>.', array('@account_settings' => url('admin/config/people/accounts'))) . '</li>';
Angie Byron
committed
$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>';
}
}
Angie Byron
committed
Dries Buytaert
committed
/**
Dries Buytaert
committed
* Implements hook_theme().
Dries Buytaert
committed
*/
function user_theme() {
return array(
'user_profile' => array(
'render element' => 'elements',
'template' => 'user-profile',
'file' => 'user.pages.inc',
Steven Wittens
committed
),
Dries Buytaert
committed
'user_admin_permissions' => array(
'render element' => 'form',
'file' => 'user.admin.inc',
Dries Buytaert
committed
),
'user_admin_roles' => array(
'render element' => 'form',
'file' => 'user.admin.inc',
Dries Buytaert
committed
),
Dries Buytaert
committed
'user_permission_description' => array(
'variables' => array('permission_item' => NULL, 'hide' => NULL),
'file' => 'user.admin.inc',
),
Dries Buytaert
committed
'user_signature' => array(
'variables' => array('signature' => NULL),
Dries Buytaert
committed
),
'username' => array(
'variables' => array('account' => NULL),
),
Dries Buytaert
committed
);
}
Angie Byron
committed
/**
Angie Byron
committed
* Entity URI callback.
Angie Byron
committed
*/
Angie Byron
committed
function user_uri($user) {
return array(
'path' => 'user/' . $user->uid,
);
Angie Byron
committed
}
/**
* Entity label callback.
*
Angie Byron
committed
* This label callback has langcode for security reasons. The username is the
* visual identifier for a user and needs to be consistent in all languages.
*
* @param $entity_type
* The entity type.
* @param $entity
* The entity object.
*
* @return
* The name of the user.
*
* @see user_format_name()
*/
function user_label($entity_type, $entity) {
return user_format_name($entity);
}
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
/**
* Populates $entity->account for each prepared entity.
*
* Called by hook_entity_prepare_view() implementations.
*
* @param array $entities
* The entities keyed by entity ID.
*/
function user_attach_accounts(array $entities) {
$uids = array();
foreach ($entities as $entity) {
$uids[] = $entity->uid;
}
$uids = array_unique($uids);
$accounts = user_load_multiple($uids);
$anonymous = drupal_anonymous_user();
foreach ($entities as $id => $entity) {
if (isset($accounts[$entity->uid])) {
$entities[$id]->account = $accounts[$entity->uid];
}
else {
$entities[$id]->account = $anonymous;
}
}
}
/**
* Returns whether this site supports the default user picture feature.
*
* This approach preserves compatibility with node/comment templates. Alternate
* user picture implementations (e.g., Gravatar) should provide their own
* add/edit/delete forms and populate the 'picture' variable during the
* preprocess stage.
*/
function user_picture_enabled() {
return (bool) field_info_instance('user', 'user_picture', 'user');
}
Angie Byron
committed
/**
* Implements hook_field_info_alter().
*/
function user_field_info_alter(&$info) {
// Add the 'user_register_form' instance setting to all field types.
Angie Byron
committed
foreach ($info as $field_type => &$field_type_info) {
$field_type_info += array('instance_settings' => array());
$field_type_info['instance_settings'] += array(
Angie Byron
committed
'user_register_form' => FALSE,
);
}
}
Angie Byron
committed
/**
Dries Buytaert
committed
* Implements hook_field_extra_fields().
Angie Byron
committed
*/
function user_field_extra_fields() {
$return['user']['user'] = array(
Dries Buytaert
committed
'form' => array(
'account' => array(
Dries Buytaert
committed
'label' => t('User name and password'),
'description' => t('User module account form elements.'),
Dries Buytaert
committed
'weight' => -10,
),
'timezone' => array(
Dries Buytaert
committed
'label' => t('Timezone'),
Dries Buytaert
committed
'description' => t('User module timezone form element.'),
'weight' => 6,
),
Dries Buytaert
committed
'display' => array(
catch
committed
'member_for' => array(
'label' => t('Member for'),
'description' => t('User module \'member for\' view element.'),
Dries Buytaert
committed
'weight' => 5,
),
Angie Byron
committed
Angie Byron
committed
}
Angie Byron
committed
/**
* Fetches a user object based on an external authentication source.
*
* @param string $authname
* The external authentication username.
*
* @return
* A fully-loaded user object if the user is found or FALSE if not found.
*/
Angie Byron
committed
$uid = db_query("SELECT uid FROM {authmap} WHERE authname = :authname", array(':authname' => $authname))->fetchField();
Angie Byron
committed
if ($uid) {
return user_load($uid);
return FALSE;
* Loads multiple users based on certain conditions.
Angie Byron
committed
* 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 array $uids
* (optional) An array of entity IDs. If omitted, all entities are loaded.
* @param bool $reset
Angie Byron
committed
* 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.
Angie Byron
committed
*
* @return array
Angie Byron
committed
* An array of user objects, indexed by uid.
*
* @see entity_load_multiple()
Angie Byron
committed
* @see user_load()
* @see user_load_by_mail()
* @see user_load_by_name()
* @see \Drupal\Core\Entity\Query\QueryInterface
function user_load_multiple(array $uids = NULL, $reset = FALSE) {
return entity_load_multiple('user', $uids, $reset);
Dries Buytaert
committed
}
Angie Byron
committed
/**
Dries Buytaert
committed
* Loads a user object.
*
* Drupal has a global $user object, which represents the currently-logged-in
* user. So to avoid confusion and to avoid clobbering the global $user object,
* it is a good idea to assign the result of this function to a different local
* variable, generally $account. If you actually do want to act as the user you
* are loading, it is essential to call drupal_save_session(FALSE); first.
* See
* @link http://drupal.org/node/218104 Safely impersonating another user @endlink
* for more information.
Angie Byron
committed
*
* @param int $uid
Dries Buytaert
committed
* Integer specifying the user ID to load.
* @param bool $reset
Dries Buytaert
committed
* TRUE to reset the internal cache and load from the database; FALSE
* (default) to load from the internal cache, if set.
*
* @return object
Dries Buytaert
committed
* A fully-loaded user object upon successful user load, or FALSE if the user
Angie Byron
committed
* cannot be loaded.
*
* @see user_load_multiple()
*/
function user_load($uid, $reset = FALSE) {
return entity_load('user', $uid, $reset);
Angie Byron
committed
}
/**
* Fetches a user object by email address.
Angie Byron
committed
*
* @param string $mail
Angie Byron
committed
* String with the account's e-mail address.
* @return object|bool
Angie Byron
committed
* 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 = entity_load_multiple_by_properties('user', array('mail' => $mail));
Angie Byron
committed
return reset($users);
}
/**
* Fetches a user object by account name.
Angie Byron
committed
*
* @param string $name
Angie Byron
committed
* String with the account's user name.
* @return object|bool
Angie Byron
committed
* 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 = entity_load_multiple_by_properties('user', array('name' => $name));
Angie Byron
committed
return reset($users);
/**
* Verify the syntax of the given 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));
}
/**
* 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
Gábor Hojtsy
committed
// 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)];
/**
* 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.
Gábor Hojtsy
committed
* 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) {
Gábor Hojtsy
committed
if (!isset($account)) {
$account = $user;
}
Dries Buytaert
committed
// User #1 has all privileges:
Dries Buytaert
committed
if ($account->uid == 1) {
Dries Buytaert
committed
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.
Angie Byron
committed
static $drupal_static_fast;
if (!isset($drupal_static_fast)) {
$drupal_static_fast['perm'] = &drupal_static(__FUNCTION__);
}
$perm = &$drupal_static_fast['perm'];
Dries Buytaert
committed
if (!isset($perm[$account->uid])) {
$role_permissions = user_role_permissions($account->roles);
Dries Buytaert
committed
$perms = array();
foreach ($role_permissions as $one_role) {
$perms += $one_role;
Dries Buytaert
committed
$perm[$account->uid] = $perms;
Dries Buytaert
committed
Dries Buytaert
committed
return isset($perm[$account->uid][$string]);
Dries Buytaert
committed
/**
Gábor Hojtsy
committed
* Checks for usernames blocked by user administration.
Dries Buytaert
committed
*
* @param $name
* A string containing a name of the user.
*
* @return
* Object with property 'name' (the user name), if the user is blocked;
* FALSE if the user is not blocked.
Dries Buytaert
committed
*/
function user_is_blocked($name) {
Angie Byron
committed
return db_select('users')
->fields('users', array('name'))
->condition('name', db_like($name), 'LIKE')
->condition('status', 0)
->execute()->fetchObject();
Dries Buytaert
committed
}
Dries Buytaert
committed
* Implements hook_permission().
function user_permission() {
return array(
'administer permissions' => array(
'title' => t('Administer permissions'),
Dries Buytaert
committed
'restrict access' => TRUE,
),
'administer users' => array(
'title' => t('Administer users'),
Dries Buytaert
committed
'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'),
Angie Byron
committed
'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' => config('user.settings')->get('anonymous'), '@user-settings-url' => url('admin/config/people/accounts'))),
),
'select account cancellation method' => array(
'title' => t('Select method for cancelling own account'),
Dries Buytaert
committed
'restrict access' => TRUE,
Dries Buytaert
committed
* Implements hook_search_info().
Dries Buytaert
committed
function user_search_info() {
return array(
'title' => 'Users',
);
}
/**
Dries Buytaert
committed
* Implements hook_search_access().
Dries Buytaert
committed
*/
function user_search_access() {
return user_access('access user profiles');
}
/**
Dries Buytaert
committed
* Implements hook_search_execute().
Dries Buytaert
committed
*/
Dries Buytaert
committed
function user_search_execute($keys = NULL, $conditions = NULL) {
Dries Buytaert
committed
$find = array();
// Replace wildcards with MySQL/PostgreSQL wildcards.
$keys = preg_replace('!\*+!', '%', $keys);
catch
committed
$query = db_select('users')
->extend('Drupal\Core\Database\Query\PagerSelectExtender');
$query->fields('users', array('uid'));
Dries Buytaert
committed
if (user_access('administer users')) {
// Administrators can also search in the otherwise private email field.
Dries Buytaert
committed
$query->fields('users', array('mail'));
Dries Buytaert
committed
$query->condition(db_or()->
Dries Buytaert
committed
condition('name', '%' . db_like($keys) . '%', 'LIKE')->
condition('mail', '%' . db_like($keys) . '%', 'LIKE'));
Dries Buytaert
committed
}
else {
Dries Buytaert
committed
$query->condition('name', '%' . db_like($keys) . '%', 'LIKE');
Dries Buytaert
committed
}
$uids = $query
Dries Buytaert
committed
->limit(15)
->execute()
->fetchCol();
$accounts = user_load_multiple($uids);
$results = array();
foreach ($accounts as $account) {
$result = array(
'title' => user_format_name($account),
'link' => url('user/' . $account->uid, array('absolute' => TRUE)),
);
if (user_access('administer users')) {
$result['title'] .= ' (' . $account->mail . ')';
Dries Buytaert
committed
}
$results[] = $result;
return $results;
Dries Buytaert
committed
* Implements hook_user_view().
Dries Buytaert
committed
function user_user_view($account) {
catch
committed
$account->content['member_for'] = array(
'#type' => 'item',
Dries Buytaert
committed
'#title' => t('Member for'),
'#markup' => format_interval(REQUEST_TIME - $account->created),
catch
committed
'#weight' => 5,
Dries Buytaert
committed
);
}
/**
* Sets the value of the user register and profile forms' langcode element.
*/
function _user_language_selector_langcode_value($element, $input, &$form_state) {
// Only add to the description if the form element have a description.
if (isset($form_state['complete_form']['language']['preferred_langcode']['#description'])) {
$form_state['complete_form']['language']['preferred_langcode']['#description'] .= ' ' . t("This is also assumed to be the primary language of this account's profile information.");
}
return $form_state['values']['preferred_langcode'];
Angie Byron
committed
/**
* Form validation handler for the current password on the user account form.
Dries Buytaert
committed
*
* @see AccountFormController::form()
Angie Byron
committed
*/
function user_validate_current_pass(&$form, &$form_state) {
$account = $form_state['user'];
Angie Byron
committed
foreach ($form_state['values']['current_pass_required_values'] as $key => $name) {
// This validation only works for required textfields (like mail) or
// form values like password_confirm that have their own validation
// that prevent them from being empty if they are changed.
if ((strlen(trim($form_state['values'][$key])) > 0) && ($form_state['values'][$key] != $account->$key)) {
Dries Buytaert
committed
$current_pass_failed = empty($form_state['values']['current_pass']) || !drupal_container()->get('password')->check($form_state['values']['current_pass'], $account);
Angie Byron
committed
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);
}
// We only need to check the password once.
break;
}
}
}
Dries Buytaert
committed
* Implements hook_block_info().
Dries Buytaert
committed
function user_block_info() {
Dries Buytaert
committed
$blocks['login']['info'] = t('User login');
// Not worth caching.
$blocks['login']['cache'] = DRUPAL_NO_CACHE;
Dries Buytaert
committed
$blocks['new']['info'] = t('Who\'s new');
Angie Byron
committed
$blocks['new']['properties']['administrative'] = TRUE;
Dries Buytaert
committed
// Too dynamic to cache.
$blocks['online']['info'] = t('Who\'s online');
$blocks['online']['cache'] = DRUPAL_NO_CACHE;
Angie Byron
committed
$blocks['online']['properties']['administrative'] = TRUE;
Dries Buytaert
committed
return $blocks;
}
Dries Buytaert
committed
/**
Dries Buytaert
committed
* Implements hook_block_configure().
Dries Buytaert
committed
*/
function user_block_configure($delta = '') {
global $user;
catch
committed
$config = config('user.block');
switch ($delta) {
Dries Buytaert
committed
case 'new':
$form['user_block_whois_new_count'] = array(
'#type' => 'select',
'#title' => t('Number of users to display'),
catch
committed
'#default_value' => $config->get('whois_new_count'),
Dries Buytaert
committed
'#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');
catch
committed
$form['user_block_seconds_online'] = array(
'#type' => 'select',
'#title' => t('User activity'),
'#default_value' => $config->get('seconds_online'),
'#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' => $config->get('max_list_count'),
'#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.')
);
Dries Buytaert
committed
return $form;
Neil Drumm
committed
}
Dries Buytaert
committed
}
/**
Dries Buytaert
committed
* Implements hook_block_save().
Dries Buytaert
committed
*/
function user_block_save($delta = '', $edit = array()) {
global $user;
catch
committed
$config = config('user.block');
Dries Buytaert
committed
switch ($delta) {
case 'new':
catch
committed
$config->set('whois_new_count', $edit['user_block_whois_new_count'])->save();
Dries Buytaert
committed
break;
case 'online':
catch
committed
$config->set('seconds_online', $edit['user_block_seconds_online'])->save();
$config->set('max_list_count', $edit['user_block_max_list_count'])->save();
Dries Buytaert
committed
break;
}
Dries Buytaert
committed
}
Dries Buytaert
committed
/**
Dries Buytaert
committed
* Implements hook_block_view().
Dries Buytaert
committed
*/
function user_block_view($delta = '') {
global $user;
Dries Buytaert
committed
$block = array();
catch
committed
$block_config = config('user.block');
Dries Buytaert
committed
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)))) {
Angie Byron
committed
// Customize the login form.
$form = drupal_get_form('user_login_form');
unset($form['name']['#attributes']['autofocus']);
unset($form['name']['#description']);
unset($form['pass']['#description']);
$form['name']['#size'] = 15;
$form['pass']['#size'] = 15;
$form['#action'] = url(current_path(), array('query' => drupal_get_destination(), 'external' => FALSE));
// Build action links.
$items = array();
if (config('user.settings')->get('register') != USER_REGISTER_ADMINISTRATORS_ONLY) {
$items['create_account'] = l(t('Create new account'), 'user/register', array(
'attributes' => array(
'title' => t('Create a new user account.'),
'class' => array('create-account-link'),
),
));
}
$items['request_password'] = l(t('Request new password'), 'user/password', array(
'attributes' => array(
'title' => t('Request new password via e-mail.'),
'class' => array('request-password-link'),
),
));
// Build a block as renderable array.
Dries Buytaert
committed
$block['subject'] = t('User login');
Angie Byron
committed
$block['content'] = array(
'user_login_form' => $form,
'user_links' => array(
'#theme' => 'item_list',
'#items' => $items,
)
);
Dries Buytaert
committed
}
return $block;
Dries Buytaert
committed
case 'new':
if (user_access('access content')) {
// Retrieve a list of new users who have subsequently accessed the site successfully.
catch
committed
$from = 0;
$count = $block_config->get('whois_new_count');
$items = db_query_range('SELECT uid, name FROM {users} WHERE status <> 0 AND access <> 0 ORDER BY created DESC', $from, $count)->fetchAll();
Dries Buytaert
committed
$block['subject'] = t('Who\'s new');
$block['content'] = array(
'#theme' => 'item_list__user__new',
'#items' => array(),
);
foreach ($items as $account) {
$block['content']['#items'][] = theme('username', array('account' => $account));
}
Dries Buytaert
committed
}
return $block;
// @todo: Move this block to statistics.module and remove dependency on
// user.access.
Dries Buytaert
committed
case 'online':
if (user_access('access content')) {
// Count users active within the defined period.
catch
committed
$interval = REQUEST_TIME - $block_config->get('seconds_online');
// Perform database queries to gather online user lists.
$authenticated_count = db_query("SELECT COUNT(uid) FROM {users} WHERE access >= :timestamp", array(':timestamp' => $interval))->fetchField();
Dries Buytaert
committed
$block['subject'] = t('Who\'s online');
$block['content'] = array(
'#theme' => 'item_list__user__online',
'#items' => array(),
'#prefix' => '<p>' . format_plural($authenticated_count, 'There is currently 1 user online.', 'There are currently @count users online.') . '</p>',
);
Dries Buytaert
committed
// Display a list of currently online users.
catch
committed
$max_users = $block_config->get('max_list_count');
Dries Buytaert
committed
if ($authenticated_count && $max_users) {
$uids = db_query_range('SELECT uid FROM {users} WHERE access >= :interval AND uid > 0 ORDER BY access DESC', 0, $max_users, array(':interval' => $interval))->fetchCol();
foreach (user_load_multiple($uids) as $account) {
$block['content']['#items'][] = theme('username', array('account' => $account));
}
}
Dries Buytaert
committed
}
return $block;
/**
Jennifer Hodgdon
committed
* Implements hook_preprocess_HOOK() for block.tpl.php.
*/
function user_preprocess_block(&$variables) {
if ($variables['block']->module == 'user') {
switch ($variables['block']->delta) {
case 'login':
Dries Buytaert
committed
$variables['attributes']['role'] = 'form';
break;
case 'new':
Dries Buytaert
committed
$variables['attributes']['role'] = 'complementary';
break;
case 'online':
Dries Buytaert
committed
$variables['attributes']['role'] = 'complementary';
break;
}
}
}
/**
* Format a username.
*
* By default, the passed-in object's 'name' property is used if it exists, or
* else, the site-defined value for the 'anonymous' variable. However, a module
* may override this by implementing
* hook_user_format_name_alter(&$name, $account).
*
* @see hook_user_format_name_alter()
*
* @param $account
* The account object for the user whose name is to be formatted.
*
* @return
* An unsanitized string with the username to display. The code receiving
* this result must ensure that check_plain() is called on it before it is
* printed to the page.
*/
function user_format_name($account) {
Angie Byron
committed
$name = !empty($account->name) ? $account->name : config('user.settings')->get('anonymous');
drupal_alter('user_format_name', $name, $account);
return $name;
}
/**
* Implements hook_template_preprocess_default_variables_alter().
*
* @see user_user_login()
* @see user_user_logout()
*/
function user_template_preprocess_default_variables_alter(&$variables) {
global $user;
$variables['user'] = clone $user;
// Remove password and session IDs, since themes should not need nor see them.
unset($variables['user']->pass, $variables['user']->sid, $variables['user']->ssid);
$variables['is_admin'] = user_access('access administration pages');
$variables['logged_in'] = ($user->uid > 0);
}
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
/**
* Preprocesses variables for theme_username().
*
* Modules that make any changes to variables like 'name' or 'extra' must insure
* that the final string is safe to include directly in the output by using
* check_plain() or filter_xss().
*
* @see template_process_username()
*/
function template_preprocess_username(&$variables) {
$account = $variables['account'];
$variables['extra'] = '';
if (empty($account->uid)) {
$variables['uid'] = 0;
if (theme_get_setting('toggle_comment_user_verification')) {
$variables['extra'] = ' (' . t('not verified') . ')';
}
}
else {
$variables['uid'] = (int) $account->uid;
}
// Set the name to a formatted name that is safe for printing and
// that won't break tables by being too long. Keep an unshortened,
// unsanitized version, in case other preprocess functions want to implement
// their own shortening logic or add markup. If they do so, they must ensure
// that $variables['name'] is safe for printing.
$name = $variables['name_raw'] = user_format_name($account);
if (drupal_strlen($name) > 20) {
$name = drupal_substr($name, 0, 15) . '...';
}
$variables['name'] = check_plain($name);
$variables['profile_access'] = user_access('access user profiles');
Dries Buytaert
committed
// Populate link path and attributes if appropriate.
if ($variables['uid'] && $variables['profile_access']) {
// We are linking to a local user.
Dries Buytaert
committed
$variables['link_attributes']['title'] = t('View user profile.');
$variables['link_path'] = 'user/' . $variables['uid'];
}
elseif (!empty($account->homepage)) {
// Like the 'class' attribute, the 'rel' attribute can hold a
// space-separated set of values, so initialize it as an array to make it
// easier for other preprocess functions to append to it.
Dries Buytaert
committed
$variables['link_attributes']['rel'] = 'nofollow';
$variables['link_path'] = $account->homepage;
$variables['homepage'] = $account->homepage;
}
// We do not want the l() function to check_plain() a second time.
$variables['link_options']['html'] = TRUE;
// Set a default class.
Dries Buytaert
committed
$variables['attributes'] = array('class' => array('username'));
}
/**
* Processes variables for theme_username().
*
* @see template_preprocess_username()
*/
function template_process_username(&$variables) {
// Finalize the link_options array for passing to the l() function.
// This is done in the process phase so that attributes may be added by
// modules or the theme during the preprocess phase.
if (isset($variables['link_path'])) {
Dries Buytaert
committed
// $variables['attributes'] contains attributes that should be applied
// regardless of whether a link is being rendered or not.
// $variables['link_attributes'] contains attributes that should only be
// applied if a link is being rendered. Preprocess functions are encouraged
// to use the former unless they want to add attributes on the link only.
// If a link is being rendered, these need to be merged. Some attributes are
// themselves arrays, so the merging needs to be recursive.
Dries Buytaert
committed
$variables['link_options']['attributes'] = array_merge_recursive($variables['link_attributes'], $variables['attributes']);
}
}
/**
* Returns HTML for a username, potentially linked to the user's page.
*
* @param $variables
* An associative array containing:
* - account: The user object to format.
* - name: The user's name, sanitized.
* - extra: Additional text to append to the user's name, sanitized.
* - link_path: The path or URL of the user's profile page, home page, or
* other desired page to link to for more information about the user.
* - link_options: An array of options to pass to the l() function's $options
* parameter if linking the user's name to the user's page.
* - attributes: An array of attributes to instantiate the
* Drupal\Core\Template\Attribute class if not linking to the user's page.
*
* @see template_preprocess_username()
* @see template_process_username()
*/
function theme_username($variables) {
if (isset($variables['link_path'])) {
// We have a link path, so we should generate a link using l().
// Additional classes may be added as array elements like
// $variables['link_options']['attributes']['class'][] = 'myclass';
$output = l($variables['name'] . $variables['extra'], $variables['link_path'], $variables['link_options']);
}
else {
// Modules may have added important attributes so they must be included
// in the output. Additional classes may be added as array elements like
Dries Buytaert
committed
// $variables['attributes']['class'][] = 'myclass';
$output = '<span' . new Attribute($variables['attributes']) . '>' . $variables['name'] . $variables['extra'] . '</span>';
}
return $output;
}
Dries Buytaert
committed
function user_is_anonymous() {
Dries Buytaert
committed
// Menu administrators can see items for anonymous when administering.
return !$GLOBALS['user']->uid || !empty($GLOBALS['menu_admin']);
Dries Buytaert
committed
}
function user_is_logged_in() {
return (bool) $GLOBALS['user']->uid;
Dries Buytaert
committed
}
function user_register_access() {
Angie Byron
committed
return user_is_anonymous() && (config('user.settings')->get('register') != USER_REGISTER_ADMINISTRATORS_ONLY);
Dries Buytaert
committed
}
Dries Buytaert
committed
/**
* User view access callback.
*
* @param $account
* Can either be a full user object or a $uid.
*/