Skip to content
user.module 112 KiB
Newer Older
Dries Buytaert's avatar
 
Dries Buytaert committed
<?php

use Drupal\Core\Database\Query\SelectInterface;
use Drupal\entity\EntityInterface;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
Dries Buytaert's avatar
 
Dries Buytaert committed
/**
 * @file
 * Enables the user registration and login system.
 */

/**
 * Maximum length of username text field.
 */

/**
 * Maximum length of user e-mail text field.
 */
/**
 * Only administrators can create user accounts.
 */
const USER_REGISTER_ADMINISTRATORS_ONLY = 'admin_only';
const USER_REGISTER_VISITORS = 'visitors';

/**
 * Visitors can create accounts, but they don't become active without
 * administrative approval.
 */
const USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL = 'visitors_admin_approval';
/**
 * Implement hook_help().
 */
function user_help($path, $arg) {
  global $user;

  switch ($path) {
    case 'admin/help#user':
      $output = '';
      $output .= '<h3>' . t('About') . '</h3>';
      $output .= '<p>' . t('The User module allows users to register, log in, and log out. It also allows users with proper permissions to manage user roles (used to classify users) and permissions associated with those roles. For more information, see the online handbook entry for <a href="@user">User module</a>.', array('@user' => 'http://drupal.org/documentation/modules/user')) . '</p>';
      $output .= '<h3>' . t('Uses') . '</h3>';
      $output .= '<dl>';
      $output .= '<dt>' . t('Creating and managing users') . '</dt>';
      $output .= '<dd>' . t('The User module allows users with the appropriate <a href="@permissions">permissions</a> to create user accounts through the <a href="@people">People administration page</a>, where they can also assign users to one or more roles, and block or delete user accounts. If allowed, users without accounts (anonymous users) can create their own accounts on the <a href="@register">Create new account</a> page.', array('@permissions' => url('admin/people/permissions', array('fragment' => 'module-user')), '@people' => url('admin/people'), '@register' => url('user/register'))) . '</dd>';
      $output .= '<dt>' . t('User roles and permissions') . '</dt>';
      $output .= '<dd>' . t('<em>Roles</em> are used to group and classify users; each user can be assigned one or more roles. By default there are two roles: <em>anonymous user</em> (users that are not logged in) and <em>authenticated user</em> (users that are registered and logged in). Depending on choices you made when you installed Drupal, the installation process may have defined more roles, and you can create additional custom roles on the <a href="@roles">Roles page</a>. After creating roles, you can set permissions for each role on the <a href="@permissions_user">Permissions page</a>. Granting a permission allows users who have been assigned a particular role to perform an action on the site, such as viewing a particular type of content, editing or creating content, administering settings for a particular module, or using a particular function of the site (such as search).', array('@permissions_user' => url('admin/people/permissions'), '@roles' => url('admin/people/roles'))) . '</dd>';
      $output .= '<dt>' . t('Account settings') . '</dt>';
      $output .= '<dd>' . t('The <a href="@accounts">Account settings page</a> allows you to manage settings for the displayed name of the anonymous user role, personal contact forms, user registration, and account cancellation. On this page you can also manage settings for account personalization (including signatures and user pictures), and adapt the text for the e-mail messages that are sent automatically during the user registration process.', array('@accounts'  => url('admin/config/people/accounts'))) . '</dd>';
      $output .= '</dl>';
      return $output;
    case 'admin/people/create':
      return '<p>' . t("This web page allows administrators to register new users. Users' e-mail addresses and usernames must be unique.") . '</p>';
      return '<p>' . t('Permissions let you control what users can do and see on your site. You can define a specific set of permissions for each role. (See the <a href="@role">Roles</a> page to create a role). Two important roles to consider are Authenticated Users and Administrators. Any permissions granted to the Authenticated Users role will be given to any user who can log into your site. You can make any role the Administrator role for the site, meaning this will be granted all new permissions automatically. You can do this on the <a href="@settings">User Settings</a> page. You should be careful to ensure that only trusted users are given this access and level of control of your site.', array('@role' => url('admin/people/roles'), '@settings' => url('admin/config/people/accounts'))) . '</p>';
    case 'admin/people/roles':
      $output = '<p>' . t('Roles allow you to fine tune the security and administration of Drupal. A role defines a group of users that have certain privileges as defined on the <a href="@permissions">permissions page</a>. Examples of roles include: anonymous user, authenticated user, moderator, administrator and so on. In this area you will define the names and order of the roles on your site. It is recommended to order your roles from least permissive (anonymous user) to most permissive (administrator). To delete a role choose "edit role".', array('@permissions' => url('admin/people/permissions'))) . '</p>';
      $output .= '<p>' . t('Drupal has three special user roles:') . '</p>';
      $output .= '<ul>';
      $output .= '<li>' . t("Anonymous user: this role is used for users that don't have a user account or that are not authenticated.") . '</li>';
      $output .= '<li>' . t('Authenticated user: this role is automatically granted to all logged in users.') . '</li>';
      $output .= '<li>' . t('Administrator role: this role is automatically granted all new permissions when you install a new module. Configure which role is the administrator role on the <a href="@account_settings">Account settings page</a>.', array('@account_settings' => url('admin/config/people/accounts'))) . '</li>';
      $output .= '</ul>';
      return $output;
    case 'admin/config/people/accounts/fields':
      return '<p>' . t('This form lets administrators add, edit, and arrange fields for storing user data.') . '</p>';
    case 'admin/config/people/accounts/display':
      return '<p>' . t('This form lets administrators configure how fields should be displayed when rendering a user profile page.') . '</p>';
    case 'admin/people/search':
      return '<p>' . t('Enter a simple pattern ("*" may be used as a wildcard match) to search for a username or e-mail address. For example, one may search for "br" and Drupal might return "brian", "brad", and "brenda@example.com".') . '</p>';
  }
}
 * Invokes a user hook in every module.
 * We cannot use module_invoke() for this, because the arguments need to
 * be passed by reference.
 *   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;
