Newer
Older
/**
* Maximum length of username text field.
*/
define('USERNAME_MAX_LENGTH', 60);
/**
* Maximum length of user e-mail text field.
*/
Dries Buytaert
committed
define('EMAIL_MAX_LENGTH', 254);
Dries Buytaert
committed
/**
* Only administrators can create user accounts.
*/
define('USER_REGISTER_ADMINISTRATORS_ONLY', 0);
/**
* Visitors can create their own accounts.
*/
define('USER_REGISTER_VISITORS', 1);
/**
* Visitors can create accounts, but they don't become active without
* administrative approval.
*/
define('USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL', 2);
Angie Byron
committed
/**
* Implement hook_help().
*/
function user_help($path, $arg) {
global $user;
switch ($path) {
case 'admin/help#user':
$output = '';
$output .= '<h3>' . t('About') . '</h3>';
Jennifer Hodgdon
committed
$output .= '<p>' . t('The User module allows users to register, log in, and log out. It also allows users with proper permissions to manage user roles (used to classify users) and permissions associated with those roles. For more information, see the online handbook entry for <a href="@user">User module</a>.', array('@user' => 'http://drupal.org/documentation/modules/user')) . '</p>';
Angie Byron
committed
$output .= '<h3>' . t('Uses') . '</h3>';
$output .= '<dl>';
$output .= '<dt>' . t('Creating and managing users') . '</dt>';
Angie Byron
committed
$output .= '<dd>' . t('The User module allows users with the appropriate <a href="@permissions">permissions</a> to create user accounts through the <a href="@people">People administration page</a>, where they can also assign users to one or more roles, and block or delete user accounts. If allowed, users without accounts (anonymous users) can create their own accounts on the <a href="@register">Create new account</a> page.', array('@permissions' => url('admin/people/permissions', array('fragment' => 'module-user')), '@people' => url('admin/people'), '@register' => url('user/register'))) . '</dd>';
Angie Byron
committed
$output .= '<dt>' . t('User roles and permissions') . '</dt>';
Dries Buytaert
committed
$output .= '<dd>' . t('<em>Roles</em> are used to group and classify users; each user can be assigned one or more roles. By default there are two roles: <em>anonymous user</em> (users that are not logged in) and <em>authenticated user</em> (users that are registered and logged in). Depending on choices you made when you installed Drupal, the installation process may have defined more roles, and you can create additional custom roles on the <a href="@roles">Roles page</a>. After creating roles, you can set permissions for each role on the <a href="@permissions_user">Permissions page</a>. Granting a permission allows users who have been assigned a particular role to perform an action on the site, such as viewing a particular type of content, editing or creating content, administering settings for a particular module, or using a particular function of the site (such as search).', array('@permissions_user' => url('admin/people/permissions'), '@roles' => url('admin/people/permissions/roles'))) . '</dd>';
Angie Byron
committed
$output .= '<dt>' . t('Account settings') . '</dt>';
Dries Buytaert
committed
$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>';
Angie Byron
committed
$output .= '</dl>';
return $output;
case 'admin/people/create':
return '<p>' . t("This web page allows administrators to register new users. Users' e-mail addresses and usernames must be unique.") . '</p>';
Angie Byron
committed
case 'admin/people/permissions':
Dries Buytaert
committed
return '<p>' . t('Permissions let you control what users can do and see on your site. You can define a specific set of permissions for each role. (See the <a href="@role">Roles</a> page to create a role). Two important roles to consider are Authenticated Users and Administrators. Any permissions granted to the Authenticated Users role will be given to any user who can log into your site. You can make any role the Administrator role for the site, meaning this will be granted all new permissions automatically. You can do this on the <a href="@settings">User Settings</a> page. You should be careful to ensure that only trusted users are given this access and level of control of your site.', array('@role' => url('admin/people/permissions/roles'), '@settings' => url('admin/config/people/accounts'))) . '</p>';
Angie Byron
committed
case 'admin/people/permissions/roles':
$output = '<p>' . t('Roles allow you to fine tune the security and administration of Drupal. A role defines a group of users that have certain privileges as defined on the <a href="@permissions">permissions page</a>. Examples of roles include: anonymous user, authenticated user, moderator, administrator and so on. In this area you will define the names and order of the roles on your site. It is recommended to order your roles from least permissive (anonymous user) to most permissive (administrator). To delete a role choose "edit role".', array('@permissions' => url('admin/people/permissions'))) . '</p>';
Dries Buytaert
committed
$output .= '<p>' . t('By default, Drupal comes with two user roles:') . '</p>';
Angie Byron
committed
$output .= '<ul>';
$output .= '<li>' . t("Anonymous user: this role is used for users that don't have a user account or that are not authenticated.") . '</li>';
$output .= '<li>' . t('Authenticated user: this role is automatically granted to all logged in users.') . '</li>';
$output .= '</ul>';
return $output;
case 'admin/config/people/accounts/fields':
return '<p>' . t('This form lets administrators add, edit, and arrange fields for storing user data.') . '</p>';
case 'admin/config/people/accounts/display':
return '<p>' . t('This form lets administrators configure how fields should be displayed when rendering a user profile page.') . '</p>';
case 'admin/people/search':
return '<p>' . t('Enter a simple pattern ("*" may be used as a wildcard match) to search for a username or e-mail address. For example, one may search for "br" and Drupal might return "brian", "brad", and "brenda@example.com".') . '</p>';
}
}
Angie Byron
committed
* Invokes a user hook in every module.
* We cannot use module_invoke() for this, because the arguments need to
*
* @param $type
* A text string that controls which user hook to invoke. Valid choices are:
* - cancel: Invokes hook_user_cancel().
* - insert: Invokes hook_user_insert().
* - login: Invokes hook_user_login().
* - presave: Invokes hook_user_presave().
* - update: Invokes hook_user_update().
* @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.
* @param $category
* The category of user information being acted upon.
Dries Buytaert
committed
function user_module_invoke($type, &$edit, $account, $category = NULL) {
Dries Buytaert
committed
foreach (module_implements('user_' . $type) as $module) {
Dries Buytaert
committed
$function = $module . '_user_' . $type;
Dries Buytaert
committed
$function($edit, $account, $category);
Dries Buytaert
committed
/**
Dries Buytaert
committed
* Implements hook_theme().
Dries Buytaert
committed
*/
function user_theme() {
return array(
'user_picture' => array(
'variables' => array('account' => NULL),
'template' => 'user-picture',
Dries Buytaert
committed
),
'user_profile' => array(
'render element' => 'elements',
'template' => 'user-profile',
'file' => 'user.pages.inc',
Steven Wittens
committed
),
'user_profile_category' => array(
'render element' => 'element',
'template' => 'user-profile-category',
'file' => 'user.pages.inc',
Steven Wittens
committed
),
'user_profile_item' => array(
'render element' => 'element',
'template' => 'user-profile-item',
'file' => 'user.pages.inc',
Dries Buytaert
committed
),
'user_list' => array(
'variables' => array('users' => NULL, 'title' => NULL),
Dries Buytaert
committed
),
Dries Buytaert
committed
'user_admin_permissions' => array(
'render element' => 'form',
'file' => 'user.admin.inc',
Dries Buytaert
committed
),
'user_admin_roles' => array(
'render element' => 'form',
'file' => 'user.admin.inc',
Dries Buytaert
committed
),
Dries Buytaert
committed
'user_permission_description' => array(
'variables' => array('permission_item' => NULL, 'hide' => NULL),
'file' => 'user.admin.inc',
),
Dries Buytaert
committed
'user_signature' => array(
'variables' => array('signature' => NULL),
Dries Buytaert
committed
),
Dries Buytaert
committed
);
}
Dries Buytaert
committed
* Implements hook_entity_info().
Dries Buytaert
committed
function user_entity_info() {
'label' => t('User'),
Dries Buytaert
committed
'controller class' => 'UserController',
'base table' => 'users',
Angie Byron
committed
'uri callback' => 'user_uri',
Angie Byron
committed
'label callback' => 'format_username',
Dries Buytaert
committed
'fieldable' => TRUE,
// $user->language is only the preferred user language for the user
// interface textual elements. As it is not necessarily related to the
// language assigned to fields, we do not define it as the entity language
// key.
'entity keys' => array(
'id' => 'uid',
),
'bundles' => array(
'user' => array(
'label' => t('User'),
'admin' => array(
Dries Buytaert
committed
'path' => 'admin/config/people/accounts',
'access arguments' => array('administer users'),
),
),
),
'view modes' => array(
'full' => array(
'label' => t('User account'),
Dries Buytaert
committed
'custom settings' => FALSE,
Angie Byron
committed
/**
Jennifer Hodgdon
committed
* Entity URI callback.
Angie Byron
committed
*/
Angie Byron
committed
function user_uri($user) {
return array(
'path' => 'user/' . $user->uid,
);
Angie Byron
committed
}
Angie Byron
committed
/**
* Implements hook_field_info_alter().
*/
function user_field_info_alter(&$info) {
// Add the 'user_register_form' instance setting to all field types.
Angie Byron
committed
foreach ($info as $field_type => &$field_type_info) {
$field_type_info += array('instance_settings' => array());
$field_type_info['instance_settings'] += array(
Angie Byron
committed
'user_register_form' => FALSE,
);
}
}
Angie Byron
committed
/**
Dries Buytaert
committed
* Implements hook_field_extra_fields().
Angie Byron
committed
*/
function user_field_extra_fields() {
$return['user']['user'] = array(
Dries Buytaert
committed
'form' => array(
'account' => array(
Dries Buytaert
committed
'label' => t('User name and password'),
'description' => t('User module account form elements.'),
Dries Buytaert
committed
'weight' => -10,
),
'timezone' => array(
Dries Buytaert
committed
'label' => t('Timezone'),
Dries Buytaert
committed
'description' => t('User module timezone form element.'),
'weight' => 6,
),
Dries Buytaert
committed
'display' => array(
'summary' => array(
Dries Buytaert
committed
'label' => t('History'),
Dries Buytaert
committed
'description' => t('User module history view element.'),
'weight' => 5,
),
Angie Byron
committed
Angie Byron
committed
}
Angie Byron
committed
/**
* Fetches a user object based on an external authentication source.
*
* @param string $authname
* The external authentication username.
*
* @return
* A fully-loaded user object if the user is found or FALSE if not found.
*/
Angie Byron
committed
$uid = db_query("SELECT uid FROM {authmap} WHERE authname = :authname", array(':authname' => $authname))->fetchField();
Angie Byron
committed
if ($uid) {
return user_load($uid);
return FALSE;
Angie Byron
committed
* Load multiple users based on certain conditions.
Angie Byron
committed
* This function should be used whenever you need to load more than one user
* from the database. Users are loaded into memory and will not require
* database access if loaded again during the same page request.
Angie Byron
committed
* @param $uids
* An array of user IDs.
* @param $conditions
Angie Byron
committed
* (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.
Angie Byron
committed
* @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.
Angie Byron
committed
*
* @return
Angie Byron
committed
* An array of user objects, indexed by uid.
*
Dries Buytaert
committed
* @see entity_load()
Angie Byron
committed
* @see user_load()
* @see user_load_by_mail()
* @see user_load_by_name()
Angie Byron
committed
* @see EntityFieldQuery
*
* @todo Remove $conditions in Drupal 8.
Angie Byron
committed
function user_load_multiple($uids = array(), $conditions = array(), $reset = FALSE) {
Dries Buytaert
committed
return entity_load('user', $uids, $conditions, $reset);
}
Angie Byron
committed
Dries Buytaert
committed
/**
* Controller class for users.
*
* This extends the DrupalDefaultEntityController class, adding required
* special handling for user objects.
*/
class UserController extends DrupalDefaultEntityController {
function attachLoad(&$queried_users, $revision_id = FALSE) {
Angie Byron
committed
// Build an array of user picture IDs so that these can be fetched later.
$picture_fids = array();
Dries Buytaert
committed
foreach ($queried_users as $key => $record) {
Angie Byron
committed
$picture_fids[] = $record->picture;
$queried_users[$key]->data = unserialize($record->data);
Dries Buytaert
committed
$queried_users[$key]->roles = array();
Angie Byron
committed
if ($record->uid) {
$queried_users[$record->uid]->roles[DRUPAL_AUTHENTICATED_RID] = 'authenticated user';
}
else {
$queried_users[$record->uid]->roles[DRUPAL_ANONYMOUS_RID] = 'anonymous user';
}
Steven Wittens
committed
}
Dries Buytaert
committed
// Add any additional roles from the database.
$result = db_query('SELECT r.rid, r.name, ur.uid FROM {role} r INNER JOIN {users_roles} ur ON ur.rid = r.rid WHERE ur.uid IN (:uids)', array(':uids' => array_keys($queried_users)));
foreach ($result as $record) {
$queried_users[$record->uid]->roles[$record->rid] = $record->name;
}
Dries Buytaert
committed
// Add the full file objects for user pictures if enabled.
if (!empty($picture_fids) && variable_get('user_pictures', 1) == 1) {
$pictures = file_load_multiple($picture_fids);
foreach ($queried_users as $account) {
if (!empty($account->picture) && isset($pictures[$account->picture])) {
$account->picture = $pictures[$account->picture];
}
else {
$account->picture = NULL;
Angie Byron
committed
}
}
}
Dries Buytaert
committed
// Call the default attachLoad() method. This will add fields and call
// hook_user_load().
parent::attachLoad($queried_users, $revision_id);
Angie Byron
committed
}
/**
Dries Buytaert
committed
* Loads a user object.
*
* Drupal has a global $user object, which represents the currently-logged-in
* user. So to avoid confusion and to avoid clobbering the global $user object,
* it is a good idea to assign the result of this function to a different local
* variable, generally $account. If you actually do want to act as the user you
* are loading, it is essential to call drupal_save_session(FALSE); first.
* See
* @link http://drupal.org/node/218104 Safely impersonating another user @endlink
* for more information.
Angie Byron
committed
*
* @param $uid
Dries Buytaert
committed
* Integer specifying the user ID to load.
Angie Byron
committed
* @param $reset
Dries Buytaert
committed
* TRUE to reset the internal cache and load from the database; FALSE
* (default) to load from the internal cache, if set.
*
Angie Byron
committed
* @return
Dries Buytaert
committed
* A fully-loaded user object upon successful user load, or FALSE if the user
Angie Byron
committed
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
* cannot be loaded.
*
* @see user_load_multiple()
*/
function user_load($uid, $reset = FALSE) {
$users = user_load_multiple(array($uid), array(), $reset);
return reset($users);
}
/**
* Fetch a user object by email address.
*
* @param $mail
* String with the account's e-mail address.
* @return
* A fully-loaded $user object upon successful user load or FALSE if user
* cannot be loaded.
*
* @see user_load_multiple()
*/
function user_load_by_mail($mail) {
$users = user_load_multiple(array(), array('mail' => $mail));
return reset($users);
}
/**
* Fetch a user object by account name.
*
* @param $name
* String with the account's user name.
* @return
* A fully-loaded $user object upon successful user load or FALSE if user
* cannot be loaded.
*
* @see user_load_multiple()
*/
function user_load_by_name($name) {
$users = user_load_multiple(array(), array('name' => $name));
return reset($users);
* Save changes to a user account or add a new user.
*
* @param $account
* (optional) The user object to modify or add. If you want to modify
* an existing user account, you will need to ensure that (a) $account
* is an object, and (b) you have set $account->uid to the numeric
* user ID of the user account you wish to modify. If you
* want to create a new user account, you can set $account->is_new to
* TRUE or omit the $account->uid field.
Dries Buytaert
committed
* @param $edit
Dries Buytaert
committed
* An array of fields and values to save. For example array('name'
* => 'My name'). Key / value pairs added to the $edit['data'] will be
* serialized and saved in the {users.data} column.
* @param $category
* (optional) The category for storing profile information in.
*
* @return
* A fully-loaded $user object upon successful save or FALSE if the save failed.
*
* @todo D8: Drop $edit and fix user_save() to be consistent with others.
Dries Buytaert
committed
function user_save($account, $edit = array(), $category = 'account') {
Angie Byron
committed
$transaction = db_transaction();
try {
if (!empty($edit['pass'])) {
// Allow alternate password hashing schemes.
require_once DRUPAL_ROOT . '/' . variable_get('password_inc', 'includes/password.inc');
$edit['pass'] = user_hash_password(trim($edit['pass']));
// Abort if the hashing failed and returned FALSE.
if (!$edit['pass']) {
return FALSE;
}
}
else {
// Avoid overwriting an existing password with a blank password.
unset($edit['pass']);
}
if (isset($edit['mail'])) {
$edit['mail'] = trim($edit['mail']);
}
Dries Buytaert
committed
Dries Buytaert
committed
// Load the stored entity, if any.
if (!empty($account->uid) && !isset($account->original)) {
$account->original = entity_load_unchanged('user', $account->uid);
}
Dries Buytaert
committed
if (empty($account)) {
$account = new stdClass();
}
Angie Byron
committed
if (!isset($account->is_new)) {
$account->is_new = empty($account->uid);
}
Dries Buytaert
committed
// Prepopulate $edit['data'] with the current value of $account->data.
// Modules can add to or remove from this array in hook_user_presave().
if (!empty($account->data)) {
$edit['data'] = !empty($edit['data']) ? array_merge($account->data, $edit['data']) : $account->data;
Dries Buytaert
committed
}
// Invoke hook_user_presave() for all modules.
Angie Byron
committed
user_module_invoke('presave', $edit, $account, $category);
// Invoke presave operations of Field Attach API and Entity API. Those APIs
Angie Byron
committed
// require a fully-fledged and updated entity object. Therefore, we need to
// copy any new property values of $edit into it.
foreach ($edit as $key => $value) {
Angie Byron
committed
$account->$key = $value;
Angie Byron
committed
field_attach_presave('user', $account);
module_invoke_all('entity_presave', $account, 'user');
Angie Byron
committed
if (is_object($account) && !$account->is_new) {
// Process picture uploads.
Angie Byron
committed
if (!empty($account->picture->fid) && (!isset($account->original->picture->fid) || $account->picture->fid != $account->original->picture->fid)) {
$picture = $account->picture;
Angie Byron
committed
// If the picture is a temporary file move it to its final location and
// make it permanent.
Dries Buytaert
committed
if (!$picture->status) {
Angie Byron
committed
$info = image_get_info($picture->uri);
$picture_directory = file_default_scheme() . '://' . variable_get('user_picture_path', 'pictures');
Angie Byron
committed
// Prepare the pictures directory.
file_prepare_directory($picture_directory, FILE_CREATE_DIRECTORY);
Dries Buytaert
committed
$destination = file_stream_wrapper_uri_normalize($picture_directory . '/picture-' . $account->uid . '-' . REQUEST_TIME . '.' . $info['extension']);
Angie Byron
committed
Dries Buytaert
committed
// Move the temporary file into the final location.
Dries Buytaert
committed
if ($picture = file_move($picture, $destination, FILE_EXISTS_RENAME)) {
Dries Buytaert
committed
$picture->status = FILE_STATUS_PERMANENT;
Angie Byron
committed
$account->picture = file_save($picture);
Dries Buytaert
committed
file_usage_add($picture, 'user', 'user', $account->uid);
Angie Byron
committed
}
Angie Byron
committed
// Delete the previous picture if it was deleted or replaced.
if (!empty($account->original->picture->fid)) {
file_usage_delete($account->original->picture, 'user', 'user', $account->uid);
file_delete($account->original->picture);
}
Angie Byron
committed
elseif (isset($edit['picture_delete']) && $edit['picture_delete']) {
file_usage_delete($account->original->picture, 'user', 'user', $account->uid);
file_delete($account->original->picture);
}
Angie Byron
committed
$account->picture = empty($account->picture->fid) ? 0 : $account->picture->fid;
Angie Byron
committed
// Do not allow 'uid' to be changed.
Angie Byron
committed
$account->uid = $account->original->uid;
Angie Byron
committed
// Save changes to the user table.
Angie Byron
committed
$success = drupal_write_record('users', $account, 'uid');
Angie Byron
committed
if ($success === FALSE) {
// The query failed - better to abort the save than risk further
// data loss.
return FALSE;
}
Angie Byron
committed
// Reload user roles if provided.
Angie Byron
committed
if ($account->roles != $account->original->roles) {
Angie Byron
committed
db_delete('users_roles')
->condition('uid', $account->uid)
->execute();
$query = db_insert('users_roles')->fields(array('uid', 'rid'));
Angie Byron
committed
foreach (array_keys($account->roles) as $rid) {
Angie Byron
committed
if (!in_array($rid, array(DRUPAL_ANONYMOUS_RID, DRUPAL_AUTHENTICATED_RID))) {
$query->values(array(
'uid' => $account->uid,
'rid' => $rid,
));
}
Dries Buytaert
committed
}
Angie Byron
committed
$query->execute();
Angie Byron
committed
// Delete a blocked user's sessions to kick them if they are online.
Angie Byron
committed
if ($account->original->status != $account->status && $account->status == 0) {
Angie Byron
committed
drupal_session_destroy_uid($account->uid);
}
Angie Byron
committed
// If the password changed, delete all open sessions and recreate
// the current one.
Angie Byron
committed
if ($account->pass != $account->original->pass) {
Angie Byron
committed
drupal_session_destroy_uid($account->uid);
if ($account->uid == $GLOBALS['user']->uid) {
drupal_session_regenerate();
}
Dries Buytaert
committed
}
Dries Buytaert
committed
Angie Byron
committed
// Save Field data.
Angie Byron
committed
field_attach_update('user', $account);
Gábor Hojtsy
committed
Angie Byron
committed
// Send emails after we have the new user object.
Angie Byron
committed
if ($account->status != $account->original->status) {
Angie Byron
committed
// The user's status is changing; conditionally send notification email.
Angie Byron
committed
$op = $account->status == 1 ? 'status_activated' : 'status_blocked';
_user_mail_notify($op, $account);
Angie Byron
committed
}
Gábor Hojtsy
committed
Angie Byron
committed
// Update $edit with any interim changes to $account.
foreach ($account as $key => $value) {
if (!property_exists($account->original, $key) || $value !== $account->original->$key) {
$edit[$key] = $value;
}
}
user_module_invoke('update', $edit, $account, $category);
module_invoke_all('entity_update', $account, 'user');
Gábor Hojtsy
committed
}
Angie Byron
committed
else {
// Allow 'uid' to be set by the caller. There is no danger of writing an
// existing user as drupal_write_record will do an INSERT.
Angie Byron
committed
if (empty($account->uid)) {
$account->uid = db_next_id(db_query('SELECT MAX(uid) FROM {users}')->fetchField());
Angie Byron
committed
}
// Allow 'created' to be set by the caller.
Angie Byron
committed
if (!isset($account->created)) {
$account->created = REQUEST_TIME;
Angie Byron
committed
}
Angie Byron
committed
$success = drupal_write_record('users', $account);
Angie Byron
committed
if ($success === FALSE) {
// On a failed INSERT some other existing user's uid may be returned.
// We must abort to avoid overwriting their account.
return FALSE;
}
Gábor Hojtsy
committed
Angie Byron
committed
// Make sure $account is properly initialized.
$account->roles[DRUPAL_AUTHENTICATED_RID] = 'authenticated user';
Angie Byron
committed
field_attach_insert('user', $account);
$edit = (array) $account;
user_module_invoke('insert', $edit, $account, $category);
module_invoke_all('entity_insert', $account, 'user');
Dries Buytaert
committed
// Save user roles.
Angie Byron
committed
if (count($account->roles) > 1) {
Angie Byron
committed
$query = db_insert('users_roles')->fields(array('uid', 'rid'));
Angie Byron
committed
foreach (array_keys($account->roles) as $rid) {
Angie Byron
committed
if (!in_array($rid, array(DRUPAL_ANONYMOUS_RID, DRUPAL_AUTHENTICATED_RID))) {
$query->values(array(
Angie Byron
committed
'uid' => $account->uid,
Angie Byron
committed
'rid' => $rid,
));
}
Angie Byron
committed
$query->execute();
Dries Buytaert
committed
}
}
Angie Byron
committed
// Clear internal properties.
unset($account->is_new);
unset($account->original);
// Clear the static loading cache.
entity_get_controller('user')->resetCache(array($account->uid));
Dries Buytaert
committed
Angie Byron
committed
return $account;
Angie Byron
committed
}
catch (Exception $e) {
Dries Buytaert
committed
$transaction->rollback();
watchdog_exception('user', $e);
/**
* Verify the syntax of the given name.
*/
if (!$name) {
return t('You must enter a username.');
}
if (substr($name, 0, 1) == ' ') {
return t('The username cannot begin with a space.');
}
if (substr($name, -1) == ' ') {
return t('The username cannot end with a space.');
}
if (strpos($name, ' ') !== FALSE) {
return t('The username cannot contain multiple spaces in a row.');
}
if (preg_match('/[^\x{80}-\x{F7} a-z0-9@_.\'-]/i', $name)) {
return t('The username contains an illegal character.');
}
if (preg_match('/[\x{80}-\x{A0}' . // Non-printable ISO-8859-1 + NBSP
'\x{AD}' . // Soft-hyphen
'\x{2000}-\x{200F}' . // Various space characters
'\x{2028}-\x{202F}' . // Bidirectional text overrides
'\x{205F}-\x{206F}' . // Various text hinting characters
'\x{FEFF}' . // Byte order mark
'\x{FF01}-\x{FF60}' . // Full-width latin
'\x{FFF9}-\x{FFFD}' . // Replacement characters
'\x{0}-\x{1F}]/u', // NULL byte and control characters
$name)) {
return t('The username contains an illegal character.');
}
if (drupal_strlen($name) > USERNAME_MAX_LENGTH) {
return t('The username %name is too long: it must be %max characters or less.', array('%name' => $name, '%max' => USERNAME_MAX_LENGTH));
}
/**
* Validates a user's email address.
*
* Checks that a user's email address exists and follows all standard
* validation rules. Returns error messages when the address is invalid.
*
* @param $mail
* A user's email address.
*
* @return
* If the address is invalid, a human-readable error message is returned.
* If the address is valid, nothing is returned.
*/
if (!$mail) {
return t('You must enter an e-mail address.');
}
return t('The e-mail address %mail is not valid.', array('%mail' => $mail));
Dries Buytaert
committed
/**
* Validates an image uploaded by a user.
*
* @see user_account_form()
*/
Dries Buytaert
committed
function user_validate_picture(&$form, &$form_state) {
Dries Buytaert
committed
// 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),
);
Gábor Hojtsy
committed
// Save the file as a temporary file.
$file = file_save_upload('picture_upload', $validators);
if ($file === FALSE) {
form_set_error('picture_upload', t("Failed to upload the picture image; the %directory directory doesn't exist or is not writable.", array('%directory' => variable_get('user_picture_path', 'pictures'))));
}
elseif ($file !== NULL) {
$form_state['values']['picture_upload'] = $file;
/**
* Generate a random alphanumeric password.
*/
function user_password($length = 10) {
// This variable contains the list of allowable characters for the
// password. Note that the number 0 and the letter 'O' have been
// removed to avoid confusion between the two. The same is true
Gábor Hojtsy
committed
// of 'I', 1, and 'l'.
$allowable_characters = 'abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789';
// Zero-based count of characters in the allowable list:
$len = strlen($allowable_characters) - 1;
// Declare the password as a blank string.
$pass = '';
// Loop the number of times specified by $length.
for ($i = 0; $i < $length; $i++) {
// Each iteration, pick a random character from the
// allowable string and append it to the password:
$pass .= $allowable_characters[mt_rand(0, $len)];
/**
* Determine the permissions for one or more roles.
*
* @param $roles
* An array whose keys are the role IDs of interest, such as $user->roles.
*
* @return
* An array indexed by role ID. Each value is an array whose keys are the
* permission strings for the given role ID.
*/
function user_role_permissions($roles = array()) {
$cache = &drupal_static(__FUNCTION__, array());
$role_permissions = $fetch = array();
if ($roles) {
foreach ($roles as $rid => $name) {
if (isset($cache[$rid])) {
$role_permissions[$rid] = $cache[$rid];
}
else {
// Add this rid to the list of those needing to be fetched.
$fetch[] = $rid;
// Prepare in case no permissions are returned.
$cache[$rid] = array();
}
}
if ($fetch) {
// Get from the database permissions that were not in the static variable.
// Only role IDs with at least one permission assigned will return rows.
$result = db_query("SELECT rid, permission FROM {role_permission} WHERE rid IN (:fetch)", array(':fetch' => $fetch));
foreach ($result as $row) {
$cache[$row->rid][$row->permission] = TRUE;
}
foreach ($fetch as $rid) {
// For every rid, we know we at least assigned an empty array.
$role_permissions[$rid] = $cache[$rid];
}
}
}
return $role_permissions;
}
/**
* Determine whether the user has a given privilege.
*
* @param $string
* The permission, such as "administer nodes", being checked for.
* @param $account
* (optional) The account to check, if not given use currently logged in user.
Gábor Hojtsy
committed
* Boolean TRUE if the current user has the requested permission.
*
* All permission checks in Drupal should go through this function. This
* way, we guarantee consistent behavior, and ensure that the superuser
* can perform all actions.
*/
function user_access($string, $account = NULL) {
Gábor Hojtsy
committed
if (!isset($account)) {
$account = $user;
}
Dries Buytaert
committed
// User #1 has all privileges:
Dries Buytaert
committed
if ($account->uid == 1) {
Dries Buytaert
committed
return TRUE;
// To reduce the number of SQL queries, we cache the user's permissions
// in a static variable.
// Use the advanced drupal_static() pattern, since this is called very often.
Angie Byron
committed
static $drupal_static_fast;
if (!isset($drupal_static_fast)) {
$drupal_static_fast['perm'] = &drupal_static(__FUNCTION__);
}
$perm = &$drupal_static_fast['perm'];
Dries Buytaert
committed
if (!isset($perm[$account->uid])) {
$role_permissions = user_role_permissions($account->roles);
Dries Buytaert
committed
$perms = array();
foreach ($role_permissions as $one_role) {
$perms += $one_role;
Dries Buytaert
committed
$perm[$account->uid] = $perms;
Dries Buytaert
committed
Dries Buytaert
committed
return isset($perm[$account->uid][$string]);
Dries Buytaert
committed
/**
Gábor Hojtsy
committed
* Checks for usernames blocked by user administration.
Dries Buytaert
committed
*
* @param $name
* A string containing a name of the user.
*
* @return
* Object with property 'name' (the user name), if the user is blocked;
* FALSE if the user is not blocked.
Dries Buytaert
committed
*/
function user_is_blocked($name) {
Angie Byron
committed
return db_select('users')
->fields('users', array('name'))
->condition('name', db_like($name), 'LIKE')
->condition('status', 0)
->execute()->fetchObject();
Dries Buytaert
committed
}
Dries Buytaert
committed
* Implements hook_permission().
function user_permission() {
return array(
'administer permissions' => array(
'title' => t('Administer permissions'),
Dries Buytaert
committed
'restrict access' => TRUE,
),
'administer users' => array(
'title' => t('Administer users'),
Dries Buytaert
committed
'restrict access' => TRUE,
),
'access user profiles' => array(
'title' => t('View user profiles'),
),
'change own username' => array(
'title' => t('Change own username'),
),
'cancel account' => array(
'title' => t('Cancel own user account'),
'description' => t('Note: content may be kept, unpublished, deleted or transferred to the %anonymous-name user depending on the configured <a href="@user-settings-url">user settings</a>.', array('%anonymous-name' => variable_get('anonymous', t('Anonymous')), '@user-settings-url' => url('admin/config/people/accounts'))),
),
'select account cancellation method' => array(
'title' => t('Select method for cancelling own account'),
Dries Buytaert
committed
'restrict access' => TRUE,
Dries Buytaert
committed
* Implements hook_file_download().
*
* Ensure that user pictures (avatars) are always downloadable.
*/
Dries Buytaert
committed
function user_file_download($uri) {
if (strpos(file_uri_target($uri), variable_get('user_picture_path', 'pictures') . '/picture-') === 0) {
$info = image_get_info($uri);
Dries Buytaert
committed
return array('Content-Type' => $info['mime_type']);
Dries Buytaert
committed
* Implements hook_file_move().
Dries Buytaert
committed
function user_file_move($file, $source) {
// 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();
Dries Buytaert
committed
* Implements hook_file_delete().
*/
function user_file_delete($file) {
// Remove any references to the file.
Angie Byron
committed
db_update('users')
->fields(array('picture' => 0))
->condition('picture', $file->fid)
->execute();
}
Dries Buytaert
committed
* Implements hook_search_info().
Dries Buytaert
committed
function user_search_info() {
return array(
'title' => 'Users',
);
}
/**
Dries Buytaert
committed
* Implements hook_search_access().
Dries Buytaert
committed
*/
function user_search_access() {
return user_access('access user profiles');
}
/**
Dries Buytaert
committed
* Implements hook_search_execute().
Dries Buytaert
committed
*/
Dries Buytaert
committed
function user_search_execute($keys = NULL, $conditions = NULL) {
Dries Buytaert
committed
$find = array();
// Replace wildcards with MySQL/PostgreSQL wildcards.
$keys = preg_replace('!\*+!', '%', $keys);
$query = db_select('users')->extend('PagerDefault');
$query->fields('users', array('uid'));
Dries Buytaert
committed
if (user_access('administer users')) {
// Administrators can also search in the otherwise private email field.
Dries Buytaert
committed
$query->fields('users', array('mail'));
Dries Buytaert
committed
$query->condition(db_or()->
Dries Buytaert
committed
condition('name', '%' . db_like($keys) . '%', 'LIKE')->
condition('mail', '%' . db_like($keys) . '%', 'LIKE'));
Dries Buytaert
committed
}
else {
Dries Buytaert
committed
$query->condition('name', '%' . db_like($keys) . '%', 'LIKE');
Dries Buytaert
committed
}
$uids = $query
Dries Buytaert
committed
->limit(15)
->execute()
->fetchCol();
$accounts = user_load_multiple($uids);
$results = array();
foreach ($accounts as $account) {
$result = array(
'title' => format_username($account),
'link' => url('user/' . $account->uid, array('absolute' => TRUE)),
);
if (user_access('administer users')) {
$result['title'] .= ' (' . $account->mail . ')';
Dries Buytaert
committed
}
$results[] = $result;
return $results;
Dries Buytaert
committed
* Implements hook_element_info().
Dries Buytaert
committed
function user_element_info() {
$types['user_profile_category'] = array(
'#theme_wrappers' => array('user_profile_category'),
);
$types['user_profile_item'] = array(
'#theme' => 'user_profile_item',
Dries Buytaert
committed
return $types;
Dries Buytaert
committed
* Implements hook_user_view().
Dries Buytaert
committed
function user_user_view($account) {
Dries Buytaert
committed
$account->content['user_picture'] = array(
Dries Buytaert
committed
'#markup' => theme('user_picture', array('account' => $account)),
Dries Buytaert
committed
'#weight' => -10,
);
if (!isset($account->content['summary'])) {
$account->content['summary'] = array();
}
$account->content['summary'] += array(
'#type' => 'user_profile_category',
'#attributes' => array('class' => array('user-member')),
Dries Buytaert
committed
'#weight' => 5,
'#title' => t('History'),
);
$account->content['summary']['member_for'] = array(
Dries Buytaert
committed
'#type' => 'user_profile_item',
'#title' => t('Member for'),
'#markup' => format_interval(REQUEST_TIME - $account->created),
);