- <?php
- * @file
- * Enables the user registration and login system.
- */
-
- * Maximum length of username text field.
- */
- define('USERNAME_MAX_LENGTH', 60);
-
- * Users can login with username only.
- */
- define('USER_LOGIN_USERNAME_ONLY', 'username_only');
-
- * Users can login with email address only.
- */
- define('USER_LOGIN_EMAIL_ONLY', 'email_only');
-
- * Users can login using either username or email address.
- */
- define('USER_LOGIN_USERNAME_OR_EMAIL', 'username_or_email');
-
- * Only administrators can create user accounts.
- */
- define('USER_REGISTER_ADMINISTRATORS_ONLY', 'admin_only');
-
- * Visitors can create their own accounts.
- */
- define('USER_REGISTER_VISITORS', 'visitors');
-
- * Visitors can create accounts, but they don't become active without
- * administrative approval.
- */
- define('USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL', 'visitors_admin_approval');
-
- * Password strength modifier to encourage longer passwords.
- */
- define('USER_PASSWORD_STRENGTH_MODIFIER', 0.7);
-
- * Password strength levels: weak, fair, good and strong.
- */
- define('USER_PASSWORD_STRENGTH_WEAK', 0);
- define('USER_PASSWORD_STRENGTH_FAIR', 50);
- define('USER_PASSWORD_STRENGTH_GOOD', 70);
- define('USER_PASSWORD_STRENGTH_STRONG', 90);
-
- * Invokes a user hook in every module.
- *
- * We cannot use module_invoke() for this, because the arguments need to
- * be passed by reference.
- *
- * @param $type
- * A text string that controls which user hook to invoke. Valid choices are:
- * - login: Invokes hook_user_login().
- * @param $edit
- * An associative array variable containing form values to be passed
- * as the first parameter of the hook function.
- * @param $account
- * The user account object to be passed as the second parameter of the hook
- * function.
- */
- function user_module_invoke($type, &$edit, $account) {
- foreach (module_implements('user_' . $type) as $module) {
- $function = $module . '_user_' . $type;
- $function($edit, $account);
- }
- }
-
- * Implements hook_theme().
- */
- function user_theme() {
- $base = array(
- 'file' => 'user.theme.inc',
- );
-
- return array(
- 'user_picture' => array(
- 'variables' => array('account' => NULL),
- 'template' => 'templates/user-picture',
- ) + $base,
- 'user_profile' => array(
- 'render element' => 'elements',
- 'template' => 'templates/user-profile',
- ) + $base,
- 'user_list' => array(
- 'variables' => array('users' => NULL, 'title' => NULL),
- ) + $base,
- 'user_admin_permissions' => array(
- 'render element' => 'form',
- ) + $base,
- 'user_admin_roles' => array(
- 'render element' => 'form',
- ) + $base,
- 'user_permission_description' => array(
- 'variables' => array('permission_item' => NULL),
- ) + $base,
- 'user_signature' => array(
- 'variables' => array('signature' => NULL),
- ) + $base,
- 'username' => array(
- 'variables' => array('account' => NULL),
- ) + $base,
- );
- }
-
- * Implements hook_entity_info().
- */
- function user_entity_info() {
- $entity_info = array(
- 'user' => array(
- 'label' => t('User account'),
- 'bundle label' => t('Type'),
- 'controller class' => 'UserStorageController',
- 'base table' => 'users',
- 'fieldable' => TRUE,
- 'redirect support' => TRUE,
- 'entity class' => 'User',
- 'entity keys' => array(
- 'id' => 'uid',
- ),
- 'bundles' => array(
- 'user' => array(
- 'label' => t('User account'),
- 'admin' => array(
- 'path' => 'admin/config/people/manage',
- 'access arguments' => array('administer account settings'),
- ),
- ),
- ),
- 'view modes' => array(
- 'full' => array(
- 'label' => t('User account'),
- 'custom settings' => FALSE,
- ),
- 'token' => array(
- 'label' => t('Tokens'),
- 'custom settings' => FALSE,
- ),
- ),
- ),
- );
-
-
- if (db_table_exists('cache_entity_user')) {
- $entity_info['user']['entity cache'] = TRUE;
- $entity_info['user']['field cache'] = FALSE;
- }
-
- return $entity_info;
- }
-
- * Implements hook_layout_context_info().
- */
- function user_layout_context_info() {
- $info['user'] = array(
- 'title' => t('User account'),
-
- 'class' => 'EntityLayoutContext',
-
- 'menu paths' => array(
- 'user/%user',
- 'user/%user/view',
- 'user/%user/edit',
- ),
-
-
- 'path placeholder' => '%user',
-
-
- 'load callback' => 'user_load',
- );
- return $info;
- }
-
- * Implements hook_field_info_alter().
- */
- 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,
- );
- }
- }
-
- * Implements hook_field_extra_fields().
- */
- 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,
- ),
- 'account_settings' => array(
- 'label' => t('Account status and user roles'),
- 'description' => t('User module account settings form elements.'),
- 'weight' => 1,
- ),
- 'timezone' => array(
- 'label' => t('Timezone'),
- 'description' => t('User module timezone form element.'),
- 'weight' => 6,
- ),
- ),
- 'display' => array(
- 'member_for' => array(
- 'label' => t('Member for'),
- 'description' => t('User module \'member for\' view element.'),
- 'weight' => 5,
- ),
- ),
- );
-
- return $return;
- }
-
- * Load multiple users based on certain conditions.
- *
- * This function should be used whenever you need to load more than one user
- * from the database. Users are loaded into memory and will not require
- * database access if loaded again during the same page request.
- *
- * @param $uids
- * An array of user IDs.
- * @param $conditions
- * (deprecated) An associative array of conditions on the {users}
- * table, where the keys are the database fields and the values are the
- * values those fields must have. Instead, it is preferable to use
- * EntityFieldQuery to retrieve a list of entity IDs loadable by
- * this function.
- * @param $reset
- * A boolean indicating that the internal cache should be reset. Use this if
- * loading a user object which has been altered during the page request.
- *
- * @return
- * An array of user objects, indexed by uid.
- *
- * @see entity_load()
- * @see user_load()
- * @see user_load_by_mail()
- * @see user_load_by_name()
- * @see EntityFieldQuery
- *
- * @todo Remove $conditions for consistency with other loaders.
- */
- function user_load_multiple($uids = array(), $conditions = array(), $reset = FALSE) {
- return entity_load('user', $uids, $conditions, $reset);
- }
-
- * Loads a user object.
- *
- * Backdrop 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 backdrop_save_session(FALSE); first.
- * See
- * @link http://drupal.org/node/218104 Safely impersonating another user @endlink
- * for more information.
- *
- * @param $uid
- * Integer specifying the user ID to load.
- * @param $reset
- * TRUE to reset the internal cache and load from the database; FALSE
- * (default) to load from the internal cache, if set.
- *
- * @return
- * A fully-loaded user object upon successful user load, or FALSE if the user
- * cannot be loaded.
- *
- * @see user_load_multiple()
- */
- function user_load($uid, $reset = FALSE) {
- $users = user_load_multiple(array($uid), array(), $reset);
- return reset($users);
- }
-
- * Fetch a user object by email address.
- *
- * @param $mail
- * String with the account's email address.
- * @return
- * A fully-loaded $user object upon successful user load or FALSE if user
- * cannot be loaded.
- *
- * @see user_load_multiple()
- */
- function user_load_by_mail($mail) {
- $users = user_load_multiple(array(), array('mail' => $mail));
- return reset($users);
- }
-
- * Fetch a user object by account name.
- *
- * @param $name
- * String with the account's user name.
- * @return
- * A fully-loaded $user object upon successful user load or FALSE if user
- * cannot be loaded.
- *
- * @see user_load_multiple()
- */
- function user_load_by_name($name) {
- $users = user_load_multiple(array(), array('name' => $name));
- return reset($users);
- }
-
- * Save a new or updated user.
- *
- * @param User $account
- * The user entity object to add or modify.
- * @return int
- * Either SAVED_NEW or SAVED_UPDATED depending on the operation performed.
- *
- * @see entity_create()
- * @see user_load()
- */
- function user_save($account) {
- return $account->save();
- }
-
- * Element validate handler for the password field.
- *
- * Set a default value if one-time login link goes out,
- * set a form error if not and password value is empty.
- */
- function user_pass_required_validate($element, &$form_state, $form) {
- $values = $form_state['values'];
- if ($values['notify'] == 1) {
- $form_state['values']['pass'] = user_password(22);
- }
- else {
- if (empty($values['pass']) && $values['pass'] !== '0') {
- $message = t('!name field is required.', array('!name' => $element['#title']));
- form_set_error('pass', $message);
- }
- }
- }
-
- * Verify the syntax of the given name.
- */
- function user_validate_name($name) {
- if (!$name) {
- return t('You must enter a username.');
- }
- if (substr($name, 0, 1) == ' ') {
- return t('The username cannot begin with a space.');
- }
- if (substr($name, -1) == ' ') {
- return t('The username cannot end with a space.');
- }
- if (strpos($name, ' ') !== FALSE) {
- return t('The username cannot contain multiple spaces in a row.');
- }
- if (preg_match('/[^\x{80}-\x{F7} a-z0-9@+_.\'-]/i', $name)) {
- return t('The username contains an illegal character.');
- }
- if (preg_match('/[\x{80}-\x{A0}' .
- '\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 (backdrop_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));
- }
- }
-
- * Validates an image uploaded by a user.
- *
- * @see user_account_form()
- */
- function user_validate_picture(&$form, &$form_state) {
- $site_config = config('system.core');
-
- $validators = array(
- 'file_validate_is_image' => array(),
- 'file_validate_image_orientation' => array(TRUE),
- 'file_validate_image_resolution' => array($site_config->get('user_picture_dimensions')),
- 'file_validate_size' => array((int) $site_config->get('user_picture_file_size') * 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' => $site_config->get('user_picture_path'))));
- }
- elseif ($file !== NULL) {
- $form_state['values']['picture_upload'] = $file;
- }
- }
-
- * Generate a random alphanumeric password.
- */
- function user_password($length = 10) {
-
-
-
-
- $allowable_characters = 'abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789';
-
-
- $len = strlen($allowable_characters) - 1;
-
-
- $pass = '';
-
-
- for ($i = 0; $i < $length; $i++) {
- do {
-
- $index = ord(backdrop_random_bytes(1));
- } while ($index > $len);
-
-
-
- $pass .= $allowable_characters[$index];
- }
-
- return $pass;
- }
-
- * Determine the permissions for one or more roles.
- *
- * @param $role_names
- * An unindexed array of role names, such as those in $user->roles.
- *
- * @return
- * An array of permission strings for all the given role names.
- */
- function user_role_permissions($role_names = array()) {
- $all_roles = user_roles(FALSE, NULL, TRUE);
- $role_permissions = array();
- foreach ($role_names as $role_name) {
- if (isset($all_roles[$role_name])) {
- foreach ($all_roles[$role_name]->permissions as $permission) {
- if (!in_array($permission, $role_permissions)) {
- $role_permissions[] = $permission;
- }
- }
- }
- }
-
- return $role_permissions;
- }
-
- * Determine whether the user has a given privilege.
- *
- * @param $string
- * The permission, such as "administer nodes", being checked for.
- * @param $account
- * (optional) The account to check, if not given use currently logged in user.
- *
- * @return
- * Boolean TRUE if the user has the requested permission.
- *
- * All permission checks in Backdrop should go through this function. This
- * way, we guarantee consistent behavior, and ensure that the superuser
- * can perform all actions.
- */
- function user_access($permission_name, $account = NULL) {
- global $user;
-
- if (!isset($account)) {
- $account = $user;
- }
-
-
- if ($account->uid == 1) {
- return TRUE;
- }
-
-
-
-
- static $backdrop_static_fast;
- if (!isset($backdrop_static_fast)) {
- $backdrop_static_fast['perm'] = &backdrop_static(__FUNCTION__);
- }
- $perm = &$backdrop_static_fast['perm'];
- if (!isset($perm[$account->uid])) {
- $perm[$account->uid] = user_role_permissions($account->roles);
- }
-
- return in_array($permission_name, $perm[$account->uid]);
- }
-
- * Checks for usernames blocked by user administration.
- *
- * @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.
- */
- function user_is_blocked($name) {
- return db_select('users')
- ->fields('users', array('name'))
- ->condition('name', db_like($name), 'LIKE')
- ->condition('status', 0)
- ->execute()->fetchObject();
- }
-
- * Checks if a user has a role.
- *
- * @param string $role_name
- * A string representing the role name.
- * @param User $account
- * (optional) A user account. Defaults to the current user.
- *
- * @return bool
- * TRUE or FALSE.
- *
- * @since 1.14.0 First parameter changed from $rid to $role_name.
- */
- function user_has_role($role_name, $account = NULL) {
- if (!$account) {
- $account = $GLOBALS['user'];
- }
-
- return in_array($role_name, $account->roles);
- }
-
- * Implements hook_permission().
- */
- function user_permission() {
- return array(
- 'administer permissions' => array(
- 'title' => t('Administer permissions'),
- 'restrict access' => TRUE,
- ),
- 'administer users' => array(
- 'title' => t('Administer user accounts'),
- 'restrict access' => TRUE,
- ),
- 'assign roles' => array(
- 'title' => t('Assign user roles'),
- 'restrict access' => TRUE,
- ),
- 'administer account settings' => array(
- 'title' => t('Administer user account settings'),
- 'description' => t('Manage settings that apply to all user accounts.'),
- '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' => config_get_translated('system.core', 'anonymous'), '@user-settings-url' => url('admin/config/people/settings'))),
- ),
- 'select account cancellation method' => array(
- 'title' => t('Select method for cancelling own account'),
- 'restrict access' => TRUE,
- ),
- );
- }
-
- * Implements hook_config_info().
- */
- function user_config_info() {
- $prefixes['user.flood'] = array(
- 'label' => t('User flood'),
- 'group' => t('Configuration'),
- );
- $prefixes['user.mail'] = array(
- 'label' => t('User email templates'),
- 'group' => t('Configuration'),
- );
- $prefixes['user.role'] = array(
- 'name_key' => 'name',
- 'label_key' => 'label',
- 'group' => t('User roles'),
- );
- return $prefixes;
- }
-
- * Implements hook_views_api().
- */
- function user_views_api() {
- return array(
- 'api' => '3.0',
- 'path' => backdrop_get_path('module', 'user') . '/views',
- );
- }
-
- * Implements hook_file_download().
- *
- * Ensure that user pictures (avatars) are always downloadable.
- */
- function user_file_download($uri) {
- if (strpos(file_uri_target($uri), config_get('system.core', 'user_picture_path') . '/picture-') === 0) {
- $info = image_get_info($uri);
- return array('Content-Type' => $info['mime_type']);
- }
- }
-
- * Implements hook_file_move().
- */
- function user_file_move(File $file, 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();
- }
- }
-
- * Implements hook_file_predelete().
- */
- function user_file_predelete(File $file) {
-
- db_update('users')
- ->fields(array('picture' => 0))
- ->condition('picture', $file->fid)
- ->execute();
- }
-
- * Implements hook_search_info().
- */
- function user_search_info() {
- return array(
- 'title' => 'User accounts',
- );
- }
-
- * Implements hook_search_access().
- */
- function user_search_access() {
- return user_access('access user profiles');
- }
-
- * Implements hook_search_execute().
- */
- 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' => user_format_name($account),
- 'link' => url('user/' . $account->uid, array('absolute' => TRUE)),
- );
- if (user_access('administer users')) {
- $result['title'] .= ' (' . $account->mail . ')';
- }
- $results[] = $result;
- }
-
- return $results;
- }
-
- * Implements hook_user_view().
- */
- function user_user_view($account) {
- $account->content['user_picture'] = array(
- '#markup' => theme('user_picture', array('account' => $account)),
- '#weight' => -10,
- );
- $account->content['member_for'] = array(
- '#type' => 'item',
- '#title' => t('Member for'),
- '#markup' => format_interval(REQUEST_TIME - $account->created),
- '#weight' => 5,
- );
- }
-
- * Helper function to add default user account fields to user registration and edit form.
- *
- * @see user_account_form_validate()
- * @see user_validate_current_pass()
- * @see user_validate_picture()
- * @see user_validate_mail()
- * @see user_password_policy_validate()
- */
- function user_account_form(&$form, &$form_state) {
- global $user;
- $site_config = config('system.core');
-
- $account = $form['#user'];
- $register = ($form['#user']->uid > 0 ? FALSE : TRUE);
-
- $admin_users = user_access('administer users');
- $admin_roles = user_access('assign roles');
-
- $form['#validate'][] = 'user_account_form_validate';
- module_load_include('password.inc', 'user', 'user');
- $reject_weak = user_password_reject_weak($user->name);
-
- if ($reject_weak) {
- $form['#validate'][] = 'user_password_policy_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_users),
- '#weight' => -10,
- );
-
- if ($register) {
- $form['account']['name']['#attributes']['autofocus'] = 'autofocus';
- }
-
- $form['account']['mail'] = array(
- '#type' => 'email',
- '#title' => t('E-mail address'),
- '#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(
- '#title' => t('New password'),
- '#type' => 'password',
- '#password_toggle' => TRUE,
- '#password_strength' => TRUE,
- );
-
-
-
- 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('Reset password'), 'user/password', array('attributes' => array('title' => t('Reset password via one-time login link.'))));
- $current_pass_description = t('Required if you want to change the %mail or %pass below. !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'),
- '#access' => !empty($protected_values),
- '#description' => $current_pass_description,
- '#weight' => -5,
- '#password_toggle' => TRUE,
-
-
-
- '#attributes' => array('autocomplete' => 'off'),
- );
- $form['#validate'][] = 'user_validate_current_pass';
- }
- }
- else {
- if (!$site_config->get('user_email_verification') && !$admin_users) {
-
- $form['account']['pass'] = array(
- '#type' => 'password',
- '#title' => t('Password'),
- '#password_toggle' => TRUE,
- '#password_strength' => TRUE,
- '#required' => TRUE,
- );
- }
- if ($admin_users) {
-
- $form['account']['notify'] = array(
- '#type' => 'checkbox',
- '#title' => t('Notify user of new account'),
- '#default_value' => 1,
- '#description' => t('The user will receive an email with a one-time login link which leads to a page where they can set their password.'),
- );
- $form['account']['pass'] = array(
- '#type' => 'password',
- '#title' => t('Password'),
- '#password_toggle' => TRUE,
- '#password_strength' => TRUE,
- '#required' => FALSE,
- '#element_validate' => array('user_pass_required_validate'),
- '#states' => array(
- 'visible' => array(
- ':input[name="notify"]' => array('checked' => FALSE),
- ),
- 'required' => array(
- ':input[name="notify"]' => array('checked' => FALSE),
- ),
- ),
- );
- }
- }
-
- $description = !$register && $user->uid == $account->uid ? t('The current password must be entered to set a new password.') : '';
-
-
- if ($reject_weak) {
- $description .= !empty($description) ? '<br /><br />' : '';
- $description .= _user_password_policy_help();
- }
- $form['account']['pass']['#description'] = $description;
-
- $form['account_settings'] = array(
- '#type' => 'fieldset',
- '#title' => t('Account settings'),
- '#weight' => 1,
- '#access' => $admin_users || $admin_roles,
- '#collapsible' => TRUE,
- '#group' => 'additional_settings',
- );
-
- if ($admin_users) {
- $status = isset($account->status) ? $account->status : 1;
- }
- else {
- $status = $register ? $site_config->get('user_register') == USER_REGISTER_VISITORS : $account->status;
- }
- $form['account_settings']['status'] = array(
- '#type' => 'radios',
- '#title' => t('Status'),
- '#default_value' => $status,
- '#options' => array(t('Blocked'), t('Active')),
- '#access' => $admin_users,
- );
-
- $roles = array_map('check_plain', user_roles(TRUE));
- $form['account_settings']['roles'] = array(
- '#type' => 'checkboxes',
- '#title' => t('Roles'),
- '#default_value' => (!$register && isset($account->roles) ? $account->roles : array()),
- '#options' => $roles,
- '#access' => $roles && $admin_roles,
- );
- $form['account_settings']['roles'][BACKDROP_AUTHENTICATED_ROLE] = array(
- '#disabled' => TRUE,
- '#value' => 'authenticated',
- );
-
-
- $form['signature_settings'] = array(
- '#type' => 'fieldset',
- '#title' => t('Signature settings'),
- '#weight' => 2,
- '#access' => (!$register && $site_config->get('user_signatures')),
- );
-
- $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' => 2,
- '#access' => (!$register && $site_config->get('user_pictures')),
- );
- $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' => $site_config->get('user_picture_dimensions'))) . ' ' . filter_xss_admin($site_config->get('user_picture_guidelines')),
- );
- $form['#validate'][] = 'user_validate_picture';
- }
-
- * Form validation handler for the current password on the user_account_form().
- *
- * @see user_account_form()
- */
- 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 BACKDROP_ROOT . '/' . settings_get('password_inc', 'core/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;
- }
- }
- }
-
- * Form validation handler for user_account_form().
- *
- * @see user_account_form()
- */
- function user_account_form_validate($form, &$form_state) {
- $account = $form['#user'];
- $mail = $form_state['values']['mail'];
-
-
- if (isset($form_state['values']['name'])) {
- $name = $form_state['values']['name'];
- if ($error = user_validate_name($name)) {
- form_set_error('name', $error);
- }
-
-
- else {
- $name_taken = (bool) db_select('users')
- ->fields('users', array('uid'))
- ->condition('uid', (int) $account->uid, '<>')
- ->condition('name', db_like($name), 'LIKE')
- ->range(0, 1)
- ->execute()
- ->fetchField();
-
- if ($name_taken) {
- form_set_error('name', t('The name %name is already taken.', array('%name' => $name)));
- }
-
-
- if (config('system.core')->get('user_email_match') && (valid_email_address($name))) {
- if ($name !== $mail) {
- form_set_error('name', t('An email address was provided as a username, but does not match the account email address.'));
- }
- }
- }
- }
-
- if (!empty($mail)) {
- $mail_taken = (bool) db_select('users')
- ->fields('users', array('uid'))
- ->condition('uid', (int) $account->uid, '<>')
- ->condition('mail', db_like($mail), 'LIKE')
- ->range(0, 1)
- ->execute()
- ->fetchField();
-
- if ($mail_taken) {
-
- if ($GLOBALS['user']->uid) {
- form_set_error('mail', t('The e-mail address %email is already taken.', array('%email' => $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' => $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 = backdrop_get_schema('users');
- if (backdrop_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'])));
- }
- }
- }
-
- * Validation callback for password constraints.
- *
- * @see user_account_form()
- * @see user_pass_reset_form()
- */
- function user_password_policy_validate($form, &$form_state) {
- $strength = 0;
- if (!array_key_exists('pass', $form_state['values'])) {
-
-
- return;
- }
- $password = trim($form_state['values']['pass']);
-
- if ($form['#form_id'] == 'user_profile_form' && strlen($password) == 0) {
-
- return;
- }
- $config = config('system.core');
- $messages = array();
- if ($form['#form_id'] == 'user_pass_reset_form') {
- $account = $form['#account'];
- $username = $account->name;
- $email = $account->mail;
- }
- else {
- $username = $form_state['values']['name'];
- $email = $form_state['values']['mail'];
- }
- module_load_include('password.inc', 'user', 'user');
-
- $strength = _user_password_evaluate_strength($password, $username, $email);
-
- if ($strength < $config->get('user_password_strength_threshold')) {
- form_set_error('complex_pass', t('The password is too weak. Please consider making your password longer or more complex: that it contains a number of lower- and uppercase letters, digits and punctuation.'));
- }
-
- if (backdrop_strtolower($password) == backdrop_strtolower($username)) {
- form_set_error('username_pass', t('The password cannot be the same as the username.'));
- }
- if (backdrop_strtolower($password) == backdrop_strtolower($email)) {
- form_set_error('email_pass', t('The password cannot be the same as the e-mail.'));
- }
- }
-
- function user_login_block($form) {
- $site_config = config('system.core');
- $credentials = $site_config->get('user_login_method');
-
- $form['#action'] = url(current_path(), array('query' => backdrop_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' => $credentials === USER_LOGIN_EMAIL_ONLY ? t('Email address') : ($credentials === USER_LOGIN_USERNAME_OR_EMAIL ? t('Username or email') : t('Username')),
- '#maxlength' => $credentials === USER_LOGIN_USERNAME_ONLY ? USERNAME_MAX_LENGTH : EMAIL_MAX_LENGTH,
- '#size' => 15,
- '#required' => TRUE,
- '#weight' => 1,
- );
- $form['pass'] = array(
- '#type' => 'password',
- '#title' => t('Password'),
- '#size' => 15,
- '#required' => TRUE,
- '#weight' => 2,
- '#password_toggle' => TRUE,
- );
- $form['actions'] = array(
- '#type' => 'actions',
- '#weight' => 3,
- );
- $form['actions']['submit'] = array(
- '#type' => 'submit',
- '#value' => t('Log in'),
- );
- $items = array();
- if ($site_config->get('user_register') != USER_REGISTER_ADMINISTRATORS_ONLY) {
- $items[] = l(t('Create new account'), 'user/register', array('attributes' => array('title' => t('Create a new user account.'))));
- }
- $items[] = l(t('Reset password'), 'user/password', array('attributes' => array('title' => t('Reset password via one-time login link.'))));
- $form['links'] = array(
- '#theme' => 'item_list',
- '#items' => $items,
- '#weight' => 4,
- );
- return $form;
- }
-
- * Implements hook_block_info().
- */
- function user_block_info() {
- $blocks = array();
-
- $blocks['login'] = array(
- 'info' => t('User login'),
- 'description' => t('The user login form if logged out.'),
- );
-
- return $blocks;
- }
-
- * Implements hook_block_view().
- */
- function user_block_view($delta = '', $settings = array()) {
- 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'] = backdrop_get_form('user_login_block');
- }
- return $block;
- }
- }
-
- * Implements hook_preprocess_block().
- */
- function user_preprocess_block(&$variables) {
- if ($variables['block']->module == 'user') {
- switch ($variables['block']->delta) {
- case 'login':
- $variables['attributes']['role'] = 'form';
- break;
- case 'new':
- $variables['attributes']['role'] = 'complementary';
- break;
- case 'online':
- $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) {
- $name = !empty($account->name) ? $account->name : config_get('system.core', 'anonymous');
- backdrop_alter('user_format_name', $name, $account);
- return $name;
- }
-
- * Determines if the current user is anonymous.
- *
- * @return bool
- * TRUE if the user is anonymous, FALSE if the user is authenticated.
- */
- function user_is_anonymous() {
-
- return !$GLOBALS['user']->uid || !empty($GLOBALS['menu_admin']);
- }
-
- * Determines if the current user is logged in.
- *
- * @return bool
- * TRUE if the user is logged in, FALSE if the user is anonymous.
- */
- function user_is_logged_in() {
- return (bool) $GLOBALS['user']->uid;
- }
-
- * Determines if the current user has access to the user registration page.
- *
- * @return bool
- * TRUE if the user is not already logged in and can register for an account.
- */
- function user_register_access() {
- return user_is_anonymous() && config_get('system.core', 'user_register') !== USER_REGISTER_ADMINISTRATORS_ONLY;
- }
-
- * User view access callback.
- *
- * @param User|AnonymousUser|object $account
- * Can either be a full user object or a $uid.
- *
- * @return bool
- * Whether access is allowed or not.
- */
- function user_view_access($account) {
- if ($account instanceof User) {
- return $account && $account->access('view');
- }
- return FALSE;
- }
-
- * Access callback for user account editing.
- */
- function user_edit_access($account) {
-
- if ($account instanceof User) {
-
- return $account->access('update');
- }
- return FALSE;
- }
-
- * Menu access callback; limit access to account cancellation pages.
- *
- * Limit access to users with the 'cancel account' permission or administrative
- * users, and prevent the anonymous user from cancelling the account.
- */
- function user_cancel_access($account) {
-
- if ($account instanceof User) {
-
- return $account->access('delete');
- }
- return FALSE;
- }
-
- * Implements hook_menu().
- */
- function user_menu() {
- $items['user/autocomplete'] = array(
- 'title' => 'User autocomplete',
- 'page callback' => 'user_autocomplete',
- 'delivery callback' => 'backdrop_json_deliver',
- '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',
- 'page callback' => 'backdrop_get_form',
- 'page arguments' => array('user_login'),
- 'access callback' => 'user_is_anonymous',
- 'type' => MENU_DEFAULT_LOCAL_TASK,
- );
-
- $items['user/register'] = array(
- 'title' => 'Create new account',
- 'page callback' => 'backdrop_get_form',
- 'page arguments' => array('user_register_form'),
- 'access callback' => 'user_register_access',
- 'type' => MENU_LOCAL_TASK,
- );
-
- $items['user/password'] = array(
- 'title' => 'Reset password',
- 'page callback' => 'backdrop_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' => 'user_pass_reset',
- 'page arguments' => array(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/create'] = array(
- 'title' => 'Add user account',
- 'page callback' => 'backdrop_get_form',
- 'page arguments' => array('user_register_form'),
- 'access arguments' => array('administer users'),
- 'type' => MENU_LOCAL_ACTION,
- );
- $items['admin/people/cancel'] = array(
- 'title' => 'Cancel user accounts',
- 'page callback' => 'backdrop_get_form',
- 'page arguments' => array('user_multiple_cancel_confirm'),
- 'access arguments' => array('administer users'),
- 'file' => 'user.admin.inc',
- 'type' => MENU_CALLBACK,
- );
-
-
- $items['admin/config/people'] = array(
- 'title' => 'User accounts',
- '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' => backdrop_get_path('module', 'system'),
- );
- $items['admin/config/people/settings'] = array(
- 'title' => 'Account settings',
- 'description' => 'Configure settings for user accounts.',
- 'page callback' => 'backdrop_get_form',
- 'page arguments' => array('user_admin_settings'),
- 'access arguments' => array('administer account settings'),
- 'file' => 'user.admin.inc',
- );
-
-
- $items['admin/config/people/login'] = array(
- 'title' => 'Login settings',
- 'description' => 'Configure the way visitors may log in and limit login attempts.',
- 'page callback' => 'backdrop_get_form',
- 'page arguments' => array('user_login_settings'),
- 'access arguments' => array('administer account settings'),
- 'file' => 'user.admin.inc',
- );
-
-
- $items['admin/config/people/permissions'] = array(
- 'title' => 'Permissions',
- 'description' => 'Determine access to features by selecting permissions for roles.',
- 'page callback' => 'backdrop_get_form',
- 'page arguments' => array('user_admin_permissions'),
- 'access arguments' => array('administer permissions'),
- 'file' => 'user.admin.inc',
- );
-
-
- $items['admin/config/people/roles'] = array(
- 'title' => 'Roles',
- 'description' => 'List, edit, or add levels of access, or <em>user roles</em>.',
- 'page callback' => 'backdrop_get_form',
- 'page arguments' => array('user_admin_roles'),
- 'access arguments' => array('administer permissions'),
- 'file' => 'user.admin.inc',
- );
- $items['admin/config/people/roles/add'] = array(
- 'title' => 'Add role',
- 'description' => 'Add a new user role.',
- 'page arguments' => array('user_admin_role'),
- 'access arguments' => array('administer permissions'),
- 'type' => MENU_LOCAL_ACTION,
- 'file' => 'user.admin.inc',
- );
- $items['admin/config/people/roles/configure/%user_role'] = array(
- 'title' => 'Configure role',
- 'page arguments' => array('user_admin_role', 5),
- 'access arguments' => array('administer permissions'),
- );
-
- $items['admin/config/people/roles/edit/%user_role'] = array(
- 'page callback' => 'system_redirect_deprecated_page',
- 'page arguments' => array('admin/config/people/roles/configure/%user_role'),
- 'access arguments' => array('administer permissions'),
- 'type' => MENU_CALLBACK,
- );
- $items['admin/config/people/roles/delete/%user_role'] = array(
- 'title' => 'Delete role',
- 'page callback' => 'backdrop_get_form',
- 'page arguments' => array('user_admin_role_delete_confirm', 5),
- 'access callback' => 'user_role_delete_access',
- 'access arguments' => array(5),
- 'file' => 'user.admin.inc',
- );
-
-
- $items['admin/config/people/emails'] = array(
- 'title' => 'Account emails',
- 'description' => 'Configure email templates used for account registration and management.',
- 'page callback' => 'backdrop_get_form',
- 'page arguments' => array('user_settings_email'),
- 'access arguments' => array('administer account settings'),
- 'file' => 'user.admin.inc',
- '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' => 'management',
- );
-
- $items['user/%user/view'] = array(
- 'title' => 'View',
- 'type' => MENU_DEFAULT_LOCAL_TASK,
- 'weight' => -10,
- );
-
- $items['user/%user/cancel'] = array(
- 'title' => 'Cancel account',
- 'page callback' => 'backdrop_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' => 'backdrop_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',
- );
- return $items;
- }
- * Implements hook_menu_alter().
- */
- function user_menu_alter(&$items) {
- if (module_exists('field_ui')) {
-
- $items['admin/config/people/manage'] = $items['admin/config/people/manage/fields'];
- $items['admin/config/people/manage']['type'] = MENU_NORMAL_ITEM;
- $items['admin/config/people/manage']['weight'] = 1;
- $items['admin/config/people/manage']['description'] = 'Configure fields and display of fields on user accounts.';
-
-
- $items['admin/config/people/manage/fields']['type'] = MENU_DEFAULT_LOCAL_TASK;
- }
- }
-
- * Implements hook_admin_menu_output_alter().
- */
- function user_admin_menu_output_alter(&$content) {
-
-
- if (isset($content['menu']['menu']['admin/config']['admin/config/people']['admin/config/people/manage/fields'])) {
- unset($content['menu']['menu']['admin/config']['admin/config/people']['admin/config/people/manage/fields']);
- }
- }
-
- * Implements hook_menu_site_status_alter().
- */
- 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':
-
- backdrop_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') {
-
- backdrop_goto('user');
- }
- if ($path == 'user/register') {
-
- backdrop_goto('user/' . $GLOBALS['user']->uid . '/edit');
- }
- }
- }
-
- * Implements hook_menu_link_alter().
- */
- 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;
- }
- }
-
- * Implements hook_translated_menu_link_alter().
- */
- function user_translated_menu_link_alter(&$link) {
-
- if ($link['link_path'] == 'user' && $link['module'] == 'system' && !$GLOBALS['user']->uid) {
- $link['hidden'] = 1;
- }
- }
-
- * Implements hook_admin_paths().
- */
- function user_admin_paths() {
- $paths = array(
- 'user/*/cancel' => TRUE,
- 'user/*/edit' => TRUE,
- 'user/*/edit/*' => TRUE,
- );
- return $paths;
- }
-
- * Load either a specified or the current user account.
- *
- * @param $uid
- * An optional user ID of the user to load. If not provided, the current
- * user's ID will be used.
- * @return
- * A fully-loaded $user object upon successful user load, FALSE if user
- * cannot be loaded.
- *
- * @see user_load()
- * @todo rethink the naming of this.
- */
- function user_uid_optional_load($uid = NULL) {
- if (!isset($uid)) {
- $uid = $GLOBALS['user']->uid;
- }
- return user_load($uid);
- }
-
- * Returns $arg or the user ID of the current user if $arg is '%' or empty.
- *
- * @todo rethink the naming of this.
- */
- function user_uid_optional_to_arg($arg) {
-
-
-
- return empty($arg) || $arg == '%' ? $GLOBALS['user']->uid : $arg;
- }
-
- * Menu item title callback for the 'user' path.
- *
- * Anonymous users should see "User account", but authenticated users are
- * expected to see "My account".
- */
- function user_menu_title() {
- return user_is_logged_in() ? t('My account') : t('User account');
- }
-
- * Menu item title callback - use the user name.
- */
- function user_page_title($account) {
- return is_object($account) ? user_format_name($account) : '';
- }
-
- * Form builder; the main user login form.
- *
- * @ingroup forms
- */
- function user_login($form, &$form_state) {
- global $user;
-
-
- if ($user->uid) {
- backdrop_goto('user/' . $user->uid);
- }
-
- backdrop_set_title(t('Log in'));
-
-
- $credentials = config_get('system.core', 'user_login_method');
- $form['name'] = array('#type' => 'textfield',
- '#title' => $credentials === USER_LOGIN_EMAIL_ONLY ? t('Email address') : ($credentials === USER_LOGIN_USERNAME_OR_EMAIL ? t('Username or email') : t('Username')),
- '#maxlength' => $credentials === USER_LOGIN_USERNAME_ONLY ? USERNAME_MAX_LENGTH : EMAIL_MAX_LENGTH,
- '#size' => 60,
- '#required' => TRUE,
- '#attributes' => array(
- 'autofocus' => 'autofocus',
- ),
- );
-
- $form['pass'] = array(
- '#type' => 'password',
- '#title' => t('Password'),
- '#required' => TRUE,
- '#password_toggle' => TRUE,
- );
- $form['#validate'] = user_login_default_validators();
- $form['actions'] = array('#type' => 'actions');
- $form['actions']['submit'] = array('#type' => 'submit', '#value' => t('Log in'));
-
- return $form;
- }
-
- * Set up a series for validators which check for blocked users,
- * then authenticate against local database, then return an error if
- * authentication fails. Distributed authentication modules are welcome
- * to use hook_form_alter() to change this series in order to
- * authenticate against their user database instead of the local users
- * table. If a distributed authentication module is successful, it
- * should set $form_state['uid'] to a user ID.
- *
- * We use three validators instead of one since external authentication
- * modules usually only need to alter the second validator.
- *
- * @see user_login_name_validate()
- * @see user_login_authenticate_validate()
- * @see user_login_final_validate()
- * @return array
- * A simple list of validate functions.
- */
- function user_login_default_validators() {
- return array('user_login_name_validate', 'user_login_authenticate_validate', 'user_login_final_validate');
- }
-
- * First phase validation handler for the login form.
- *
- * Check for invalid email addresses and blocked accounts.
- */
- function user_login_name_validate($form, &$form_state) {
- if (isset($form_state['values']['name'])) {
- $name = $form_state['values']['name'];
- $credentials = config_get('system.core', 'user_login_method');
- if ($credentials !== USER_LOGIN_USERNAME_ONLY) {
- if ($account = db_query("SELECT * FROM {users} WHERE mail = :mail", array(':mail' => $name))->fetchObject()) {
- $name = $account->name;
- }
-
- elseif ($credentials === USER_LOGIN_EMAIL_ONLY && !valid_email_address($name)) {
- form_set_error('name', t('The e-mail address %email is not valid.', array('%email' => $form_state['values']['name'])));
- }
- }
-
- if ($name && user_is_blocked($name)) {
- form_set_error('name', t('The account for %name has not been activated or is blocked.', array('%name' => $form_state['values']['name'])));
- }
- }
- }
-
- * Second phase validation handler on the login form.
- *
- * Checks supplied username/password against local users table. If successful,
- * $form_state['uid'] is set to the matching user ID. If an account is found
- * $form_state['account_found'] is set to TRUE, though the password may still
- * fail even if an account is found.
- */
- function user_login_authenticate_validate($form, &$form_state) {
- $password = trim($form_state['values']['pass']);
- $flood_config = config('user.flood');
- if (!empty($form_state['values']['name']) && strlen(trim($password)) > 0) {
-
-
-
-
-
- if (!flood_is_allowed('failed_login_attempt_ip', $flood_config->get('flood_ip_limit'), $flood_config->get('flood_ip_window'))) {
- $form_state['flood_control_triggered'] = 'ip';
- return;
- }
- $account = FALSE;
- $credentials = config_get('system.core', 'user_login_method');
- if (($credentials === USER_LOGIN_USERNAME_OR_EMAIL || $credentials === USER_LOGIN_EMAIL_ONLY) && valid_email_address($form_state['values']['name'])) {
- $account = db_query("SELECT * FROM {users} WHERE mail = :mail AND status = 1", array(':mail' => $form_state['values']['name']))->fetchObject();
- }
- if (!$account && $credentials !== USER_LOGIN_EMAIL_ONLY) {
- $account = db_query("SELECT * FROM {users} WHERE name = :name AND status = 1", array(':name' => $form_state['values']['name']))->fetchObject();
- }
-
- if ($account) {
- $form_state['account_found'] = TRUE;
- if ($flood_config->get('flood_uid_only')) {
-
-
- $identifier = $account->uid;
- }
- else {
-
-
-
- $identifier = $account->uid . '-' . ip_address();
- }
- $form_state['flood_control_user_identifier'] = $identifier;
-
-
-
- if (!flood_is_allowed('failed_login_attempt_user', $flood_config->get('flood_user_limit'), $flood_config->get('flood_user_window'), $identifier)) {
- $form_state['flood_control_triggered'] = 'user';
- return;
- }
-
-
- $form_state['uid'] = user_authenticate($account->name, $password);
- }
- else {
- $form_state['account_found'] = FALSE;
- }
- }
- }
-
- * The final validation handler on the login form.
- *
- * Sets a form error if user has not been authenticated, or if too many
- * logins have been attempted. This validation function should always
- * be the last one.
- */
- function user_login_final_validate($form, &$form_state) {
- $flood_config = config('user.flood');
- if (empty($form_state['uid'])) {
-
- flood_register_event('failed_login_attempt_ip', $flood_config->get('flood_ip_window'));
-
- if (isset($form_state['flood_control_user_identifier'])) {
- flood_register_event('failed_login_attempt_user', $flood_config->get('flood_user_window'), $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($flood_config->get('flood_user_limit'), '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'))));
- }
- 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'))));
- }
- }
- elseif (empty($form_state['account_found'])) {
- $login_method = config_get('system.core', 'user_login_method');
- if ((valid_email_address($form_state['values']['name']) && $login_method === USER_LOGIN_USERNAME_OR_EMAIL) || $login_method === USER_LOGIN_EMAIL_ONLY) {
- form_set_error('name', t('Sorry, no account with that email address found.'));
- }
- else {
- form_set_error('name', t('Sorry, unrecognized username.'));
- }
- watchdog('user', 'The user account or email %name could not be found.', array('%name' => $form_state['values']['name']), WATCHDOG_WARNING);
- }
- else {
- form_set_error('pass', t('Sorry, incorrect password. <a href="@password">Have you forgotten your password?</a>', array('@password' => url('user/password', array('query' => array('name' => $form_state['values']['name']))))));
- watchdog('user', 'Login attempt failed for %user.', array('%user' => $form_state['values']['name']), WATCHDOG_WARNING);
- }
- }
- elseif (isset($form_state['flood_control_user_identifier'])) {
-
-
- flood_clear_event('failed_login_attempt_user', $form_state['flood_control_user_identifier']);
- }
- }
-
- * Try to validate the user's login credentials locally.
- *
- * @param $name
- * User name to authenticate.
- * @param $password
- * A plain-text password, such as trimmed text from form values.
- * @return
- * The user's uid on success, or FALSE on failure to authenticate.
- */
- function user_authenticate($name, $password) {
- $uid = FALSE;
- if (!empty($name) && strlen(trim($password)) > 0) {
- $account = user_load_by_name($name);
- if ($account) {
-
- require_once BACKDROP_ROOT . '/' . settings_get('password_inc', 'core/includes/password.inc');
- if (user_check_password($password, $account)) {
-
- $uid = $account->uid;
-
-
- if (user_needs_new_hash($account)) {
- $account->pass = $password;
- $account->save();
- }
- }
- }
- }
- return $uid;
- }
-
- * Finalize the login process. Must be called when logging in a user.
- *
- * The function records a watchdog message about the new session, saves the
- * login timestamp, calls hook_user_login(), and generates a new session.
- *
- * @param array $edit
- * The array of form values submitted by the user.
- *
- * @see hook_user_login()
- */
- 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();
-
-
-
-
- backdrop_session_regenerate();
-
-
- $entity_info = entity_get_info('user');
- if (isset($entity_info['entity cache']) && $entity_info['entity cache']) {
- cache('entity_user')->delete($user->uid);
- }
-
- user_module_invoke('login', $edit, $user);
- }
-
- * Submit handler for the login form. Load $user object and perform standard login
- * tasks. The user is then redirected to the My Account page. Setting the
- * destination in the query string overrides the redirect.
- */
- function user_login_submit($form, &$form_state) {
- global $user;
- $user = user_load($form_state['uid']);
- $form_state['redirect'] = 'user/' . $user->uid;
-
- user_login_finalize($form_state);
- }
-
- * Generates a unique URL for a user to login and reset their password.
- *
- * @param object $account
- * An object containing the user account, which must contain at least the
- * following properties:
- * - uid: The user ID number.
- * - login: The UNIX timestamp of the user's last login.
- *
- * @return
- * A unique URL that provides a one-time log in for the user, from which
- * they can change their password.
- */
- 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));
- }
-
- * Generates a URL to confirm an account cancellation request.
- *
- * @param object $account
- * The user account object, which must contain at least the following
- * properties:
- * - uid: The user ID number.
- * - pass: The hashed user password string.
- * - login: The UNIX timestamp of the user's last login.
- *
- * @return
- * A unique URL that may be used to confirm the cancellation of the user
- * account.
- *
- * @see user_mail_tokens()
- * @see user_cancel_confirm()
- */
- function user_cancel_url($account) {
- $timestamp = REQUEST_TIME;
- return url("user/$account->uid/cancel/confirm/$timestamp/" . user_pass_rehash($account->pass, $timestamp, $account->login, $account->uid), array('absolute' => TRUE));
- }
-
- * Creates a unique hash value for use in time-dependent per-user URLs.
- *
- * This hash is normally used to build a unique and secure URL that is sent to
- * the user by email for purposes such as resetting the user's password. In
- * order to validate the URL, the same hash can be generated again, from the
- * same information, and compared to the hash value from the URL. The URL
- * normally contains both the time stamp and the numeric user ID. The login
- * timestamp and hashed password are retrieved from the database as necessary.
- * For a usage example, see user_cancel_url() and user_cancel_confirm().
- *
- * @param string $password
- * The hashed user account password value.
- * @param int $timestamp
- * A UNIX timestamp, typically REQUEST_TIME.
- * @param int $login
- * The UNIX timestamp of the user's last login.
- * @param int $uid
- * The user ID of the user account.
- *
- * @return
- * A string that is safe for use in URLs and SQL statements.
- */
- 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 backdrop_random_key();
- }
- }
-
- return backdrop_hmac_base64($timestamp . $login . $uid, backdrop_get_hash_salt() . $password);
- }
-
- * Cancel a user account.
- *
- * Since the user cancellation process needs to be run in a batch, either
- * Form API will invoke it, or batch_process() needs to be invoked after calling
- * this function and should define the path to redirect to.
- *
- * @param $edit
- * An array of submitted form values.
- * @param $uid
- * The user ID of the user account to cancel.
- * @param $method
- * The account cancellation method to use.
- *
- * @see _user_cancel()
- */
- function user_cancel($edit, $uid, $method) {
- global $user;
-
- $account = user_load($uid);
-
- if (!$account) {
- backdrop_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);
-
-
-
- }
-
- * Last batch processing step for cancelling a user account.
- *
- * Since batch and session API require a valid user account, the actual
- * cancellation of a user account needs to happen last.
- *
- * @see user_cancel()
- */
- function _user_cancel($edit, $account, $method) {
- global $user;
-
- switch ($method) {
- case 'user_cancel_block':
- case 'user_cancel_block_unpublish':
- default:
-
- if (!empty($edit['user_cancel_notify'])) {
- _user_mail_notify('status_blocked', $account);
- }
- $account->status = 0;
- $account->save();
- backdrop_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);
- backdrop_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 = backdrop_anonymous_user();
- }
- }
-
- * Finished batch processing callback for cancelling a user account.
- *
- * @see user_cancel()
- */
- function _user_cancel_session_regenerate() {
-
-
- backdrop_session_regenerate();
- }
-
- * Delete a user.
- *
- * @param $uid
- * A user ID.
- */
- function user_delete($uid) {
- user_delete_multiple(array($uid));
- }
-
- * Delete multiple user accounts.
- *
- * @param $uids
- * An array of user IDs.
- *
- * @see hook_user_predelete()
- * @see hook_user_delete()
- */
- 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_predelete', $account);
- module_invoke_all('entity_predelete', $account, 'user');
-
- field_attach_delete('user', $account);
- backdrop_session_destroy_uid($account->uid);
- }
-
- db_delete('users')
- ->condition('uid', $uids, 'IN')
- ->execute();
- db_delete('users_roles')
- ->condition('uid', $uids, 'IN')
- ->execute();
-
-
- module_invoke_all('user_delete', $account);
- module_invoke_all('entity_delete', $account, 'user');
- }
- catch (Exception $e) {
- $transaction->rollback();
- watchdog_exception('user', $e);
- throw $e;
- }
- entity_get_controller('user')->resetCache();
- }
- }
-
- * Page callback wrapper for user_view().
- */
- function user_view_page($account) {
-
-
- return is_object($account) ? user_view($account) : MENU_NOT_FOUND;
- }
-
- * Generate an array for rendering the given user.
- *
- * When viewing a user profile, the $page array contains:
- *
- * - $page['content']['user_picture']:
- * User's rendered picture.
- * - $page['content']['member_for']:
- * Contains the default "Member for" profile data for a user.
- * - $page['content']['#account']:
- * The user account of the profile being viewed.
- *
- * To theme user profiles, copy modules/user/user-profile.tpl.php
- * to your theme directory, and edit it as instructed in that file's comments.
- *
- * @param $account
- * A user object.
- * @param $view_mode
- * (optional) Display mode, e.g. 'full' or 'teaser'. Defaults to 'full'.
- * @param $langcode
- * (optional) A language code to use for rendering. Defaults to the global
- * content language of the current request.
- *
- * @return
- * An array as expected by backdrop_render().
- */
- function user_view($account, $view_mode = 'full', $langcode = NULL) {
- if (!isset($langcode)) {
- $langcode = $GLOBALS['language_content']->langcode;
- }
-
-
- user_build_content($account, $view_mode, $langcode);
-
- $build = $account->content;
-
- unset($account->content);
-
- $build += array(
- '#theme' => 'user_profile__' . $view_mode,
- '#account' => $account,
- '#view_mode' => $view_mode,
- '#language' => $langcode,
- );
-
-
- $type = 'user';
- backdrop_alter(array('user_view', 'entity_view'), $build, $type);
-
- return $build;
- }
-
- * Builds a structured array representing the profile content.
- *
- * @param $account
- * A user object.
- * @param $view_mode
- * (optional) Display mode, e.g. 'full' or 'teaser'. Defaults to 'full'.
- * @param $langcode
- * (optional) A language code to use for rendering. Defaults to the global
- * content language of the current request.
- */
- function user_build_content($account, $view_mode = 'full', $langcode = NULL) {
- if (!isset($langcode)) {
- $langcode = $GLOBALS['language_content']->langcode;
- }
-
-
- $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);
- }
-
- * Implements hook_mail().
- */
- function user_mail($key, &$message, $params) {
- $language = $message['language'];
- $variables = array('user' => $params['account']);
- $message['subject'] .= _user_mail_text($key . '_subject', $language, $variables);
- $message['body'][] = _user_mail_text($key . '_body', $language, $variables);
- }
-
- * Returns a mail string for a variable name.
- *
- * @param string $key
- * The config key that provides the mail text.
- * @param object $language
- * A language object.
- * @param array $variables
- * An array of token keys and values.
- *
- * @return
- * A string value containing the text for the user.mail config key.
- */
- function _user_mail_text($key, $language = NULL, $variables = array()) {
- $langcode = isset($language) ? $language->langcode : NULL;
-
-
-
- return token_replace(config('user.mail')->getTranslated($key, array(), array('langcode' => $langcode)), $variables, array('langcode' => $langcode, 'callback' => 'user_mail_tokens', 'sanitize' => FALSE, 'clear' => TRUE));
- }
-
- * Token callback to add unsafe tokens for user mails.
- *
- * This function is used by the token_replace() call at the end of
- * _user_mail_text() to set up some additional tokens that can be
- * used in email messages generated by user_mail().
- *
- * @param $replacements
- * An associative array variable containing mappings from token names to
- * values (for use with strtr()).
- * @param $data
- * An associative array of token replacement values. If the 'user' element
- * exists, it must contain a user account object with the following
- * properties:
- * - login: The UNIX timestamp of the user's last login.
- * - pass: The hashed account login password.
- * @param $options
- * Unused parameter required by the token_replace() function.
- */
- 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']);
- }
- }
-
-
-
- * Retrieve an array of roles matching specified conditions.
- *
- * @param $members_only
- * Set this to TRUE to exclude the 'anonymous' role.
- * @param $permission
- * A string containing a permission. If set, only roles containing that
- * permission are returned.
- * @param $full_objects
- * TRUE to return complete role objects; FALSE to return role labels.
- *
- * @return
- * An associative array of role objects (or role labels, depending on
- * $full_objects) indexed by role names.
- */
- function user_roles($members_only = FALSE, $permission = NULL, $full_objects = FALSE) {
- $user_roles = &backdrop_static(__FUNCTION__);
-
- if (!isset($user_roles)) {
- $user_roles = array();
-
-
- $names = config_get_names_with_prefix('user.role.');
- foreach ($names as $config_name) {
- $config = config($config_name);
- $role_name = str_replace('user.role.', '', $config_name);
- $role_data = $config->get();
- $role_data += array(
- 'weight' => 0,
- 'permissions' => array(),
- );
- $user_roles[$role_name] = $role_data;
- }
- backdrop_sort($user_roles, array('weight' => SORT_NUMERIC, 'name' => SORT_STRING));
-
-
-
- foreach ($user_roles as $role_name => $role_data) {
- $user_roles[$role_name] = (object) $user_roles[$role_name];
- $user_roles[$role_name]->label = t($role_data['label']);
- }
- }
-
- $return_roles = $user_roles;
- if ($members_only) {
- unset($return_roles['anonymous']);
- }
-
- if ($permission) {
- foreach ($return_roles as $role_name => $role) {
- if (array_search($permission, $role->permissions) === FALSE) {
- unset($return_roles[$role_name]);
- }
- }
- }
-
- if (!$full_objects) {
- foreach ($return_roles as $role_name => $role) {
- $return_roles[$role_name] = $role->label;
- }
- }
-
- return $return_roles;
- }
-
- * Load a user role.
- *
- * @param string $role_name
- * The role name to be loaded.
- *
- * @return stdClass|FALSE
- * A fully-loaded role object if a role with the given name exists, or FALSE
- * otherwise.
- */
- function user_role_load($role_name) {
- $roles = user_roles(FALSE, NULL, TRUE);
- return isset($roles[$role_name]) ? $roles[$role_name] : FALSE;
- }
-
- * Legacy wrapper function preserved for backwards-compatibility. This function
- * is no longer used by Backdrop core, since all roles are loaded by name now.
- * See https://api.backdropcms.org/change-records/converted-user-roles-cmi
- *
- * Do not call this function; use user_role_load() instead.
- *
- * @param $role_name
- * A string representing the role name.
- *
- * @return
- * A fully-loaded role object if a role with the given name exists, or FALSE
- * otherwise.
- *
- * @see user_role_load()
- *
- * @deprecated since 1.0.0
- */
- function user_role_load_by_name($role_name) {
- watchdog_deprecated_function('user', __FUNCTION__, t('Change record:') . ' ' . l(t('Converted User roles to CMI'), 'https://api.backdropcms.org/change-records/converted-user-roles-cmi', array('attributes' => array('target' => '_blank'))));
- user_role_load($role_name);
- }
-
- * Save a user role to the database.
- *
- * @param $role
- * A role object to modify or add.
- * @return
- * Status constant indicating if role was created or updated.
- * Failure to write the user role record will return FALSE. Otherwise.
- * SAVED_NEW or SAVED_UPDATED is returned depending on the operation
- * performed.
- */
- function user_role_save($role) {
-
- $role->name = trim($role->name);
- $role->label = trim($role->label);
-
- if (!isset($role->weight)) {
-
- $weight = 0;
- foreach (user_roles(FALSE, NULL, TRUE) as $existing_role) {
- $weight = max($existing_role->weight, $weight);
- }
- $role->weight = $weight + 1;
- }
-
-
- module_invoke_all('user_role_presave', $role);
-
- $config = config('user.role.' . $role->name);
- $config->set('name', $role->name);
- $config->set('label', $role->label);
- $config->set('weight', $role->weight);
- if (isset($role->permissions)) {
- $config->set('permissions', $role->permissions);
- }
- $is_new = $config->isNew();
- $config->save();
- if ($is_new) {
- module_invoke_all('user_role_insert', $role);
- $status = SAVED_NEW;
- }
- else {
- module_invoke_all('user_role_update', $role);
- $status = SAVED_UPDATED;
- }
-
-
- backdrop_static_reset('user_roles');
- backdrop_static_reset('user_access');
-
- return $status;
- }
-
- * Delete a user role from database.
- *
- * @param string $role_name
- * The name of the role to be deleted.
- */
- function user_role_delete($role_name) {
- $role = user_role_load($role_name);
-
-
-
- $system_config = config('system.core');
- if ($role_name == $system_config->get('user_admin_role')) {
- $system_config->set('user_admin_role', 0);
- $system_config->save();
- }
-
- $user_config = config('user.role.' . $role_name);
- $user_config->delete();
-
-
- db_delete('users_roles')
- ->condition('role', $role_name)
- ->execute();
-
- module_invoke_all('user_role_delete', $role);
-
-
- backdrop_static_reset('user_roles');
- backdrop_static_reset('user_access');
- }
-
- * Menu access callback for deleting a user.
- */
- function user_role_delete_access($role) {
-
- if ($role->name == BACKDROP_ANONYMOUS_ROLE || $role->name == BACKDROP_AUTHENTICATED_ROLE) {
- return FALSE;
- }
-
- return user_access('administer permissions');
- }
-
- * Determine the modules that permissions belong to.
- *
- * @return
- * An associative array in the format $permission => $module.
- */
- 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;
- }
-
- * Change permissions for a user role.
- *
- * This function may be used to grant and revoke multiple permissions at once.
- * For example, when a form exposes checkboxes to configure permissions for a
- * role, the form submit handler may directly pass the submitted values for the
- * checkboxes form element to this function.
- *
- * @param string $role_name
- * The name of a user role to alter.
- * @param array $permissions
- * An associative array, where the key holds the permission name and the value
- * determines whether to grant or revoke that permission. Any value that
- * evaluates to TRUE will cause the permission to be granted. Any value that
- * evaluates to FALSE will cause the permission to be revoked.
- * @code
- * array(
- * 'administer nodes' => 0, // Revoke 'administer nodes'
- * 'administer blocks' => FALSE, // Revoke 'administer blocks'
- * 'access user profiles' => 1, // Grant 'access user profiles'
- * 'access content' => TRUE, // Grant 'access content'
- * 'access comments' => 'access comments', // Grant 'access comments'
- * )
- * @endcode
- * Existing permissions are not changed, unless specified in $permissions.
- *
- * @see user_role_grant_permissions()
- * @see user_role_revoke_permissions()
- */
- function user_role_change_permissions($role_name, array $permissions = array()) {
-
- $grant = array_filter($permissions);
- if (!empty($grant)) {
- user_role_grant_permissions($role_name, array_keys($grant));
- }
-
- $revoke = array_diff_assoc($permissions, $grant);
- if (!empty($revoke)) {
- user_role_revoke_permissions($role_name, array_keys($revoke));
- }
- }
-
- * Grant permissions to a user role.
- *
- * @param string $role_name
- * The name of a user role to alter.
- * @param array $permissions
- * A list of permission names to grant.
- *
- * @see user_role_change_permissions()
- * @see user_role_revoke_permissions()
- */
- function user_role_grant_permissions($role_name, array $permissions = array()) {
- $user_role = user_role_load($role_name);
- $user_role->permissions = array_values(array_unique(array_merge($user_role->permissions, $permissions)));
- user_role_save($user_role);
- }
-
- * Revoke permissions from a user role.
- *
- * @param string $role_name
- * The name of a user role to alter.
- * @param array $permissions
- * A list of permission names to revoke.
- *
- * @see user_role_change_permissions()
- * @see user_role_grant_permissions()
- */
- function user_role_revoke_permissions($role_name, array $permissions = array()) {
-
- $user_role = user_role_load($role_name);
- $user_role->permissions = array_values(array_diff($user_role->permissions, $permissions));
- user_role_save($user_role);
- }
-
- * List user administration filters that can be applied.
- */
- function user_filters() {
-
- $filters = array();
- $roles = user_roles(TRUE);
- unset($roles[BACKDROP_AUTHENTICATED_ROLE]);
- if (count($roles)) {
- $filters['role'] = array(
- 'title' => t('role'),
- 'field' => 'ur.role',
- '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;
- }
-
- * Extends a query object for user administration filters based on session.
- *
- * @param $query
- * Query object that should be filtered.
- */
- 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 = entity_create('user', array());
- $account->uid = 'user_filter';
- $account->roles = array(BACKDROP_AUTHENTICATED_ROLE);
- if (user_access($value, $account)) {
- continue;
- }
- $role_list = array();
- $user_roles = user_roles(FALSE, NULL, TRUE);
- foreach ($user_roles as $user_role) {
- if (in_array($value, $user_role->permissions)) {
- $role_list[] = $user_role->name;
- }
- }
- $users_roles_alias = $query->join('users_roles', 'ur', '%alias.uid = u.uid');
- $query->condition($users_roles_alias . '.role', $role_list);
- }
- elseif ($key == 'role') {
- $users_roles_alias = $query->join('users_roles', 'ur', '%alias.uid = u.uid');
- $query->condition($users_roles_alias . '.role' , $value);
- }
- else {
- $query->condition($filters[$key]['field'], $value);
- }
- }
- }
-
- * Implements hook_comment_view().
- */
- function user_comment_view($comment) {
- if (config_get('system.core', 'user_signatures') && !empty($comment->signature)) {
-
-
-
-
- $comment->signature = check_markup($comment->signature, $comment->signature_format, '', TRUE);
- }
- else {
- $comment->signature = '';
- }
- }
-
- * Get the language object preferred by the user. This user preference can
- * be set on the user account editing page, and is only available if there
- * are more than one languages enabled on the site. If the user did not
- * choose a preferred language, or is the anonymous user, the $default
- * value, or if it is not set, the site default language will be returned.
- *
- * @param $account
- * User account to look up language for.
- * @param $default
- * Optional default language object to return if the account
- * has no valid language.
- */
- 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();
- }
- }
-
- * Conditionally create and send a notification email when a certain
- * operation happens on the given user account.
- *
- * @see user_mail_tokens()
- * @see backdrop_mail()
- *
- * @param $op
- * The operation being performed on the account. Possible values:
- * - 'register_admin_created': Welcome message for user created by the admin.
- * - 'register_no_approval_required': Welcome message when user
- * self-registers.
- * - 'register_pending_approval': Welcome message, user pending admin
- * approval.
- * - 'password_reset': Password recovery request.
- * - 'status_activated': Account activated.
- * - 'status_blocked': Account blocked.
- * - 'cancel_confirm': Account cancellation request.
- * - 'status_canceled': Account canceled.
- *
- * @param $account
- * The user object of the account being notified. Must contain at
- * least the fields 'uid', 'name', and 'mail'.
- * @param $language
- * Optional language to use for the notification, overriding account language.
- *
- * @return
- * The return value from backdrop_mail_system()->mail(), if ends up being
- * called.
- */
- function _user_mail_notify($op, $account, $language = NULL) {
-
-
-
- $default_notify = ($op != 'status_canceled' && $op != 'status_blocked');
- $config = config('system.core');
- $notify = $config->get('user_mail_' . $op . '_notify');
- $notify = isset($notify) ? $notify : $default_notify;
- if ($notify) {
- $params['account'] = $account;
- $language = $language ? $language : user_preferred_language($account);
- $mail = backdrop_mail('user', $op, $account->mail, $language, $params);
- if ($op == 'register_pending_approval') {
-
-
- $site_mail = $config->get('site_mail');
- if (empty($site_mail)) {
- $site_mail = ini_get('sendmail_from');
- }
- backdrop_mail('user', 'register_pending_approval_admin', $site_mail, language_default(), $params);
-
- }
- }
- return empty($mail) ? NULL : $mail['result'];
- }
-
- * Form element process handler for client-side password hide/show and strength.
- *
- * @param array $element
- * The form element to process.
- * @param array $form_state
- * The $form_state array of the form this element belongs to.
- */
- function user_form_process_password($element, $form_state = array()) {
- global $user;
- $config = config('system.core');
-
- if ($element['#password_strength']) {
- if (isset($form_state['user']) && is_a($form_state['user'], 'User')) {
-
- $username = $form_state['user']->name;
- $email = $form_state['user']->mail;
- }
- else {
-
-
- $username = (isset($user->name) ? $user->name : '');
- $email = (isset($user->mail) ? $user->mail : '');
- }
- $strength_settings = array(
- 'scores' => array(
- 'weak' => USER_PASSWORD_STRENGTH_WEAK,
- 'fair' => USER_PASSWORD_STRENGTH_FAIR,
- 'good' => USER_PASSWORD_STRENGTH_GOOD,
- 'strong' => USER_PASSWORD_STRENGTH_STRONG,
- ),
- 'labels' => array(
- 'strengthTitle' => t('Password strength: '),
- 'weak' => t('weak'),
- 'fair' => t('fair'),
- 'good' => t('good'),
- 'strong' => t('excellent'),
- ),
- 'data' => array(
- 'username' => $username,
- 'email' => $email,
- ),
- 'config' => array(
- 'strengthModifier' => USER_PASSWORD_STRENGTH_MODIFIER,
- ),
- );
-
- $element['#attributes']['data-password-strength'] = backdrop_json_encode($strength_settings, FALSE);
- }
-
- if ($element['#password_toggle']) {
- $toggle_settings = array(
- 'toggleShowTitle' => t('Show password'),
- 'toggleHideTitle' => t('Hide password'),
- 'toggleDefault' => $element['#password_shown'] ? 'show' : 'hide',
- );
-
- $element['#attributes']['data-password-toggle'] = backdrop_json_encode($toggle_settings, FALSE);
- }
-
- if ($element['#password_strength'] || $element['#password_toggle']) {
- $element['#attached']['js'][] = backdrop_get_path('module', 'user') . '/js/user.js';
- }
- return $element;
- }
-
- * Form element process handler for client-side password validation.
- *
- * This #process handler is automatically invoked for 'password_confirm' form
- * elements to add the JavaScript and string translations for dynamic password
- * validation.
- *
- * @see system_element_info()
- */
- function user_form_process_password_confirm($element) {
- $confirm_settings = array(
- 'confirmTitle' => t('Passwords match: '),
- 'confirmSuccess' => t('yes'),
- 'confirmFailure' => t('no'),
- );
-
- $element['#attached']['js'][] = backdrop_get_path('module', 'user') . '/js/user.js';
- $element['pass2']['#attributes']['data-password-confirm'] = backdrop_json_encode($confirm_settings, FALSE);
-
- return $element;
- }
-
- * Implements hook_node_load().
- */
- 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;
- }
- }
-
- * Implements hook_image_style_delete().
- */
- function user_image_style_delete($style) {
-
-
- user_image_style_save($style);
- }
-
- * Implements hook_image_style_save().
- */
- function user_image_style_save($style) {
-
- if (isset($style['old_name']) && $style['old_name'] == config_get('system.core', 'user_picture_style')) {
- config_set('system.core', 'user_picture_style', $style['name']);
- }
- }
-
- * Implements hook_action_info().
- */
- function user_action_info() {
- $actions['user_block_user_action'] = array(
- 'label' => t('Block user(s)'),
- 'type' => 'user',
- 'callback' => 'user_block_user_action',
- 'file' => 'user.actions.inc',
- 'weight' => -2,
- );
- $actions['user_unblock_user_action'] = array(
- 'label' => t('Unblock user(s)'),
- 'type' => 'user',
- 'callback' => 'user_unblock_user_action',
- 'file' => 'user.actions.inc',
- 'weight' => -1,
- );
- $actions['user_cancel_user_action'] = array(
- 'label' => t('Cancel user account(s)'),
- 'type' => 'user',
- 'callback' => 'user_cancel_user_action',
- 'file' => 'user.actions.inc',
- 'weight' => 10,
- );
-
- $roles = user_roles(TRUE, NULL, TRUE);
- $index = 0;
- foreach ($roles as $role_name => $role) {
- if ($role_name === BACKDROP_AUTHENTICATED_ROLE) {
- continue;
- }
- if (!user_access('assign roles') && !user_access('administer permissions')) {
- continue;
- }
- $index++;
-
- $actions['user_add_role_' . $role_name] = array(
- 'label' => t('Add role "@label"', array('@label' => $role->label)),
- 'type' => 'user',
- 'callback' => 'user_add_role_action',
- 'file' => 'user.actions.inc',
- 'weight' => 120 + $index,
- 'role_name' => $role_name,
- );
- $actions['user_remove_role_' . $role_name] = array(
- 'label' => t('Remove role "@label"', array('@label' => $role->label)),
- 'type' => 'user',
- 'callback' => 'user_remove_role_action',
- 'file' => 'user.actions.inc',
- 'weight' => 150 + $index,
- 'role_name' => $role_name,
- );
- }
-
- return $actions;
- }
-
- * Implements hook_form_FORM_ID_alter().
- *
- * Add a checkbox for the 'user_register_form' instance settings on the 'Edit
- * field instance' form.
- */
- 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'] + .1,
-
- '#states' => array(
- 'enabled' => array('input[name="instance[required]"]' => array('checked' => FALSE)),
- ),
-
-
-
- '#attached' => array(
- 'js' => array(backdrop_get_path('module', 'user') . '/js/user.js'),
- ),
- );
-
- array_unshift($form['#submit'], 'user_form_field_ui_field_edit_form_submit');
- }
- }
-
- * Additional submit handler for the 'Edit field instance' form.
- *
- * Make sure the 'user_register_form' setting is set for required fields.
- */
- 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);
- }
- }
-
- * Form builder; the user registration form.
- *
- * @ingroup forms
- * @see user_account_form()
- * @see user_account_form_validate()
- * @see user_register_submit()
- */
- function user_register_form($form, &$form_state) {
- global $user;
-
- backdrop_set_title(t('Create new account'));
-
- $admin = user_access('administer users');
-
-
-
-
- $form['administer_users'] = array(
- '#type' => 'value',
- '#value' => $admin,
- );
-
-
- if (!$admin && $user->uid) {
- backdrop_goto('user/' . $user->uid);
- }
-
- $form['#user'] = entity_create('user', array());
-
- $form['#attached']['library'][] = array('system', 'jquery.cookie');
- $form['#attributes']['class'][] = 'user-info-from-cookie';
-
-
- user_account_form($form, $form_state);
-
-
-
- field_attach_form('user', $form['#user'], $form, $form_state);
- 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'];
- }
-
-
- if (isset($_GET['destination'])) {
- $path = $_GET['destination'];
- }
- elseif (isset($_SERVER['HTTP_REFERER'])) {
- $path = $_SERVER['HTTP_REFERER'];
- }
- elseif (user_access('administer users')) {
- $path = 'admin/people';
- }
- else {
- $path = '<front>';
- }
- $options = backdrop_parse_url($path);
- $options['attributes']['class'][] = 'form-cancel';
-
- $form['actions'] = array('#type' => 'actions');
- $form['actions']['submit'] = array(
- '#type' => 'submit',
- '#value' => t('Create new account'),
- );
- $form['actions']['cancel'] = array(
- '#type' => 'link',
- '#title' => t('Cancel'),
- '#href' => $options['path'],
- '#options' => $options,
- '#weight' => 1,
- );
-
- $form['#validate'][] = 'user_register_validate';
-
- $form['#submit'][] = 'user_register_submit';
-
- return $form;
- }
-
- * Validation function for the user registration form.
- */
- function user_register_validate($form, &$form_state) {
- entity_form_field_validate('user', $form, $form_state);
- }
-
- * Submit handler for the user registration form.
- *
- * This function is shared by the installation form and the normal registration form,
- * which is why it can't be in the user.pages.inc file.
- *
- * @see user_register_form()
- */
- function user_register_submit($form, &$form_state) {
- $user_email_verification = config_get('system.core', 'user_email_verification');
- $admin = $form_state['values']['administer_users'];
-
- if (!$user_email_verification || $admin) {
- $pass = $form_state['values']['pass'];
- }
- else {
- $pass = user_password();
- }
- $notify = !empty($form_state['values']['notify']);
-
-
- form_state_values_clean($form_state);
-
-
- if (isset($form_state['values']['roles'])) {
- $form_state['values']['roles'] = array_keys(array_filter($form_state['values']['roles']));
- }
-
- $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);
- $status = $account->save();
-
-
- if ($status != SAVED_NEW) {
- backdrop_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 = $account->uri();
- if ($admin && !$notify) {
- backdrop_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 && !$user_email_verification && $account->status) {
- _user_mail_notify('register_no_approval_required', $account);
- $form_state['uid'] = $account->uid;
- user_login_submit(array(), $form_state);
- backdrop_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) {
- backdrop_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 {
- backdrop_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);
- backdrop_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'] = '';
- }
- }
-
- * Implements hook_modules_installed().
- */
- function user_modules_installed($modules) {
-
- $role_name = config_get('system.core', 'user_admin_role');
- $role = user_role_load($role_name);
- if ($role) {
- $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($role_name, $permissions);
- }
- }
- }
-
- * Implements hook_modules_uninstalled().
- */
- function user_modules_uninstalled($modules) {
-
- $removed_permissions = array();
- foreach ($modules as $module_name) {
- if ($module_permissions = module_invoke($module_name, 'permission')) {
- $removed_permissions = array_merge($removed_permissions, array_keys($module_permissions));
- }
- }
-
- $roles = user_roles();
- foreach ($roles as $role_name => $role_label) {
- user_role_revoke_permissions($role_name, $removed_permissions);
- }
- }
-
- * Helper function to rewrite the destination to avoid redirecting to login page after login.
- *
- * Third-party authentication modules may use this function to determine the
- * proper destination after a user has been properly logged in.
- */
- function user_login_destination() {
- global $user;
- $destination = backdrop_get_destination();
- if ($destination['destination'] == 'user/login') {
- $destination['destination'] = 'user/' . $user->uid;
- }
- return $destination;
- }
-
- * Saves visitor information as a cookie so it can be reused.
- *
- * @param $values
- * An array of key/value pairs to be saved into a cookie.
- */
- function user_cookie_save(array $values) {
- foreach ($values as $field => $value) {
-
- setrawcookie('Backdrop.visitor.' . $field, rawurlencode($value), REQUEST_TIME + 31536000, '/');
- }
- }
-
- * Delete a visitor information cookie.
- *
- * @param $cookie_name
- * A cookie name such as 'homepage'.
- */
- function user_cookie_delete($cookie_name) {
- setrawcookie('Backdrop.visitor.' . $cookie_name, '', REQUEST_TIME - 3600, '/');
- }
-
- * Implements hook_autoload_info().
- */
- function user_autoload_info() {
- return array(
- 'User' => 'user.entity.inc',
- 'UserStorageController' => 'user.entity.inc',
-
-
- 'views_handler_argument_user_uid' => 'views/views_handler_argument_user_uid.inc',
- 'views_handler_argument_users_roles' => 'views/views_handler_argument_users_roles.inc',
- 'views_handler_field_user' => 'views/views_handler_field_user.inc',
- 'views_handler_field_user_language' => 'views/views_handler_field_user_language.inc',
- 'views_handler_field_user_link' => 'views/views_handler_field_user_link.inc',
- 'views_handler_field_user_link_cancel' => 'views/views_handler_field_user_link_cancel.inc',
- 'views_handler_field_user_link_edit' => 'views/views_handler_field_user_link_edit.inc',
- 'views_handler_field_user_mail' => 'views/views_handler_field_user_mail.inc',
- 'views_handler_field_user_name' => 'views/views_handler_field_user_name.inc',
- 'views_handler_field_user_permissions' => 'views/views_handler_field_user_permissions.inc',
- 'views_handler_field_user_picture' => 'views/views_handler_field_user_picture.inc',
- 'views_handler_field_user_roles' => 'views/views_handler_field_user_roles.inc',
- 'views_handler_filter_user_current' => 'views/views_handler_filter_user_current.inc',
- 'views_handler_filter_user_name' => 'views/views_handler_filter_user_name.inc',
- 'views_handler_filter_user_permissions' => 'views/views_handler_filter_user_permissions.inc',
- 'views_handler_filter_user_roles' => 'views/views_handler_filter_user_roles.inc',
- 'views_plugin_argument_default_current_user' => 'views/views_plugin_argument_default_current_user.inc',
- 'views_plugin_argument_default_user' => 'views/views_plugin_argument_default_user.inc',
- 'views_plugin_argument_validate_user' => 'views/views_plugin_argument_validate_user.inc',
- 'views_plugin_row_user_view' => 'views/views_plugin_row_user_view.inc',
- );
- }
-
- * Implements hook_file_download_access().
- */
- function user_file_download_access($field, $entity_type, $entity) {
- if ($entity_type == 'user') {
- return user_view_access($entity);
- }
- }