Dries Buytaert's avatar
 
Dries Buytaert committed
  }
}

 */
function user_theme() {
  return array(
    'user_picture' => array(
      'variables' => array('account' => NULL),
      'variables' => array('users' => NULL, 'title' => NULL),
    'user_permission_description' => array(
      'variables' => array('permission_item' => NULL, 'hide' => NULL),
      'file' => 'user.admin.inc',
    ),
      'variables' => array('signature' => NULL),
    'username' => array(
      'variables' => array('account' => NULL),
    ),
Dries Buytaert's avatar
 
Dries Buytaert committed
/**
Dries Buytaert's avatar
 
Dries Buytaert committed
 */
Dries Buytaert's avatar
 
Dries Buytaert committed
    'user' => array(
      'controller class' => 'Drupal\user\UserStorageController',
      'form controller class' => array(
        'profile' => 'Drupal\user\ProfileFormController',
        'register' => 'Drupal\user\RegisterFormController',
      ),
      'entity class' => 'Drupal\user\User',
      ),
      'bundles' => array(
        'user' => array(
          'label' => t('User'),
          'admin' => array(
            'path' => 'admin/config/people/accounts',
            'access arguments' => array('administer users'),
          ),
        ),
      ),
      'view modes' => array(
        'full' => array(
          'label' => t('User account'),
Dries Buytaert's avatar
 
Dries Buytaert committed
    ),
  );
}

function user_uri($user) {
  return array(
    'path' => 'user/' . $user->uid,
  );
 * This label callback has langcode for security reasons. The username is the
 * visual identifier for a user and needs to be consistent in all languages.
 *
 * @param $entity_type
 *   The entity type.
 * @param $entity
 *   The entity object.
 *
 * @return
 *   The name of the user.
 *
 * @see user_format_name()
 */
function user_label($entity_type, $entity) {
  return user_format_name($entity);
/**
 * Implements hook_field_info_alter().
 */
function user_field_info_alter(&$info) {
  // Add the 'user_register_form' instance setting to all field types.
  foreach ($info as $field_type => &$field_type_info) {
    $field_type_info += array('instance_settings' => array());
    $field_type_info['instance_settings'] += array(
function user_field_extra_fields() {
  $return['user']['user'] = array(
        'label' => t('User name and password'),
        'description' => t('User module account form elements.'),
        'description' => t('User module timezone form element.'),
        'weight' => 6,
      ),
      'member_for' => array(
        'label' => t('Member for'),
        'description' => t('User module \'member for\' view element.'),
/**
 * Fetches a user object based on an external authentication source.
 *
 * @param string $authname
 *   The external authentication username.
 *
 * @return
 *   A fully-loaded user object if the user is found or FALSE if not found.
 */
Dries Buytaert's avatar
 
Dries Buytaert committed
function user_external_load($authname) {
  $uid = db_query("SELECT uid FROM {authmap} WHERE authname = :authname", array(':authname' => $authname))->fetchField();
Dries Buytaert's avatar
 
Dries Buytaert committed

Dries Buytaert's avatar
 
Dries Buytaert committed
  }
  else {
Dries Buytaert's avatar
 
Dries Buytaert committed
  }
}

 * Loads 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 array $uids
 *   (optional) An array of entity IDs. If omitted, all entities are loaded.
 *   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.
 * @see user_load()
 * @see user_load_by_mail()
 * @see user_load_by_name()
 * @see Drupal\entity\EntityFieldQuery
function user_load_multiple(array $uids = NULL, $reset = FALSE) {
  return entity_load_multiple('user', $uids, $reset);
 * Loads a user object.
 *
 * Drupal has a global $user object, which represents the currently-logged-in
 * user. So to avoid confusion and to avoid clobbering the global $user object,
 * it is a good idea to assign the result of this function to a different local
 * variable, generally $account. If you actually do want to act as the user you
 * are loading, it is essential to call drupal_save_session(FALSE); first.
 * See
 * @link http://drupal.org/node/218104 Safely impersonating another user @endlink
 * for more information.
 *   Integer specifying the user ID to load.
 *   TRUE to reset the internal cache and load from the database; FALSE
 *   (default) to load from the internal cache, if set.
 *
 *   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) {
  return entity_load('user', $uid, $reset);
 * Fetches a user object by email address.
 *   A fully-loaded $user object upon successful user load or FALSE if user
 *   cannot be loaded.
 *
 * @see user_load_multiple()
 */
function user_load_by_mail($mail) {
  $users = entity_load_multiple_by_properties('user', array('mail' => $mail));
 * Fetches a user object by account name.
 *   A fully-loaded $user object upon successful user load or FALSE if user
 *   cannot be loaded.
 *
 * @see user_load_multiple()
 */
function user_load_by_name($name) {
  $users = entity_load_multiple_by_properties('user', array('name' => $name));
Dries Buytaert's avatar
 
Dries Buytaert committed
}

/**
 * Verify the syntax of the given name.
 */
Dries Buytaert's avatar
 
Dries Buytaert committed
function user_validate_name($name) {
  if (!$name) {
    return t('You must enter a username.');
  }
  if (substr($name, 0, 1) == ' ') {
    return t('The username cannot begin with a space.');
  }
  if (substr($name, -1) == ' ') {
    return t('The username cannot end with a space.');
  }
  if (strpos($name, '  ') !== FALSE) {
    return t('The username cannot contain multiple spaces in a row.');
  }
  if (preg_match('/[^\x{80}-\x{F7} a-z0-9@_.\'-]/i', $name)) {
    return t('The username contains an illegal character.');
  }
  if (preg_match('/[\x{80}-\x{A0}' .         // Non-printable ISO-8859-1 + NBSP
                  '\x{AD}' .                // Soft-hyphen
                  '\x{2000}-\x{200F}' .     // Various space characters
                  '\x{2028}-\x{202F}' .     // Bidirectional text overrides
                  '\x{205F}-\x{206F}' .     // Various text hinting characters
                  '\x{FEFF}' .              // Byte order mark
                  '\x{FF01}-\x{FF60}' .     // Full-width latin
                  '\x{FFF9}-\x{FFFD}' .     // Replacement characters
                  '\x{0}-\x{1F}]/u',        // NULL byte and control characters
                  $name)) {
    return t('The username contains an illegal character.');
  }
  if (drupal_strlen($name) > USERNAME_MAX_LENGTH) {
    return t('The username %name is too long: it must be %max characters or less.', array('%name' => $name, '%max' => USERNAME_MAX_LENGTH));
  }
Dries Buytaert's avatar
 
Dries Buytaert committed
}

 * @see AccountFormController::form()
function user_validate_picture(&$form, &$form_state) {
  // If required, validate the uploaded picture.
  $validators = array(
    'file_validate_is_image' => array(),
    'file_validate_image_resolution' => array(variable_get('user_picture_dimensions', '85x85')),
    'file_validate_size' => array(variable_get('user_picture_file_size', '30') * 1024),
  );
  // Save the file as a temporary file.
  $file = file_save_upload('picture_upload', $validators);
  if ($file === FALSE) {
    form_set_error('picture_upload', t("Failed to upload the picture image; the %directory directory doesn't exist or is not writable.", array('%directory' => variable_get('user_picture_path', 'pictures'))));
  }
  elseif ($file !== NULL) {
    $form_state['values']['picture_upload'] = $file;
Dries Buytaert's avatar
 
Dries Buytaert committed
  }
}

/**
 * Generate a random alphanumeric password.
 */
Dries Buytaert's avatar
 
Dries Buytaert committed
function user_password($length = 10) {
  // This variable contains the list of allowable characters for the
  // password. Note that the number 0 and the letter 'O' have been
  // removed to avoid confusion between the two. The same is true
  $allowable_characters = 'abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789';
  // Zero-based count of characters in the allowable list:
  $len = strlen($allowable_characters) - 1;
Dries Buytaert's avatar
 
Dries Buytaert committed

  // Declare the password as a blank string.
  $pass = '';
Dries Buytaert's avatar
 
Dries Buytaert committed

  // Loop the number of times specified by $length.
Dries Buytaert's avatar
 
Dries Buytaert committed
  for ($i = 0; $i < $length; $i++) {

    // Each iteration, pick a random character from the
    // allowable string and append it to the password:
    $pass .= $allowable_characters[mt_rand(0, $len)];
Dries Buytaert's avatar
 
Dries Buytaert committed
  }

  return $pass;
Dries Buytaert's avatar
 
Dries Buytaert committed
}

/**
 * Determine the permissions for one or more roles.
 *
 * @param $roles
 *   An array whose keys are the role IDs of interest, such as $user->roles.
 *
 * @return
 *   An array indexed by role ID. Each value is an array whose keys are the
 *   permission strings for the given role ID.
 */
function user_role_permissions($roles = array()) {
  $cache = &drupal_static(__FUNCTION__, array());

  $role_permissions = $fetch = array();

  if ($roles) {
    foreach ($roles as $rid => $name) {
      if (isset($cache[$rid])) {
        $role_permissions[$rid] = $cache[$rid];
      }
      else {
        // Add this rid to the list of those needing to be fetched.
        $fetch[] = $rid;
        // Prepare in case no permissions are returned.
      }
    }

    if ($fetch) {
      // Get from the database permissions that were not in the static variable.
      // Only role IDs with at least one permission assigned will return rows.
      $result = db_query("SELECT rid, permission FROM {role_permission} WHERE rid IN (:fetch)", array(':fetch' => $fetch));
        $cache[$row->rid][$row->permission] = TRUE;
      }
      foreach ($fetch as $rid) {
        // For every rid, we know we at least assigned an empty array.
        $role_permissions[$rid] = $cache[$rid];
/**
 * Determine whether the user has a given privilege.
 *
 * @param $string
 *   The permission, such as "administer nodes", being checked for.
Dries Buytaert's avatar
 
Dries Buytaert committed
 * @param $account
 *   (optional) The account to check, if not given use currently logged in user.
 *   Boolean TRUE if the current user has the requested permission.
 *
 * All permission checks in Drupal should go through this function. This
 * way, we guarantee consistent behavior, and ensure that the superuser
 * can perform all actions.
 */
function user_access($string, $account = NULL) {
Dries Buytaert's avatar
 
Dries Buytaert committed
  global $user;
Dries Buytaert's avatar
 
Dries Buytaert committed
  }

  // To reduce the number of SQL queries, we cache the user's permissions
  // in a static variable.
  // Use the advanced drupal_static() pattern, since this is called very often.
  static $drupal_static_fast;
  if (!isset($drupal_static_fast)) {
    $drupal_static_fast['perm'] = &drupal_static(__FUNCTION__);
  }
  $perm = &$drupal_static_fast['perm'];
    $role_permissions = user_role_permissions($account->roles);
Dries Buytaert's avatar
 
Dries Buytaert committed

    foreach ($role_permissions as $one_role) {
      $perms += $one_role;
Dries Buytaert's avatar
 
Dries Buytaert committed
    }
Dries Buytaert's avatar
 
Dries Buytaert committed
  }
  return isset($perm[$account->uid][$string]);
Dries Buytaert's avatar
 
Dries Buytaert committed
}

 * 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.
  return db_select('users')
    ->fields('users', array('name'))
    ->condition('name', db_like($name), 'LIKE')
    ->condition('status', 0)
    ->execute()->fetchObject();
  return array(
    'administer permissions' =>  array(
      'title' => t('Administer permissions'),
    ),
    'administer users' => array(
      'title' => t('Administer users'),
    ),
    '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('user.settings')->get('anonymous'), '@user-settings-url' => url('admin/config/people/accounts'))),
    ),
    'select account cancellation method' => array(
      'title' => t('Select method for cancelling own account'),
Dries Buytaert's avatar
 
Dries Buytaert committed
}

 *
 * Ensure that user pictures (avatars) are always downloadable.
 */
function user_file_download($uri) {
  if (strpos(file_uri_target($uri), variable_get('user_picture_path', 'pictures') . '/picture-') === 0) {
    $info = image_get_info($uri);
    return array('Content-Type' => $info['mime_type']);
Dries Buytaert's avatar
 
Dries Buytaert committed
  }
}

  // If a user's picture is replaced with a new one, update the record in
  // the users table.
  if (isset($file->fid) && isset($source->fid) && $file->fid != $source->fid) {
    db_update('users')
      ->fields(array(
        'picture' => $file->fid,
      ))
      ->condition('picture', $source->fid)
      ->execute();
  // Remove any references to the file.
    ->fields(array('picture' => 0))
    ->condition('picture', $file->fid)
    ->execute();
}

function user_search_info() {
  return array(
    'title' => 'Users',
  );
}

/**
 */
function user_search_access() {
  return user_access('access user profiles');
}

/**
function user_search_execute($keys = NULL, $conditions = NULL) {
  $find = array();
  // Replace wildcards with MySQL/PostgreSQL wildcards.
  $keys = preg_replace('!\*+!', '%', $keys);
  $query = db_select('users')
    ->extend('Drupal\Core\Database\Query\PagerSelectExtender');
  $query->fields('users', array('uid'));
  if (user_access('administer users')) {
    // Administrators can also search in the otherwise private email field.
    $query->fields('users', array('mail'));
      condition('name', '%' . db_like($keys) . '%', 'LIKE')->
      condition('mail', '%' . db_like($keys) . '%', 'LIKE'));
    $query->condition('name', '%' . db_like($keys) . '%', 'LIKE');
    ->execute()
    ->fetchCol();
  $accounts = user_load_multiple($uids);

  $results = array();
  foreach ($accounts as $account) {
    $result = array(
      'title' => user_format_name($account),
      'link' => url('user/' . $account->uid, array('absolute' => TRUE)),
    );
    if (user_access('administer users')) {
      $result['title'] .= ' (' . $account->mail . ')';
Dries Buytaert's avatar
 
Dries Buytaert committed
  }
Dries Buytaert's avatar
 
Dries Buytaert committed
}

  $account->content['user_picture'] = array(
    '#markup' => theme('user_picture', array('account' => $account)),
  $account->content['member_for'] = array(
    '#type' => 'item',
    '#title' => t('Member for'),
    '#markup' => format_interval(REQUEST_TIME - $account->created),
/**
 * Sets the value of the user register and profile forms' langcode element.
 */
function _user_language_selector_langcode_value($element, $input, &$form_state) {
  // Only add to the description if the form element have a description.
  if (isset($form_state['complete_form']['language']['preferred_langcode']['#description'])) {
    $form_state['complete_form']['language']['preferred_langcode']['#description'] .= ' ' . t("This is also assumed to be the primary language of this account's profile information.");
  }
  return $form_state['values']['preferred_langcode'];
 * Form validation handler for the current password on the user account form.
 * @see AccountFormController::form()
 */
function user_validate_current_pass(&$form, &$form_state) {
  $account = $form_state['user'];
  foreach ($form_state['values']['current_pass_required_values'] as $key => $name) {
    // This validation only works for required textfields (like mail) or
    // form values like password_confirm that have their own validation
    // that prevent them from being empty if they are changed.
    if ((strlen(trim($form_state['values'][$key])) > 0) && ($form_state['values'][$key] != $account->$key)) {
      require_once DRUPAL_ROOT . '/' . variable_get('password_inc', 'core/includes/password.inc');
      $current_pass_failed = empty($form_state['values']['current_pass']) || !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);
      }
      // We only need to check the password once.
      break;
    }
  }
}

  $form['#action'] = url(current_path(), array('query' => drupal_get_destination(), 'external' => FALSE));
  $form['#id'] = 'user-login-form';
  $form['#validate'] = user_login_default_validators();
  $form['#submit'][] = 'user_login_submit';
  $form['name'] = array('#type' => 'textfield',
    '#title' => t('Username'),
    '#size' => 15,
    '#required' => TRUE,
  );
  $form['pass'] = array('#type' => 'password',
    '#title' => t('Password'),
  $form['actions'] = array('#type' => 'actions');
  $form['actions']['submit'] = array('#type' => 'submit',
  if (config('user.settings')->get('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('Request new password'), 'user/password', array('attributes' => array('title' => t('Request new password via e-mail.'))));
  $form['links'] = array('#theme' => 'item_list', '#items' => $items);
Dries Buytaert's avatar
 
Dries Buytaert committed
  global $user;

  $blocks['login']['info'] = t('User login');
  // Not worth caching.
  $blocks['login']['cache'] = DRUPAL_NO_CACHE;
  $blocks['new']['properties']['administrative'] = TRUE;
  // Too dynamic to cache.
  $blocks['online']['info'] = t('Who\'s online');
  $blocks['online']['cache'] = DRUPAL_NO_CACHE;
  $blocks['online']['properties']['administrative'] = TRUE;

 */
function user_block_configure($delta = '') {
  global $user;

    case 'new':
      $form['user_block_whois_new_count'] = array(
        '#type' => 'select',
        '#title' => t('Number of users to display'),
        '#default_value' => variable_get('user_block_whois_new_count', 5),
        '#options' => drupal_map_assoc(array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)),
      );
      return $form;

    case 'online':
      $period = drupal_map_assoc(array(30, 60, 120, 180, 300, 600, 900, 1800, 2700, 3600, 5400, 7200, 10800, 21600, 43200, 86400), 'format_interval');
      $form['user_block_seconds_online'] = array('#type' => 'select', '#title' => t('User activity'), '#default_value' => variable_get('user_block_seconds_online', 900), '#options' => $period, '#description' => t('A user is considered online for this long after they have last viewed a page.'));
      $form['user_block_max_list_count'] = array('#type' => 'select', '#title' => t('User list length'), '#default_value' => variable_get('user_block_max_list_count', 10), '#options' => drupal_map_assoc(array(0, 5, 10, 15, 20, 25, 30, 40, 50, 75, 100)), '#description' => t('Maximum number of currently online users to display.'));
      return $form;
 */
function user_block_save($delta = '', $edit = array()) {
  global $user;

  switch ($delta) {
    case 'new':
      variable_set('user_block_whois_new_count', $edit['user_block_whois_new_count']);
      break;

    case 'online':
      variable_set('user_block_seconds_online', $edit['user_block_seconds_online']);
      variable_set('user_block_max_list_count', $edit['user_block_max_list_count']);
      break;
Dries Buytaert's avatar
 
Dries Buytaert committed

 */
function user_block_view($delta = '') {
  global $user;
Dries Buytaert's avatar
 
Dries Buytaert committed

  switch ($delta) {
    case 'login':
      // For usability's sake, avoid showing two login forms on one page.
      if (!$user->uid && !(arg(0) == 'user' && !is_numeric(arg(1)))) {
        $block['content'] = drupal_get_form('user_login_block');
Dries Buytaert's avatar
 
Dries Buytaert committed

    case 'new':
      if (user_access('access content')) {
        // Retrieve a list of new users who have subsequently accessed the site successfully.
        $items = db_query_range('SELECT uid, name FROM {users} WHERE status <> 0 AND access <> 0 ORDER BY created DESC', 0, variable_get('user_block_whois_new_count', 5))->fetchAll();
        $output = theme('user_list', array('users' => $items));
        $block['subject'] = t('Who\'s new');
        $block['content'] = $output;
      }
      return $block;
Dries Buytaert's avatar
 
Dries Buytaert committed

    case 'online':
      if (user_access('access content')) {
        // Count users active within the defined period.
        $interval = REQUEST_TIME - variable_get('user_block_seconds_online', 900);
Dries Buytaert's avatar
 
Dries Buytaert committed

        // Perform database queries to gather online user lists. We use s.timestamp
        // rather than u.access because it is much faster.
        $authenticated_count = db_query("SELECT COUNT(DISTINCT s.uid) FROM {sessions} s WHERE s.timestamp >= :timestamp AND s.uid > 0", array(':timestamp' => $interval))->fetchField();
        $output = '<p>' . format_plural($authenticated_count, 'There is currently 1 user online.', 'There are currently @count users online.') . '</p>';

        // Display a list of currently online users.
        $max_users = variable_get('user_block_max_list_count', 10);
        if ($authenticated_count && $max_users) {
          $items = db_query_range('SELECT u.uid, u.name, MAX(s.timestamp) AS max_timestamp FROM {users} u INNER JOIN {sessions} s ON u.uid = s.uid WHERE s.timestamp >= :interval AND s.uid > 0 GROUP BY u.uid, u.name ORDER BY max_timestamp DESC', 0, $max_users, array(':interval' => $interval))->fetchAll();
          $output .= theme('user_list', array('users' => $items));
        }

        $block['subject'] = t('Who\'s online');
        $block['content'] = $output;
      }
      return $block;
Dries Buytaert's avatar
 
Dries Buytaert committed
  }
 * Implements hook_preprocess_HOOK() for block.tpl.php.
 */
function user_preprocess_block(&$variables) {
  if ($variables['block']->module == 'user') {
    switch ($variables['block']->delta) {
      case 'login':
        $variables['attributes']['role'] = 'form';
        $variables['attributes']['role'] = 'complementary';
        $variables['attributes']['role'] = 'complementary';
/**
 * 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('user.settings')->get('anonymous');
  drupal_alter('user_format_name', $name, $account);
/**
 * Process variables for user-picture.tpl.php.
 *
 * The $variables array contains the following arguments:
 * - $account: A user, node or comment object with 'name', 'uid' and 'picture'
 *   fields.
 *
 * @see user-picture.tpl.php
 */
function template_preprocess_user_picture(&$variables) {
Dries Buytaert's avatar
 
Dries Buytaert committed
  if (variable_get('user_pictures', 0)) {
    $account = $variables['account'];
    if (!empty($account->picture)) {
      // @TODO: Ideally this function would only be passed file entities, but
      // since there's a lot of legacy code that JOINs the {users} table to
      // {node} or {comments} and passes the results into this function if we
      // a numeric value in the picture field we'll assume it's a file id
      // and load it for them. Once we've got user_load_multiple() and
      // comment_load_multiple() functions the user module will be able to load
      // the picture files in mass during the object's load process.
      if (is_numeric($account->picture)) {
        $account->picture = file_load($account->picture);
      }
      if (!empty($account->picture->uri)) {
        $filepath = $account->picture->uri;
Dries Buytaert's avatar
 
Dries Buytaert committed
    }
    elseif (variable_get('user_picture_default', '')) {
      $filepath = variable_get('user_picture_default', '');
Dries Buytaert's avatar
 
Dries Buytaert committed
    }
    if (isset($filepath)) {
      $alt = t("@user's picture", array('@user' => user_format_name($account)));
      // If the image does not have a valid Drupal scheme (for eg. HTTP),
      // don't load image styles.
      if (module_exists('image') && file_valid_uri($filepath) && $style = variable_get('user_picture_style', '')) {
        $variables['user_picture'] = theme('image_style', array('style_name' => $style, 'uri' => $filepath, 'alt' => $alt, 'title' => $alt));
        $variables['user_picture'] = theme('image', array('uri' => $filepath, 'alt' => $alt, 'title' => $alt));
      if (!empty($account->uid) && user_access('access user profiles')) {
        $attributes = array('attributes' => array('title' => t('View user profile.')), 'html' => TRUE);
        $variables['user_picture'] = l($variables['user_picture'], "user/$account->uid", $attributes);
Dries Buytaert's avatar
 
Dries Buytaert committed
      }
    }
  }
}

/**
 * Preprocesses variables for theme_username().
 *
 * Modules that make any changes to variables like 'name' or 'extra' must insure
 * that the final string is safe to include directly in the output by using
 * check_plain() or filter_xss().
 *
 * @see template_process_username()
 */
function template_preprocess_username(&$variables) {
  $account = $variables['account'];

  $variables['extra'] = '';
  if (empty($account->uid)) {
   $variables['uid'] = 0;
   if (theme_get_setting('toggle_comment_user_verification')) {
     $variables['extra'] = ' (' . t('not verified') . ')';
   }
  }
  else {
    $variables['uid'] = (int) $account->uid;
  }

  // Set the name to a formatted name that is safe for printing and
  // that won't break tables by being too long. Keep an unshortened,
  // unsanitized version, in case other preprocess functions want to implement
  // their own shortening logic or add markup. If they do so, they must ensure