diff options
author | Nathan Haug <nate@quicksketch.org> | 2011-10-30 16:32:37 -0700 |
---|---|---|
committer | Nathaniel <catch@35733.no-reply.drupal.org> | 2011-11-01 12:48:40 +0900 |
commit | 06fb770bd340e5a18555e0da55a4dd6ba22f76ba (patch) | |
tree | e814bc08d51db3af473ae5be565219c0249b7870 /core/modules/user | |
parent | 906a6db34707d27120dddd43a23f26f24153255d (diff) | |
download | drupal-06fb770bd340e5a18555e0da55a4dd6ba22f76ba.tar.gz drupal-06fb770bd340e5a18555e0da55a4dd6ba22f76ba.zip |
Issue #22336 by quicksketch, scor, boombatower, and rfay. Move all core Drupal files under a core subdirectory.
Diffstat (limited to 'core/modules/user')
-rw-r--r-- | core/modules/user/tests/user_form_test.info | 6 | ||||
-rw-r--r-- | core/modules/user/tests/user_form_test.module | 64 | ||||
-rw-r--r-- | core/modules/user/user-picture.tpl.php | 21 | ||||
-rw-r--r-- | core/modules/user/user-profile-category.tpl.php | 35 | ||||
-rw-r--r-- | core/modules/user/user-profile-item.tpl.php | 26 | ||||
-rw-r--r-- | core/modules/user/user-profile.tpl.php | 37 | ||||
-rw-r--r-- | core/modules/user/user-rtl.css | 34 | ||||
-rw-r--r-- | core/modules/user/user.admin.inc | 1037 | ||||
-rw-r--r-- | core/modules/user/user.api.php | 460 | ||||
-rw-r--r-- | core/modules/user/user.css | 102 | ||||
-rw-r--r-- | core/modules/user/user.entity.inc | 52 | ||||
-rw-r--r-- | core/modules/user/user.info | 10 | ||||
-rw-r--r-- | core/modules/user/user.install | 337 | ||||
-rw-r--r-- | core/modules/user/user.js | 196 | ||||
-rw-r--r-- | core/modules/user/user.module | 3897 | ||||
-rw-r--r-- | core/modules/user/user.pages.inc | 553 | ||||
-rw-r--r-- | core/modules/user/user.permissions.js | 69 | ||||
-rw-r--r-- | core/modules/user/user.test | 2211 | ||||
-rw-r--r-- | core/modules/user/user.tokens.inc | 131 |
19 files changed, 9278 insertions, 0 deletions
diff --git a/core/modules/user/tests/user_form_test.info b/core/modules/user/tests/user_form_test.info new file mode 100644 index 00000000000..ed2f39e3a44 --- /dev/null +++ b/core/modules/user/tests/user_form_test.info @@ -0,0 +1,6 @@ +name = "User module form tests" +description = "Support module for user form testing." +package = Testing +version = VERSION +core = 8.x +hidden = TRUE diff --git a/core/modules/user/tests/user_form_test.module b/core/modules/user/tests/user_form_test.module new file mode 100644 index 00000000000..4e907f361b3 --- /dev/null +++ b/core/modules/user/tests/user_form_test.module @@ -0,0 +1,64 @@ +<?php + +/** + * @file + * Dummy module implementing a form to test user password validation + */ + +/** + * Implements hook_menu(). + * + * Sets up a form that allows a user to validate password. + */ +function user_form_test_menu() { + $items = array(); + $items['user_form_test_current_password/%user'] = array( + 'title' => 'User form test for current password validation', + 'page callback' => 'drupal_get_form', + 'page arguments' => array('user_form_test_current_password',1), + 'access arguments' => array('administer users'), + 'type' => MENU_SUGGESTED_ITEM, + ); + return $items; +} + +/** + * A test form for user_validate_current_pass(). + */ +function user_form_test_current_password($form, &$form_state, $account) { + $account->user_form_test_field = ''; + $form['#user'] = $account; + + $form['user_form_test_field'] = array( + '#type' => 'textfield', + '#title' => t('Test field'), + '#description' => t('A field that would require a correct password to change.'), + '#required' => TRUE, + ); + + $form['current_pass'] = array( + '#type' => 'password', + '#title' => t('Current password'), + '#size' => 25, + '#description' => t('Enter your current password'), + ); + + $form['current_pass_required_values'] = array( + '#type' => 'value', + '#value' => array('user_form_test_field' => t('Test field')), + ); + + $form['#validate'][] = 'user_validate_current_pass'; + $form['submit'] = array( + '#type' => 'submit', + '#value' => t('Test'), + ); + return $form; +} + +/** + * Submit function for the test form for user_validate_current_pass(). + */ +function user_form_test_current_password_submit($form, &$form_state) { + drupal_set_message(t('The password has been validated and the form submitted successfully.')); +} diff --git a/core/modules/user/user-picture.tpl.php b/core/modules/user/user-picture.tpl.php new file mode 100644 index 00000000000..a33d2661d74 --- /dev/null +++ b/core/modules/user/user-picture.tpl.php @@ -0,0 +1,21 @@ +<?php + +/** + * @file + * Default theme implementation to present a picture configured for the + * user's account. + * + * Available variables: + * - $user_picture: Image set by the user or the site's default. Will be linked + * depending on the viewer's permission to view the user's profile page. + * - $account: Array of account information. Potentially unsafe. Be sure to + * check_plain() before use. + * + * @see template_preprocess_user_picture() + */ +?> +<?php if ($user_picture): ?> + <div class="user-picture"> + <?php print $user_picture; ?> + </div> +<?php endif; ?> diff --git a/core/modules/user/user-profile-category.tpl.php b/core/modules/user/user-profile-category.tpl.php new file mode 100644 index 00000000000..8b6cd9991a6 --- /dev/null +++ b/core/modules/user/user-profile-category.tpl.php @@ -0,0 +1,35 @@ +<?php + +/** + * @file + * Default theme implementation to present profile categories (groups of + * profile items). + * + * Categories are defined when configuring user profile fields for the site. + * It can also be defined by modules. All profile items for a category will be + * output through the $profile_items variable. + * + * @see user-profile-item.tpl.php + * where each profile item is rendered. It is implemented as a definition + * list by default. + * @see user-profile.tpl.php + * where all items and categories are collected and printed out. + * + * Available variables: + * - $title: Category title for the group of items. + * - $profile_items: All the items for the group rendered through + * user-profile-item.tpl.php. + * - $attributes: HTML attributes. Usually renders classes. + * + * @see template_preprocess_user_profile_category() + */ +?> +<section class="<?php print $classes; ?>"> + <?php if ($title): ?> + <h2><?php print $title; ?></h2> + <?php endif; ?> + + <dl<?php print $attributes; ?>> + <?php print $profile_items; ?> + </dl> +</section> diff --git a/core/modules/user/user-profile-item.tpl.php b/core/modules/user/user-profile-item.tpl.php new file mode 100644 index 00000000000..042d43a8795 --- /dev/null +++ b/core/modules/user/user-profile-item.tpl.php @@ -0,0 +1,26 @@ +<?php + +/** + * @file + * Default theme implementation to present profile items (values from user + * account profile fields or modules). + * + * This template is used to loop through and render each field configured + * for the user's account. It can also be the data from modules. The output is + * grouped by categories. + * + * @see user-profile-category.tpl.php + * for the parent markup. Implemented as a definition list by default. + * @see user-profile.tpl.php + * where all items and categories are collected and printed out. + * + * Available variables: + * - $title: Field title for the profile item. + * - $value: User defined value for the profile item or data from a module. + * - $attributes: HTML attributes. Usually renders classes. + * + * @see template_preprocess_user_profile_item() + */ +?> +<dt<?php print $attributes; ?>><?php print $title; ?></dt> +<dd<?php print $attributes; ?>><?php print $value; ?></dd> diff --git a/core/modules/user/user-profile.tpl.php b/core/modules/user/user-profile.tpl.php new file mode 100644 index 00000000000..a1611c83531 --- /dev/null +++ b/core/modules/user/user-profile.tpl.php @@ -0,0 +1,37 @@ +<?php + +/** + * @file + * Default theme implementation to present all user profile data. + * + * This template is used when viewing a registered member's profile page, + * e.g., example.com/user/123. 123 being the users ID. + * + * Use render($user_profile) to print all profile items, or print a subset + * such as render($user_profile['user_picture']). Always call + * render($user_profile) at the end in order to print all remaining items. If + * the item is a category, it will contain all its profile items. By default, + * $user_profile['summary'] is provided, which contains data on the user's + * history. Other data can be included by modules. $user_profile['user_picture'] + * is available for showing the account picture. + * + * Available variables: + * - $user_profile: An array of profile items. Use render() to print them. + * - Field variables: for each field instance attached to the user a + * corresponding variable is defined; e.g., $account->field_example has a + * variable $field_example defined. When needing to access a field's raw + * values, developers/themers are strongly encouraged to use these + * variables. Otherwise they will have to explicitly specify the desired + * field language, e.g. $account->field_example['en'], thus overriding any + * language negotiation rule that was previously applied. + * + * @see user-profile-category.tpl.php + * Where the html is handled for the group. + * @see user-profile-item.tpl.php + * Where the html is handled for each item in the group. + * @see template_preprocess_user_profile() + */ +?> +<div class="profile"<?php print $attributes; ?>> + <?php print render($user_profile); ?> +</div> diff --git a/core/modules/user/user-rtl.css b/core/modules/user/user-rtl.css new file mode 100644 index 00000000000..642c9434716 --- /dev/null +++ b/core/modules/user/user-rtl.css @@ -0,0 +1,34 @@ + +#permissions td.permission { + padding-left: 0; + padding-right: 1.5em; +} + +#user-admin-roles .form-item-name { + float: right; + margin-left: 1em; + margin-right: 0; +} + +/** + * Password strength indicator. + */ +.password-strength { + float: left; +} +.password-strength-text { + float: left; +} +div.password-confirm { + float: left; +} +.confirm-parent, +.password-parent { + clear: right; +} + +/* Generated by user.module but used by profile.module: */ +.profile .user-picture { + float: left; + margin: 0 0 1em 1em; +} diff --git a/core/modules/user/user.admin.inc b/core/modules/user/user.admin.inc new file mode 100644 index 00000000000..4789e7e7313 --- /dev/null +++ b/core/modules/user/user.admin.inc @@ -0,0 +1,1037 @@ +<?php + +/** + * @file + * Admin page callback file for the user module. + */ + +function user_admin($callback_arg = '') { + $op = isset($_POST['op']) ? $_POST['op'] : $callback_arg; + + switch ($op) { + case t('Create new account'): + case 'create': + $build['user_register'] = drupal_get_form('user_register_form'); + break; + default: + if (!empty($_POST['accounts']) && isset($_POST['operation']) && ($_POST['operation'] == 'cancel')) { + $build['user_multiple_cancel_confirm'] = drupal_get_form('user_multiple_cancel_confirm'); + } + else { + $build['user_filter_form'] = drupal_get_form('user_filter_form'); + $build['user_admin_account'] = drupal_get_form('user_admin_account'); + } + } + return $build; +} + +/** + * Form builder; Return form for user administration filters. + * + * @ingroup forms + * @see user_filter_form_submit() + */ +function user_filter_form() { + $session = isset($_SESSION['user_overview_filter']) ? $_SESSION['user_overview_filter'] : array(); + $filters = user_filters(); + + $i = 0; + $form['filters'] = array( + '#type' => 'fieldset', + '#title' => t('Show only users where'), + '#theme' => 'exposed_filters__user', + ); + foreach ($session as $filter) { + list($type, $value) = $filter; + if ($type == 'permission') { + // Merge arrays of module permissions into one. + // Slice past the first element '[any]' whose value is not an array. + $options = call_user_func_array('array_merge', array_slice($filters[$type]['options'], 1)); + $value = $options[$value]; + } + else { + $value = $filters[$type]['options'][$value]; + } + $t_args = array('%property' => $filters[$type]['title'], '%value' => $value); + if ($i++) { + $form['filters']['current'][] = array('#markup' => t('and where %property is %value', $t_args)); + } + else { + $form['filters']['current'][] = array('#markup' => t('%property is %value', $t_args)); + } + } + + $form['filters']['status'] = array( + '#type' => 'container', + '#attributes' => array('class' => array('clearfix')), + '#prefix' => ($i ? '<div class="additional-filters">' . t('and where') . '</div>' : ''), + ); + $form['filters']['status']['filters'] = array( + '#type' => 'container', + '#attributes' => array('class' => array('filters')), + ); + foreach ($filters as $key => $filter) { + $form['filters']['status']['filters'][$key] = array( + '#type' => 'select', + '#options' => $filter['options'], + '#title' => $filter['title'], + '#default_value' => '[any]', + ); + } + + $form['filters']['status']['actions'] = array( + '#type' => 'actions', + '#attributes' => array('class' => array('container-inline')), + ); + $form['filters']['status']['actions']['submit'] = array( + '#type' => 'submit', + '#value' => (count($session) ? t('Refine') : t('Filter')), + ); + if (count($session)) { + $form['filters']['status']['actions']['undo'] = array( + '#type' => 'submit', + '#value' => t('Undo'), + ); + $form['filters']['status']['actions']['reset'] = array( + '#type' => 'submit', + '#value' => t('Reset'), + ); + } + + drupal_add_library('system', 'drupal.form'); + + return $form; +} + +/** + * Process result from user administration filter form. + */ +function user_filter_form_submit($form, &$form_state) { + $op = $form_state['values']['op']; + $filters = user_filters(); + switch ($op) { + case t('Filter'): + case t('Refine'): + // Apply every filter that has a choice selected other than 'any'. + foreach ($filters as $filter => $options) { + if (isset($form_state['values'][$filter]) && $form_state['values'][$filter] != '[any]') { + // Merge an array of arrays into one if necessary. + $options = ($filter == 'permission') ? form_options_flatten($filters[$filter]['options']) : $filters[$filter]['options']; + // Only accept valid selections offered on the dropdown, block bad input. + if (isset($options[$form_state['values'][$filter]])) { + $_SESSION['user_overview_filter'][] = array($filter, $form_state['values'][$filter]); + } + } + } + break; + case t('Undo'): + array_pop($_SESSION['user_overview_filter']); + break; + case t('Reset'): + $_SESSION['user_overview_filter'] = array(); + break; + case t('Update'): + return; + } + + $form_state['redirect'] = 'admin/people'; + return; +} + +/** + * Form builder; User administration page. + * + * @ingroup forms + * @see user_admin_account_validate() + * @see user_admin_account_submit() + */ +function user_admin_account() { + + $header = array( + 'username' => array('data' => t('Username'), 'field' => 'u.name'), + 'status' => array('data' => t('Status'), 'field' => 'u.status'), + 'roles' => array('data' => t('Roles')), + 'member_for' => array('data' => t('Member for'), 'field' => 'u.created', 'sort' => 'desc'), + 'access' => array('data' => t('Last access'), 'field' => 'u.access'), + 'operations' => array('data' => t('Operations')), + ); + + $query = db_select('users', 'u'); + $query->condition('u.uid', 0, '<>'); + user_build_filter_query($query); + + $count_query = clone $query; + $count_query->addExpression('COUNT(u.uid)'); + + $query = $query->extend('PagerDefault')->extend('TableSort'); + $query + ->fields('u', array('uid', 'name', 'status', 'created', 'access')) + ->limit(50) + ->orderByHeader($header) + ->setCountQuery($count_query); + $result = $query->execute(); + + $form['options'] = array( + '#type' => 'fieldset', + '#title' => t('Update options'), + '#attributes' => array('class' => array('container-inline')), + ); + $options = array(); + foreach (module_invoke_all('user_operations') as $operation => $array) { + $options[$operation] = $array['label']; + } + $form['options']['operation'] = array( + '#type' => 'select', + '#title' => t('Operation'), + '#title_display' => 'invisible', + '#options' => $options, + '#default_value' => 'unblock', + ); + $options = array(); + $form['options']['submit'] = array( + '#type' => 'submit', + '#value' => t('Update'), + ); + + $destination = drupal_get_destination(); + + $status = array(t('blocked'), t('active')); + $roles = array_map('check_plain', user_roles(TRUE)); + $accounts = array(); + foreach ($result as $account) { + $users_roles = array(); + $roles_result = db_query('SELECT rid FROM {users_roles} WHERE uid = :uid', array(':uid' => $account->uid)); + foreach ($roles_result as $user_role) { + $users_roles[] = $roles[$user_role->rid]; + } + asort($users_roles); + + $options[$account->uid] = array( + 'username' => theme('username', array('account' => $account)), + 'status' => $status[$account->status], + 'roles' => theme('item_list', array('items' => $users_roles)), + 'member_for' => format_interval(REQUEST_TIME - $account->created), + 'access' => $account->access ? t('@time ago', array('@time' => format_interval(REQUEST_TIME - $account->access))) : t('never'), + 'operations' => array('data' => array('#type' => 'link', '#title' => t('edit'), '#href' => "user/$account->uid/edit", '#options' => array('query' => $destination))), + ); + } + + $form['accounts'] = array( + '#type' => 'tableselect', + '#header' => $header, + '#options' => $options, + '#empty' => t('No people available.'), + ); + $form['pager'] = array('#markup' => theme('pager')); + + return $form; +} + +/** + * Submit the user administration update form. + */ +function user_admin_account_submit($form, &$form_state) { + $operations = module_invoke_all('user_operations', $form, $form_state); + $operation = $operations[$form_state['values']['operation']]; + // Filter out unchecked accounts. + $accounts = array_filter($form_state['values']['accounts']); + if ($function = $operation['callback']) { + // Add in callback arguments if present. + if (isset($operation['callback arguments'])) { + $args = array_merge(array($accounts), $operation['callback arguments']); + } + else { + $args = array($accounts); + } + call_user_func_array($function, $args); + + drupal_set_message(t('The update has been performed.')); + } +} + +function user_admin_account_validate($form, &$form_state) { + $form_state['values']['accounts'] = array_filter($form_state['values']['accounts']); + if (count($form_state['values']['accounts']) == 0) { + form_set_error('', t('No users selected.')); + } +} + +/** + * Form builder; Configure user settings for this site. + * + * @ingroup forms + * @see system_settings_form() + */ +function user_admin_settings() { + // Settings for anonymous users. + $form['anonymous_settings'] = array( + '#type' => 'fieldset', + '#title' => t('Anonymous users'), + ); + $form['anonymous_settings']['anonymous'] = array( + '#type' => 'textfield', + '#title' => t('Name'), + '#default_value' => variable_get('anonymous', t('Anonymous')), + '#description' => t('The name used to indicate anonymous users.'), + '#required' => TRUE, + ); + + // Administrative role option. + $form['admin_role'] = array( + '#type' => 'fieldset', + '#title' => t('Administrator role'), + ); + + // Do not allow users to set the anonymous or authenticated user roles as the + // administrator role. + $roles = user_roles(); + unset($roles[DRUPAL_ANONYMOUS_RID]); + unset($roles[DRUPAL_AUTHENTICATED_RID]); + $roles[0] = t('disabled'); + + $form['admin_role']['user_admin_role'] = array( + '#type' => 'select', + '#title' => t('Administrator role'), + '#default_value' => variable_get('user_admin_role', 0), + '#options' => $roles, + '#description' => t('This role will be automatically assigned new permissions whenever a module is enabled. Changing this setting will not affect existing permissions.'), + ); + + // User registration settings. + $form['registration_cancellation'] = array( + '#type' => 'fieldset', + '#title' => t('Registration and cancellation'), + ); + $form['registration_cancellation']['user_register'] = array( + '#type' => 'radios', + '#title' => t('Who can register accounts?'), + '#default_value' => variable_get('user_register', USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL), + '#options' => array( + USER_REGISTER_ADMINISTRATORS_ONLY => t('Administrators only'), + USER_REGISTER_VISITORS => t('Visitors'), + USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL => t('Visitors, but administrator approval is required'), + ) + ); + $form['registration_cancellation']['user_email_verification'] = array( + '#type' => 'checkbox', + '#title' => t('Require e-mail verification when a visitor creates an account.'), + '#default_value' => variable_get('user_email_verification', TRUE), + '#description' => t('New users will be required to validate their e-mail address prior to logging into the site, and will be assigned a system-generated password. With this setting disabled, users will be logged in immediately upon registering, and may select their own passwords during registration.') + ); + module_load_include('inc', 'user', 'user.pages'); + $form['registration_cancellation']['user_cancel_method'] = array( + '#type' => 'item', + '#title' => t('When cancelling a user account'), + '#description' => t('Users with the %select-cancel-method or %administer-users <a href="@permissions-url">permissions</a> can override this default method.', array('%select-cancel-method' => t('Select method for cancelling account'), '%administer-users' => t('Administer users'), '@permissions-url' => url('admin/people/permissions'))), + ); + $form['registration_cancellation']['user_cancel_method'] += user_cancel_methods(); + foreach (element_children($form['registration_cancellation']['user_cancel_method']) as $element) { + // Remove all account cancellation methods that have #access defined, as + // those cannot be configured as default method. + if (isset($form['registration_cancellation']['user_cancel_method'][$element]['#access'])) { + $form['registration_cancellation']['user_cancel_method'][$element]['#access'] = FALSE; + } + // Remove the description (only displayed on the confirmation form). + else { + unset($form['registration_cancellation']['user_cancel_method'][$element]['#description']); + } + } + + // Account settings. + $form['personalization'] = array( + '#type' => 'fieldset', + '#title' => t('Personalization'), + ); + $form['personalization']['user_signatures'] = array( + '#type' => 'checkbox', + '#title' => t('Enable signatures.'), + '#default_value' => variable_get('user_signatures', 0), + ); + // If picture support is enabled, check whether the picture directory exists. + if (variable_get('user_pictures', 0)) { + $picture_path = file_default_scheme() . '://' . variable_get('user_picture_path', 'pictures'); + if (!file_prepare_directory($picture_path, FILE_CREATE_DIRECTORY)) { + form_set_error('user_picture_path', t('The directory %directory does not exist or is not writable.', array('%directory' => $picture_path))); + watchdog('file system', 'The directory %directory does not exist or is not writable.', array('%directory' => $picture_path), WATCHDOG_ERROR); + } + } + $picture_support = variable_get('user_pictures', 0); + $form['personalization']['user_pictures'] = array( + '#type' => 'checkbox', + '#title' => t('Enable user pictures.'), + '#default_value' => $picture_support, + ); + drupal_add_js(drupal_get_path('module', 'user') . '/user.js'); + $form['personalization']['pictures'] = array( + '#type' => 'container', + '#states' => array( + // Hide the additional picture settings when user pictures are disabled. + 'invisible' => array( + 'input[name="user_pictures"]' => array('checked' => FALSE), + ), + ), + ); + $form['personalization']['pictures']['user_picture_path'] = array( + '#type' => 'textfield', + '#title' => t('Picture directory'), + '#default_value' => variable_get('user_picture_path', 'pictures'), + '#size' => 30, + '#maxlength' => 255, + '#description' => t('Subdirectory in the file upload directory where pictures will be stored.'), + ); + $form['personalization']['pictures']['user_picture_default'] = array( + '#type' => 'textfield', + '#title' => t('Default picture'), + '#default_value' => variable_get('user_picture_default', ''), + '#size' => 30, + '#maxlength' => 255, + '#description' => t('URL of picture to display for users with no custom picture selected. Leave blank for none.'), + ); + if (module_exists('image')) { + $form['personalization']['pictures']['settings']['user_picture_style'] = array( + '#type' => 'select', + '#title' => t('Picture display style'), + '#options' => image_style_options(TRUE), + '#default_value' => variable_get('user_picture_style', ''), + '#description' => t('The style selected will be used on display, while the original image is retained. Styles may be configured in the <a href="!url">Image styles</a> administration area.', array('!url' => url('admin/config/media/image-styles'))), + ); + } + $form['personalization']['pictures']['user_picture_dimensions'] = array( + '#type' => 'textfield', + '#title' => t('Picture upload dimensions'), + '#default_value' => variable_get('user_picture_dimensions', '85x85'), + '#size' => 10, + '#maxlength' => 10, + '#field_suffix' => ' ' . t('pixels'), + '#description' => t('Pictures larger than this will be scaled down to this size.'), + ); + $form['personalization']['pictures']['user_picture_file_size'] = array( + '#type' => 'textfield', + '#title' => t('Picture upload file size'), + '#default_value' => variable_get('user_picture_file_size', '30'), + '#size' => 10, + '#maxlength' => 10, + '#field_suffix' => ' ' . t('KB'), + '#description' => t('Maximum allowed file size for uploaded pictures. Upload size is normally limited only by the PHP maximum post and file upload settings, and images are automatically scaled down to the dimensions specified above.'), + ); + $form['personalization']['pictures']['user_picture_guidelines'] = array( + '#type' => 'textarea', + '#title' => t('Picture guidelines'), + '#default_value' => variable_get('user_picture_guidelines', ''), + '#description' => t("This text is displayed at the picture upload form in addition to the default guidelines. It's useful for helping or instructing your users."), + ); + + $form['email_title'] = array( + '#type' => 'item', + '#title' => t('E-mails'), + ); + $form['email'] = array( + '#type' => 'vertical_tabs', + ); + // These email tokens are shared for all settings, so just define + // the list once to help ensure they stay in sync. + $email_token_help = t('Available variables are: [site:name], [site:url], [user:name], [user:mail], [site:login-url], [site:url-brief], [user:edit-url], [user:one-time-login-url], [user:cancel-url].'); + + $form['email_admin_created'] = array( + '#type' => 'fieldset', + '#title' => t('Welcome (new user created by administrator)'), + '#collapsible' => TRUE, + '#collapsed' => (variable_get('user_register', USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL) != USER_REGISTER_ADMINISTRATORS_ONLY), + '#description' => t('Edit the welcome e-mail messages sent to new member accounts created by an administrator.') . ' ' . $email_token_help, + '#group' => 'email', + ); + $form['email_admin_created']['user_mail_register_admin_created_subject'] = array( + '#type' => 'textfield', + '#title' => t('Subject'), + '#default_value' => _user_mail_text('register_admin_created_subject', NULL, array(), FALSE), + '#maxlength' => 180, + ); + $form['email_admin_created']['user_mail_register_admin_created_body'] = array( + '#type' => 'textarea', + '#title' => t('Body'), + '#default_value' => _user_mail_text('register_admin_created_body', NULL, array(), FALSE), + '#rows' => 15, + ); + + $form['email_pending_approval'] = array( + '#type' => 'fieldset', + '#title' => t('Welcome (awaiting approval)'), + '#collapsible' => TRUE, + '#collapsed' => (variable_get('user_register', USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL) != USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL), + '#description' => t('Edit the welcome e-mail messages sent to new members upon registering, when administrative approval is required.') . ' ' . $email_token_help, + '#group' => 'email', + ); + $form['email_pending_approval']['user_mail_register_pending_approval_subject'] = array( + '#type' => 'textfield', + '#title' => t('Subject'), + '#default_value' => _user_mail_text('register_pending_approval_subject', NULL, array(), FALSE), + '#maxlength' => 180, + ); + $form['email_pending_approval']['user_mail_register_pending_approval_body'] = array( + '#type' => 'textarea', + '#title' => t('Body'), + '#default_value' => _user_mail_text('register_pending_approval_body', NULL, array(), FALSE), + '#rows' => 8, + ); + + $form['email_no_approval_required'] = array( + '#type' => 'fieldset', + '#title' => t('Welcome (no approval required)'), + '#collapsible' => TRUE, + '#collapsed' => (variable_get('user_register', USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL) != USER_REGISTER_VISITORS), + '#description' => t('Edit the welcome e-mail messages sent to new members upon registering, when no administrator approval is required.') . ' ' . $email_token_help, + '#group' => 'email', + ); + $form['email_no_approval_required']['user_mail_register_no_approval_required_subject'] = array( + '#type' => 'textfield', + '#title' => t('Subject'), + '#default_value' => _user_mail_text('register_no_approval_required_subject', NULL, array(), FALSE), + '#maxlength' => 180, + ); + $form['email_no_approval_required']['user_mail_register_no_approval_required_body'] = array( + '#type' => 'textarea', + '#title' => t('Body'), + '#default_value' => _user_mail_text('register_no_approval_required_body', NULL, array(), FALSE), + '#rows' => 15, + ); + + $form['email_password_reset'] = array( + '#type' => 'fieldset', + '#title' => t('Password recovery'), + '#collapsible' => TRUE, + '#collapsed' => TRUE, + '#description' => t('Edit the e-mail messages sent to users who request a new password.') . ' ' . $email_token_help, + '#group' => 'email', + '#weight' => 10, + ); + $form['email_password_reset']['user_mail_password_reset_subject'] = array( + '#type' => 'textfield', + '#title' => t('Subject'), + '#default_value' => _user_mail_text('password_reset_subject', NULL, array(), FALSE), + '#maxlength' => 180, + ); + $form['email_password_reset']['user_mail_password_reset_body'] = array( + '#type' => 'textarea', + '#title' => t('Body'), + '#default_value' => _user_mail_text('password_reset_body', NULL, array(), FALSE), + '#rows' => 12, + ); + + $form['email_activated'] = array( + '#type' => 'fieldset', + '#title' => t('Account activation'), + '#collapsible' => TRUE, + '#collapsed' => TRUE, + '#description' => t('Enable and edit e-mail messages sent to users upon account activation (when an administrator activates an account of a user who has already registered, on a site where administrative approval is required).') . ' ' . $email_token_help, + '#group' => 'email', + ); + $form['email_activated']['user_mail_status_activated_notify'] = array( + '#type' => 'checkbox', + '#title' => t('Notify user when account is activated.'), + '#default_value' => variable_get('user_mail_status_activated_notify', TRUE), + ); + $form['email_activated']['settings'] = array( + '#type' => 'container', + '#states' => array( + // Hide the additional settings when this email is disabled. + 'invisible' => array( + 'input[name="user_mail_status_activated_notify"]' => array('checked' => FALSE), + ), + ), + ); + $form['email_activated']['settings']['user_mail_status_activated_subject'] = array( + '#type' => 'textfield', + '#title' => t('Subject'), + '#default_value' => _user_mail_text('status_activated_subject', NULL, array(), FALSE), + '#maxlength' => 180, + ); + $form['email_activated']['settings']['user_mail_status_activated_body'] = array( + '#type' => 'textarea', + '#title' => t('Body'), + '#default_value' => _user_mail_text('status_activated_body', NULL, array(), FALSE), + '#rows' => 15, + ); + + $form['email_blocked'] = array( + '#type' => 'fieldset', + '#title' => t('Account blocked'), + '#collapsible' => TRUE, + '#collapsed' => TRUE, + '#description' => t('Enable and edit e-mail messages sent to users when their accounts are blocked.') . ' ' . $email_token_help, + '#group' => 'email', + ); + $form['email_blocked']['user_mail_status_blocked_notify'] = array( + '#type' => 'checkbox', + '#title' => t('Notify user when account is blocked.'), + '#default_value' => variable_get('user_mail_status_blocked_notify', FALSE), + ); + $form['email_blocked']['settings'] = array( + '#type' => 'container', + '#states' => array( + // Hide the additional settings when the blocked email is disabled. + 'invisible' => array( + 'input[name="user_mail_status_blocked_notify"]' => array('checked' => FALSE), + ), + ), + ); + $form['email_blocked']['settings']['user_mail_status_blocked_subject'] = array( + '#type' => 'textfield', + '#title' => t('Subject'), + '#default_value' => _user_mail_text('status_blocked_subject', NULL, array(), FALSE), + '#maxlength' => 180, + ); + $form['email_blocked']['settings']['user_mail_status_blocked_body'] = array( + '#type' => 'textarea', + '#title' => t('Body'), + '#default_value' => _user_mail_text('status_blocked_body', NULL, array(), FALSE), + '#rows' => 3, + ); + + $form['email_cancel_confirm'] = array( + '#type' => 'fieldset', + '#title' => t('Account cancellation confirmation'), + '#collapsible' => TRUE, + '#collapsed' => TRUE, + '#description' => t('Edit the e-mail messages sent to users when they attempt to cancel their accounts.') . ' ' . $email_token_help, + '#group' => 'email', + ); + $form['email_cancel_confirm']['user_mail_cancel_confirm_subject'] = array( + '#type' => 'textfield', + '#title' => t('Subject'), + '#default_value' => _user_mail_text('cancel_confirm_subject', NULL, array(), FALSE), + '#maxlength' => 180, + ); + $form['email_cancel_confirm']['user_mail_cancel_confirm_body'] = array( + '#type' => 'textarea', + '#title' => t('Body'), + '#default_value' => _user_mail_text('cancel_confirm_body', NULL, array(), FALSE), + '#rows' => 3, + ); + + $form['email_canceled'] = array( + '#type' => 'fieldset', + '#title' => t('Account canceled'), + '#collapsible' => TRUE, + '#collapsed' => TRUE, + '#description' => t('Enable and edit e-mail messages sent to users when their accounts are canceled.') . ' ' . $email_token_help, + '#group' => 'email', + ); + $form['email_canceled']['user_mail_status_canceled_notify'] = array( + '#type' => 'checkbox', + '#title' => t('Notify user when account is canceled.'), + '#default_value' => variable_get('user_mail_status_canceled_notify', FALSE), + ); + $form['email_canceled']['settings'] = array( + '#type' => 'container', + '#states' => array( + // Hide the settings when the cancel notify checkbox is disabled. + 'invisible' => array( + 'input[name="user_mail_status_canceled_notify"]' => array('checked' => FALSE), + ), + ), + ); + $form['email_canceled']['settings']['user_mail_status_canceled_subject'] = array( + '#type' => 'textfield', + '#title' => t('Subject'), + '#default_value' => _user_mail_text('status_canceled_subject', NULL, array(), FALSE), + '#maxlength' => 180, + ); + $form['email_canceled']['settings']['user_mail_status_canceled_body'] = array( + '#type' => 'textarea', + '#title' => t('Body'), + '#default_value' => _user_mail_text('status_canceled_body', NULL, array(), FALSE), + '#rows' => 3, + ); + + return system_settings_form($form); +} + +/** + * Menu callback: administer permissions. + * + * @ingroup forms + * @see user_admin_permissions_submit() + * @see theme_user_admin_permissions() + */ +function user_admin_permissions($form, $form_state, $rid = NULL) { + + // Retrieve role names for columns. + $role_names = user_roles(); + if (is_numeric($rid)) { + $role_names = array($rid => $role_names[$rid]); + } + // Fetch permissions for all roles or the one selected role. + $role_permissions = user_role_permissions($role_names); + + // Store $role_names for use when saving the data. + $form['role_names'] = array( + '#type' => 'value', + '#value' => $role_names, + ); + // Render role/permission overview: + $options = array(); + $module_info = system_get_info('module'); + $hide_descriptions = system_admin_compact_mode(); + + // Get a list of all the modules implementing a hook_permission() and sort by + // display name. + $modules = array(); + foreach (module_implements('permission') as $module) { + $modules[$module] = $module_info[$module]['name']; + } + asort($modules); + + foreach ($modules as $module => $display_name) { + if ($permissions = module_invoke($module, 'permission')) { + $form['permission'][] = array( + '#markup' => $module_info[$module]['name'], + '#id' => $module, + ); + foreach ($permissions as $perm => $perm_item) { + // Fill in default values for the permission. + $perm_item += array( + 'description' => '', + 'restrict access' => FALSE, + 'warning' => !empty($perm_item['restrict access']) ? t('Warning: Give to trusted roles only; this permission has security implications.') : '', + ); + $options[$perm] = ''; + $form['permission'][$perm] = array( + '#type' => 'item', + '#markup' => $perm_item['title'], + '#description' => theme('user_permission_description', array('permission_item' => $perm_item, 'hide' => $hide_descriptions)), + ); + foreach ($role_names as $rid => $name) { + // Builds arrays for checked boxes for each role + if (isset($role_permissions[$rid][$perm])) { + $status[$rid][] = $perm; + } + } + } + } + } + + // Have to build checkboxes here after checkbox arrays are built + foreach ($role_names as $rid => $name) { + $form['checkboxes'][$rid] = array( + '#type' => 'checkboxes', + '#options' => $options, + '#default_value' => isset($status[$rid]) ? $status[$rid] : array(), + '#attributes' => array('class' => array('rid-' . $rid)), + ); + $form['role_names'][$rid] = array('#markup' => check_plain($name), '#tree' => TRUE); + } + + $form['actions'] = array('#type' => 'actions'); + $form['actions']['submit'] = array('#type' => 'submit', '#value' => t('Save permissions')); + + $form['#attached']['js'][] = drupal_get_path('module', 'user') . '/user.permissions.js'; + + return $form; +} + +/** + * Save permissions selected on the administer permissions page. + * + * @see user_admin_permissions() + */ +function user_admin_permissions_submit($form, &$form_state) { + foreach ($form_state['values']['role_names'] as $rid => $name) { + user_role_change_permissions($rid, $form_state['values'][$rid]); + } + + drupal_set_message(t('The changes have been saved.')); + + // Clear the cached pages and blocks. + cache_clear_all(); +} + +/** + * Returns HTML for the administer permissions page. + * + * @param $variables + * An associative array containing: + * - form: A render element representing the form. + * + * @ingroup themeable + */ +function theme_user_admin_permissions($variables) { + $form = $variables['form']; + + $roles = user_roles(); + foreach (element_children($form['permission']) as $key) { + $row = array(); + // Module name + if (is_numeric($key)) { + $row[] = array('data' => drupal_render($form['permission'][$key]), 'class' => array('module'), 'id' => 'module-' . $form['permission'][$key]['#id'], 'colspan' => count($form['role_names']['#value']) + 1); + } + else { + // Permission row. + $row[] = array( + 'data' => drupal_render($form['permission'][$key]), + 'class' => array('permission'), + ); + foreach (element_children($form['checkboxes']) as $rid) { + $form['checkboxes'][$rid][$key]['#title'] = $roles[$rid] . ': ' . $form['permission'][$key]['#markup']; + $form['checkboxes'][$rid][$key]['#title_display'] = 'invisible'; + $row[] = array('data' => drupal_render($form['checkboxes'][$rid][$key]), 'class' => array('checkbox')); + } + } + $rows[] = $row; + } + $header[] = (t('Permission')); + foreach (element_children($form['role_names']) as $rid) { + $header[] = array('data' => drupal_render($form['role_names'][$rid]), 'class' => array('checkbox')); + } + $output = theme('system_compact_link'); + $output .= theme('table', array('header' => $header, 'rows' => $rows, 'attributes' => array('id' => 'permissions'))); + $output .= drupal_render_children($form); + return $output; +} + +/** + * Returns HTML for an individual permission description. + * + * @param $variables + * An associative array containing: + * - permission_item: An associative array representing the permission whose + * description is being themed. Useful keys include: + * - description: The text of the permission description. + * - warning: A security-related warning message about the permission (if + * there is one). + * - hide: A boolean indicating whether or not the permission description was + * requested to be hidden rather than shown. + * + * @ingroup themeable + */ +function theme_user_permission_description($variables) { + if (!$variables['hide']) { + $description = array(); + $permission_item = $variables['permission_item']; + if (!empty($permission_item['description'])) { + $description[] = $permission_item['description']; + } + if (!empty($permission_item['warning'])) { + $description[] = '<em class="permission-warning">' . $permission_item['warning'] . '</em>'; + } + if (!empty($description)) { + return implode(' ', $description); + } + } +} + +/** + * Form to re-order roles or add a new one. + * + * @ingroup forms + * @see theme_user_admin_roles() + */ +function user_admin_roles($form, $form_state) { + $roles = user_roles(); + + $form['roles'] = array( + '#tree' => TRUE, + ); + $order = 0; + foreach ($roles as $rid => $name) { + $form['roles'][$rid]['#role'] = (object) array( + 'rid' => $rid, + 'name' => $name, + 'weight' => $order, + ); + $form['roles'][$rid]['#weight'] = $order; + $form['roles'][$rid]['weight'] = array( + '#type' => 'textfield', + '#title' => t('Weight for @title', array('@title' => $name)), + '#title_display' => 'invisible', + '#size' => 4, + '#default_value' => $order, + '#attributes' => array('class' => array('role-weight')), + ); + $order++; + } + + $form['name'] = array( + '#type' => 'textfield', + '#title' => t('Name'), + '#title_display' => 'invisible', + '#size' => 32, + '#maxlength' => 64, + ); + $form['add'] = array( + '#type' => 'submit', + '#value' => t('Add role'), + '#validate' => array('user_admin_role_validate'), + '#submit' => array('user_admin_role_submit'), + ); + $form['actions'] = array('#type' => 'actions'); + $form['actions']['submit'] = array( + '#type' => 'submit', + '#value' => t('Save order'), + '#submit' => array('user_admin_roles_order_submit'), + ); + + return $form; +} + +/** + * Form submit function. Update the role weights. + */ +function user_admin_roles_order_submit($form, &$form_state) { + foreach ($form_state['values']['roles'] as $rid => $role_values) { + $role = $form['roles'][$rid]['#role']; + $role->weight = $role_values['weight']; + user_role_save($role); + } + drupal_set_message(t('The role settings have been updated.')); +} + +/** + * Returns HTML for the role order and new role form. + * + * @param $variables + * An associative array containing: + * - form: A render element representing the form. + * + * @ingroup themeable + */ +function theme_user_admin_roles($variables) { + $form = $variables['form']; + + $header = array(t('Name'), t('Weight'), array('data' => t('Operations'), 'colspan' => 2)); + foreach (element_children($form['roles']) as $rid) { + $name = $form['roles'][$rid]['#role']->name; + $row = array(); + if (in_array($rid, array(DRUPAL_ANONYMOUS_RID, DRUPAL_AUTHENTICATED_RID))) { + $row[] = t('@name <em>(locked)</em>', array('@name' => $name)); + $row[] = drupal_render($form['roles'][$rid]['weight']); + $row[] = ''; + $row[] = l(t('edit permissions'), 'admin/people/permissions/' . $rid); + } + else { + $row[] = check_plain($name); + $row[] = drupal_render($form['roles'][$rid]['weight']); + $row[] = l(t('edit role'), 'admin/people/permissions/roles/edit/' . $rid); + $row[] = l(t('edit permissions'), 'admin/people/permissions/' . $rid); + } + $rows[] = array('data' => $row, 'class' => array('draggable')); + } + $rows[] = array(array('data' => drupal_render($form['name']) . drupal_render($form['add']), 'colspan' => 4, 'class' => 'edit-name')); + + drupal_add_tabledrag('user-roles', 'order', 'sibling', 'role-weight'); + + $output = theme('table', array('header' => $header, 'rows' => $rows, 'attributes' => array('id' => 'user-roles'))); + $output .= drupal_render_children($form); + + return $output; +} + +/** + * Form to configure a single role. + * + * @ingroup forms + * @see user_admin_role_validate() + * @see user_admin_role_submit() + */ +function user_admin_role($form, $form_state, $role) { + if ($role->rid == DRUPAL_ANONYMOUS_RID || $role->rid == DRUPAL_AUTHENTICATED_RID) { + drupal_goto('admin/people/permissions/roles'); + } + + // Display the edit role form. + $form['name'] = array( + '#type' => 'textfield', + '#title' => t('Role name'), + '#default_value' => $role->name, + '#size' => 30, + '#required' => TRUE, + '#maxlength' => 64, + '#description' => t('The name for this role. Example: "moderator", "editorial board", "site architect".'), + ); + $form['rid'] = array( + '#type' => 'value', + '#value' => $role->rid, + ); + $form['weight'] = array( + '#type' => 'value', + '#value' => $role->weight, + ); + $form['actions'] = array('#type' => 'actions'); + $form['actions']['submit'] = array( + '#type' => 'submit', + '#value' => t('Save role'), + ); + $form['actions']['delete'] = array( + '#type' => 'submit', + '#value' => t('Delete role'), + '#submit' => array('user_admin_role_delete_submit'), + ); + + return $form; +} + +/** + * Form validation handler for the user_admin_role() form. + */ +function user_admin_role_validate($form, &$form_state) { + if (!empty($form_state['values']['name'])) { + if ($form_state['values']['op'] == t('Save role')) { + $role = user_role_load_by_name($form_state['values']['name']); + if ($role && $role->rid != $form_state['values']['rid']) { + form_set_error('name', t('The role name %name already exists. Choose another role name.', array('%name' => $form_state['values']['name']))); + } + } + elseif ($form_state['values']['op'] == t('Add role')) { + if (user_role_load_by_name($form_state['values']['name'])) { + form_set_error('name', t('The role name %name already exists. Choose another role name.', array('%name' => $form_state['values']['name']))); + } + } + } + else { + form_set_error('name', t('You must specify a valid role name.')); + } +} + +/** + * Form submit handler for the user_admin_role() form. + */ +function user_admin_role_submit($form, &$form_state) { + $role = (object) $form_state['values']; + if ($form_state['values']['op'] == t('Save role')) { + user_role_save($role); + drupal_set_message(t('The role has been renamed.')); + } + elseif ($form_state['values']['op'] == t('Add role')) { + user_role_save($role); + drupal_set_message(t('The role has been added.')); + } + $form_state['redirect'] = 'admin/people/permissions/roles'; + return; +} + +/** + * Form submit handler for the user_admin_role() form. + */ +function user_admin_role_delete_submit($form, &$form_state) { + $form_state['redirect'] = 'admin/people/permissions/roles/delete/' . $form_state['values']['rid']; +} + +/** + * Form to confirm role delete operation. + */ +function user_admin_role_delete_confirm($form, &$form_state, $role) { + $form['rid'] = array( + '#type' => 'value', + '#value' => $role->rid, + ); + return confirm_form($form, t('Are you sure you want to delete the role %name ?', array('%name' => $role->name)), 'admin/people/permissions/roles', t('This action cannot be undone.'), t('Delete')); +} + +/** + * Form submit handler for user_admin_role_delete_confirm(). + */ +function user_admin_role_delete_confirm_submit($form, &$form_state) { + user_role_delete((int) $form_state['values']['rid']); + drupal_set_message(t('The role has been deleted.')); + $form_state['redirect'] = 'admin/people/permissions/roles'; +} + diff --git a/core/modules/user/user.api.php b/core/modules/user/user.api.php new file mode 100644 index 00000000000..0b4f38f054a --- /dev/null +++ b/core/modules/user/user.api.php @@ -0,0 +1,460 @@ +<?php + +/** + * @file + * Hooks provided by the User module. + */ + +/** + * @addtogroup hooks + * @{ + */ + +/** + * Act on user objects when loaded from the database. + * + * Due to the static cache in user_load_multiple() you should not use this + * hook to modify the user properties returned by the {users} table itself + * since this may result in unreliable results when loading from cache. + * + * @param $users + * An array of user objects, indexed by uid. + * + * @see user_load_multiple() + * @see profile_user_load() + */ +function hook_user_load($users) { + $result = db_query('SELECT uid, foo FROM {my_table} WHERE uid IN (:uids)', array(':uids' => array_keys($users))); + foreach ($result as $record) { + $users[$record->uid]->foo = $record->foo; + } +} + +/** + * Respond to user deletion. + * + * This hook is invoked from user_delete_multiple() before field_attach_delete() + * is called and before users are actually removed from the database. + * + * Modules should additionally implement hook_user_cancel() to process stored + * user data for other account cancellation methods. + * + * @param $account + * The account that is being deleted. + * + * @see user_delete_multiple() + */ +function hook_user_delete($account) { + db_delete('mytable') + ->condition('uid', $account->uid) + ->execute(); +} + +/** + * Act on user account cancellations. + * + * This hook is invoked from user_cancel() before a user account is canceled. + * Depending on the account cancellation method, the module should either do + * nothing, unpublish content, or anonymize content. See user_cancel_methods() + * for the list of default account cancellation methods provided by User module. + * Modules may add further methods via hook_user_cancel_methods_alter(). + * + * This hook is NOT invoked for the 'user_cancel_delete' account cancellation + * method. To react on this method, implement hook_user_delete() instead. + * + * Expensive operations should be added to the global account cancellation batch + * by using batch_set(). + * + * @param $edit + * The array of form values submitted by the user. + * @param $account + * The user object on which the operation is being performed. + * @param $method + * The account cancellation method. + * + * @see user_cancel_methods() + * @see hook_user_cancel_methods_alter() + */ +function hook_user_cancel($edit, $account, $method) { + switch ($method) { + case 'user_cancel_block_unpublish': + // Unpublish nodes (current revisions). + module_load_include('inc', 'node', 'node.admin'); + $nodes = db_select('node', 'n') + ->fields('n', array('nid')) + ->condition('uid', $account->uid) + ->execute() + ->fetchCol(); + node_mass_update($nodes, array('status' => 0)); + break; + + case 'user_cancel_reassign': + // Anonymize nodes (current revisions). + module_load_include('inc', 'node', 'node.admin'); + $nodes = db_select('node', 'n') + ->fields('n', array('nid')) + ->condition('uid', $account->uid) + ->execute() + ->fetchCol(); + node_mass_update($nodes, array('uid' => 0)); + // Anonymize old revisions. + db_update('node_revision') + ->fields(array('uid' => 0)) + ->condition('uid', $account->uid) + ->execute(); + // Clean history. + db_delete('history') + ->condition('uid', $account->uid) + ->execute(); + break; + } +} + +/** + * Modify account cancellation methods. + * + * By implementing this hook, modules are able to add, customize, or remove + * account cancellation methods. All defined methods are turned into radio + * button form elements by user_cancel_methods() after this hook is invoked. + * The following properties can be defined for each method: + * - title: The radio button's title. + * - description: (optional) A description to display on the confirmation form + * if the user is not allowed to select the account cancellation method. The + * description is NOT used for the radio button, but instead should provide + * additional explanation to the user seeking to cancel their account. + * - access: (optional) A boolean value indicating whether the user can access + * a method. If #access is defined, the method cannot be configured as default + * method. + * + * @param $methods + * An array containing user account cancellation methods, keyed by method id. + * + * @see user_cancel_methods() + * @see user_cancel_confirm_form() + */ +function hook_user_cancel_methods_alter(&$methods) { + // Limit access to disable account and unpublish content method. + $methods['user_cancel_block_unpublish']['access'] = user_access('administer site configuration'); + + // Remove the content re-assigning method. + unset($methods['user_cancel_reassign']); + + // Add a custom zero-out method. + $methods['mymodule_zero_out'] = array( + 'title' => t('Delete the account and remove all content.'), + 'description' => t('All your content will be replaced by empty strings.'), + // access should be used for administrative methods only. + 'access' => user_access('access zero-out account cancellation method'), + ); +} + +/** + * Add mass user operations. + * + * This hook enables modules to inject custom operations into the mass operations + * dropdown found at admin/people, by associating a callback function with + * the operation, which is called when the form is submitted. The callback function + * receives one initial argument, which is an array of the checked users. + * + * @return + * An array of operations. Each operation is an associative array that may + * contain the following key-value pairs: + * - "label": Required. The label for the operation, displayed in the dropdown menu. + * - "callback": Required. The function to call for the operation. + * - "callback arguments": Optional. An array of additional arguments to pass to + * the callback function. + * + */ +function hook_user_operations() { + $operations = array( + 'unblock' => array( + 'label' => t('Unblock the selected users'), + 'callback' => 'user_user_operations_unblock', + ), + 'block' => array( + 'label' => t('Block the selected users'), + 'callback' => 'user_user_operations_block', + ), + 'cancel' => array( + 'label' => t('Cancel the selected user accounts'), + ), + ); + return $operations; +} + +/** + * Retrieve a list of user setting or profile information categories. + * + * @return + * An array of associative arrays. Each inner array has elements: + * - "name": The internal name of the category. + * - "title": The human-readable, localized name of the category. + * - "weight": An integer specifying the category's sort ordering. + * - "access callback": Name of the access callback function to use to + * determine whether the user can edit the category. Defaults to using + * user_edit_access(). See hook_menu() for more information on access + * callbacks. + * - "access arguments": Arguments for the access callback function. Defaults + * to array(1). + */ +function hook_user_categories() { + return array(array( + 'name' => 'account', + 'title' => t('Account settings'), + 'weight' => 1, + )); +} + +/** + * A user account is about to be created or updated. + * + * This hook is primarily intended for modules that want to store properties in + * the serialized {users}.data column, which is automatically loaded whenever a + * user account object is loaded, modules may add to $edit['data'] in order + * to have their data serialized on save. + * + * @param $edit + * The array of form values submitted by the user. + * @param $account + * The user object on which the operation is performed. + * @param $category + * The active category of user information being edited. + * + * @see hook_user_insert() + * @see hook_user_update() + */ +function hook_user_presave(&$edit, $account, $category) { + // Make sure that our form value 'mymodule_foo' is stored as 'mymodule_bar'. + if (isset($edit['mymodule_foo'])) { + $edit['data']['my_module_foo'] = $edit['my_module_foo']; + } +} + +/** + * A user account was created. + * + * The module should save its custom additions to the user object into the + * database. + * + * @param $edit + * The array of form values submitted by the user. + * @param $account + * The user object on which the operation is being performed. + * @param $category + * The active category of user information being edited. + * + * @see hook_user_presave() + * @see hook_user_update() + */ +function hook_user_insert(&$edit, $account, $category) { + db_insert('mytable') + ->fields(array( + 'myfield' => $edit['myfield'], + 'uid' => $account->uid, + )) + ->execute(); +} + +/** + * A user account was updated. + * + * Modules may use this hook to update their user data in a custom storage + * after a user account has been updated. + * + * @param $edit + * The array of form values submitted by the user. + * @param $account + * The user object on which the operation is performed. + * @param $category + * The active category of user information being edited. + * + * @see hook_user_presave() + * @see hook_user_insert() + */ +function hook_user_update(&$edit, $account, $category) { + db_insert('user_changes') + ->fields(array( + 'uid' => $account->uid, + 'changed' => time(), + )) + ->execute(); +} + +/** + * The user just logged in. + * + * @param $edit + * The array of form values submitted by the user. + * @param $account + * The user object on which the operation was just performed. + */ +function hook_user_login(&$edit, $account) { + // If the user has a NULL time zone, notify them to set a time zone. + if (!$account->timezone && variable_get('configurable_timezones', 1) && variable_get('empty_timezone_message', 0)) { + drupal_set_message(t('Configure your <a href="@user-edit">account time zone setting</a>.', array('@user-edit' => url("user/$account->uid/edit", array('query' => drupal_get_destination(), 'fragment' => 'edit-timezone'))))); + } +} + +/** + * The user just logged out. + * + * @param $account + * The user object on which the operation was just performed. + */ +function hook_user_logout($account) { + db_insert('logouts') + ->fields(array( + 'uid' => $account->uid, + 'time' => time(), + )) + ->execute(); +} + +/** + * The user's account information is being displayed. + * + * The module should format its custom additions for display and add them to the + * $account->content array. + * + * @param $account + * The user object on which the operation is being performed. + * @param $view_mode + * View mode, e.g. 'full'. + * @param $langcode + * The language code used for rendering. + * + * @see hook_user_view_alter() + * @see hook_entity_view() + */ +function hook_user_view($account, $view_mode, $langcode) { + $account->content['user_picture'] = array( + '#markup' => theme('user_picture', array('account' => $account)), + '#weight' => -10, + ); + if (!isset($account->content['summary'])) { + $account->content['summary'] = array(); + } + $account->content['summary'] += array( + '#type' => 'user_profile_category', + '#attributes' => array('class' => array('user-member')), + '#weight' => 5, + '#title' => t('History'), + ); + $account->content['summary']['member_for'] = array( + '#type' => 'user_profile_item', + '#title' => t('Member for'), + '#markup' => format_interval(REQUEST_TIME - $account->created), + ); +} + +/** + * The user was built; the module may modify the structured content. + * + * This hook is called after the content has been assembled in a structured array + * and may be used for doing processing which requires that the complete user + * content structure has been built. + * + * If the module wishes to act on the rendered HTML of the user rather than the + * structured content array, it may use this hook to add a #post_render callback. + * Alternatively, it could also implement hook_preprocess_user_profile(). See + * drupal_render() and theme() documentation respectively for details. + * + * @param $build + * A renderable array representing the user. + * + * @see user_view() + * @see hook_entity_view_alter() + */ +function hook_user_view_alter(&$build) { + // Check for the existence of a field added by another module. + if (isset($build['an_additional_field'])) { + // Change its weight. + $build['an_additional_field']['#weight'] = -10; + } + + // Add a #post_render callback to act on the rendered HTML of the user. + $build['#post_render'][] = 'my_module_user_post_render'; +} + +/** + * Inform other modules that a user role is about to be saved. + * + * Modules implementing this hook can act on the user role object before + * it has been saved to the database. + * + * @param $role + * A user role object. + * + * @see hook_user_role_insert() + * @see hook_user_role_update() + */ +function hook_user_role_presave($role) { + // Set a UUID for the user role if it doesn't already exist + if (empty($role->uuid)) { + $role->uuid = uuid_uuid(); + } +} + +/** + * Inform other modules that a user role has been added. + * + * Modules implementing this hook can act on the user role object when saved to + * the database. It's recommended that you implement this hook if your module + * adds additional data to user roles object. The module should save its custom + * additions to the database. + * + * @param $role + * A user role object. + */ +function hook_user_role_insert($role) { + // Save extra fields provided by the module to user roles. + db_insert('my_module_table') + ->fields(array( + 'rid' => $role->rid, + 'role_description' => $role->description, + )) + ->execute(); +} + +/** + * Inform other modules that a user role has been updated. + * + * Modules implementing this hook can act on the user role object when updated. + * It's recommended that you implement this hook if your module adds additional + * data to user roles object. The module should save its custom additions to + * the database. + * + * @param $role + * A user role object. + */ +function hook_user_role_update($role) { + // Save extra fields provided by the module to user roles. + db_merge('my_module_table') + ->key(array('rid' => $role->rid)) + ->fields(array( + 'role_description' => $role->description + )) + ->execute(); +} + +/** + * Inform other modules that a user role has been deleted. + * + * This hook allows you act when a user role has been deleted. + * If your module stores references to roles, it's recommended that you + * implement this hook and delete existing instances of the deleted role + * in your module database tables. + * + * @param $role + * The $role object being deleted. + */ +function hook_user_role_delete($role) { + // Delete existing instances of the deleted role. + db_delete('my_module_table') + ->condition('rid', $role->rid) + ->execute(); +} + +/** + * @} End of "addtogroup hooks". + */ diff --git a/core/modules/user/user.css b/core/modules/user/user.css new file mode 100644 index 00000000000..a3033073345 --- /dev/null +++ b/core/modules/user/user.css @@ -0,0 +1,102 @@ + +#permissions td.module { + font-weight: bold; +} +#permissions td.permission { + padding-left: 1.5em; /* LTR */ +} +#permissions tr.odd .form-item, +#permissions tr.even .form-item { + white-space: normal; +} +#user-admin-settings fieldset .fieldset-description { + font-size: 0.85em; + padding-bottom: .5em; +} + +/** + * Override default textfield float to put the "Add role" button next to + * the input textfield. + */ +#user-admin-roles td.edit-name { + clear: both; +} +#user-admin-roles .form-item-name { + float: left; /* LTR */ + margin-right: 1em; /* LTR */ +} + +/** + * Password strength indicator. + */ +.password-strength { + width: 17em; + float: right; /* LTR */ + margin-top: 1.4em; +} +.password-strength-title { + display: inline; +} +.password-strength-text { + float: right; /* LTR */ + font-weight: bold; +} +.password-indicator { + background-color: #C4C4C4; + height: 0.3em; + width: 100%; +} +.password-indicator div { + height: 100%; + width: 0%; + background-color: #47C965; +} +input.password-confirm, +input.password-field { + width: 16em; + margin-bottom: 0.4em; +} +div.password-confirm { + float: right; /* LTR */ + margin-top: 1.5em; + visibility: hidden; + width: 17em; +} +div.form-item div.password-suggestions { + padding: 0.2em 0.5em; + margin: 0.7em 0; + width: 38.5em; + border: 1px solid #B4B4B4; +} +div.password-suggestions ul { + margin-bottom: 0; +} +.confirm-parent, +.password-parent { + clear: left; /* LTR */ + margin: 0; + width: 36.3em; +} + +/* Generated by user.module but used by profile.module: */ +.profile { + clear: both; + margin: 1em 0; +} +.profile .user-picture { + float: right; /* LTR */ + margin: 0 1em 1em 0; /* LTR */ +} +.profile h2 { + border-bottom: 1px solid #ccc; +} +.profile dl { + margin: 0 0 1.5em 0; +} +.profile dt { + margin: 0 0 0.2em 0; + font-weight: bold; +} +.profile dd { + margin: 0 0 1em 0; +} diff --git a/core/modules/user/user.entity.inc b/core/modules/user/user.entity.inc new file mode 100644 index 00000000000..5549c770718 --- /dev/null +++ b/core/modules/user/user.entity.inc @@ -0,0 +1,52 @@ +<?php + +/** + * @file Controller class for users. + */ + +/** + * 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) { + // Build an array of user picture IDs so that these can be fetched later. + $picture_fids = array(); + foreach ($queried_users as $key => $record) { + $picture_fids[] = $record->picture; + $queried_users[$key]->data = unserialize($record->data); + $queried_users[$key]->roles = array(); + if ($record->uid) { + $queried_users[$record->uid]->roles[DRUPAL_AUTHENTICATED_RID] = 'authenticated user'; + } + else { + $queried_users[$record->uid]->roles[DRUPAL_ANONYMOUS_RID] = 'anonymous user'; + } + } + + // 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; + } + + // 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; + } + } + } + // Call the default attachLoad() method. This will add fields and call + // hook_user_load(). + parent::attachLoad($queried_users, $revision_id); + } +} diff --git a/core/modules/user/user.info b/core/modules/user/user.info new file mode 100644 index 00000000000..d887352760e --- /dev/null +++ b/core/modules/user/user.info @@ -0,0 +1,10 @@ +name = User +description = Manages the user registration and login system. +package = Core +version = VERSION +core = 8.x +files[] = user.entity.inc +files[] = user.test +required = TRUE +configure = admin/config/people +stylesheets[all][] = user.css diff --git a/core/modules/user/user.install b/core/modules/user/user.install new file mode 100644 index 00000000000..370427f86be --- /dev/null +++ b/core/modules/user/user.install @@ -0,0 +1,337 @@ +<?php + +/** + * @file + * Install, update and uninstall functions for the user module. + */ + +/** + * Implements hook_schema(). + */ +function user_schema() { + $schema['authmap'] = array( + 'description' => 'Stores distributed authentication mapping.', + 'fields' => array( + 'aid' => array( + 'description' => 'Primary Key: Unique authmap ID.', + 'type' => 'serial', + 'unsigned' => TRUE, + 'not null' => TRUE, + ), + 'uid' => array( + 'type' => 'int', + 'not null' => TRUE, + 'default' => 0, + 'description' => "User's {users}.uid.", + ), + 'authname' => array( + 'type' => 'varchar', + 'length' => 128, + 'not null' => TRUE, + 'default' => '', + 'description' => 'Unique authentication name.', + ), + 'module' => array( + 'type' => 'varchar', + 'length' => 128, + 'not null' => TRUE, + 'default' => '', + 'description' => 'Module which is controlling the authentication.', + ), + ), + 'unique keys' => array( + 'authname' => array('authname'), + ), + 'primary key' => array('aid'), + 'foreign keys' => array( + 'user' => array( + 'table' => 'users', + 'columns' => array('uid' => 'uid'), + ), + ), + ); + + $schema['role_permission'] = array( + 'description' => 'Stores the permissions assigned to user roles.', + 'fields' => array( + 'rid' => array( + 'type' => 'int', + 'unsigned' => TRUE, + 'not null' => TRUE, + 'description' => 'Foreign Key: {role}.rid.', + ), + 'permission' => array( + 'type' => 'varchar', + 'length' => 128, + 'not null' => TRUE, + 'default' => '', + 'description' => 'A single permission granted to the role identified by rid.', + ), + 'module' => array( + 'type' => 'varchar', + 'length' => 255, + 'not null' => TRUE, + 'default' => '', + 'description' => "The module declaring the permission.", + ), + ), + 'primary key' => array('rid', 'permission'), + 'indexes' => array( + 'permission' => array('permission'), + ), + 'foreign keys' => array( + 'role' => array( + 'table' => 'roles', + 'columns' => array('rid' => 'rid'), + ), + ), + ); + + $schema['role'] = array( + 'description' => 'Stores user roles.', + 'fields' => array( + 'rid' => array( + 'type' => 'serial', + 'unsigned' => TRUE, + 'not null' => TRUE, + 'description' => 'Primary Key: Unique role ID.', + ), + 'name' => array( + 'type' => 'varchar', + 'length' => 64, + 'not null' => TRUE, + 'default' => '', + 'description' => 'Unique role name.', + 'translatable' => TRUE, + ), + 'weight' => array( + 'type' => 'int', + 'not null' => TRUE, + 'default' => 0, + 'description' => 'The weight of this role in listings and the user interface.', + ), + ), + 'unique keys' => array( + 'name' => array('name'), + ), + 'primary key' => array('rid'), + 'indexes' => array( + 'name_weight' => array('name', 'weight'), + ), + ); + + $schema['users'] = array( + 'description' => 'Stores user data.', + 'fields' => array( + 'uid' => array( + 'type' => 'int', + 'unsigned' => TRUE, + 'not null' => TRUE, + 'description' => 'Primary Key: Unique user ID.', + 'default' => 0, + ), + 'name' => array( + 'type' => 'varchar', + 'length' => 60, + 'not null' => TRUE, + 'default' => '', + 'description' => 'Unique user name.', + ), + 'pass' => array( + 'type' => 'varchar', + 'length' => 128, + 'not null' => TRUE, + 'default' => '', + 'description' => "User's password (hashed).", + ), + 'mail' => array( + 'type' => 'varchar', + 'length' => 254, + 'not null' => FALSE, + 'default' => '', + 'description' => "User's e-mail address.", + ), + 'theme' => array( + 'type' => 'varchar', + 'length' => 255, + 'not null' => TRUE, + 'default' => '', + 'description' => "User's default theme.", + ), + 'signature' => array( + 'type' => 'varchar', + 'length' => 255, + 'not null' => TRUE, + 'default' => '', + 'description' => "User's signature.", + ), + 'signature_format' => array( + 'type' => 'varchar', + 'length' => 255, + 'not null' => FALSE, + 'description' => 'The {filter_format}.format of the signature.', + ), + 'created' => array( + 'type' => 'int', + 'not null' => TRUE, + 'default' => 0, + 'description' => 'Timestamp for when user was created.', + ), + 'access' => array( + 'type' => 'int', + 'not null' => TRUE, + 'default' => 0, + 'description' => 'Timestamp for previous time user accessed the site.', + ), + 'login' => array( + 'type' => 'int', + 'not null' => TRUE, + 'default' => 0, + 'description' => "Timestamp for user's last login.", + ), + 'status' => array( + 'type' => 'int', + 'not null' => TRUE, + 'default' => 0, + 'size' => 'tiny', + 'description' => 'Whether the user is active(1) or blocked(0).', + ), + 'timezone' => array( + 'type' => 'varchar', + 'length' => 32, + 'not null' => FALSE, + 'description' => "User's time zone.", + ), + 'language' => array( + 'type' => 'varchar', + 'length' => 12, + 'not null' => TRUE, + 'default' => '', + 'description' => "User's default language.", + ), + 'picture' => array( + 'type' => 'int', + 'not null' => TRUE, + 'default' => 0, + 'description' => "Foreign key: {file_managed}.fid of user's picture.", + ), + 'init' => array( + 'type' => 'varchar', + 'length' => 254, + 'not null' => FALSE, + 'default' => '', + 'description' => 'E-mail address used for initial account creation.', + ), + 'data' => array( + 'type' => 'blob', + 'not null' => FALSE, + 'size' => 'big', + 'serialize' => TRUE, + 'description' => 'A serialized array of name value pairs that are related to the user. Any form values posted during user edit are stored and are loaded into the $user object during user_load(). Use of this field is discouraged and it will likely disappear in a future version of Drupal.', + ), + ), + 'indexes' => array( + 'access' => array('access'), + 'created' => array('created'), + 'mail' => array('mail'), + ), + 'unique keys' => array( + 'name' => array('name'), + ), + 'primary key' => array('uid'), + 'foreign keys' => array( + 'signature_format' => array( + 'table' => 'filter_format', + 'columns' => array('signature_format' => 'format'), + ), + ), + ); + + $schema['users_roles'] = array( + 'description' => 'Maps users to roles.', + 'fields' => array( + 'uid' => array( + 'type' => 'int', + 'unsigned' => TRUE, + 'not null' => TRUE, + 'default' => 0, + 'description' => 'Primary Key: {users}.uid for user.', + ), + 'rid' => array( + 'type' => 'int', + 'unsigned' => TRUE, + 'not null' => TRUE, + 'default' => 0, + 'description' => 'Primary Key: {role}.rid for role.', + ), + ), + 'primary key' => array('uid', 'rid'), + 'indexes' => array( + 'rid' => array('rid'), + ), + 'foreign keys' => array( + 'user' => array( + 'table' => 'users', + 'columns' => array('uid' => 'uid'), + ), + 'role' => array( + 'table' => 'roles', + 'columns' => array('rid' => 'rid'), + ), + ), + ); + + return $schema; +} + +/** + * Implements hook_install(). + */ +function user_install() { + // Insert a row for the anonymous user. + db_insert('users') + ->fields(array( + 'uid' => 0, + 'name' => '', + 'mail' => '', + )) + ->execute(); + + // We need some placeholders here as name and mail are uniques and data is + // presumed to be a serialized array. This will be changed by the settings + // form in the installer. + db_insert('users') + ->fields(array( + 'uid' => 1, + 'name' => 'placeholder-for-uid-1', + 'mail' => 'placeholder-for-uid-1', + 'created' => REQUEST_TIME, + 'status' => 1, + 'data' => NULL, + )) + ->execute(); + + // Built-in roles. + $rid_anonymous = db_insert('role') + ->fields(array('name' => 'anonymous user', 'weight' => 0)) + ->execute(); + $rid_authenticated = db_insert('role') + ->fields(array('name' => 'authenticated user', 'weight' => 1)) + ->execute(); + + // Sanity check to ensure the anonymous and authenticated role IDs are the + // same as the drupal defined constants. In certain situations, this will + // not be true. + if ($rid_anonymous != DRUPAL_ANONYMOUS_RID) { + db_update('role') + ->fields(array('rid' => DRUPAL_ANONYMOUS_RID)) + ->condition('rid', $rid_anonymous) + ->execute(); + } + if ($rid_authenticated != DRUPAL_AUTHENTICATED_RID) { + db_update('role') + ->fields(array('rid' => DRUPAL_AUTHENTICATED_RID)) + ->condition('rid', $rid_authenticated) + ->execute(); + } +} diff --git a/core/modules/user/user.js b/core/modules/user/user.js new file mode 100644 index 00000000000..44c00f344a0 --- /dev/null +++ b/core/modules/user/user.js @@ -0,0 +1,196 @@ +(function ($) { + +/** + * Attach handlers to evaluate the strength of any password fields and to check + * that its confirmation is correct. + */ +Drupal.behaviors.password = { + attach: function (context, settings) { + var translate = settings.password; + $('input.password-field', context).once('password', function () { + var passwordInput = $(this); + var innerWrapper = $(this).parent(); + var outerWrapper = $(this).parent().parent(); + + // Add identifying class to password element parent. + innerWrapper.addClass('password-parent'); + + // Add the password confirmation layer. + $('input.password-confirm', outerWrapper).parent().prepend('<div class="password-confirm">' + translate['confirmTitle'] + ' <span></span></div>').addClass('confirm-parent'); + var confirmInput = $('input.password-confirm', outerWrapper); + var confirmResult = $('div.password-confirm', outerWrapper); + var confirmChild = $('span', confirmResult); + + // Add the description box. + var passwordMeter = '<div class="password-strength"><div class="password-strength-text" aria-live="assertive"></div><div class="password-strength-title">' + translate['strengthTitle'] + '</div><div class="password-indicator"><div class="indicator"></div></div></div>'; + $(confirmInput).parent().after('<div class="password-suggestions description"></div>'); + $(innerWrapper).prepend(passwordMeter); + var passwordDescription = $('div.password-suggestions', outerWrapper).hide(); + + // Check the password strength. + var passwordCheck = function () { + + // Evaluate the password strength. + var result = Drupal.evaluatePasswordStrength(passwordInput.val(), settings.password); + + // Update the suggestions for how to improve the password. + if (passwordDescription.html() != result.message) { + passwordDescription.html(result.message); + } + + // Only show the description box if there is a weakness in the password. + if (result.strength == 100) { + passwordDescription.hide(); + } + else { + passwordDescription.show(); + } + + // Adjust the length of the strength indicator. + $(innerWrapper).find('.indicator').css('width', result.strength + '%'); + + // Update the strength indication text. + $(innerWrapper).find('.password-strength-text').html(result.indicatorText); + + passwordCheckMatch(); + }; + + // Check that password and confirmation inputs match. + var passwordCheckMatch = function () { + + if (confirmInput.val()) { + var success = passwordInput.val() === confirmInput.val(); + + // Show the confirm result. + confirmResult.css({ visibility: 'visible' }); + + // Remove the previous styling if any exists. + if (this.confirmClass) { + confirmChild.removeClass(this.confirmClass); + } + + // Fill in the success message and set the class accordingly. + var confirmClass = success ? 'ok' : 'error'; + confirmChild.html(translate['confirm' + (success ? 'Success' : 'Failure')]).addClass(confirmClass); + this.confirmClass = confirmClass; + } + else { + confirmResult.css({ visibility: 'hidden' }); + } + }; + + // Monitor keyup and blur events. + // Blur must be used because a mouse paste does not trigger keyup. + passwordInput.keyup(passwordCheck).focus(passwordCheck).blur(passwordCheck); + confirmInput.keyup(passwordCheckMatch).blur(passwordCheckMatch); + }); + } +}; + +/** + * Evaluate the strength of a user's password. + * + * Returns the estimated strength and the relevant output message. + */ +Drupal.evaluatePasswordStrength = function (password, translate) { + var weaknesses = 0, strength = 100, msg = []; + + var hasLowercase = password.match(/[a-z]+/); + var hasUppercase = password.match(/[A-Z]+/); + var hasNumbers = password.match(/[0-9]+/); + var hasPunctuation = password.match(/[^a-zA-Z0-9]+/); + + // If there is a username edit box on the page, compare password to that, otherwise + // use value from the database. + var usernameBox = $('input.username'); + var username = (usernameBox.length > 0) ? usernameBox.val() : translate.username; + + // Lose 5 points for every character less than 6, plus a 30 point penalty. + if (password.length < 6) { + msg.push(translate.tooShort); + strength -= ((6 - password.length) * 5) + 30; + } + + // Count weaknesses. + if (!hasLowercase) { + msg.push(translate.addLowerCase); + weaknesses++; + } + if (!hasUppercase) { + msg.push(translate.addUpperCase); + weaknesses++; + } + if (!hasNumbers) { + msg.push(translate.addNumbers); + weaknesses++; + } + if (!hasPunctuation) { + msg.push(translate.addPunctuation); + weaknesses++; + } + + // Apply penalty for each weakness (balanced against length penalty). + switch (weaknesses) { + case 1: + strength -= 12.5; + break; + + case 2: + strength -= 25; + break; + + case 3: + strength -= 40; + break; + + case 4: + strength -= 40; + break; + } + + // Check if password is the same as the username. + if (password !== '' && password.toLowerCase() === username.toLowerCase()) { + msg.push(translate.sameAsUsername); + // Passwords the same as username are always very weak. + strength = 5; + } + + // Based on the strength, work out what text should be shown by the password strength meter. + if (strength < 60) { + indicatorText = translate.weak; + } else if (strength < 70) { + indicatorText = translate.fair; + } else if (strength < 80) { + indicatorText = translate.good; + } else if (strength <= 100) { + indicatorText = translate.strong; + } + + // Assemble the final message. + msg = translate.hasWeaknesses + '<ul><li>' + msg.join('</li><li>') + '</li></ul>'; + return { strength: strength, message: msg, indicatorText: indicatorText } + +}; + +/** + * Field instance settings screen: force the 'Display on registration form' + * checkbox checked whenever 'Required' is checked. + */ +Drupal.behaviors.fieldUserRegistration = { + attach: function (context, settings) { + var $checkbox = $('form#field-ui-field-edit-form input#edit-instance-settings-user-register-form'); + + if ($checkbox.size()) { + $('input#edit-instance-required', context).once('user-register-form-checkbox', function () { + $(this).bind('change', function (e) { + if ($(this).attr('checked')) { + $checkbox.attr('checked', true); + } + }); + }); + + } + } +}; + +})(jQuery); diff --git a/core/modules/user/user.module b/core/modules/user/user.module new file mode 100644 index 00000000000..bae0ffc332c --- /dev/null +++ b/core/modules/user/user.module @@ -0,0 +1,3897 @@ +<?php + +/** + * @file + * Enables the user registration and login system. + */ + +/** + * Maximum length of username text field. + */ +define('USERNAME_MAX_LENGTH', 60); + +/** + * Maximum length of user e-mail text field. + */ +define('EMAIL_MAX_LENGTH', 254); + +/** + * 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); + +/** + * 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/handbook/modules/user')) . '</p>'; + $output .= '<h3>' . t('Uses') . '</h3>'; + $output .= '<dl>'; + $output .= '<dt>' . t('Creating and managing users') . '</dt>'; + $output .= '<dd>' . t('The User module allows users with the appropriate <a href="@permissions">permissions</a> to create user accounts through the <a href="@people">People administration page</a>, where they can also assign users to one or more roles, and block or delete user accounts. If allowed, users without accounts (anonymous users) can create their own accounts on the <a href="@register">Create new account</a> page.', array('@permissions' => url('admin/people/permissions', array('fragment' => 'module-user')), '@people' => url('admin/people'), '@register' => url('user/register'))) . '</dd>'; + $output .= '<dt>' . t('User roles and permissions') . '</dt>'; + $output .= '<dd>' . t('<em>Roles</em> are used to group and classify users; each user can be assigned one or more roles. By default there are two roles: <em>anonymous user</em> (users that are not logged in) and <em>authenticated user</em> (users that are registered and logged in). Depending on choices you made when you installed Drupal, the installation process may have defined more roles, and you can create additional custom roles on the <a href="@roles">Roles page</a>. After creating roles, you can set permissions for each role on the <a href="@permissions_user">Permissions page</a>. Granting a permission allows users who have been assigned a particular role to perform an action on the site, such as viewing a particular type of content, editing or creating content, administering settings for a particular module, or using a particular function of the site (such as search).', array('@permissions_user' => url('admin/people/permissions'), '@roles' => url('admin/people/permissions/roles'))) . '</dd>'; + $output .= '<dt>' . t('Account settings') . '</dt>'; + $output .= '<dd>' . t('The <a href="@accounts">Account settings page</a> allows you to manage settings for the displayed name of the anonymous user role, personal contact forms, user registration, and account cancellation. On this page you can also manage settings for account personalization (including signatures and user pictures), and adapt the text for the e-mail messages that are sent automatically during the user registration process.', array('@accounts' => url('admin/config/people/accounts'))) . '</dd>'; + $output .= '</dl>'; + return $output; + case 'admin/people/create': + return '<p>' . t("This web page allows administrators to register new users. Users' e-mail addresses and usernames must be unique.") . '</p>'; + case 'admin/people/permissions': + return '<p>' . t('Permissions let you control what users can do and see on your site. You can define a specific set of permissions for each role. (See the <a href="@role">Roles</a> page to create a role). Two important roles to consider are Authenticated Users and Administrators. Any permissions granted to the Authenticated Users role will be given to any user who can log into your site. You can make any role the Administrator role for the site, meaning this will be granted all new permissions automatically. You can do this on the <a href="@settings">User Settings</a> page. You should be careful to ensure that only trusted users are given this access and level of control of your site.', array('@role' => url('admin/people/permissions/roles'), '@settings' => url('admin/config/people/accounts'))) . '</p>'; + case 'admin/people/permissions/roles': + $output = '<p>' . t('Roles allow you to fine tune the security and administration of Drupal. A role defines a group of users that have certain privileges as defined on the <a href="@permissions">permissions page</a>. Examples of roles include: anonymous user, authenticated user, moderator, administrator and so on. In this area you will define the names and order of the roles on your site. It is recommended to order your roles from least permissive (anonymous user) to most permissive (administrator). To delete a role choose "edit role".', array('@permissions' => url('admin/people/permissions'))) . '</p>'; + $output .= '<p>' . t('By default, Drupal comes with two user roles:') . '</p>'; + $output .= '<ul>'; + $output .= '<li>' . t("Anonymous user: this role is used for users that don't have a user account or that are not authenticated.") . '</li>'; + $output .= '<li>' . t('Authenticated user: this role is automatically granted to all logged in users.') . '</li>'; + $output .= '</ul>'; + return $output; + case 'admin/config/people/accounts/fields': + return '<p>' . t('This form lets administrators add, edit, and arrange fields for storing user data.') . '</p>'; + case 'admin/config/people/accounts/display': + return '<p>' . t('This form lets administrators configure how fields should be displayed when rendering a user profile page.') . '</p>'; + case 'admin/people/search': + return '<p>' . t('Enter a simple pattern ("*" may be used as a wildcard match) to search for a username or e-mail address. For example, one may search for "br" and Drupal might return "brian", "brad", and "brenda@example.com".') . '</p>'; + } +} + +/** + * 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: + * - 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. + */ +function user_module_invoke($type, &$edit, $account, $category = NULL) { + foreach (module_implements('user_' . $type) as $module) { + $function = $module . '_user_' . $type; + $function($edit, $account, $category); + } +} + +/** + * Implements hook_theme(). + */ +function user_theme() { + return array( + 'user_picture' => array( + 'variables' => array('account' => NULL), + 'template' => 'user-picture', + ), + 'user_profile' => array( + 'render element' => 'elements', + 'template' => 'user-profile', + 'file' => 'user.pages.inc', + ), + 'user_profile_category' => array( + 'render element' => 'element', + 'template' => 'user-profile-category', + 'file' => 'user.pages.inc', + ), + 'user_profile_item' => array( + 'render element' => 'element', + 'template' => 'user-profile-item', + 'file' => 'user.pages.inc', + ), + 'user_list' => array( + 'variables' => array('users' => NULL, 'title' => NULL), + ), + 'user_admin_permissions' => array( + 'render element' => 'form', + 'file' => 'user.admin.inc', + ), + 'user_admin_roles' => array( + 'render element' => 'form', + 'file' => 'user.admin.inc', + ), + 'user_permission_description' => array( + 'variables' => array('permission_item' => NULL, 'hide' => NULL), + 'file' => 'user.admin.inc', + ), + 'user_signature' => array( + 'variables' => array('signature' => NULL), + ), + ); +} + +/** + * Implements hook_entity_info(). + */ +function user_entity_info() { + $return = array( + 'user' => array( + 'label' => t('User'), + 'controller class' => 'UserController', + 'base table' => 'users', + 'uri callback' => 'user_uri', + 'label callback' => 'user_label', + 'fieldable' => TRUE, + 'entity keys' => array( + 'id' => 'uid', + ), + 'bundles' => array( + 'user' => array( + 'label' => t('User'), + 'admin' => array( + 'path' => 'admin/config/people/accounts', + 'access arguments' => array('administer users'), + ), + ), + ), + 'view modes' => array( + 'full' => array( + 'label' => t('User account'), + 'custom settings' => FALSE, + ), + ), + ), + ); + return $return; +} + +/** + * Entity uri callback. + */ +function user_uri($user) { + return array( + 'path' => 'user/' . $user->uid, + ); +} + +/** + * Entity label callback. + * + * @param $entity_type + * The entity type. + * @param $entity + * The entity object. + * + * @return + * The name of the user. + * + * @see format_username + */ +function user_label($entity_type, $entity) { + return format_username($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( + '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, + ), + 'timezone' => array( + 'label' => t('Timezone'), + 'description' => t('User module timezone form element.'), + 'weight' => 6, + ), + ), + 'display' => array( + 'summary' => array( + 'label' => t('History'), + 'description' => t('User module history view element.'), + 'weight' => 5, + ), + ), + ); + + return $return; +} + +/** + * 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. + */ +function user_external_load($authname) { + $uid = db_query("SELECT uid FROM {authmap} WHERE authname = :authname", array(':authname' => $authname))->fetchField(); + + if ($uid) { + return user_load($uid); + } + else { + return FALSE; + } +} + +/** + * 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 in Drupal 8. + */ +function user_load_multiple($uids = array(), $conditions = array(), $reset = FALSE) { + return entity_load('user', $uids, $conditions, $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. + * + * @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 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. + * @param $edit + * 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. + */ +function user_save($account, $edit = array(), $category = 'account') { + $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']); + } + + // Load the stored entity, if any. + if (!empty($account->uid) && !isset($account->original)) { + $account->original = entity_load_unchanged('user', $account->uid); + } + + if (empty($account)) { + $account = new stdClass(); + } + if (!isset($account->is_new)) { + $account->is_new = empty($account->uid); + } + // 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; + } + + // Invoke hook_user_presave() for all modules. + user_module_invoke('presave', $edit, $account, $category); + + // Invoke presave operations of Field Attach API and Entity API. Those APIs + // 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) { + $account->$key = $value; + } + field_attach_presave('user', $account); + module_invoke_all('entity_presave', $account, 'user'); + + if (is_object($account) && !$account->is_new) { + // Process picture uploads. + if (!empty($account->picture->fid) && (!isset($account->original->picture->fid) || $account->picture->fid != $account->original->picture->fid)) { + $picture = $account->picture; + // If the picture is a temporary file move it to its final location and + // make it permanent. + if (!$picture->status) { + $info = image_get_info($picture->uri); + $picture_directory = file_default_scheme() . '://' . variable_get('user_picture_path', 'pictures'); + + // Prepare the pictures directory. + file_prepare_directory($picture_directory, FILE_CREATE_DIRECTORY); + $destination = file_stream_wrapper_uri_normalize($picture_directory . '/picture-' . $account->uid . '-' . REQUEST_TIME . '.' . $info['extension']); + + // Move the temporary file into the final location. + if ($picture = file_move($picture, $destination, FILE_EXISTS_RENAME)) { + $picture->status = FILE_STATUS_PERMANENT; + $account->picture = file_save($picture); + file_usage_add($picture, 'user', 'user', $account->uid); + } + } + // 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); + } + } + $account->picture = empty($account->picture->fid) ? 0 : $account->picture->fid; + + // Do not allow 'uid' to be changed. + $account->uid = $account->original->uid; + // Save changes to the user table. + $success = drupal_write_record('users', $account, 'uid'); + if ($success === FALSE) { + // The query failed - better to abort the save than risk further + // data loss. + return FALSE; + } + + // Reload user roles if provided. + if ($account->roles != $account->original->roles) { + db_delete('users_roles') + ->condition('uid', $account->uid) + ->execute(); + + $query = db_insert('users_roles')->fields(array('uid', 'rid')); + foreach (array_keys($account->roles) as $rid) { + if (!in_array($rid, array(DRUPAL_ANONYMOUS_RID, DRUPAL_AUTHENTICATED_RID))) { + $query->values(array( + 'uid' => $account->uid, + 'rid' => $rid, + )); + } + } + $query->execute(); + } + + // Delete a blocked user's sessions to kick them if they are online. + if ($account->original->status != $account->status && $account->status == 0) { + drupal_session_destroy_uid($account->uid); + } + + // If the password changed, delete all open sessions and recreate + // the current one. + if ($account->pass != $account->original->pass) { + drupal_session_destroy_uid($account->uid); + if ($account->uid == $GLOBALS['user']->uid) { + drupal_session_regenerate(); + } + } + + // Save Field data. + field_attach_update('user', $account); + + // Send emails after we have the new user object. + if ($account->status != $account->original->status) { + // The user's status is changing; conditionally send notification email. + $op = $account->status == 1 ? 'status_activated' : 'status_blocked'; + _user_mail_notify($op, $account); + } + + // 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'); + } + 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. + if (empty($account->uid)) { + $account->uid = db_next_id(db_query('SELECT MAX(uid) FROM {users}')->fetchField()); + } + // Allow 'created' to be set by the caller. + if (!isset($account->created)) { + $account->created = REQUEST_TIME; + } + $success = drupal_write_record('users', $account); + 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; + } + + // Make sure $account is properly initialized. + $account->roles[DRUPAL_AUTHENTICATED_RID] = 'authenticated user'; + + field_attach_insert('user', $account); + $edit = (array) $account; + user_module_invoke('insert', $edit, $account, $category); + module_invoke_all('entity_insert', $account, 'user'); + + // Save user roles. + if (count($account->roles) > 1) { + $query = db_insert('users_roles')->fields(array('uid', 'rid')); + foreach (array_keys($account->roles) as $rid) { + if (!in_array($rid, array(DRUPAL_ANONYMOUS_RID, DRUPAL_AUTHENTICATED_RID))) { + $query->values(array( + 'uid' => $account->uid, + 'rid' => $rid, + )); + } + } + $query->execute(); + } + } + // Clear internal properties. + unset($account->is_new); + unset($account->original); + // Clear the static loading cache. + entity_get_controller('user')->resetCache(array($account->uid)); + + return $account; + } + catch (Exception $e) { + $transaction->rollback(); + watchdog_exception('user', $e); + throw $e; + } +} + +/** + * 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}' . // 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. + */ +function user_validate_mail($mail) { + if (!$mail) { + return t('You must enter an e-mail address.'); + } + if (!valid_email_address($mail)) { + return t('The e-mail address %mail is not valid.', array('%mail' => $mail)); + } +} + +/** + * Validates an image uploaded by a user. + * + * @see user_account_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; + } +} + +/** + * 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 + // 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)]; + } + + return $pass; +} + +/** + * 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. + * + * @return + * 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) { + global $user; + + if (!isset($account)) { + $account = $user; + } + + // User #1 has all privileges: + if ($account->uid == 1) { + 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. + static $drupal_static_fast; + if (!isset($drupal_static_fast)) { + $drupal_static_fast['perm'] = &drupal_static(__FUNCTION__); + } + $perm = &$drupal_static_fast['perm']; + if (!isset($perm[$account->uid])) { + $role_permissions = user_role_permissions($account->roles); + + $perms = array(); + foreach ($role_permissions as $one_role) { + $perms += $one_role; + } + $perm[$account->uid] = $perms; + } + + return isset($perm[$account->uid][$string]); +} + +/** + * Checks for usernames blocked by user administration. + * + * @return boolean TRUE for blocked users, FALSE for active. + */ +function user_is_blocked($name) { + return db_select('users') + ->fields('users', array('name')) + ->condition('name', db_like($name), 'LIKE') + ->condition('status', 0) + ->execute()->fetchObject(); +} + +/** + * Implements hook_permission(). + */ +function user_permission() { + return array( + 'administer permissions' => array( + 'title' => t('Administer permissions'), + 'restrict access' => TRUE, + ), + 'administer users' => array( + 'title' => t('Administer users'), + 'restrict access' => TRUE, + ), + 'access user profiles' => array( + 'title' => t('View user profiles'), + ), + 'change own username' => array( + 'title' => t('Change own username'), + ), + 'cancel account' => array( + 'title' => t('Cancel own user account'), + 'description' => t('Note: content may be kept, unpublished, deleted or transferred to the %anonymous-name user depending on the configured <a href="@user-settings-url">user settings</a>.', array('%anonymous-name' => variable_get('anonymous', t('Anonymous')), '@user-settings-url' => url('admin/config/people/accounts'))), + ), + 'select account cancellation method' => array( + 'title' => t('Select method for cancelling own account'), + 'restrict access' => TRUE, + ), + ); +} + +/** + * Implements hook_file_download(). + * + * 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']); + } +} + +/** + * Implements hook_file_move(). + */ +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(); + } +} + +/** + * Implements hook_file_delete(). + */ +function user_file_delete($file) { + // Remove any references to the file. + db_update('users') + ->fields(array('picture' => 0)) + ->condition('picture', $file->fid) + ->execute(); +} + +/** + * Implements hook_search_info(). + */ +function user_search_info() { + return array( + 'title' => 'Users', + ); +} + +/** + * 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(); + // Replace wildcards with MySQL/PostgreSQL wildcards. + $keys = preg_replace('!\*+!', '%', $keys); + $query = db_select('users')->extend('PagerDefault'); + $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')); + $query->condition(db_or()-> + condition('name', '%' . db_like($keys) . '%', 'LIKE')-> + condition('mail', '%' . db_like($keys) . '%', 'LIKE')); + } + else { + $query->condition('name', '%' . db_like($keys) . '%', 'LIKE'); + } + $uids = $query + ->limit(15) + ->execute() + ->fetchCol(); + $accounts = user_load_multiple($uids); + + $results = array(); + foreach ($accounts as $account) { + $result = array( + 'title' => format_username($account), + 'link' => url('user/' . $account->uid, array('absolute' => TRUE)), + ); + if (user_access('administer users')) { + $result['title'] .= ' (' . $account->mail . ')'; + } + $results[] = $result; + } + + return $results; +} + +/** + * Implements hook_element_info(). + */ +function user_element_info() { + $types['user_profile_category'] = array( + '#theme_wrappers' => array('user_profile_category'), + ); + $types['user_profile_item'] = array( + '#theme' => 'user_profile_item', + ); + return $types; +} + +/** + * Implements hook_user_view(). + */ +function user_user_view($account) { + $account->content['user_picture'] = array( + '#markup' => theme('user_picture', array('account' => $account)), + '#weight' => -10, + ); + if (!isset($account->content['summary'])) { + $account->content['summary'] = array(); + } + $account->content['summary'] += array( + '#type' => 'user_profile_category', + '#attributes' => array('class' => array('user-member')), + '#weight' => 5, + '#title' => t('History'), + ); + $account->content['summary']['member_for'] = array( + '#type' => 'user_profile_item', + '#title' => t('Member for'), + '#markup' => format_interval(REQUEST_TIME - $account->created), + ); +} + +/** + * 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() + */ +function user_account_form(&$form, &$form_state) { + global $user; + + $account = $form['#user']; + $register = ($form['#user']->uid > 0 ? FALSE : TRUE); + + $admin = user_access('administer users'); + + $form['#validate'][] = 'user_account_form_validate'; + + // Account information. + $form['account'] = array( + '#type' => 'container', + '#weight' => -10, + ); + // Only show name field on registration form or user can change own username. + $form['account']['name'] = array( + '#type' => 'textfield', + '#title' => t('Username'), + '#maxlength' => USERNAME_MAX_LENGTH, + '#description' => t('Spaces are allowed; punctuation is not allowed except for periods, hyphens, apostrophes, and underscores.'), + '#required' => TRUE, + '#attributes' => array('class' => array('username')), + '#default_value' => (!$register ? $account->name : ''), + '#access' => ($register || ($user->uid == $account->uid && user_access('change own username')) || $admin), + '#weight' => -10, + ); + + $form['account']['mail'] = array( + '#type' => 'textfield', + '#title' => t('E-mail address'), + '#maxlength' => EMAIL_MAX_LENGTH, + '#description' => t('A valid e-mail address. All e-mails from the system will be sent to this address. The e-mail address is not made public and will only be used if you wish to receive a new password or wish to receive certain news or notifications by e-mail.'), + '#required' => TRUE, + '#default_value' => (!$register ? $account->mail : ''), + ); + + // Display password field only for existing users or when user is allowed to + // assign a password during registration. + if (!$register) { + $form['account']['pass'] = array( + '#type' => 'password_confirm', + '#size' => 25, + '#description' => t('To change the current user password, enter the new password in both fields.'), + ); + // To skip the current password field, the user must have logged in via a + // one-time link and have the token in the URL. + $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 = ''; + // The user may only change their own password without their current + // password if they logged in via a one-time login link. + if (!$pass_reset) { + $protected_values['mail'] = $form['account']['mail']['#title']; + $protected_values['pass'] = t('Password'); + $request_new = l(t('Request new password'), 'user/password', array('attributes' => array('title' => t('Request new password via e-mail.')))); + $current_pass_description = t('Enter your current password to change the %mail or %pass. !request_new.', array('%mail' => $protected_values['mail'], '%pass' => $protected_values['pass'], '!request_new' => $request_new)); + } + // The user must enter their current password to change to a new one. + if ($user->uid == $account->uid) { + $form['account']['current_pass_required_values'] = array( + '#type' => 'value', + '#value' => $protected_values, + ); + $form['account']['current_pass'] = array( + '#type' => 'password', + '#title' => t('Current password'), + '#size' => 25, + '#access' => !empty($protected_values), + '#description' => $current_pass_description, + '#weight' => -5, + '#attributes' => array('autocomplete' => 'off'), + ); + $form['#validate'][] = 'user_validate_current_pass'; + } + } + elseif (!variable_get('user_email_verification', TRUE) || $admin) { + $form['account']['pass'] = array( + '#type' => 'password_confirm', + '#size' => 25, + '#description' => t('Provide a password for the new account in both fields.'), + '#required' => TRUE, + ); + } + + if ($admin) { + $status = isset($account->status) ? $account->status : 1; + } + else { + $status = $register ? variable_get('user_register', USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL) == USER_REGISTER_VISITORS : $account->status; + } + $form['account']['status'] = array( + '#type' => 'radios', + '#title' => t('Status'), + '#default_value' => $status, + '#options' => array(t('Blocked'), t('Active')), + '#access' => $admin, + ); + + $roles = array_map('check_plain', user_roles(TRUE)); + // The disabled checkbox subelement for the 'authenticated user' role + // must be generated separately and added to the checkboxes element, + // because of a limitation in Form API not supporting a single disabled + // checkbox within a set of checkboxes. + // @todo This should be solved more elegantly. See issue #119038. + $checkbox_authenticated = array( + '#type' => 'checkbox', + '#title' => $roles[DRUPAL_AUTHENTICATED_RID], + '#default_value' => TRUE, + '#disabled' => TRUE, + ); + unset($roles[DRUPAL_AUTHENTICATED_RID]); + $form['account']['roles'] = array( + '#type' => 'checkboxes', + '#title' => t('Roles'), + '#default_value' => (!$register && isset($account->roles) ? array_keys($account->roles) : array()), + '#options' => $roles, + '#access' => $roles && user_access('administer permissions'), + DRUPAL_AUTHENTICATED_RID => $checkbox_authenticated, + ); + + $form['account']['notify'] = array( + '#type' => 'checkbox', + '#title' => t('Notify user of new account'), + '#access' => $register && $admin, + ); + + // Signature. + $form['signature_settings'] = array( + '#type' => 'fieldset', + '#title' => t('Signature settings'), + '#weight' => 1, + '#access' => (!$register && variable_get('user_signatures', 0)), + ); + + $form['signature_settings']['signature'] = array( + '#type' => 'text_format', + '#title' => t('Signature'), + '#default_value' => isset($account->signature) ? $account->signature : '', + '#description' => t('Your signature will be publicly displayed at the end of your comments.'), + '#format' => isset($account->signature_format) ? $account->signature_format : NULL, + ); + + // Picture/avatar. + $form['picture'] = array( + '#type' => 'fieldset', + '#title' => t('Picture'), + '#weight' => 1, + '#access' => (!$register && variable_get('user_pictures', 0)), + ); + $form['picture']['picture'] = array( + '#type' => 'value', + '#value' => isset($account->picture) ? $account->picture : NULL, + ); + $form['picture']['picture_current'] = array( + '#markup' => theme('user_picture', array('account' => $account)), + ); + $form['picture']['picture_delete'] = array( + '#type' => 'checkbox', + '#title' => t('Delete picture'), + '#access' => !empty($account->picture->fid), + '#description' => t('Check this box to delete your current picture.'), + ); + $form['picture']['picture_upload'] = array( + '#type' => 'file', + '#title' => t('Upload picture'), + '#size' => 48, + '#description' => t('Your virtual face or picture. Pictures larger than @dimensions pixels will be scaled down.', array('@dimensions' => variable_get('user_picture_dimensions', '85x85'))) . ' ' . filter_xss_admin(variable_get('user_picture_guidelines', '')), + ); + $form['#validate'][] = 'user_validate_picture'; +} + +/** + * 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) { + // 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', '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 validation handler for user_account_form(). + * + * @see user_account_form() + */ +function user_account_form_validate($form, &$form_state) { + if ($form['#user_category'] == 'account' || $form['#user_category'] == 'register') { + $account = $form['#user']; + // Validate new or changing username. + if (isset($form_state['values']['name'])) { + if ($error = user_validate_name($form_state['values']['name'])) { + form_set_error('name', $error); + } + elseif ((bool) db_select('users')->fields('users', array('uid'))->condition('uid', $account->uid, '<>')->condition('name', db_like($form_state['values']['name']), 'LIKE')->range(0, 1)->execute()->fetchField()) { + form_set_error('name', t('The name %name is already taken.', array('%name' => $form_state['values']['name']))); + } + } + + // Trim whitespace from mail, to prevent confusing 'e-mail not valid' + // warnings often caused by cutting and pasting. + $mail = trim($form_state['values']['mail']); + form_set_value($form['account']['mail'], $mail, $form_state); + + // Validate the e-mail address, and check if it is taken by an existing user. + if ($error = user_validate_mail($form_state['values']['mail'])) { + form_set_error('mail', $error); + } + elseif ((bool) db_select('users')->fields('users', array('uid'))->condition('uid', $account->uid, '<>')->condition('mail', db_like($form_state['values']['mail']), 'LIKE')->range(0, 1)->execute()->fetchField()) { + // Format error message dependent on whether the user is logged in or not. + if ($GLOBALS['user']->uid) { + form_set_error('mail', t('The e-mail address %email is already taken.', array('%email' => $form_state['values']['mail']))); + } + else { + form_set_error('mail', t('The e-mail address %email is already registered. <a href="@password">Have you forgotten your password?</a>', array('%email' => $form_state['values']['mail'], '@password' => url('user/password')))); + } + } + + // Make sure the signature isn't longer than the size of the database field. + // Signatures are disabled by default, so make sure it exists first. + if (isset($form_state['values']['signature'])) { + // Move text format for user signature into 'signature_format'. + $form_state['values']['signature_format'] = $form_state['values']['signature']['format']; + // Move text value for user signature into 'signature'. + $form_state['values']['signature'] = $form_state['values']['signature']['value']; + + $user_schema = drupal_get_schema('users'); + if (drupal_strlen($form_state['values']['signature']) > $user_schema['fields']['signature']['length']) { + form_set_error('signature', t('The signature is too long: it must be %max characters or less.', array('%max' => $user_schema['fields']['signature']['length']))); + } + } + } +} + +/** + * Implements hook_user_presave(). + */ +function user_user_presave(&$edit, $account, $category) { + if ($category == 'account' || $category == 'register') { + if (!empty($edit['picture_upload'])) { + $edit['picture'] = $edit['picture_upload']; + } + // Delete picture if requested, and if no replacement picture was given. + elseif (!empty($edit['picture_delete'])) { + $edit['picture'] = NULL; + } + // Prepare user roles. + if (isset($edit['roles'])) { + $edit['roles'] = array_filter($edit['roles']); + } + } + + // Move account cancellation information into $user->data. + foreach (array('user_cancel_method', 'user_cancel_notify') as $key) { + if (isset($edit[$key])) { + $edit['data'][$key] = $edit[$key]; + } + } +} + +/** + * Implements hook_user_categories(). + */ +function user_user_categories() { + return array(array( + 'name' => 'account', + 'title' => t('Account settings'), + 'weight' => 1, + )); +} + +function user_login_block($form) { + $form['#action'] = url($_GET['q'], array('query' => drupal_get_destination())); + $form['#id'] = 'user-login-form'; + $form['#validate'] = user_login_default_validators(); + $form['#submit'][] = 'user_login_submit'; + $form['name'] = array('#type' => 'textfield', + '#title' => t('Username'), + '#maxlength' => USERNAME_MAX_LENGTH, + '#size' => 15, + '#required' => TRUE, + ); + $form['pass'] = array('#type' => 'password', + '#title' => t('Password'), + '#maxlength' => 60, + '#size' => 15, + '#required' => TRUE, + ); + $form['actions'] = array('#type' => 'actions'); + $form['actions']['submit'] = array('#type' => 'submit', + '#value' => t('Log in'), + ); + $items = array(); + if (variable_get('user_register', USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL)) { + $items[] = l(t('Create new account'), 'user/register', array('attributes' => array('title' => t('Create a new user account.')))); + } + $items[] = l(t('Request new password'), 'user/password', array('attributes' => array('title' => t('Request new password via e-mail.')))); + $form['links'] = array('#markup' => theme('item_list', array('items' => $items))); + return $form; +} + +/** + * Implements hook_block_info(). + */ +function user_block_info() { + global $user; + + $blocks['login']['info'] = t('User login'); + // Not worth caching. + $blocks['login']['cache'] = DRUPAL_NO_CACHE; + + $blocks['new']['info'] = t('Who\'s new'); + $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; + + return $blocks; +} + +/** + * Implements hook_block_configure(). + */ +function user_block_configure($delta = '') { + global $user; + + switch ($delta) { + case 'new': + $form['user_block_whois_new_count'] = array( + '#type' => 'select', + '#title' => t('Number of users to display'), + '#default_value' => variable_get('user_block_whois_new_count', 5), + '#options' => drupal_map_assoc(array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)), + ); + return $form; + + case 'online': + $period = drupal_map_assoc(array(30, 60, 120, 180, 300, 600, 900, 1800, 2700, 3600, 5400, 7200, 10800, 21600, 43200, 86400), 'format_interval'); + $form['user_block_seconds_online'] = array('#type' => 'select', '#title' => t('User activity'), '#default_value' => variable_get('user_block_seconds_online', 900), '#options' => $period, '#description' => t('A user is considered online for this long after they have last viewed a page.')); + $form['user_block_max_list_count'] = array('#type' => 'select', '#title' => t('User list length'), '#default_value' => variable_get('user_block_max_list_count', 10), '#options' => drupal_map_assoc(array(0, 5, 10, 15, 20, 25, 30, 40, 50, 75, 100)), '#description' => t('Maximum number of currently online users to display.')); + return $form; + } +} + +/** + * Implements hook_block_save(). + */ +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; + } +} + +/** + * Implements hook_block_view(). + */ +function user_block_view($delta = '') { + global $user; + + $block = array(); + + 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['subject'] = t('User login'); + $block['content'] = drupal_get_form('user_login_block'); + } + return $block; + + 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; + + case 'online': + if (user_access('access content')) { + // Count users active within the defined period. + $interval = REQUEST_TIME - variable_get('user_block_seconds_online', 900); + + // 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; + } +} + +/** + * 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) { + $variables['user_picture'] = ''; + if (variable_get('user_pictures', 0)) { + $account = $variables['account']; + if (!empty($account->picture)) { + // @TODO: Ideally this function would only be passed file objects, 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; + } + } + elseif (variable_get('user_picture_default', '')) { + $filepath = variable_get('user_picture_default', ''); + } + if (isset($filepath)) { + $alt = t("@user's picture", array('@user' => format_username($account))); + // If 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, 'path' => $filepath, 'alt' => $alt, 'title' => $alt)); + } + else { + $variables['user_picture'] = theme('image', array('path' => $filepath, 'alt' => $alt, 'title' => $alt)); + } + if (!empty($account->uid) && user_access('access user profiles')) { + $attributes = array('attributes' => array('title' => t('View user profile.')), 'html' => TRUE); + $variables['user_picture'] = l($variables['user_picture'], "user/$account->uid", $attributes); + } + } + } +} + +/** + * Returns HTML for a list of users. + * + * @param $variables + * An associative array containing: + * - users: An array with user objects. Should contain at least the name and + * uid. + * - title: (optional) Title to pass on to theme_item_list(). + * + * @ingroup themeable + */ +function theme_user_list($variables) { + $users = $variables['users']; + $title = $variables['title']; + $items = array(); + + if (!empty($users)) { + foreach ($users as $user) { + $items[] = theme('username', array('account' => $user)); + } + } + return theme('item_list', array('items' => $items, 'title' => $title)); +} + +function user_is_anonymous() { + // Menu administrators can see items for anonymous when administering. + return !$GLOBALS['user']->uid || !empty($GLOBALS['menu_admin']); +} + +function user_is_logged_in() { + return (bool) $GLOBALS['user']->uid; +} + +function user_register_access() { + return user_is_anonymous() && variable_get('user_register', USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL); +} + +/** + * User view access callback. + * + * @param $account + * Can either be a full user object or a $uid. + */ +function user_view_access($account) { + $uid = is_object($account) ? $account->uid : (int) $account; + + // Never allow access to view the anonymous user account. + if ($uid) { + // Admins can view all, users can view own profiles at all times. + if ($GLOBALS['user']->uid == $uid || user_access('administer users')) { + return TRUE; + } + elseif (user_access('access user profiles')) { + // At this point, load the complete account object. + if (!is_object($account)) { + $account = user_load($uid); + } + return (is_object($account) && $account->status); + } + } + return FALSE; +} + +/** + * Access callback for user account editing. + */ +function user_edit_access($account) { + return (($GLOBALS['user']->uid == $account->uid) || user_access('administer users')) && $account->uid > 0; +} + +/** + * 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) { + return ((($GLOBALS['user']->uid == $account->uid) && user_access('cancel account')) || user_access('administer users')) && $account->uid > 0; +} + +/** + * Implements hook_menu(). + */ +function user_menu() { + $items['user/autocomplete'] = array( + 'title' => 'User autocomplete', + 'page callback' => 'user_autocomplete', + 'access callback' => 'user_access', + 'access arguments' => array('access user profiles'), + 'type' => MENU_CALLBACK, + 'file' => 'user.pages.inc', + ); + + // Registration and login pages. + $items['user'] = array( + 'title' => 'User account', + 'title callback' => 'user_menu_title', + 'page callback' => 'user_page', + 'access callback' => TRUE, + 'file' => 'user.pages.inc', + 'weight' => -10, + 'menu_name' => 'user-menu', + ); + + $items['user/login'] = array( + 'title' => 'Log in', + 'access callback' => 'user_is_anonymous', + 'type' => MENU_DEFAULT_LOCAL_TASK, + ); + + $items['user/register'] = array( + 'title' => 'Create new account', + 'page callback' => 'drupal_get_form', + 'page arguments' => array('user_register_form'), + 'access callback' => 'user_register_access', + 'type' => MENU_LOCAL_TASK, + ); + + $items['user/password'] = array( + 'title' => 'Request new password', + 'page callback' => 'drupal_get_form', + 'page arguments' => array('user_pass'), + 'access callback' => TRUE, + 'type' => MENU_LOCAL_TASK, + 'file' => 'user.pages.inc', + ); + $items['user/reset/%/%/%'] = array( + 'title' => 'Reset password', + 'page callback' => 'drupal_get_form', + 'page arguments' => array('user_pass_reset', 2, 3, 4), + 'access callback' => TRUE, + 'type' => MENU_CALLBACK, + 'file' => 'user.pages.inc', + ); + + $items['user/logout'] = array( + 'title' => 'Log out', + 'access callback' => 'user_is_logged_in', + 'page callback' => 'user_logout', + 'weight' => 10, + 'menu_name' => 'user-menu', + 'file' => 'user.pages.inc', + ); + + // User listing pages. + $items['admin/people'] = array( + 'title' => 'People', + 'description' => 'Manage user accounts, roles, and permissions.', + 'page callback' => 'user_admin', + 'page arguments' => array('list'), + 'access arguments' => array('administer users'), + 'position' => 'left', + 'weight' => -4, + 'file' => 'user.admin.inc', + ); + $items['admin/people/people'] = array( + 'title' => 'List', + 'description' => 'Find and manage people interacting with your site.', + 'access arguments' => array('administer users'), + 'type' => MENU_DEFAULT_LOCAL_TASK, + 'weight' => -10, + 'file' => 'user.admin.inc', + ); + + // Permissions and role forms. + $items['admin/people/permissions'] = array( + 'title' => 'Permissions', + 'description' => 'Determine access to features by selecting permissions for roles.', + 'page callback' => 'drupal_get_form', + 'page arguments' => array('user_admin_permissions'), + 'access arguments' => array('administer permissions'), + 'file' => 'user.admin.inc', + 'type' => MENU_LOCAL_TASK, + ); + $items['admin/people/permissions/list'] = array( + 'title' => 'Permissions', + 'description' => 'Determine access to features by selecting permissions for roles.', + 'type' => MENU_DEFAULT_LOCAL_TASK, + 'weight' => -8, + ); + $items['admin/people/permissions/roles'] = array( + 'title' => 'Roles', + 'description' => 'List, edit, or add user roles.', + 'page callback' => 'drupal_get_form', + 'page arguments' => array('user_admin_roles'), + 'access arguments' => array('administer permissions'), + 'file' => 'user.admin.inc', + 'type' => MENU_LOCAL_TASK, + 'weight' => -5, + ); + $items['admin/people/permissions/roles/edit/%user_role'] = array( + 'title' => 'Edit role', + 'page arguments' => array('user_admin_role', 5), + 'access callback' => 'user_role_edit_access', + 'access arguments' => array(5), + ); + $items['admin/people/permissions/roles/delete/%user_role'] = array( + 'title' => 'Delete role', + 'page callback' => 'drupal_get_form', + 'page arguments' => array('user_admin_role_delete_confirm', 5), + 'access callback' => 'user_role_edit_access', + 'access arguments' => array(5), + 'file' => 'user.admin.inc', + ); + + $items['admin/people/create'] = array( + 'title' => 'Add user', + 'page arguments' => array('create'), + 'access arguments' => array('administer users'), + 'type' => MENU_LOCAL_ACTION, + ); + + // Administration pages. + $items['admin/config/people'] = array( + 'title' => 'People', + 'description' => 'Configure user accounts.', + 'position' => 'left', + 'weight' => -20, + 'page callback' => 'system_admin_menu_block_page', + 'access arguments' => array('access administration pages'), + 'file' => 'system.admin.inc', + 'file path' => drupal_get_path('module', 'system'), + ); + $items['admin/config/people/accounts'] = array( + 'title' => 'Account settings', + 'description' => 'Configure default behavior of users, including registration requirements, e-mails, fields, and user pictures.', + 'page callback' => 'drupal_get_form', + 'page arguments' => array('user_admin_settings'), + 'access arguments' => array('administer users'), + 'file' => 'user.admin.inc', + 'weight' => -10, + ); + $items['admin/config/people/accounts/settings'] = array( + 'title' => 'Settings', + 'type' => MENU_DEFAULT_LOCAL_TASK, + 'weight' => -10, + ); + + $items['user/%user'] = array( + 'title' => 'My account', + 'title callback' => 'user_page_title', + 'title arguments' => array(1), + 'page callback' => 'user_view_page', + 'page arguments' => array(1), + 'access callback' => 'user_view_access', + 'access arguments' => array(1), + // By assigning a different menu name, this item (and all registered child + // paths) are no longer considered as children of 'user'. When accessing the + // user account pages, the preferred menu link that is used to build the + // active trail (breadcrumb) will be found in this menu (unless there is + // more specific link), so the link to 'user' will not be in the breadcrumb. + 'menu_name' => 'navigation', + ); + + $items['user/%user/view'] = array( + 'title' => 'View', + 'type' => MENU_DEFAULT_LOCAL_TASK, + 'weight' => -10, + ); + + $items['user/%user/cancel'] = array( + 'title' => 'Cancel account', + 'page callback' => 'drupal_get_form', + 'page arguments' => array('user_cancel_confirm_form', 1), + 'access callback' => 'user_cancel_access', + 'access arguments' => array(1), + 'file' => 'user.pages.inc', + ); + + $items['user/%user/cancel/confirm/%/%'] = array( + 'title' => 'Confirm account cancellation', + 'page callback' => 'user_cancel_confirm', + 'page arguments' => array(1, 4, 5), + 'access callback' => 'user_cancel_access', + 'access arguments' => array(1), + 'file' => 'user.pages.inc', + ); + + $items['user/%user/edit'] = array( + 'title' => 'Edit', + 'page callback' => 'drupal_get_form', + 'page arguments' => array('user_profile_form', 1), + 'access callback' => 'user_edit_access', + 'access arguments' => array(1), + 'type' => MENU_LOCAL_TASK, + 'file' => 'user.pages.inc', + ); + + $items['user/%user_category/edit/account'] = array( + 'title' => 'Account', + 'type' => MENU_DEFAULT_LOCAL_TASK, + 'load arguments' => array('%map', '%index'), + ); + + if (($categories = _user_categories()) && (count($categories) > 1)) { + foreach ($categories as $key => $category) { + // 'account' is already handled by the MENU_DEFAULT_LOCAL_TASK. + if ($category['name'] != 'account') { + $items['user/%user_category/edit/' . $category['name']] = array( + 'title callback' => 'check_plain', + 'title arguments' => array($category['title']), + 'page callback' => 'drupal_get_form', + 'page arguments' => array('user_profile_form', 1, 3), + 'access callback' => isset($category['access callback']) ? $category['access callback'] : 'user_edit_access', + 'access arguments' => isset($category['access arguments']) ? $category['access arguments'] : array(1), + 'type' => MENU_LOCAL_TASK, + 'weight' => $category['weight'], + 'load arguments' => array('%map', '%index'), + 'tab_parent' => 'user/%/edit', + 'file' => 'user.pages.inc', + ); + } + } + } + return $items; +} + +/** + * Implements hook_menu_site_status_alter(). + */ +function user_menu_site_status_alter(&$menu_site_status, $path) { + if ($menu_site_status == MENU_SITE_OFFLINE) { + // If the site is offline, log out unprivileged users. + 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': + // Forward anonymous user to login page. + drupal_goto('user/login'); + case 'user/login': + case 'user/password': + // Disable offline mode. + $menu_site_status = MENU_SITE_ONLINE; + break; + default: + if (strpos($path, 'user/reset/') === 0) { + // Disable offline mode. + $menu_site_status = MENU_SITE_ONLINE; + } + break; + } + } + } + if (user_is_logged_in()) { + if ($path == 'user/login') { + // If user is logged in, redirect to 'user' instead of giving 403. + drupal_goto('user'); + } + if ($path == 'user/register') { + // Authenticated user should be redirected to user edit page. + drupal_goto('user/' . $GLOBALS['user']->uid . '/edit'); + } + } +} + +/** + * Implements hook_menu_link_alter(). + */ +function user_menu_link_alter(&$link) { + // The path 'user' must be accessible for anonymous users, but only visible + // for authenticated users. Authenticated users should see "My account", but + // anonymous users should not see it at all. Therefore, invoke + // user_translated_menu_link_alter() to conditionally hide the link. + if ($link['link_path'] == 'user' && $link['module'] == 'system') { + $link['options']['alter'] = TRUE; + } + + // Force the Logout link to appear on the top-level of 'user-menu' menu by + // default (i.e., unless it has been customized). + if ($link['link_path'] == 'user/logout' && $link['module'] == 'system' && empty($link['customized'])) { + $link['plid'] = 0; + } +} + +/** + * Implements hook_translated_menu_link_alter(). + */ +function user_translated_menu_link_alter(&$link) { + // Hide the "User account" link for anonymous users. + if ($link['link_path'] == 'user' && $link['module'] == 'system' && user_is_anonymous()) { + $link['hidden'] = 1; + } +} + +/** + * Implements hook_admin_paths(). + */ +function user_admin_paths() { + $paths = array( + 'user/*/cancel' => TRUE, + 'user/*/edit' => TRUE, + 'user/*/edit/*' => TRUE, + ); + return $paths; +} + +/** + * Returns $arg or the user ID of the current user if $arg is '%' or empty. + * + * Deprecated. Use %user_uid_optional instead. + * + * @todo D8: Remove. + */ +function user_uid_only_optional_to_arg($arg) { + return user_uid_optional_to_arg($arg); +} + +/** + * 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 in Drupal 8. + */ +function user_uid_optional_load($uid = NULL) { + if (!isset($uid)) { + $uid = $GLOBALS['user']->uid; + } + return user_load($uid); +} + +/** + * Return a user object after checking if any profile category in the path exists. + */ +function user_category_load($uid, &$map, $index) { + static $user_categories, $accounts; + + // Cache $account - this load function will get called for each profile tab. + if (!isset($accounts[$uid])) { + $accounts[$uid] = user_load($uid); + } + $valid = TRUE; + if ($account = $accounts[$uid]) { + // Since the path is like user/%/edit/category_name, the category name will + // be at a position 2 beyond the index corresponding to the % wildcard. + $category_index = $index + 2; + // Valid categories may contain slashes, and hence need to be imploded. + $category_path = implode('/', array_slice($map, $category_index)); + if ($category_path) { + // Check that the requested category exists. + $valid = FALSE; + if (!isset($user_categories)) { + $user_categories = _user_categories(); + } + foreach ($user_categories as $category) { + if ($category['name'] == $category_path) { + $valid = TRUE; + // Truncate the map array in case the category name had slashes. + $map = array_slice($map, 0, $category_index); + // Assign the imploded category name to the last map element. + $map[$category_index] = $category_path; + break; + } + } + } + } + return $valid ? $account : FALSE; +} + +/** + * Returns $arg or the user ID of the current user if $arg is '%' or empty. + * + * @todo rethink the naming of this in Drupal 8. + */ +function user_uid_optional_to_arg($arg) { + // Give back the current user uid when called from eg. tracker, aka. + // with an empty arg. Also use the current user uid when called from + // the menu with a % for the current account link. + 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) ? format_username($account) : ''; +} + +/** + * Discover which external authentication module(s) authenticated a username. + * + * @param $authname + * A username used by an external authentication module. + * @return + * An associative array with module as key and username as value. + */ +function user_get_authmaps($authname = NULL) { + $authmaps = db_query("SELECT module, authname FROM {authmap} WHERE authname = :authname", array(':authname' => $authname))->fetchAllKeyed(); + return count($authmaps) ? $authmaps : 0; +} + +/** + * Save mappings of which external authentication module(s) authenticated + * a user. Maps external usernames to user ids in the users table. + * + * @param $account + * A user object. + * @param $authmaps + * An associative array with a compound key and the username as the value. + * The key is made up of 'authname_' plus the name of the external authentication + * module. + * @see user_external_login_register() + */ +function user_set_authmaps($account, $authmaps) { + foreach ($authmaps as $key => $value) { + $module = explode('_', $key, 2); + if ($value) { + db_merge('authmap') + ->key(array( + 'uid' => $account->uid, + 'module' => $module[1], + )) + ->fields(array('authname' => $value)) + ->execute(); + } + else { + db_delete('authmap') + ->condition('uid', $account->uid) + ->condition('module', $module[1]) + ->execute(); + } + } +} + +/** + * Form builder; the main user login form. + * + * @ingroup forms + */ +function user_login($form, &$form_state) { + global $user; + + // If we are already logged on, go to the user page instead. + if ($user->uid) { + drupal_goto('user/' . $user->uid); + } + + // Display login form: + $form['name'] = array('#type' => 'textfield', + '#title' => t('Username'), + '#size' => 60, + '#maxlength' => USERNAME_MAX_LENGTH, + '#required' => TRUE, + ); + + $form['name']['#description'] = t('Enter your @s username.', array('@s' => variable_get('site_name', 'Drupal'))); + $form['pass'] = array('#type' => 'password', + '#title' => t('Password'), + '#description' => t('Enter the password that accompanies your username.'), + '#required' => TRUE, + ); + $form['#validate'] = user_login_default_validators(); + $form['actions'] = array('#type' => 'actions'); + $form['actions']['submit'] = array('#type' => 'submit', '#value' => t('Log in')); + + return $form; +} + +/** + * 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'); +} + +/** + * A FAPI validate handler. Sets an error if supplied username has been blocked. + */ +function user_login_name_validate($form, &$form_state) { + if (isset($form_state['values']['name']) && user_is_blocked($form_state['values']['name'])) { + // Blocked in user administration. + form_set_error('name', t('The username %name has not been activated or is blocked.', array('%name' => $form_state['values']['name']))); + } +} + +/** + * A validate handler on the login form. Check supplied username/password + * against local users table. If successful, $form_state['uid'] + * is set to the matching user ID. + */ +function user_login_authenticate_validate($form, &$form_state) { + $password = trim($form_state['values']['pass']); + if (!empty($form_state['values']['name']) && !empty($password)) { + // Do not allow any login from the current user's IP if the limit has been + // reached. Default is 50 failed attempts allowed in one hour. This is + // independent of the per-user limit to catch attempts from one IP to log + // in to many different user accounts. We have a reasonably high limit + // since there may be only one apparent IP for all users at an institution. + if (!flood_is_allowed('failed_login_attempt_ip', variable_get('user_failed_login_ip_limit', 50), variable_get('user_failed_login_ip_window', 3600))) { + $form_state['flood_control_triggered'] = 'ip'; + return; + } + $account = db_query("SELECT * FROM {users} WHERE name = :name AND status = 1", array(':name' => $form_state['values']['name']))->fetchObject(); + if ($account) { + if (variable_get('user_failed_login_identifier_uid_only', FALSE)) { + // Register flood events based on the uid only, so they apply for any + // IP address. This is the most secure option. + $identifier = $account->uid; + } + else { + // The default identifier is a combination of uid and IP address. This + // is less secure but more resistant to denial-of-service attacks that + // could lock out all users with public user names. + $identifier = $account->uid . '-' . ip_address(); + } + $form_state['flood_control_user_identifier'] = $identifier; + + // Don't allow login if the limit for this user has been reached. + // Default is to allow 5 failed attempts every 6 hours. + if (!flood_is_allowed('failed_login_attempt_user', variable_get('user_failed_login_user_limit', 5), variable_get('user_failed_login_user_window', 21600), $identifier)) { + $form_state['flood_control_triggered'] = 'user'; + return; + } + } + // We are not limited by flood control, so try to authenticate. + // Set $form_state['uid'] as a flag for user_login_final_validate(). + $form_state['uid'] = user_authenticate($form_state['values']['name'], $password); + } +} + +/** + * 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) { + if (empty($form_state['uid'])) { + // Always register an IP-based failed login event. + flood_register_event('failed_login_attempt_ip', variable_get('user_failed_login_ip_window', 3600)); + // Register a per-user failed login event. + if (isset($form_state['flood_control_user_identifier'])) { + flood_register_event('failed_login_attempt_user', variable_get('user_failed_login_user_window', 21600), $form_state['flood_control_user_identifier']); + } + + if (isset($form_state['flood_control_triggered'])) { + if ($form_state['flood_control_triggered'] == 'user') { + form_set_error('name', format_plural(variable_get('user_failed_login_user_limit', 5), 'Sorry, there has been more than one failed login attempt for this account. It is temporarily blocked. Try again later or <a href="@url">request a new password</a>.', 'Sorry, there have been more than @count failed login attempts for this account. It is temporarily blocked. Try again later or <a href="@url">request a new password</a>.', array('@url' => url('user/password')))); + } + else { + // We did not find a uid, so the limit is IP-based. + 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')))); + } + } + else { + form_set_error('name', t('Sorry, unrecognized username or password. <a href="@password">Have you forgotten your password?</a>', array('@password' => url('user/password')))); + watchdog('user', 'Login attempt failed for %user.', array('%user' => $form_state['values']['name'])); + } + } + elseif (isset($form_state['flood_control_user_identifier'])) { + // Clear past failures for this user so as not to block a user who might + // log in and out more than once in an hour. + 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) && !empty($password)) { + $account = user_load_by_name($name); + if ($account) { + // Allow alternate password hashing schemes. + require_once DRUPAL_ROOT . '/' . variable_get('password_inc', 'includes/password.inc'); + if (user_check_password($password, $account)) { + // Successful authentication. + $uid = $account->uid; + + // Update user to new password scheme if needed. + if (user_needs_new_hash($account)) { + user_save($account, array('pass' => $password)); + } + } + } + } + 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 op 'login' and generates a new session. * + */ +function user_login_finalize(&$edit = array()) { + global $user; + watchdog('user', 'Session opened for %name.', array('%name' => $user->name)); + // Update the user table timestamp noting user has logged in. + // This is also used to invalidate one-time login links. + $user->login = REQUEST_TIME; + db_update('users') + ->fields(array('login' => $user->login)) + ->condition('uid', $user->uid) + ->execute(); + + // Regenerate the session ID to prevent against session fixation attacks. + // This is called before hook_user in case one of those functions fails + // or incorrectly does a redirect which would leave the old session in place. + drupal_session_regenerate(); + + 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); +} + +/** + * Helper function for authentication modules. Either logs in or registers + * the current user, based on username. Either way, the global $user object is + * populated and login tasks are performed. + */ +function user_external_login_register($name, $module) { + $account = user_external_load($name); + if (!$account) { + // Register this new user. + $userinfo = array( + 'name' => $name, + 'pass' => user_password(), + 'init' => $name, + 'status' => 1, + 'access' => REQUEST_TIME + ); + $account = user_save(drupal_anonymous_user(), $userinfo); + // Terminate if an error occurred during user_save(). + if (!$account) { + drupal_set_message(t("Error saving user account."), 'error'); + return; + } + user_set_authmaps($account, array("authname_$module" => $name)); + } + + // Log user in. + $form_state['uid'] = $account->uid; + user_login_submit(array(), $form_state); +} + +/** + * Generates a unique URL for a user to login and reset their password. + * + * @param object $account + * An object containing the user account. + * + * @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), 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 uid number. + * - pass: The hashed user password string. + * - login: The user login name. + * + * @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), 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 + * name and hashed password are retrieved from the database as necessary. For a + * usage example, see user_cancel_url() and user_cancel_confirm(). + * + * @param $password + * The hashed user account password value. + * @param $timestamp + * A unix timestamp. + * @param $login + * The user account login name. + * + * @return + * A string that is safe for use in URLs and SQL statements. + */ +function user_pass_rehash($password, $timestamp, $login) { + return drupal_hmac_base64($timestamp . $login, drupal_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) { + drupal_set_message(t('The user account %id does not exist.', array('%id' => $uid)), 'error'); + watchdog('user', 'Attempted to cancel non-existing user account: %id.', array('%id' => $uid), WATCHDOG_ERROR); + return; + } + + // Initialize batch (to set title). + $batch = array( + 'title' => t('Cancelling account'), + 'operations' => array(), + ); + batch_set($batch); + + // Modules use hook_user_delete() to respond to deletion. + if ($method != 'user_cancel_delete') { + // Allow modules to add further sets to this batch. + module_invoke_all('user_cancel', $edit, $account, $method); + } + + // Finish the batch and actually cancel the account. + $batch = array( + 'title' => t('Cancelling user account'), + 'operations' => array( + array('_user_cancel', array($edit, $account, $method)), + ), + ); + batch_set($batch); + + // Batch processing is either handled via Form API or has to be invoked + // manually. +} + +/** + * 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: + // Send account blocked notification if option was checked. + if (!empty($edit['user_cancel_notify'])) { + _user_mail_notify('status_blocked', $account); + } + user_save($account, array('status' => 0)); + drupal_set_message(t('%name has been disabled.', array('%name' => $account->name))); + watchdog('user', 'Blocked user: %name %email.', array('%name' => $account->name, '%email' => '<' . $account->mail . '>'), WATCHDOG_NOTICE); + break; + + case 'user_cancel_reassign': + case 'user_cancel_delete': + // Send account canceled notification if option was checked. + if (!empty($edit['user_cancel_notify'])) { + _user_mail_notify('status_canceled', $account); + } + user_delete($account->uid); + drupal_set_message(t('%name has been deleted.', array('%name' => $account->name))); + watchdog('user', 'Deleted user: %name %email.', array('%name' => $account->name, '%email' => '<' . $account->mail . '>'), WATCHDOG_NOTICE); + break; + } + + // After cancelling account, ensure that user is logged out. + if ($account->uid == $user->uid) { + // Destroy the current session, and reset $user to the anonymous user. + session_destroy(); + } + + // Clear the cache for anonymous users. + cache_clear_all(); +} + +/** + * 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. + */ +function user_delete_multiple(array $uids) { + if (!empty($uids)) { + $accounts = user_load_multiple($uids, array()); + + $transaction = db_transaction(); + try { + foreach ($accounts as $uid => $account) { + module_invoke_all('user_delete', $account); + module_invoke_all('entity_delete', $account, 'user'); + field_attach_delete('user', $account); + drupal_session_destroy_uid($account->uid); + } + + db_delete('users') + ->condition('uid', $uids, 'IN') + ->execute(); + db_delete('users_roles') + ->condition('uid', $uids, 'IN') + ->execute(); + db_delete('authmap') + ->condition('uid', $uids, 'IN') + ->execute(); + } + catch (Exception $e) { + $transaction->rollback(); + watchdog_exception('user', $e); + throw $e; + } + entity_get_controller('user')->resetCache(); + } +} + +/** + * Page callback wrapper for user_view(). + */ +function user_view_page($account) { + // An administrator may try to view a non-existent account, + // so we give them a 404 (versus a 403 for non-admins). + 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']['Profile Category']: + * Profile categories keyed by their human-readable names. + * - $page['content']['Profile Category']['profile_machine_name']: + * Profile fields keyed by their machine-readable names. + * - $page['content']['user_picture']: + * User's rendered picture. + * - $page['content']['summary']: + * Contains the default "History" 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 + * View mode, e.g. '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 drupal_render(). + */ +function user_view($account, $view_mode = 'full', $langcode = NULL) { + if (!isset($langcode)) { + $langcode = $GLOBALS['language_content']->language; + } + + // Retrieve all profile fields and attach to $account->content. + user_build_content($account, $view_mode, $langcode); + + $build = $account->content; + // We don't need duplicate rendering info in account->content. + unset($account->content); + + $build += array( + '#theme' => 'user_profile', + '#account' => $account, + '#view_mode' => $view_mode, + '#language' => $langcode, + ); + + // Allow modules to modify the structured user. + $type = 'user'; + drupal_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 + * View mode, e.g. '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']->language; + } + + // Remove previously built content, if exists. + $account->content = array(); + + // Build fields content. + 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); + + // Populate $account->content with a render() array. + module_invoke_all('user_view', $account, $view_mode, $langcode); + module_invoke_all('entity_view', $account, 'user', $view_mode, $langcode); +} + +/** + * 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. + * + * Used by user_mail() and the settings forms to retrieve strings. + */ +function _user_mail_text($key, $language = NULL, $variables = array(), $replace = TRUE) { + $langcode = isset($language) ? $language->language : NULL; + + if ($admin_setting = variable_get('user_mail_' . $key, FALSE)) { + // An admin setting overrides the default string. + $text = $admin_setting; + } + else { + // No override, return default string. + switch ($key) { + case 'register_no_approval_required_subject': + $text = t('Account details for [user:name] at [site:name]', array(), array('langcode' => $langcode)); + break; + case 'register_no_approval_required_body': + $text = t("[user:name], + +Thank you for registering at [site:name]. You may now log in by clicking this link or copying and pasting it to your browser: + +[user:one-time-login-url] + +This link can only be used once to log in and will lead you to a page where you can set your password. + +After setting your password, you will be able to log in at [site:login-url] in the future using: + +username: [user:name] +password: Your password + +-- [site:name] team", array(), array('langcode' => $langcode)); + break; + + case 'register_admin_created_subject': + $text = t('An administrator created an account for you at [site:name]', array(), array('langcode' => $langcode)); + break; + case 'register_admin_created_body': + $text = t("[user:name], + +A site administrator at [site:name] has created an account for you. You may now log in by clicking this link or copying and pasting it to your browser: + +[user:one-time-login-url] + +This link can only be used once to log in and will lead you to a page where you can set your password. + +After setting your password, you will be able to log in at [site:login-url] in the future using: + +username: [user:name] +password: Your password + +-- [site:name] team", array(), array('langcode' => $langcode)); + break; + + case 'register_pending_approval_subject': + case 'register_pending_approval_admin_subject': + $text = t('Account details for [user:name] at [site:name] (pending admin approval)', array(), array('langcode' => $langcode)); + break; + case 'register_pending_approval_body': + $text = t("[user:name], + +Thank you for registering at [site:name]. Your application for an account is currently pending approval. Once it has been approved, you will receive another e-mail containing information about how to log in, set your password, and other details. + + +-- [site:name] team", array(), array('langcode' => $langcode)); + break; + case 'register_pending_approval_admin_body': + $text = t("[user:name] has applied for an account. + +[user:edit-url]", array(), array('langcode' => $langcode)); + break; + + case 'password_reset_subject': + $text = t('Replacement login information for [user:name] at [site:name]', array(), array('langcode' => $langcode)); + break; + case 'password_reset_body': + $text = t("[user:name], + +A request to reset the password for your account has been made at [site:name]. + +You may now log in by clicking this link or copying and pasting it to your browser: + +[user:one-time-login-url] + +This link can only be used once to log in and will lead you to a page where you can set your password. It expires after one day and nothing will happen if it's not used. + +-- [site:name] team", array(), array('langcode' => $langcode)); + break; + + case 'status_activated_subject': + $text = t('Account details for [user:name] at [site:name] (approved)', array(), array('langcode' => $langcode)); + break; + case 'status_activated_body': + $text = t("[user:name], + +Your account at [site:name] has been activated. + +You may now log in by clicking this link or copying and pasting it into your browser: + +[user:one-time-login-url] + +This link can only be used once to log in and will lead you to a page where you can set your password. + +After setting your password, you will be able to log in at [site:login-url] in the future using: + +username: [user:name] +password: Your password + +-- [site:name] team", array(), array('langcode' => $langcode)); + break; + + case 'status_blocked_subject': + $text = t('Account details for [user:name] at [site:name] (blocked)', array(), array('langcode' => $langcode)); + break; + case 'status_blocked_body': + $text = t("[user:name], + +Your account on [site:name] has been blocked. + +-- [site:name] team", array(), array('langcode' => $langcode)); + break; + + case 'cancel_confirm_subject': + $text = t('Account cancellation request for [user:name] at [site:name]', array(), array('langcode' => $langcode)); + break; + case 'cancel_confirm_body': + $text = t("[user:name], + +A request to cancel your account has been made at [site:name]. + +You may now cancel your account on [site:url-brief] by clicking this link or copying and pasting it into your browser: + +[user:cancel-url] + +NOTE: The cancellation of your account is not reversible. + +This link expires in one day and nothing will happen if it is not used. + +-- [site:name] team", array(), array('langcode' => $langcode)); + break; + + case 'status_canceled_subject': + $text = t('Account details for [user:name] at [site:name] (canceled)', array(), array('langcode' => $langcode)); + break; + case 'status_canceled_body': + $text = t("[user:name], + +Your account on [site:name] has been canceled. + +-- [site:name] team", array(), array('langcode' => $langcode)); + break; + } + } + + if ($replace) { + // We do not sanitize the token replacement, since the output of this + // replacement is intended for an e-mail message, not a web browser. + return token_replace($text, $variables, array('language' => $language, 'callback' => 'user_mail_tokens', 'sanitize' => FALSE)); + } + + return $text; +} + +/** + * 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 account login name. + * - 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']); + } +} + +/*** Administrative features ***********************************************/ + +/** + * Retrieve an array of roles matching specified conditions. + * + * @param $membersonly + * 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. + * + * @return + * An associative array with the role id as the key and the role name as + * value. + */ +function user_roles($membersonly = FALSE, $permission = NULL) { + $user_roles = &drupal_static(__FUNCTION__); + + // Do not cache roles for specific permissions. This data is not requested + // frequently enough to justify the additional memory use. + if (empty($permission)) { + $cid = $membersonly ? DRUPAL_AUTHENTICATED_RID : DRUPAL_ANONYMOUS_RID; + if (isset($user_roles[$cid])) { + return $user_roles[$cid]; + } + } + + $query = db_select('role', 'r'); + $query->addTag('translatable'); + $query->fields('r', array('rid', 'name')); + $query->orderBy('weight'); + $query->orderBy('name'); + if (!empty($permission)) { + $query->innerJoin('role_permission', 'p', 'r.rid = p.rid'); + $query->condition('p.permission', $permission); + } + $result = $query->execute(); + + $roles = array(); + foreach ($result as $role) { + switch ($role->rid) { + // We only translate the built in role names + case DRUPAL_ANONYMOUS_RID: + if (!$membersonly) { + $roles[$role->rid] = t($role->name); + } + break; + case DRUPAL_AUTHENTICATED_RID: + $roles[$role->rid] = t($role->name); + break; + default: + $roles[$role->rid] = $role->name; + } + } + + if (empty($permission)) { + $user_roles[$cid] = $roles; + return $user_roles[$cid]; + } + + return $roles; +} + +/** + * Fetches a user role by role ID. + * + * @param $rid + * An integer representing the role ID. + * + * @return + * A fully-loaded role object if a role with the given ID exists, or FALSE + * otherwise. + * + * @see user_role_load_by_name() + */ +function user_role_load($rid) { + return db_select('role', 'r') + ->fields('r') + ->condition('rid', $rid) + ->execute() + ->fetchObject(); +} + +/** + * Fetches a user role by role name. + * + * @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() + */ +function user_role_load_by_name($role_name) { + return db_select('role', 'r') + ->fields('r') + ->condition('name', $role_name) + ->execute() + ->fetchObject(); +} + +/** + * Save a user role to the database. + * + * @param $role + * A role object to modify or add. If $role->rid is not specified, a new + * role will be created. + * @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) { + if ($role->name) { + // Prevent leading and trailing spaces in role names. + $role->name = trim($role->name); + } + if (!isset($role->weight)) { + // Set a role weight to make this new role last. + $query = db_select('role'); + $query->addExpression('MAX(weight)'); + $role->weight = $query->execute()->fetchField() + 1; + } + + // Let modules modify the user role before it is saved to the database. + module_invoke_all('user_role_presave', $role); + + if (!empty($role->rid) && $role->name) { + $status = drupal_write_record('role', $role, 'rid'); + module_invoke_all('user_role_update', $role); + } + else { + $status = drupal_write_record('role', $role); + module_invoke_all('user_role_insert', $role); + } + + // Clear the user access cache. + drupal_static_reset('user_access'); + drupal_static_reset('user_role_permissions'); + + return $status; +} + +/** + * Delete a user role from database. + * + * @param $role + * A string with the role name, or an integer with the role ID. + */ +function user_role_delete($role) { + if (is_int($role)) { + $role = user_role_load($role); + } + else { + $role = user_role_load_by_name($role); + } + + db_delete('role') + ->condition('rid', $role->rid) + ->execute(); + db_delete('role_permission') + ->condition('rid', $role->rid) + ->execute(); + // Update the users who have this role set: + db_delete('users_roles') + ->condition('rid', $role->rid) + ->execute(); + + module_invoke_all('user_role_delete', $role); + + // Clear the user access cache. + drupal_static_reset('user_access'); + drupal_static_reset('user_role_permissions'); +} + +/** + * Menu access callback for user role editing. + */ +function user_role_edit_access($role) { + // Prevent the system-defined roles from being altered or removed. + if ($role->rid == DRUPAL_ANONYMOUS_RID || $role->rid == DRUPAL_AUTHENTICATED_RID) { + 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 $rid + * The ID of a user role to alter. + * @param $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($rid, array $permissions = array()) { + // Grant new permissions for the role. + $grant = array_filter($permissions); + if (!empty($grant)) { + user_role_grant_permissions($rid, array_keys($grant)); + } + // Revoke permissions for the role. + $revoke = array_diff_assoc($permissions, $grant); + if (!empty($revoke)) { + user_role_revoke_permissions($rid, array_keys($revoke)); + } +} + +/** + * Grant permissions to a user role. + * + * @param $rid + * The ID of a user role to alter. + * @param $permissions + * A list of permission names to grant. + * + * @see user_role_change_permissions() + * @see user_role_revoke_permissions() + */ +function user_role_grant_permissions($rid, array $permissions = array()) { + $modules = user_permission_get_modules(); + // Grant new permissions for the role. + foreach ($permissions as $name) { + db_merge('role_permission') + ->key(array( + 'rid' => $rid, + 'permission' => $name, + )) + ->fields(array( + 'module' => $modules[$name], + )) + ->execute(); + } + + // Clear the user access cache. + drupal_static_reset('user_access'); + drupal_static_reset('user_role_permissions'); +} + +/** + * Revoke permissions from a user role. + * + * @param $rid + * The ID of a user role to alter. + * @param $permissions + * A list of permission names to revoke. + * + * @see user_role_change_permissions() + * @see user_role_grant_permissions() + */ +function user_role_revoke_permissions($rid, array $permissions = array()) { + // Revoke permissions for the role. + db_delete('role_permission') + ->condition('rid', $rid) + ->condition('permission', $permissions, 'IN') + ->execute(); + + // Clear the user access cache. + drupal_static_reset('user_access'); + drupal_static_reset('user_role_permissions'); +} + +/** + * Implements hook_user_operations(). + */ +function user_user_operations($form = array(), $form_state = array()) { + $operations = array( + 'unblock' => array( + 'label' => t('Unblock the selected users'), + 'callback' => 'user_user_operations_unblock', + ), + 'block' => array( + 'label' => t('Block the selected users'), + 'callback' => 'user_user_operations_block', + ), + 'cancel' => array( + 'label' => t('Cancel the selected user accounts'), + ), + ); + + if (user_access('administer permissions')) { + $roles = user_roles(TRUE); + unset($roles[DRUPAL_AUTHENTICATED_RID]); // Can't edit authenticated role. + + $add_roles = array(); + foreach ($roles as $key => $value) { + $add_roles['add_role-' . $key] = $value; + } + + $remove_roles = array(); + foreach ($roles as $key => $value) { + $remove_roles['remove_role-' . $key] = $value; + } + + if (count($roles)) { + $role_operations = array( + t('Add a role to the selected users') => array( + 'label' => $add_roles, + ), + t('Remove a role from the selected users') => array( + 'label' => $remove_roles, + ), + ); + + $operations += $role_operations; + } + } + + // If the form has been posted, we need to insert the proper data for + // role editing if necessary. + if (!empty($form_state['submitted'])) { + $operation_rid = explode('-', $form_state['values']['operation']); + $operation = $operation_rid[0]; + if ($operation == 'add_role' || $operation == 'remove_role') { + $rid = $operation_rid[1]; + if (user_access('administer permissions')) { + $operations[$form_state['values']['operation']] = array( + 'callback' => 'user_multiple_role_edit', + 'callback arguments' => array($operation, $rid), + ); + } + else { + watchdog('security', 'Detected malicious attempt to alter protected user fields.', array(), WATCHDOG_WARNING); + return; + } + } + } + + return $operations; +} + +/** + * Callback function for admin mass unblocking users. + */ +function user_user_operations_unblock($accounts) { + $accounts = user_load_multiple($accounts); + foreach ($accounts as $account) { + // Skip unblocking user if they are already unblocked. + if ($account !== FALSE && $account->status == 0) { + user_save($account, array('status' => 1)); + } + } +} + +/** + * Callback function for admin mass blocking users. + */ +function user_user_operations_block($accounts) { + $accounts = user_load_multiple($accounts); + foreach ($accounts as $account) { + // Skip blocking user if they are already blocked. + if ($account !== FALSE && $account->status == 1) { + // For efficiency manually save the original account before applying any + // changes. + $account->original = clone $account; + user_save($account, array('status' => 0)); + } + } +} + +/** + * Callback function for admin mass adding/deleting a user role. + */ +function user_multiple_role_edit($accounts, $operation, $rid) { + // The role name is not necessary as user_save() will reload the user + // object, but some modules' hook_user() may look at this first. + $role_name = db_query('SELECT name FROM {role} WHERE rid = :rid', array(':rid' => $rid))->fetchField(); + + switch ($operation) { + case 'add_role': + $accounts = user_load_multiple($accounts); + foreach ($accounts as $account) { + // Skip adding the role to the user if they already have it. + if ($account !== FALSE && !isset($account->roles[$rid])) { + $roles = $account->roles + array($rid => $role_name); + // For efficiency manually save the original account before applying + // any changes. + $account->original = clone $account; + user_save($account, array('roles' => $roles)); + } + } + break; + case 'remove_role': + $accounts = user_load_multiple($accounts); + foreach ($accounts as $account) { + // Skip removing the role from the user if they already don't have it. + if ($account !== FALSE && isset($account->roles[$rid])) { + $roles = array_diff($account->roles, array($rid => $role_name)); + // For efficiency manually save the original account before applying + // any changes. + $account->original = clone $account; + user_save($account, array('roles' => $roles)); + } + } + break; + } +} + +function user_multiple_cancel_confirm($form, &$form_state) { + $edit = $form_state['input']; + + $form['accounts'] = array('#prefix' => '<ul>', '#suffix' => '</ul>', '#tree' => TRUE); + $accounts = user_load_multiple(array_keys(array_filter($edit['accounts']))); + foreach ($accounts as $uid => $account) { + // Prevent user 1 from being canceled. + if ($uid <= 1) { + continue; + } + $form['accounts'][$uid] = array( + '#type' => 'hidden', + '#value' => $uid, + '#prefix' => '<li>', + '#suffix' => check_plain($account->name) . "</li>\n", + ); + } + + // Output a notice that user 1 cannot be canceled. + if (isset($accounts[1])) { + $redirect = (count($accounts) == 1); + $message = t('The user account %name cannot be cancelled.', array('%name' => $accounts[1]->name)); + drupal_set_message($message, $redirect ? 'error' : 'warning'); + // If only user 1 was selected, redirect to the overview. + if ($redirect) { + drupal_goto('admin/people'); + } + } + + $form['operation'] = array('#type' => 'hidden', '#value' => 'cancel'); + + module_load_include('inc', 'user', 'user.pages'); + $form['user_cancel_method'] = array( + '#type' => 'item', + '#title' => t('When cancelling these accounts'), + ); + $form['user_cancel_method'] += user_cancel_methods(); + // Remove method descriptions. + foreach (element_children($form['user_cancel_method']) as $element) { + unset($form['user_cancel_method'][$element]['#description']); + } + + // Allow to send the account cancellation confirmation mail. + $form['user_cancel_confirm'] = array( + '#type' => 'checkbox', + '#title' => t('Require e-mail confirmation to cancel account.'), + '#default_value' => FALSE, + '#description' => t('When enabled, the user must confirm the account cancellation via e-mail.'), + ); + // Also allow to send account canceled notification mail, if enabled. + $form['user_cancel_notify'] = array( + '#type' => 'checkbox', + '#title' => t('Notify user when account is canceled.'), + '#default_value' => FALSE, + '#access' => variable_get('user_mail_status_canceled_notify', FALSE), + '#description' => t('When enabled, the user will receive an e-mail notification after the account has been cancelled.'), + ); + + return confirm_form($form, + t('Are you sure you want to cancel these user accounts?'), + 'admin/people', t('This action cannot be undone.'), + t('Cancel accounts'), t('Cancel')); +} + +/** + * Submit handler for mass-account cancellation form. + * + * @see user_multiple_cancel_confirm() + * @see user_cancel_confirm_form_submit() + */ +function user_multiple_cancel_confirm_submit($form, &$form_state) { + global $user; + + if ($form_state['values']['confirm']) { + foreach ($form_state['values']['accounts'] as $uid => $value) { + // Prevent programmatic form submissions from cancelling user 1. + if ($uid <= 1) { + continue; + } + // Prevent user administrators from deleting themselves without confirmation. + if ($uid == $user->uid) { + $admin_form_state = $form_state; + unset($admin_form_state['values']['user_cancel_confirm']); + $admin_form_state['values']['_account'] = $user; + user_cancel_confirm_form_submit(array(), $admin_form_state); + } + else { + user_cancel($form_state['values'], $uid, $form_state['values']['user_cancel_method']); + } + } + } + $form_state['redirect'] = 'admin/people'; +} + +/** + * Retrieve a list of all user setting/information categories and sort them by weight. + */ +function _user_categories() { + $categories = module_invoke_all('user_categories'); + usort($categories, '_user_sort'); + + return $categories; +} + +function _user_sort($a, $b) { + $a = (array) $a + array('weight' => 0, 'title' => ''); + $b = (array) $b + array('weight' => 0, 'title' => ''); + return $a['weight'] < $b['weight'] ? -1 : ($a['weight'] > $b['weight'] ? 1 : ($a['title'] < $b['title'] ? -1 : 1)); +} + +/** + * List user administration filters that can be applied. + */ +function user_filters() { + // Regular filters + $filters = array(); + $roles = user_roles(TRUE); + unset($roles[DRUPAL_AUTHENTICATED_RID]); // Don't list authorized role. + if (count($roles)) { + $filters['role'] = array( + 'title' => t('role'), + 'field' => 'ur.rid', + 'options' => array( + '[any]' => t('any'), + ) + $roles, + ); + } + + $options = array(); + foreach (module_implements('permission') as $module) { + $function = $module . '_permission'; + if ($permissions = $function('permission')) { + 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(); + // Extend Query with filter conditions. + foreach (isset($_SESSION['user_overview_filter']) ? $_SESSION['user_overview_filter'] : array() as $filter) { + list($key, $value) = $filter; + // This checks to see if this permission filter is an enabled permission for + // the authenticated role. If so, then all users would be listed, and we can + // skip adding it to the filter query. + if ($key == 'permission') { + $account = new stdClass(); + $account->uid = 'user_filter'; + $account->roles = array(DRUPAL_AUTHENTICATED_RID => 1); + if (user_access($value, $account)) { + continue; + } + $users_roles_alias = $query->join('users_roles', 'ur', '%alias.uid = u.uid'); + $permission_alias = $query->join('role_permission', 'p', $users_roles_alias . '.rid = %alias.rid'); + $query->condition($permission_alias . '.permission', $value); + } + elseif ($key == 'role') { + $users_roles_alias = $query->join('users_roles', 'ur', '%alias.uid = u.uid'); + $query->condition($users_roles_alias . '.rid' , $value); + } + else { + $query->condition($filters[$key]['field'], $value); + } + } +} + +/** + * Implements hook_forms(). + */ +function user_forms() { + $forms['user_admin_access_add_form']['callback'] = 'user_admin_access_form'; + $forms['user_admin_access_edit_form']['callback'] = 'user_admin_access_form'; + return $forms; +} + +/** + * Implements hook_comment_view(). + */ +function user_comment_view($comment) { + if (variable_get('user_signatures', 0) && !empty($comment->signature)) { + // @todo This alters and replaces the original object value, so a + // hypothetical process of loading, viewing, and saving will hijack the + // stored data. Consider renaming to $comment->signature_safe or similar + // here and elsewhere in Drupal 8. + $comment->signature = check_markup($comment->signature, $comment->signature_format, '', TRUE); + } + else { + $comment->signature = ''; + } +} + +/** + * Returns HTML for a user signature. + * + * @param $variables + * An associative array containing: + * - signature: The user's signature. + * + * @ingroup themeable + */ +function theme_user_signature($variables) { + $signature = $variables['signature']; + $output = ''; + + if ($signature) { + $output .= '<div class="clear">'; + $output .= '<div>—</div>'; + $output .= $signature; + $output .= '</div>'; + } + + return $output; +} + +/** + * 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 drupal_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 drupal_mail_system()->mail(), if ends up being called. + */ +function _user_mail_notify($op, $account, $language = NULL) { + // By default, we always notify except for canceled and blocked. + $default_notify = ($op != 'status_canceled' && $op != 'status_blocked'); + $notify = variable_get('user_mail_' . $op . '_notify', $default_notify); + if ($notify) { + $params['account'] = $account; + $language = $language ? $language : user_preferred_language($account); + $mail = drupal_mail('user', $op, $account->mail, $language, $params); + if ($op == 'register_pending_approval') { + // If a user registered requiring admin approval, notify the admin, too. + // We use the site default language for this. + drupal_mail('user', 'register_pending_approval_admin', variable_get('site_mail', ini_get('sendmail_from')), language_default(), $params); + } + } + return empty($mail) ? NULL : $mail['result']; +} + +/** + * 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) { + global $user; + + $js_settings = array( + 'password' => array( + 'strengthTitle' => t('Password strength:'), + 'hasWeaknesses' => t('To make your password stronger:'), + 'tooShort' => t('Make it at least 6 characters'), + 'addLowerCase' => t('Add lowercase letters'), + 'addUpperCase' => t('Add uppercase letters'), + 'addNumbers' => t('Add numbers'), + 'addPunctuation' => t('Add punctuation'), + 'sameAsUsername' => t('Make it different from your username'), + 'confirmSuccess' => t('yes'), + 'confirmFailure' => t('no'), + 'weak' => t('Weak'), + 'fair' => t('Fair'), + 'good' => t('Good'), + 'strong' => t('Strong'), + 'confirmTitle' => t('Passwords match:'), + 'username' => (isset($user->name) ? $user->name : ''), + ), + ); + + $element['#attached']['js'][] = drupal_get_path('module', 'user') . '/user.js'; + // Ensure settings are only added once per page. + static $already_added = FALSE; + if (!$already_added) { + $already_added = TRUE; + $element['#attached']['js'][] = array('data' => $js_settings, 'type' => 'setting'); + } + + return $element; +} + +/** + * Implements hook_node_load(). + */ +function user_node_load($nodes, $types) { + // Build an array of all uids for node authors, keyed by nid. + $uids = array(); + foreach ($nodes as $nid => $node) { + $uids[$nid] = $node->uid; + } + + // Fetch name, picture, and data for these users. + $user_fields = db_query("SELECT uid, name, picture, data FROM {users} WHERE uid IN (:uids)", array(':uids' => $uids))->fetchAllAssoc('uid'); + + // Add these values back into the node objects. + 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) { + // If a style is deleted, update the variables. + // Administrators choose a replacement style when deleting. + user_image_style_save($style); +} + +/** + * Implements hook_image_style_save(). + */ +function user_image_style_save($style) { + // If a style is renamed, update the variables that use it. + if (isset($style['old_name']) && $style['old_name'] == variable_get('user_picture_style', '')) { + variable_set('user_picture_style', $style['name']); + } +} + +/** + * Implements hook_action_info(). + */ +function user_action_info() { + return array( + 'user_block_user_action' => array( + 'label' => t('Block current user'), + 'type' => 'user', + 'configurable' => FALSE, + 'triggers' => array('any'), + ), + ); +} + +/** + * Blocks the current user. + * + * @ingroup actions + */ +function user_block_user_action(&$entity, $context = array()) { + // First priority: If there is a $entity->uid, block that user. + // This is most likely a user object or the author if a node or comment. + if (isset($entity->uid)) { + $uid = $entity->uid; + } + elseif (isset($context['uid'])) { + $uid = $context['uid']; + } + // If neither of those are valid, then block the current user. + else { + $uid = $GLOBALS['user']->uid; + } + $account = user_load($uid); + $account = user_save($account, array('status' => 0)); + watchdog('action', 'Blocked user %name.', array('%name' => $account->name)); +} + +/** + * 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['instance']['settings']['user_register_form'] = array( + '#type' => 'checkbox', + '#title' => t('Display on user registration form.'), + '#description' => t("This is compulsory for 'required' fields."), + // Field instances created in D7 beta releases before the setting was + // introduced might be set as 'required' and 'not shown on user_register + // form'. We make sure the checkbox comes as 'checked' for those. + '#default_value' => $instance['settings']['user_register_form'] || $instance['required'], + // Display just below the 'required' checkbox. + '#weight' => $form['instance']['required']['#weight'] + .1, + // Disabled when the 'required' checkbox is checked. + '#states' => array( + 'enabled' => array('input[name="instance[required]"]' => array('checked' => FALSE)), + ), + // Checked when the 'required' checkbox is checked. This is done through + // a custom behavior, since the #states system would also synchronize on + // uncheck. + '#attached' => array( + 'js' => array(drupal_get_path('module', 'user') . '/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; + + $admin = user_access('administer users'); + + // If we aren't admin but already logged on, go to the user page instead. + if (!$admin && $user->uid) { + drupal_goto('user/' . $user->uid); + } + + $form['#user'] = drupal_anonymous_user(); + $form['#user_category'] = 'register'; + + $form['#attached']['library'][] = array('system', 'jquery.cookie'); + $form['#attributes']['class'][] = 'user-info-from-cookie'; + + // Start with the default user account fields. + user_account_form($form, $form_state); + + // Attach field widgets, and hide the ones where the 'user_register_form' + // setting is not on. + 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) { + // Redirect back to page which initiated the create request; + // usually admin/people/create. + $form_state['redirect'] = $_GET['q']; + } + + $form['actions'] = array('#type' => 'actions'); + $form['actions']['submit'] = array( + '#type' => 'submit', + '#value' => t('Create new account'), + ); + + $form['#validate'][] = 'user_register_validate'; + // Add the final user registration form submit handler. + $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) { + $admin = user_access('administer users'); + + if (!variable_get('user_email_verification', TRUE) || $admin) { + $pass = $form_state['values']['pass']; + } + else { + $pass = user_password(); + } + $notify = !empty($form_state['values']['notify']); + + // Remove unneeded values. + form_state_values_clean($form_state); + + $form_state['values']['pass'] = $pass; + $form_state['values']['init'] = $form_state['values']['mail']; + + $account = $form['#user']; + + entity_form_submit_build_entity('user', $account, $form, $form_state); + + // Populate $edit with the properties of $account, which have been edited on + // this form by taking over all values, which appear in the form values too. + $edit = array_intersect_key((array) $account, $form_state['values']); + $account = user_save($account, $edit); + + // Terminate if an error occurred during user_save(). + if (!$account) { + drupal_set_message(t("Error saving user account."), 'error'); + $form_state['redirect'] = ''; + return; + } + $form_state['user'] = $account; + $form_state['values']['uid'] = $account->uid; + + watchdog('user', 'New user: %name (%email).', array('%name' => $form_state['values']['name'], '%email' => $form_state['values']['mail']), WATCHDOG_NOTICE, l(t('edit'), 'user/' . $account->uid . '/edit')); + + // Add plain text password into user account to generate mail tokens. + $account->password = $pass; + + // New administrative account without notification. + $uri = entity_uri('user', $account); + if ($admin && !$notify) { + drupal_set_message(t('Created a new user account for <a href="@url">%name</a>. No e-mail has been sent.', array('@url' => url($uri['path'], $uri['options']), '%name' => $account->name))); + } + // No e-mail verification required; log in user immediately. + elseif (!$admin && !variable_get('user_email_verification', TRUE) && $account->status) { + _user_mail_notify('register_no_approval_required', $account); + $form_state['uid'] = $account->uid; + user_login_submit(array(), $form_state); + drupal_set_message(t('Registration successful. You are now logged in.')); + $form_state['redirect'] = ''; + } + // No administrator approval required. + elseif ($account->status || $notify) { + $op = $notify ? 'register_admin_created' : 'register_no_approval_required'; + _user_mail_notify($op, $account); + if ($notify) { + drupal_set_message(t('A welcome message with further instructions has been e-mailed to the new user <a href="@url">%name</a>.', array('@url' => url($uri['path'], $uri['options']), '%name' => $account->name))); + } + else { + drupal_set_message(t('A welcome message with further instructions has been sent to your e-mail address.')); + $form_state['redirect'] = ''; + } + } + // Administrator approval required. + else { + _user_mail_notify('register_pending_approval', $account); + drupal_set_message(t('Thank you for applying for an account. Your account is currently pending approval by the site administrator.<br />In the meantime, a welcome message with further instructions has been sent to your e-mail address.')); + $form_state['redirect'] = ''; + } +} + +/** + * Implements hook_modules_installed(). + */ +function user_modules_installed($modules) { + // Assign all available permissions to the administrator role. + $rid = variable_get('user_admin_role', 0); + if ($rid) { + $permissions = array(); + foreach ($modules as $module) { + if ($module_permissions = module_invoke($module, 'permission')) { + $permissions = array_merge($permissions, array_keys($module_permissions)); + } + } + if (!empty($permissions)) { + user_role_grant_permissions($rid, $permissions); + } + } +} + +/** + * Implements hook_modules_uninstalled(). + */ +function user_modules_uninstalled($modules) { + db_delete('role_permission') + ->condition('module', $modules, 'IN') + ->execute(); +} + +/** + * 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() { + $destination = drupal_get_destination(); + if ($destination['destination'] == 'user/login') { + $destination['destination'] = 'user'; + } + 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) { + // Set cookie for 365 days. + setrawcookie('Drupal.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('Drupal.visitor.' . $cookie_name, '', REQUEST_TIME - 3600, '/'); +} + +/** + * Implements hook_rdf_mapping(). + */ +function user_rdf_mapping() { + return array( + array( + 'type' => 'user', + 'bundle' => RDF_DEFAULT_BUNDLE, + 'mapping' => array( + 'rdftype' => array('sioc:UserAccount'), + 'name' => array( + 'predicates' => array('foaf:name'), + ), + 'homepage' => array( + 'predicates' => array('foaf:page'), + 'type' => 'rel', + ), + ), + ), + ); +} + +/** + * Implements hook_file_download_access(). + */ +function user_file_download_access($field, $entity_type, $entity) { + if ($entity_type == 'user') { + return user_view_access($entity); + } +} diff --git a/core/modules/user/user.pages.inc b/core/modules/user/user.pages.inc new file mode 100644 index 00000000000..02870e9e65a --- /dev/null +++ b/core/modules/user/user.pages.inc @@ -0,0 +1,553 @@ +<?php + +/** + * @file + * User page callback file for the user module. + */ + +/** + * Menu callback; Retrieve a JSON object containing autocomplete suggestions for existing users. + */ +function user_autocomplete($string = '') { + $matches = array(); + if ($string) { + $result = db_select('users')->fields('users', array('name'))->condition('name', db_like($string) . '%', 'LIKE')->range(0, 10)->execute(); + foreach ($result as $user) { + $matches[$user->name] = check_plain($user->name); + } + } + + drupal_json_output($matches); +} + +/** + * Form builder; Request a password reset. + * + * @ingroup forms + * @see user_pass_validate() + * @see user_pass_submit() + */ +function user_pass() { + global $user; + + $form['name'] = array( + '#type' => 'textfield', + '#title' => t('Username or e-mail address'), + '#size' => 60, + '#maxlength' => max(USERNAME_MAX_LENGTH, EMAIL_MAX_LENGTH), + '#required' => TRUE, + ); + // Allow logged in users to request this also. + if ($user->uid > 0) { + $form['name']['#type'] = 'value'; + $form['name']['#value'] = $user->mail; + $form['mail'] = array( + '#prefix' => '<p>', + '#markup' => t('Password reset instructions will be mailed to %email. You must log out to use the password reset link in the e-mail.', array('%email' => $user->mail)), + '#suffix' => '</p>', + ); + } + $form['actions'] = array('#type' => 'actions'); + $form['actions']['submit'] = array('#type' => 'submit', '#value' => t('E-mail new password')); + + return $form; +} + +function user_pass_validate($form, &$form_state) { + $name = trim($form_state['values']['name']); + // Try to load by email. + $users = user_load_multiple(array(), array('mail' => $name, 'status' => '1')); + $account = reset($users); + if (!$account) { + // No success, try to load by name. + $users = user_load_multiple(array(), array('name' => $name, 'status' => '1')); + $account = reset($users); + } + if (isset($account->uid)) { + form_set_value(array('#parents' => array('account')), $account, $form_state); + } + else { + form_set_error('name', t('Sorry, %name is not recognized as a user name or an e-mail address.', array('%name' => $name))); + } +} + +function user_pass_submit($form, &$form_state) { + global $language; + + $account = $form_state['values']['account']; + // Mail one time login URL and instructions using current language. + $mail = _user_mail_notify('password_reset', $account, $language); + if (!empty($mail)) { + watchdog('user', 'Password reset instructions mailed to %name at %email.', array('%name' => $account->name, '%email' => $account->mail)); + drupal_set_message(t('Further instructions have been sent to your e-mail address.')); + } + + $form_state['redirect'] = 'user'; + return; +} + +/** + * Menu callback; process one time login link and redirects to the user page on success. + */ +function user_pass_reset($form, &$form_state, $uid, $timestamp, $hashed_pass, $action = NULL) { + global $user; + + // When processing the one-time login link, we have to make sure that a user + // isn't already logged in. + if ($user->uid) { + // The existing user is already logged in. + if ($user->uid == $uid) { + drupal_set_message(t('You are logged in as %user. <a href="!user_edit">Change your password.</a>', array('%user' => $user->name, '!user_edit' => url("user/$user->uid/edit")))); + } + // A different user is already logged in on the computer. + else { + $reset_link_account = user_load($uid); + if (!empty($reset_link_account)) { + drupal_set_message(t('Another user (%other_user) is already logged into the site on this computer, but you tried to use a one-time link for user %resetting_user. Please <a href="!logout">logout</a> and try using the link again.', + array('%other_user' => $user->name, '%resetting_user' => $reset_link_account->name, '!logout' => url('user/logout')))); + } else { + // Invalid one-time link specifies an unknown user. + drupal_set_message(t('The one-time login link you clicked is invalid.')); + } + } + drupal_goto(); + } + else { + // Time out, in seconds, until login URL expires. 24 hours = 86400 seconds. + $timeout = 86400; + $current = REQUEST_TIME; + // Some redundant checks for extra security ? + $users = user_load_multiple(array($uid), array('status' => '1')); + if ($timestamp <= $current && $account = reset($users)) { + // No time out for first time login. + if ($account->login && $current - $timestamp > $timeout) { + drupal_set_message(t('You have tried to use a one-time login link that has expired. Please request a new one using the form below.')); + drupal_goto('user/password'); + } + elseif ($account->uid && $timestamp >= $account->login && $timestamp <= $current && $hashed_pass == user_pass_rehash($account->pass, $timestamp, $account->login)) { + // First stage is a confirmation form, then login + if ($action == 'login') { + watchdog('user', 'User %name used one-time login link at time %timestamp.', array('%name' => $account->name, '%timestamp' => $timestamp)); + // Set the new user. + $user = $account; + // user_login_finalize() also updates the login timestamp of the + // user, which invalidates further use of the one-time login link. + user_login_finalize(); + drupal_set_message(t('You have just used your one-time login link. It is no longer necessary to use this link to log in. Please change your password.')); + // Let the user's password be changed without the current password check. + $token = drupal_hash_base64(drupal_random_bytes(55)); + $_SESSION['pass_reset_' . $user->uid] = $token; + drupal_goto('user/' . $user->uid . '/edit', array('query' => array('pass-reset-token' => $token))); + } + else { + $form['message'] = array('#markup' => t('<p>This is a one-time login for %user_name and will expire on %expiration_date.</p><p>Click on this button to log in to the site and change your password.</p>', array('%user_name' => $account->name, '%expiration_date' => format_date($timestamp + $timeout)))); + $form['help'] = array('#markup' => '<p>' . t('This login can be used only once.') . '</p>'); + $form['actions'] = array('#type' => 'actions'); + $form['actions']['submit'] = array('#type' => 'submit', '#value' => t('Log in')); + $form['#action'] = url("user/reset/$uid/$timestamp/$hashed_pass/login"); + return $form; + } + } + else { + drupal_set_message(t('You have tried to use a one-time login link that has either been used or is no longer valid. Please request a new one using the form below.')); + drupal_goto('user/password'); + } + } + else { + // Deny access, no more clues. + // Everything will be in the watchdog's URL for the administrator to check. + drupal_access_denied(); + } + } +} + +/** + * Menu callback; logs the current user out, and redirects to the home page. + */ +function user_logout() { + global $user; + + watchdog('user', 'Session closed for %name.', array('%name' => $user->name)); + + module_invoke_all('user_logout', $user); + + // Destroy the current session, and reset $user to the anonymous user. + session_destroy(); + + drupal_goto(); +} + +/** + * Process variables for user-profile.tpl.php. + * + * The $variables array contains the following arguments: + * - $account + * + * @see user-profile.tpl.php + */ +function template_preprocess_user_profile(&$variables) { + $account = $variables['elements']['#account']; + + // Helpful $user_profile variable for templates. + foreach (element_children($variables['elements']) as $key) { + $variables['user_profile'][$key] = $variables['elements'][$key]; + } + + // Preprocess fields. + field_attach_preprocess('user', $account, $variables['elements'], $variables); +} + +/** + * Process variables for user-profile-item.tpl.php. + * + * The $variables array contains the following arguments: + * - $element + * + * @see user-profile-item.tpl.php + */ +function template_preprocess_user_profile_item(&$variables) { + $variables['title'] = $variables['element']['#title']; + $variables['value'] = $variables['element']['#markup']; + $variables['attributes'] = ''; + if (isset($variables['element']['#attributes'])) { + $variables['attributes'] = drupal_attributes($variables['element']['#attributes']); + } +} + +/** + * Process variables for user-profile-category.tpl.php. + * + * The $variables array contains the following arguments: + * - $element + * + * @see user-profile-category.tpl.php + */ +function template_preprocess_user_profile_category(&$variables) { + $variables['title'] = check_plain($variables['element']['#title']); + $variables['classes_array'][] = 'user-profile-category-' . drupal_html_class($variables['title']); + $variables['profile_items'] = $variables['element']['#children']; + $variables['attributes'] = ''; + if (isset($variables['element']['#attributes'])) { + $variables['attributes'] = drupal_attributes($variables['element']['#attributes']); + } +} + +/** + * Form builder; edit a user account or one of their profile categories. + * + * @ingroup forms + * @see user_account_form() + * @see user_account_form_validate() + * @see user_profile_form_validate() + * @see user_profile_form_submit() + * @see user_cancel_confirm_form_submit() + */ +function user_profile_form($form, &$form_state, $account, $category = 'account') { + global $user; + + // During initial form build, add the entity to the form state for use during + // form building and processing. During a rebuild, use what is in the form + // state. + if (!isset($form_state['user'])) { + $form_state['user'] = $account; + } + else { + $account = $form_state['user']; + } + + // @todo Legacy support. Modules are encouraged to access the entity using + // $form_state. Remove in Drupal 8. + $form['#user'] = $account; + $form['#user_category'] = $category; + + if ($category == 'account') { + user_account_form($form, $form_state); + // Attach field widgets. + field_attach_form('user', $account, $form, $form_state); + } + + $form['actions'] = array('#type' => 'actions'); + $form['actions']['submit'] = array( + '#type' => 'submit', + '#value' => t('Save'), + ); + if ($category == 'account') { + $form['actions']['cancel'] = array( + '#type' => 'submit', + '#value' => t('Cancel account'), + '#submit' => array('user_edit_cancel_submit'), + '#access' => $account->uid > 1 && (($account->uid == $user->uid && user_access('cancel account')) || user_access('administer users')), + ); + } + + $form['#validate'][] = 'user_profile_form_validate'; + // Add the final user profile form submit handler. + $form['#submit'][] = 'user_profile_form_submit'; + + return $form; +} + +/** + * Validation function for the user account and profile editing form. + */ +function user_profile_form_validate($form, &$form_state) { + entity_form_field_validate('user', $form, $form_state); +} + +/** + * Submit function for the user account and profile editing form. + */ +function user_profile_form_submit($form, &$form_state) { + $account = $form_state['user']; + $category = $form['#user_category']; + // Remove unneeded values. + form_state_values_clean($form_state); + + // Before updating the account entity, keep an unchanged copy for use with + // user_save() later. This is necessary for modules implementing the user + // hooks to be able to react on changes by comparing the values of $account + // and $edit. + $account_unchanged = clone $account; + + entity_form_submit_build_entity('user', $account, $form, $form_state); + + // Populate $edit with the properties of $account, which have been edited on + // this form by taking over all values, which appear in the form values too. + $edit = array_intersect_key((array) $account, $form_state['values']); + + user_save($account_unchanged, $edit, $category); + $form_state['values']['uid'] = $account->uid; + + if ($category == 'account' && !empty($edit['pass'])) { + // Remove the password reset tag since a new password was saved. + unset($_SESSION['pass_reset_'. $account->uid]); + } + // Clear the page cache because pages can contain usernames and/or profile information: + cache_clear_all(); + + drupal_set_message(t('The changes have been saved.')); +} + +/** + * Submit function for the 'Cancel account' button on the user edit form. + */ +function user_edit_cancel_submit($form, &$form_state) { + $destination = array(); + if (isset($_GET['destination'])) { + $destination = drupal_get_destination(); + unset($_GET['destination']); + } + // Note: We redirect from user/uid/edit to user/uid/cancel to make the tabs disappear. + $form_state['redirect'] = array("user/" . $form['#user']->uid . "/cancel", array('query' => $destination)); +} + +/** + * Form builder; confirm form for cancelling user account. + * + * @ingroup forms + * @see user_edit_cancel_submit() + */ +function user_cancel_confirm_form($form, &$form_state, $account) { + global $user; + + $form['_account'] = array('#type' => 'value', '#value' => $account); + + // Display account cancellation method selection, if allowed. + $default_method = variable_get('user_cancel_method', 'user_cancel_block'); + $admin_access = user_access('administer users'); + $can_select_method = $admin_access || user_access('select account cancellation method'); + $form['user_cancel_method'] = array( + '#type' => 'item', + '#title' => ($account->uid == $user->uid ? t('When cancelling your account') : t('When cancelling the account')), + '#access' => $can_select_method, + ); + $form['user_cancel_method'] += user_cancel_methods(); + + // Allow user administrators to skip the account cancellation confirmation + // mail (by default), as long as they do not attempt to cancel their own + // account. + $override_access = $admin_access && ($account->uid != $user->uid); + $form['user_cancel_confirm'] = array( + '#type' => 'checkbox', + '#title' => t('Require e-mail confirmation to cancel account.'), + '#default_value' => ($override_access ? FALSE : TRUE), + '#access' => $override_access, + '#description' => t('When enabled, the user must confirm the account cancellation via e-mail.'), + ); + // Also allow to send account canceled notification mail, if enabled. + $default_notify = variable_get('user_mail_status_canceled_notify', FALSE); + $form['user_cancel_notify'] = array( + '#type' => 'checkbox', + '#title' => t('Notify user when account is canceled.'), + '#default_value' => ($override_access ? FALSE : $default_notify), + '#access' => $override_access && $default_notify, + '#description' => t('When enabled, the user will receive an e-mail notification after the account has been cancelled.'), + ); + + // Prepare confirmation form page title and description. + if ($account->uid == $user->uid) { + $question = t('Are you sure you want to cancel your account?'); + } + else { + $question = t('Are you sure you want to cancel the account %name?', array('%name' => $account->name)); + } + $description = ''; + if ($can_select_method) { + $description = t('Select the method to cancel the account above.'); + foreach (element_children($form['user_cancel_method']) as $element) { + unset($form['user_cancel_method'][$element]['#description']); + } + } + else { + // The radio button #description is used as description for the confirmation + // form. + foreach (element_children($form['user_cancel_method']) as $element) { + if ($form['user_cancel_method'][$element]['#default_value'] == $form['user_cancel_method'][$element]['#return_value']) { + $description = $form['user_cancel_method'][$element]['#description']; + } + unset($form['user_cancel_method'][$element]['#description']); + } + } + + // Always provide entity id in the same form key as in the entity edit form. + $form['uid'] = array('#type' => 'value', '#value' => $account->uid); + return confirm_form($form, + $question, + 'user/' . $account->uid, + $description . ' ' . t('This action cannot be undone.'), + t('Cancel account'), t('Cancel')); +} + +/** + * Submit handler for the account cancellation confirm form. + * + * @see user_cancel_confirm_form() + * @see user_multiple_cancel_confirm_submit() + */ +function user_cancel_confirm_form_submit($form, &$form_state) { + global $user; + $account = $form_state['values']['_account']; + + // Cancel account immediately, if the current user has administrative + // privileges, no confirmation mail shall be sent, and the user does not + // attempt to cancel the own account. + if (user_access('administer users') && empty($form_state['values']['user_cancel_confirm']) && $account->uid != $user->uid) { + user_cancel($form_state['values'], $account->uid, $form_state['values']['user_cancel_method']); + + $form_state['redirect'] = 'admin/people'; + } + else { + // Store cancelling method and whether to notify the user in $account for + // user_cancel_confirm(). + $edit = array( + 'user_cancel_method' => $form_state['values']['user_cancel_method'], + 'user_cancel_notify' => $form_state['values']['user_cancel_notify'], + ); + $account = user_save($account, $edit); + _user_mail_notify('cancel_confirm', $account); + drupal_set_message(t('A confirmation request to cancel your account has been sent to your e-mail address.')); + watchdog('user', 'Sent account cancellation request to %name %email.', array('%name' => $account->name, '%email' => '<' . $account->mail . '>'), WATCHDOG_NOTICE); + + $form_state['redirect'] = "user/$account->uid"; + } +} + +/** + * Helper function to return available account cancellation methods. + * + * See documentation of hook_user_cancel_methods_alter(). + * + * @return + * An array containing all account cancellation methods as form elements. + * + * @see hook_user_cancel_methods_alter() + * @see user_admin_settings() + * @see user_cancel_confirm_form() + * @see user_multiple_cancel_confirm() + */ +function user_cancel_methods() { + $methods = array( + 'user_cancel_block' => array( + 'title' => t('Disable the account and keep its content.'), + 'description' => t('Your account will be blocked and you will no longer be able to log in. All of your content will remain attributed to your user name.'), + ), + 'user_cancel_block_unpublish' => array( + 'title' => t('Disable the account and unpublish its content.'), + 'description' => t('Your account will be blocked and you will no longer be able to log in. All of your content will be hidden from everyone but administrators.'), + ), + 'user_cancel_reassign' => array( + 'title' => t('Delete the account and make its content belong to the %anonymous-name user.', array('%anonymous-name' => variable_get('anonymous', t('Anonymous')))), + 'description' => t('Your account will be removed and all account information deleted. All of your content will be assigned to the %anonymous-name user.', array('%anonymous-name' => variable_get('anonymous', t('Anonymous')))), + ), + 'user_cancel_delete' => array( + 'title' => t('Delete the account and its content.'), + 'description' => t('Your account will be removed and all account information deleted. All of your content will also be deleted.'), + 'access' => user_access('administer users'), + ), + ); + // Allow modules to customize account cancellation methods. + drupal_alter('user_cancel_methods', $methods); + + // Turn all methods into real form elements. + $default_method = variable_get('user_cancel_method', 'user_cancel_block'); + foreach ($methods as $name => $method) { + $form[$name] = array( + '#type' => 'radio', + '#title' => $method['title'], + '#description' => (isset($method['description']) ? $method['description'] : NULL), + '#return_value' => $name, + '#default_value' => $default_method, + '#parents' => array('user_cancel_method'), + ); + } + return $form; +} + +/** + * Menu callback; Cancel a user account via e-mail confirmation link. + * + * @see user_cancel_confirm_form() + * @see user_cancel_url() + */ +function user_cancel_confirm($account, $timestamp = 0, $hashed_pass = '') { + // Time out in seconds until cancel URL expires; 24 hours = 86400 seconds. + $timeout = 86400; + $current = REQUEST_TIME; + + // Basic validation of arguments. + if (isset($account->data['user_cancel_method']) && !empty($timestamp) && !empty($hashed_pass)) { + // Validate expiration and hashed password/login. + if ($timestamp <= $current && $current - $timestamp < $timeout && $account->uid && $timestamp >= $account->login && $hashed_pass == user_pass_rehash($account->pass, $timestamp, $account->login)) { + $edit = array( + 'user_cancel_notify' => isset($account->data['user_cancel_notify']) ? $account->data['user_cancel_notify'] : variable_get('user_mail_status_canceled_notify', FALSE), + ); + user_cancel($edit, $account->uid, $account->data['user_cancel_method']); + // Since user_cancel() is not invoked via Form API, batch processing needs + // to be invoked manually and should redirect to the front page after + // completion. + batch_process(''); + } + else { + drupal_set_message(t('You have tried to use an account cancellation link that has expired. Please request a new one using the form below.')); + drupal_goto("user/$account->uid/cancel"); + } + } + drupal_access_denied(); +} + +/** + * Access callback for path /user. + * + * Displays user profile if user is logged in, or login form for anonymous + * users. + */ +function user_page() { + global $user; + if ($user->uid) { + menu_set_active_item('user/' . $user->uid); + return menu_execute_active_handler(NULL, FALSE); + } + else { + return drupal_get_form('user_login'); + } +} diff --git a/core/modules/user/user.permissions.js b/core/modules/user/user.permissions.js new file mode 100644 index 00000000000..988820e12db --- /dev/null +++ b/core/modules/user/user.permissions.js @@ -0,0 +1,69 @@ +(function ($) { + +/** + * Shows checked and disabled checkboxes for inherited permissions. + */ +Drupal.behaviors.permissions = { + attach: function (context) { + var self = this; + $('table#permissions').once('permissions', function () { + // On a site with many roles and permissions, this behavior initially has + // to perform thousands of DOM manipulations to inject checkboxes and hide + // them. By detaching the table from the DOM, all operations can be + // performed without triggering internal layout and re-rendering processes + // in the browser. + var $table = $(this); + if ($table.prev().length) { + var $ancestor = $table.prev(), method = 'after'; + } + else { + var $ancestor = $table.parent(), method = 'append'; + } + $table.detach(); + + // Create dummy checkboxes. We use dummy checkboxes instead of reusing + // the existing checkboxes here because new checkboxes don't alter the + // submitted form. If we'd automatically check existing checkboxes, the + // permission table would be polluted with redundant entries. This + // is deliberate, but desirable when we automatically check them. + var $dummy = $('<input type="checkbox" class="dummy-checkbox" disabled="disabled" checked="checked" />') + .attr('title', Drupal.t("This permission is inherited from the authenticated user role.")) + .hide(); + + $('input[type=checkbox]', this).not('.rid-2, .rid-1').addClass('real-checkbox').each(function () { + $dummy.clone().insertAfter(this); + }); + + // Initialize the authenticated user checkbox. + $('input[type=checkbox].rid-2', this) + .bind('click.permissions', self.toggle) + // .triggerHandler() cannot be used here, as it only affects the first + // element. + .each(self.toggle); + + // Re-insert the table into the DOM. + $ancestor[method]($table); + }); + }, + + /** + * Toggles all dummy checkboxes based on the checkboxes' state. + * + * If the "authenticated user" checkbox is checked, the checked and disabled + * checkboxes are shown, the real checkboxes otherwise. + */ + toggle: function () { + var authCheckbox = this, $row = $(this).closest('tr'); + // jQuery performs too many layout calculations for .hide() and .show(), + // leading to a major page rendering lag on sites with many roles and + // permissions. Therefore, we toggle visibility directly. + $row.find('.real-checkbox').each(function () { + this.style.display = (authCheckbox.checked ? 'none' : ''); + }); + $row.find('.dummy-checkbox').each(function () { + this.style.display = (authCheckbox.checked ? '' : 'none'); + }); + } +}; + +})(jQuery); diff --git a/core/modules/user/user.test b/core/modules/user/user.test new file mode 100644 index 00000000000..e94c63ffd5e --- /dev/null +++ b/core/modules/user/user.test @@ -0,0 +1,2211 @@ +<?php + +/** + * @file + * Tests for user.module. + */ + +class UserRegistrationTestCase extends DrupalWebTestCase { + public static function getInfo() { + return array( + 'name' => 'User registration', + 'description' => 'Test registration of user under different configurations.', + 'group' => 'User' + ); + } + + function setUp() { + parent::setUp('field_test'); + } + + function testRegistrationWithEmailVerification() { + // Require e-mail verification. + variable_set('user_email_verification', TRUE); + + // Set registration to administrator only. + variable_set('user_register', USER_REGISTER_ADMINISTRATORS_ONLY); + $this->drupalGet('user/register'); + $this->assertResponse(403, t('Registration page is inaccessible when only administrators can create accounts.')); + + // Allow registration by site visitors without administrator approval. + variable_set('user_register', USER_REGISTER_VISITORS); + $edit = array(); + $edit['name'] = $name = $this->randomName(); + $edit['mail'] = $mail = $edit['name'] . '@example.com'; + $this->drupalPost('user/register', $edit, t('Create new account')); + $this->assertText(t('A welcome message with further instructions has been sent to your e-mail address.'), t('User registered successfully.')); + $accounts = user_load_multiple(array(), array('name' => $name, 'mail' => $mail)); + $new_user = reset($accounts); + $this->assertTrue($new_user->status, t('New account is active after registration.')); + + // Allow registration by site visitors, but require administrator approval. + variable_set('user_register', USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL); + $edit = array(); + $edit['name'] = $name = $this->randomName(); + $edit['mail'] = $mail = $edit['name'] . '@example.com'; + $this->drupalPost('user/register', $edit, t('Create new account')); + $accounts = user_load_multiple(array(), array('name' => $name, 'mail' => $mail)); + $new_user = reset($accounts); + $this->assertFalse($new_user->status, t('New account is blocked until approved by an administrator.')); + } + + function testRegistrationWithoutEmailVerification() { + // Don't require e-mail verification. + variable_set('user_email_verification', FALSE); + + // Allow registration by site visitors without administrator approval. + variable_set('user_register', USER_REGISTER_VISITORS); + $edit = array(); + $edit['name'] = $name = $this->randomName(); + $edit['mail'] = $mail = $edit['name'] . '@example.com'; + + // Try entering a mismatching password. + $edit['pass[pass1]'] = '99999.0'; + $edit['pass[pass2]'] = '99999'; + $this->drupalPost('user/register', $edit, t('Create new account')); + $this->assertText(t('The specified passwords do not match.'), t('Typing mismatched passwords displays an error message.')); + + // Enter a correct password. + $edit['pass[pass1]'] = $new_pass = $this->randomName(); + $edit['pass[pass2]'] = $new_pass; + $this->drupalPost('user/register', $edit, t('Create new account')); + $accounts = user_load_multiple(array(), array('name' => $name, 'mail' => $mail)); + $new_user = reset($accounts); + $this->assertText(t('Registration successful. You are now logged in.'), t('Users are logged in after registering.')); + $this->drupalLogout(); + + // Allow registration by site visitors, but require administrator approval. + variable_set('user_register', USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL); + $edit = array(); + $edit['name'] = $name = $this->randomName(); + $edit['mail'] = $mail = $edit['name'] . '@example.com'; + $edit['pass[pass1]'] = $pass = $this->randomName(); + $edit['pass[pass2]'] = $pass; + $this->drupalPost('user/register', $edit, t('Create new account')); + $this->assertText(t('Thank you for applying for an account. Your account is currently pending approval by the site administrator.'), t('Users are notified of pending approval')); + + // Try to login before administrator approval. + $auth = array( + 'name' => $name, + 'pass' => $pass, + ); + $this->drupalPost('user/login', $auth, t('Log in')); + $this->assertText(t('The username @name has not been activated or is blocked.', array('@name' => $name)), t('User cannot login yet.')); + + // Activate the new account. + $accounts = user_load_multiple(array(), array('name' => $name, 'mail' => $mail)); + $new_user = reset($accounts); + $admin_user = $this->drupalCreateUser(array('administer users')); + $this->drupalLogin($admin_user); + $edit = array( + 'status' => 1, + ); + $this->drupalPost('user/' . $new_user->uid . '/edit', $edit, t('Save')); + $this->drupalLogout(); + + // Login after administrator approval. + $this->drupalPost('user/login', $auth, t('Log in')); + $this->assertText(t('Member for'), t('User can log in after administrator approval.')); + } + + function testRegistrationEmailDuplicates() { + // Don't require e-mail verification. + variable_set('user_email_verification', FALSE); + + // Allow registration by site visitors without administrator approval. + variable_set('user_register', USER_REGISTER_VISITORS); + + // Set up a user to check for duplicates. + $duplicate_user = $this->drupalCreateUser(); + + $edit = array(); + $edit['name'] = $this->randomName(); + $edit['mail'] = $duplicate_user->mail; + + // Attempt to create a new account using an existing e-mail address. + $this->drupalPost('user/register', $edit, t('Create new account')); + $this->assertText(t('The e-mail address @email is already registered.', array('@email' => $duplicate_user->mail)), t('Supplying an exact duplicate email address displays an error message')); + + // Attempt to bypass duplicate email registration validation by adding spaces. + $edit['mail'] = ' ' . $duplicate_user->mail . ' '; + + $this->drupalPost('user/register', $edit, t('Create new account')); + $this->assertText(t('The e-mail address @email is already registered.', array('@email' => $duplicate_user->mail)), t('Supplying a duplicate email address with added whitespace displays an error message')); + } + + function testRegistrationDefaultValues() { + // Allow registration by site visitors without administrator approval. + variable_set('user_register', USER_REGISTER_VISITORS); + + // Don't require e-mail verification. + variable_set('user_email_verification', FALSE); + + // Set the default timezone to Brussels. + variable_set('configurable_timezones', 1); + variable_set('date_default_timezone', 'Europe/Brussels'); + + // Check that the account information fieldset's options are not displayed + // is a fieldset if there is not more than one fieldset in the form. + $this->drupalGet('user/register'); + $this->assertNoRaw('<fieldset id="edit-account"><legend>Account information</legend>', t('Account settings fieldset was hidden.')); + + $edit = array(); + $edit['name'] = $name = $this->randomName(); + $edit['mail'] = $mail = $edit['name'] . '@example.com'; + $edit['pass[pass1]'] = $new_pass = $this->randomName(); + $edit['pass[pass2]'] = $new_pass; + $this->drupalPost(NULL, $edit, t('Create new account')); + + // Check user fields. + $accounts = user_load_multiple(array(), array('name' => $name, 'mail' => $mail)); + $new_user = reset($accounts); + $this->assertEqual($new_user->name, $name, t('Username matches.')); + $this->assertEqual($new_user->mail, $mail, t('E-mail address matches.')); + $this->assertEqual($new_user->theme, '', t('Correct theme field.')); + $this->assertEqual($new_user->signature, '', t('Correct signature field.')); + $this->assertTrue(($new_user->created > REQUEST_TIME - 20 ), t('Correct creation time.')); + $this->assertEqual($new_user->status, variable_get('user_register', USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL) == USER_REGISTER_VISITORS ? 1 : 0, t('Correct status field.')); + $this->assertEqual($new_user->timezone, variable_get('date_default_timezone'), t('Correct time zone field.')); + $this->assertEqual($new_user->language, '', t('Correct language field.')); + $this->assertEqual($new_user->picture, '', t('Correct picture field.')); + $this->assertEqual($new_user->init, $mail, t('Correct init field.')); + } + + /** + * Tests Field API fields on user registration forms. + */ + function testRegistrationWithUserFields() { + // Create a field, and an instance on 'user' entity type. + $field = array( + 'type' => 'test_field', + 'field_name' => 'test_user_field', + 'cardinality' => 1, + ); + field_create_field($field); + $instance = array( + 'field_name' => 'test_user_field', + 'entity_type' => 'user', + 'label' => 'Some user field', + 'bundle' => 'user', + 'required' => TRUE, + 'settings' => array('user_register_form' => FALSE), + ); + field_create_instance($instance); + + // Check that the field does not appear on the registration form. + $this->drupalGet('user/register'); + $this->assertNoText($instance['label'], t('The field does not appear on user registration form')); + + // Have the field appear on the registration form. + $instance['settings']['user_register_form'] = TRUE; + field_update_instance($instance); + $this->drupalGet('user/register'); + $this->assertText($instance['label'], t('The field appears on user registration form')); + + // Check that validation errors are correctly reported. + $edit = array(); + $edit['name'] = $name = $this->randomName(); + $edit['mail'] = $mail = $edit['name'] . '@example.com'; + // Missing input in required field. + $edit['test_user_field[und][0][value]'] = ''; + $this->drupalPost(NULL, $edit, t('Create new account')); + $this->assertRaw(t('@name field is required.', array('@name' => $instance['label'])), t('Field validation error was correctly reported.')); + // Invalid input. + $edit['test_user_field[und][0][value]'] = '-1'; + $this->drupalPost(NULL, $edit, t('Create new account')); + $this->assertRaw(t('%name does not accept the value -1.', array('%name' => $instance['label'])), t('Field validation error was correctly reported.')); + + // Submit with valid data. + $value = rand(1, 255); + $edit['test_user_field[und][0][value]'] = $value; + $this->drupalPost(NULL, $edit, t('Create new account')); + // Check user fields. + $accounts = user_load_multiple(array(), array('name' => $name, 'mail' => $mail)); + $new_user = reset($accounts); + $this->assertEqual($new_user->test_user_field[LANGUAGE_NONE][0]['value'], $value, t('The field value was correclty saved.')); + + // Check that the 'add more' button works. + $field['cardinality'] = FIELD_CARDINALITY_UNLIMITED; + field_update_field($field); + foreach (array('js', 'nojs') as $js) { + $this->drupalGet('user/register'); + // Add two inputs. + $value = rand(1, 255); + $edit = array(); + $edit['test_user_field[und][0][value]'] = $value; + if ($js == 'js') { + $this->drupalPostAJAX(NULL, $edit, 'test_user_field_add_more'); + $this->drupalPostAJAX(NULL, $edit, 'test_user_field_add_more'); + } + else { + $this->drupalPost(NULL, $edit, t('Add another item')); + $this->drupalPost(NULL, $edit, t('Add another item')); + } + // Submit with three values. + $edit['test_user_field[und][1][value]'] = $value + 1; + $edit['test_user_field[und][2][value]'] = $value + 2; + $edit['name'] = $name = $this->randomName(); + $edit['mail'] = $mail = $edit['name'] . '@example.com'; + $this->drupalPost(NULL, $edit, t('Create new account')); + // Check user fields. + $accounts = user_load_multiple(array(), array('name' => $name, 'mail' => $mail)); + $new_user = reset($accounts); + $this->assertEqual($new_user->test_user_field[LANGUAGE_NONE][0]['value'], $value, t('@js : The field value was correclty saved.', array('@js' => $js))); + $this->assertEqual($new_user->test_user_field[LANGUAGE_NONE][1]['value'], $value + 1, t('@js : The field value was correclty saved.', array('@js' => $js))); + $this->assertEqual($new_user->test_user_field[LANGUAGE_NONE][2]['value'], $value + 2, t('@js : The field value was correclty saved.', array('@js' => $js))); + } + } +} + +class UserValidationTestCase extends DrupalWebTestCase { + public static function getInfo() { + return array( + 'name' => 'Username/e-mail validation', + 'description' => 'Verify that username/email validity checks behave as designed.', + 'group' => 'User' + ); + } + + // Username validation. + function testUsernames() { + $test_cases = array( // '<username>' => array('<description>', 'assert<testName>'), + 'foo' => array('Valid username', 'assertNull'), + 'FOO' => array('Valid username', 'assertNull'), + 'Foo O\'Bar' => array('Valid username', 'assertNull'), + 'foo@bar' => array('Valid username', 'assertNull'), + 'foo@example.com' => array('Valid username', 'assertNull'), + 'foo@-example.com' => array('Valid username', 'assertNull'), // invalid domains are allowed in usernames + 'þòøÇߪř€' => array('Valid username', 'assertNull'), + 'ᚠᛇᚻ᛫ᛒᛦᚦ' => array('Valid UTF8 username', 'assertNull'), // runes + ' foo' => array('Invalid username that starts with a space', 'assertNotNull'), + 'foo ' => array('Invalid username that ends with a space', 'assertNotNull'), + 'foo bar' => array('Invalid username that contains 2 spaces \' \'', 'assertNotNull'), + '' => array('Invalid empty username', 'assertNotNull'), + 'foo/' => array('Invalid username containing invalid chars', 'assertNotNull'), + 'foo' . chr(0) . 'bar' => array('Invalid username containing chr(0)', 'assertNotNull'), // NULL + 'foo' . chr(13) . 'bar' => array('Invalid username containing chr(13)', 'assertNotNull'), // CR + str_repeat('x', USERNAME_MAX_LENGTH + 1) => array('Invalid excessively long username', 'assertNotNull'), + ); + foreach ($test_cases as $name => $test_case) { + list($description, $test) = $test_case; + $result = user_validate_name($name); + $this->$test($result, $description . ' (' . $name . ')'); + } + } + + // Mail validation. More extensive tests can be found at common.test + function testMailAddresses() { + $test_cases = array( // '<username>' => array('<description>', 'assert<testName>'), + '' => array('Empty mail address', 'assertNotNull'), + 'foo' => array('Invalid mail address', 'assertNotNull'), + 'foo@example.com' => array('Valid mail address', 'assertNull'), + ); + foreach ($test_cases as $name => $test_case) { + list($description, $test) = $test_case; + $result = user_validate_mail($name); + $this->$test($result, $description . ' (' . $name . ')'); + } + } +} + +/** + * Functional tests for user logins, including rate limiting of login attempts. + */ +class UserLoginTestCase extends DrupalWebTestCase { + public static function getInfo() { + return array( + 'name' => 'User login', + 'description' => 'Ensure that login works as expected.', + 'group' => 'User', + ); + } + + /** + * Test the global login flood control. + */ + function testGlobalLoginFloodControl() { + // Set the global login limit. + variable_set('user_failed_login_ip_limit', 10); + // Set a high per-user limit out so that it is not relevant in the test. + variable_set('user_failed_login_user_limit', 4000); + + $user1 = $this->drupalCreateUser(array()); + $incorrect_user1 = clone $user1; + $incorrect_user1->pass_raw .= 'incorrect'; + + // Try 2 failed logins. + for ($i = 0; $i < 2; $i++) { + $this->assertFailedLogin($incorrect_user1); + } + + // A successful login will not reset the IP-based flood control count. + $this->drupalLogin($user1); + $this->drupalLogout(); + + // Try 8 more failed logins, they should not trigger the flood control + // mechanism. + for ($i = 0; $i < 8; $i++) { + $this->assertFailedLogin($incorrect_user1); + } + + // The next login trial should result in an IP-based flood error message. + $this->assertFailedLogin($incorrect_user1, 'ip'); + + // A login with the correct password should also result in a flood error + // message. + $this->assertFailedLogin($user1, 'ip'); + } + + /** + * Test the per-user login flood control. + */ + function testPerUserLoginFloodControl() { + // Set a high global limit out so that it is not relevant in the test. + variable_set('user_failed_login_ip_limit', 4000); + // Set the per-user login limit. + variable_set('user_failed_login_user_limit', 3); + + $user1 = $this->drupalCreateUser(array()); + $incorrect_user1 = clone $user1; + $incorrect_user1->pass_raw .= 'incorrect'; + + $user2 = $this->drupalCreateUser(array()); + + // Try 2 failed logins. + for ($i = 0; $i < 2; $i++) { + $this->assertFailedLogin($incorrect_user1); + } + + // A successful login will reset the per-user flood control count. + $this->drupalLogin($user1); + $this->drupalLogout(); + + // Try 3 failed logins for user 1, they will not trigger flood control. + for ($i = 0; $i < 3; $i++) { + $this->assertFailedLogin($incorrect_user1); + } + + // Try one successful attempt for user 2, it should not trigger any + // flood control. + $this->drupalLogin($user2); + $this->drupalLogout(); + + // Try one more attempt for user 1, it should be rejected, even if the + // correct password has been used. + $this->assertFailedLogin($user1, 'user'); + } + + /** + * Test that user password is re-hashed upon login after changing $count_log2. + */ + function testPasswordRehashOnLogin() { + // Load password hashing API. + require_once DRUPAL_ROOT . '/' . variable_get('password_inc', 'includes/password.inc'); + // Set initial $count_log2 to the default, DRUPAL_HASH_COUNT. + variable_set('password_count_log2', DRUPAL_HASH_COUNT); + // Create a new user and authenticate. + $account = $this->drupalCreateUser(array()); + $password = $account->pass_raw; + $this->drupalLogin($account); + $this->drupalLogout(); + // Load the stored user. The password hash should reflect $count_log2. + $account = user_load($account->uid); + $this->assertIdentical(_password_get_count_log2($account->pass), DRUPAL_HASH_COUNT); + // Change $count_log2 and log in again. + variable_set('password_count_log2', DRUPAL_HASH_COUNT + 1); + $account->pass_raw = $password; + $this->drupalLogin($account); + // Load the stored user, which should have a different password hash now. + $account = user_load($account->uid, TRUE); + $this->assertIdentical(_password_get_count_log2($account->pass), DRUPAL_HASH_COUNT + 1); + } + + /** + * Make an unsuccessful login attempt. + * + * @param $account + * A user object with name and pass_raw attributes for the login attempt. + * @param $flood_trigger + * Whether or not to expect that the flood control mechanism will be + * triggered. + */ + function assertFailedLogin($account, $flood_trigger = NULL) { + $edit = array( + 'name' => $account->name, + 'pass' => $account->pass_raw, + ); + $this->drupalPost('user', $edit, t('Log in')); + $this->assertNoFieldByXPath("//input[@name='pass' and @value!='']", NULL, t('Password value attribute is blank.')); + if (isset($flood_trigger)) { + if ($flood_trigger == 'user') { + $this->assertRaw(format_plural(variable_get('user_failed_login_user_limit', 5), 'Sorry, there has been more than one failed login attempt for this account. It is temporarily blocked. Try again later or <a href="@url">request a new password</a>.', 'Sorry, there have been more than @count failed login attempts for this account. It is temporarily blocked. Try again later or <a href="@url">request a new password</a>.', array('@url' => url('user/password')))); + } + else { + // No uid, so the limit is IP-based. + $this->assertRaw(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')))); + } + } + else { + $this->assertText(t('Sorry, unrecognized username or password. Have you forgotten your password?')); + } + } +} + +/** + * Test cancelling a user. + */ +class UserCancelTestCase extends DrupalWebTestCase { + public static function getInfo() { + return array( + 'name' => 'Cancel account', + 'description' => 'Ensure that account cancellation methods work as expected.', + 'group' => 'User', + ); + } + + function setUp() { + parent::setUp('comment'); + } + + /** + * Attempt to cancel account without permission. + */ + function testUserCancelWithoutPermission() { + variable_set('user_cancel_method', 'user_cancel_reassign'); + + // Create a user. + $account = $this->drupalCreateUser(array()); + $this->drupalLogin($account); + // Load real user object. + $account = user_load($account->uid, TRUE); + + // Create a node. + $node = $this->drupalCreateNode(array('uid' => $account->uid)); + + // Attempt to cancel account. + $this->drupalGet('user/' . $account->uid . '/edit'); + $this->assertNoRaw(t('Cancel account'), t('No cancel account button displayed.')); + + // Attempt bogus account cancellation request confirmation. + $timestamp = $account->login; + $this->drupalGet("user/$account->uid/cancel/confirm/$timestamp/" . user_pass_rehash($account->pass, $timestamp, $account->login)); + $this->assertResponse(403, t('Bogus cancelling request rejected.')); + $account = user_load($account->uid); + $this->assertTrue($account->status == 1, t('User account was not canceled.')); + + // Confirm user's content has not been altered. + $test_node = node_load($node->nid, NULL, TRUE); + $this->assertTrue(($test_node->uid == $account->uid && $test_node->status == 1), t('Node of the user has not been altered.')); + } + + /** + * Tests that user account for uid 1 cannot be cancelled. + * + * This should never be possible, or the site owner would become unable to + * administer the site. + */ + function testUserCancelUid1() { + // Update uid 1's name and password to we know it. + $password = user_password(); + require_once DRUPAL_ROOT . '/' . variable_get('password_inc', 'includes/password.inc'); + $account = array( + 'name' => 'user1', + 'pass' => user_hash_password(trim($password)), + ); + // We cannot use user_save() here or the password would be hashed again. + db_update('users') + ->fields($account) + ->condition('uid', 1) + ->execute(); + + // Reload and log in uid 1. + $user1 = user_load(1, TRUE); + $user1->pass_raw = $password; + + // Try to cancel uid 1's account with a different user. + $this->admin_user = $this->drupalCreateUser(array('administer users')); + $this->drupalLogin($this->admin_user); + $edit = array( + 'operation' => 'cancel', + 'accounts[1]' => TRUE, + ); + $this->drupalPost('admin/people', $edit, t('Update')); + + // Verify that uid 1's account was not cancelled. + $user1 = user_load(1, TRUE); + $this->assertEqual($user1->status, 1, t('User #1 still exists and is not blocked.')); + } + + /** + * Attempt invalid account cancellations. + */ + function testUserCancelInvalid() { + variable_set('user_cancel_method', 'user_cancel_reassign'); + + // Create a user. + $account = $this->drupalCreateUser(array('cancel account')); + $this->drupalLogin($account); + // Load real user object. + $account = user_load($account->uid, TRUE); + + // Create a node. + $node = $this->drupalCreateNode(array('uid' => $account->uid)); + + // Attempt to cancel account. + $this->drupalPost('user/' . $account->uid . '/edit', NULL, t('Cancel account')); + + // Confirm account cancellation. + $timestamp = time(); + $this->drupalPost(NULL, NULL, t('Cancel account')); + $this->assertText(t('A confirmation request to cancel your account has been sent to your e-mail address.'), t('Account cancellation request mailed message displayed.')); + + // Attempt bogus account cancellation request confirmation. + $bogus_timestamp = $timestamp + 60; + $this->drupalGet("user/$account->uid/cancel/confirm/$bogus_timestamp/" . user_pass_rehash($account->pass, $bogus_timestamp, $account->login)); + $this->assertText(t('You have tried to use an account cancellation link that has expired. Please request a new one using the form below.'), t('Bogus cancelling request rejected.')); + $account = user_load($account->uid); + $this->assertTrue($account->status == 1, t('User account was not canceled.')); + + // Attempt expired account cancellation request confirmation. + $bogus_timestamp = $timestamp - 86400 - 60; + $this->drupalGet("user/$account->uid/cancel/confirm/$bogus_timestamp/" . user_pass_rehash($account->pass, $bogus_timestamp, $account->login)); + $this->assertText(t('You have tried to use an account cancellation link that has expired. Please request a new one using the form below.'), t('Expired cancel account request rejected.')); + $accounts = user_load_multiple(array($account->uid), array('status' => 1)); + $this->assertTrue(reset($accounts), t('User account was not canceled.')); + + // Confirm user's content has not been altered. + $test_node = node_load($node->nid, NULL, TRUE); + $this->assertTrue(($test_node->uid == $account->uid && $test_node->status == 1), t('Node of the user has not been altered.')); + } + + /** + * Disable account and keep all content. + */ + function testUserBlock() { + variable_set('user_cancel_method', 'user_cancel_block'); + + // Create a user. + $web_user = $this->drupalCreateUser(array('cancel account')); + $this->drupalLogin($web_user); + + // Load real user object. + $account = user_load($web_user->uid, TRUE); + + // Attempt to cancel account. + $this->drupalGet('user/' . $account->uid . '/edit'); + $this->drupalPost(NULL, NULL, t('Cancel account')); + $this->assertText(t('Are you sure you want to cancel your account?'), t('Confirmation form to cancel account displayed.')); + $this->assertText(t('Your account will be blocked and you will no longer be able to log in. All of your content will remain attributed to your user name.'), t('Informs that all content will be remain as is.')); + $this->assertNoText(t('Select the method to cancel the account above.'), t('Does not allow user to select account cancellation method.')); + + // Confirm account cancellation. + $timestamp = time(); + + $this->drupalPost(NULL, NULL, t('Cancel account')); + $this->assertText(t('A confirmation request to cancel your account has been sent to your e-mail address.'), t('Account cancellation request mailed message displayed.')); + + // Confirm account cancellation request. + $this->drupalGet("user/$account->uid/cancel/confirm/$timestamp/" . user_pass_rehash($account->pass, $timestamp, $account->login)); + $account = user_load($account->uid, TRUE); + $this->assertTrue($account->status == 0, t('User has been blocked.')); + + // Confirm user is logged out. + $this->assertNoText($account->name, t('Logged out.')); + } + + /** + * Disable account and unpublish all content. + */ + function testUserBlockUnpublish() { + variable_set('user_cancel_method', 'user_cancel_block_unpublish'); + + // Create a user. + $account = $this->drupalCreateUser(array('cancel account')); + $this->drupalLogin($account); + // Load real user object. + $account = user_load($account->uid, TRUE); + + // Create a node with two revisions. + $node = $this->drupalCreateNode(array('uid' => $account->uid)); + $settings = get_object_vars($node); + $settings['revision'] = 1; + $node = $this->drupalCreateNode($settings); + + // Attempt to cancel account. + $this->drupalGet('user/' . $account->uid . '/edit'); + $this->drupalPost(NULL, NULL, t('Cancel account')); + $this->assertText(t('Are you sure you want to cancel your account?'), t('Confirmation form to cancel account displayed.')); + $this->assertText(t('Your account will be blocked and you will no longer be able to log in. All of your content will be hidden from everyone but administrators.'), t('Informs that all content will be unpublished.')); + + // Confirm account cancellation. + $timestamp = time(); + $this->drupalPost(NULL, NULL, t('Cancel account')); + $this->assertText(t('A confirmation request to cancel your account has been sent to your e-mail address.'), t('Account cancellation request mailed message displayed.')); + + // Confirm account cancellation request. + $this->drupalGet("user/$account->uid/cancel/confirm/$timestamp/" . user_pass_rehash($account->pass, $timestamp, $account->login)); + $account = user_load($account->uid, TRUE); + $this->assertTrue($account->status == 0, t('User has been blocked.')); + + // Confirm user's content has been unpublished. + $test_node = node_load($node->nid, NULL, TRUE); + $this->assertTrue($test_node->status == 0, t('Node of the user has been unpublished.')); + $test_node = node_load($node->nid, $node->vid, TRUE); + $this->assertTrue($test_node->status == 0, t('Node revision of the user has been unpublished.')); + + // Confirm user is logged out. + $this->assertNoText($account->name, t('Logged out.')); + } + + /** + * Delete account and anonymize all content. + */ + function testUserAnonymize() { + variable_set('user_cancel_method', 'user_cancel_reassign'); + + // Create a user. + $account = $this->drupalCreateUser(array('cancel account')); + $this->drupalLogin($account); + // Load real user object. + $account = user_load($account->uid, TRUE); + + // Create a simple node. + $node = $this->drupalCreateNode(array('uid' => $account->uid)); + + // Create a node with two revisions, the initial one belonging to the + // cancelling user. + $revision_node = $this->drupalCreateNode(array('uid' => $account->uid)); + $revision = $revision_node->vid; + $settings = get_object_vars($revision_node); + $settings['revision'] = 1; + $settings['uid'] = 1; // Set new/current revision to someone else. + $revision_node = $this->drupalCreateNode($settings); + + // Attempt to cancel account. + $this->drupalGet('user/' . $account->uid . '/edit'); + $this->drupalPost(NULL, NULL, t('Cancel account')); + $this->assertText(t('Are you sure you want to cancel your account?'), t('Confirmation form to cancel account displayed.')); + $this->assertRaw(t('Your account will be removed and all account information deleted. All of your content will be assigned to the %anonymous-name user.', array('%anonymous-name' => variable_get('anonymous', t('Anonymous')))), t('Informs that all content will be attributed to anonymous account.')); + + // Confirm account cancellation. + $timestamp = time(); + $this->drupalPost(NULL, NULL, t('Cancel account')); + $this->assertText(t('A confirmation request to cancel your account has been sent to your e-mail address.'), t('Account cancellation request mailed message displayed.')); + + // Confirm account cancellation request. + $this->drupalGet("user/$account->uid/cancel/confirm/$timestamp/" . user_pass_rehash($account->pass, $timestamp, $account->login)); + $this->assertFalse(user_load($account->uid, TRUE), t('User is not found in the database.')); + + // Confirm that user's content has been attributed to anonymous user. + $test_node = node_load($node->nid, NULL, TRUE); + $this->assertTrue(($test_node->uid == 0 && $test_node->status == 1), t('Node of the user has been attributed to anonymous user.')); + $test_node = node_load($revision_node->nid, $revision, TRUE); + $this->assertTrue(($test_node->revision_uid == 0 && $test_node->status == 1), t('Node revision of the user has been attributed to anonymous user.')); + $test_node = node_load($revision_node->nid, NULL, TRUE); + $this->assertTrue(($test_node->uid != 0 && $test_node->status == 1), t("Current revision of the user's node was not attributed to anonymous user.")); + + // Confirm that user is logged out. + $this->assertNoText($account->name, t('Logged out.')); + } + + /** + * Delete account and remove all content. + */ + function testUserDelete() { + variable_set('user_cancel_method', 'user_cancel_delete'); + + // Create a user. + $account = $this->drupalCreateUser(array('cancel account', 'post comments', 'skip comment approval')); + $this->drupalLogin($account); + // Load real user object. + $account = user_load($account->uid, TRUE); + + // Create a simple node. + $node = $this->drupalCreateNode(array('uid' => $account->uid)); + + // Create comment. + $langcode = LANGUAGE_NONE; + $edit = array(); + $edit['subject'] = $this->randomName(8); + $edit['comment_body[' . $langcode . '][0][value]'] = $this->randomName(16); + + $this->drupalPost('comment/reply/' . $node->nid, $edit, t('Preview')); + $this->drupalPost(NULL, array(), t('Save')); + $this->assertText(t('Your comment has been posted.')); + $comments = comment_load_multiple(array(), array('subject' => $edit['subject'])); + $comment = reset($comments); + $this->assertTrue($comment->cid, t('Comment found.')); + + // Create a node with two revisions, the initial one belonging to the + // cancelling user. + $revision_node = $this->drupalCreateNode(array('uid' => $account->uid)); + $revision = $revision_node->vid; + $settings = get_object_vars($revision_node); + $settings['revision'] = 1; + $settings['uid'] = 1; // Set new/current revision to someone else. + $revision_node = $this->drupalCreateNode($settings); + + // Attempt to cancel account. + $this->drupalGet('user/' . $account->uid . '/edit'); + $this->drupalPost(NULL, NULL, t('Cancel account')); + $this->assertText(t('Are you sure you want to cancel your account?'), t('Confirmation form to cancel account displayed.')); + $this->assertText(t('Your account will be removed and all account information deleted. All of your content will also be deleted.'), t('Informs that all content will be deleted.')); + + // Confirm account cancellation. + $timestamp = time(); + $this->drupalPost(NULL, NULL, t('Cancel account')); + $this->assertText(t('A confirmation request to cancel your account has been sent to your e-mail address.'), t('Account cancellation request mailed message displayed.')); + + // Confirm account cancellation request. + $this->drupalGet("user/$account->uid/cancel/confirm/$timestamp/" . user_pass_rehash($account->pass, $timestamp, $account->login)); + $this->assertFalse(user_load($account->uid, TRUE), t('User is not found in the database.')); + + // Confirm that user's content has been deleted. + $this->assertFalse(node_load($node->nid, NULL, TRUE), t('Node of the user has been deleted.')); + $this->assertFalse(node_load($node->nid, $revision, TRUE), t('Node revision of the user has been deleted.')); + $this->assertTrue(node_load($revision_node->nid, NULL, TRUE), t("Current revision of the user's node was not deleted.")); + $this->assertFalse(comment_load($comment->cid), t('Comment of the user has been deleted.')); + + // Confirm that user is logged out. + $this->assertNoText($account->name, t('Logged out.')); + } + + /** + * Create an administrative user and delete another user. + */ + function testUserCancelByAdmin() { + variable_set('user_cancel_method', 'user_cancel_reassign'); + + // Create a regular user. + $account = $this->drupalCreateUser(array()); + + // Create administrative user. + $admin_user = $this->drupalCreateUser(array('administer users')); + $this->drupalLogin($admin_user); + + // Delete regular user. + $this->drupalGet('user/' . $account->uid . '/edit'); + $this->drupalPost(NULL, NULL, t('Cancel account')); + $this->assertRaw(t('Are you sure you want to cancel the account %name?', array('%name' => $account->name)), t('Confirmation form to cancel account displayed.')); + $this->assertText(t('Select the method to cancel the account above.'), t('Allows to select account cancellation method.')); + + // Confirm deletion. + $this->drupalPost(NULL, NULL, t('Cancel account')); + $this->assertRaw(t('%name has been deleted.', array('%name' => $account->name)), t('User deleted.')); + $this->assertFalse(user_load($account->uid), t('User is not found in the database.')); + } + + /** + * Create an administrative user and mass-delete other users. + */ + function testMassUserCancelByAdmin() { + variable_set('user_cancel_method', 'user_cancel_reassign'); + // Enable account cancellation notification. + variable_set('user_mail_status_canceled_notify', TRUE); + + // Create administrative user. + $admin_user = $this->drupalCreateUser(array('administer users')); + $this->drupalLogin($admin_user); + + // Create some users. + $users = array(); + for ($i = 0; $i < 3; $i++) { + $account = $this->drupalCreateUser(array()); + $users[$account->uid] = $account; + } + + // Cancel user accounts, including own one. + $edit = array(); + $edit['operation'] = 'cancel'; + foreach ($users as $uid => $account) { + $edit['accounts[' . $uid . ']'] = TRUE; + } + $edit['accounts[' . $admin_user->uid . ']'] = TRUE; + // Also try to cancel uid 1. + $edit['accounts[1]'] = TRUE; + $this->drupalPost('admin/people', $edit, t('Update')); + $this->assertText(t('Are you sure you want to cancel these user accounts?'), t('Confirmation form to cancel accounts displayed.')); + $this->assertText(t('When cancelling these accounts'), t('Allows to select account cancellation method.')); + $this->assertText(t('Require e-mail confirmation to cancel account.'), t('Allows to send confirmation mail.')); + $this->assertText(t('Notify user when account is canceled.'), t('Allows to send notification mail.')); + + // Confirm deletion. + $this->drupalPost(NULL, NULL, t('Cancel accounts')); + $status = TRUE; + foreach ($users as $account) { + $status = $status && (strpos($this->content, t('%name has been deleted.', array('%name' => $account->name))) !== FALSE); + $status = $status && !user_load($account->uid, TRUE); + } + $this->assertTrue($status, t('Users deleted and not found in the database.')); + + // Ensure that admin account was not cancelled. + $this->assertText(t('A confirmation request to cancel your account has been sent to your e-mail address.'), t('Account cancellation request mailed message displayed.')); + $admin_user = user_load($admin_user->uid); + $this->assertTrue($admin_user->status == 1, t('Administrative user is found in the database and enabled.')); + + // Verify that uid 1's account was not cancelled. + $user1 = user_load(1, TRUE); + $this->assertEqual($user1->status, 1, t('User #1 still exists and is not blocked.')); + } +} + +class UserPictureTestCase extends DrupalWebTestCase { + protected $user; + protected $_directory_test; + + public static function getInfo() { + return array( + 'name' => 'Upload user picture', + 'description' => 'Assure that dimension check, extension check and image scaling work as designed.', + 'group' => 'User' + ); + } + + function setUp() { + parent::setUp(); + // Enable user pictures. + variable_set('user_pictures', 1); + + $this->user = $this->drupalCreateUser(); + + // Test if directories specified in settings exist in filesystem. + $file_dir = 'public://'; + $file_check = file_prepare_directory($file_dir, FILE_CREATE_DIRECTORY); + // TODO: Test public and private methods? + + $picture_dir = variable_get('user_picture_path', 'pictures'); + $picture_path = $file_dir . $picture_dir; + + $pic_check = file_prepare_directory($picture_path, FILE_CREATE_DIRECTORY); + $this->_directory_test = is_writable($picture_path); + $this->assertTrue($this->_directory_test, "The directory $picture_path doesn't exist or is not writable. Further tests won't be made."); + } + + function testNoPicture() { + $this->drupalLogin($this->user); + + // Try to upload a file that is not an image for the user picture. + $not_an_image = current($this->drupalGetTestFiles('html')); + $this->saveUserPicture($not_an_image); + $this->assertRaw(t('Only JPEG, PNG and GIF images are allowed.'), t('Non-image files are not accepted.')); + } + + /** + * Do the test: + * GD Toolkit is installed + * Picture has invalid dimension + * + * results: The image should be uploaded because ImageGDToolkit resizes the picture + */ + function testWithGDinvalidDimension() { + if ($this->_directory_test && image_get_toolkit()) { + $this->drupalLogin($this->user); + + $image = current($this->drupalGetTestFiles('image')); + $info = image_get_info($image->uri); + + // Set new variables: invalid dimensions, valid filesize (0 = no limit). + $test_dim = ($info['width'] - 10) . 'x' . ($info['height'] - 10); + variable_set('user_picture_dimensions', $test_dim); + variable_set('user_picture_file_size', 0); + + $pic_path = $this->saveUserPicture($image); + // Check that the image was resized and is being displayed on the + // user's profile page. + $text = t('The image was resized to fit within the maximum allowed dimensions of %dimensions pixels.', array('%dimensions' => $test_dim)); + $this->assertRaw($text, t('Image was resized.')); + $alt = t("@user's picture", array('@user' => format_username($this->user))); + $style = variable_get('user_picture_style', ''); + $this->assertRaw(image_style_url($style, $pic_path), t("Image is displayed in user's edit page")); + + // Check if file is located in proper directory. + $this->assertTrue(is_file($pic_path), t("File is located in proper directory")); + } + } + + /** + * Do the test: + * GD Toolkit is installed + * Picture has invalid size + * + * results: The image should be uploaded because ImageGDToolkit resizes the picture + */ + function testWithGDinvalidSize() { + if ($this->_directory_test && image_get_toolkit()) { + $this->drupalLogin($this->user); + + // Images are sorted first by size then by name. We need an image + // bigger than 1 KB so we'll grab the last one. + $files = $this->drupalGetTestFiles('image'); + $image = end($files); + $info = image_get_info($image->uri); + + // Set new variables: valid dimensions, invalid filesize. + $test_dim = ($info['width'] + 10) . 'x' . ($info['height'] + 10); + $test_size = 1; + variable_set('user_picture_dimensions', $test_dim); + variable_set('user_picture_file_size', $test_size); + + $pic_path = $this->saveUserPicture($image); + + // Test that the upload failed and that the correct reason was cited. + $text = t('The specified file %filename could not be uploaded.', array('%filename' => $image->filename)); + $this->assertRaw($text, t('Upload failed.')); + $text = t('The file is %filesize exceeding the maximum file size of %maxsize.', array('%filesize' => format_size(filesize($image->uri)), '%maxsize' => format_size($test_size * 1024))); + $this->assertRaw($text, t('File size cited as reason for failure.')); + + // Check if file is not uploaded. + $this->assertFalse(is_file($pic_path), t('File was not uploaded.')); + } + } + + /** + * Do the test: + * GD Toolkit is not installed + * Picture has invalid size + * + * results: The image shouldn't be uploaded + */ + function testWithoutGDinvalidDimension() { + if ($this->_directory_test && !image_get_toolkit()) { + $this->drupalLogin($this->user); + + $image = current($this->drupalGetTestFiles('image')); + $info = image_get_info($image->uri); + + // Set new variables: invalid dimensions, valid filesize (0 = no limit). + $test_dim = ($info['width'] - 10) . 'x' . ($info['height'] - 10); + variable_set('user_picture_dimensions', $test_dim); + variable_set('user_picture_file_size', 0); + + $pic_path = $this->saveUserPicture($image); + + // Test that the upload failed and that the correct reason was cited. + $text = t('The specified file %filename could not be uploaded.', array('%filename' => $image->filename)); + $this->assertRaw($text, t('Upload failed.')); + $text = t('The image is too large; the maximum dimensions are %dimensions pixels.', array('%dimensions' => $test_dim)); + $this->assertRaw($text, t('Checking response on invalid image (dimensions).')); + + // Check if file is not uploaded. + $this->assertFalse(is_file($pic_path), t('File was not uploaded.')); + } + } + + /** + * Do the test: + * GD Toolkit is not installed + * Picture has invalid size + * + * results: The image shouldn't be uploaded + */ + function testWithoutGDinvalidSize() { + if ($this->_directory_test && !image_get_toolkit()) { + $this->drupalLogin($this->user); + + $image = current($this->drupalGetTestFiles('image')); + $info = image_get_info($image->uri); + + // Set new variables: valid dimensions, invalid filesize. + $test_dim = ($info['width'] + 10) . 'x' . ($info['height'] + 10); + $test_size = 1; + variable_set('user_picture_dimensions', $test_dim); + variable_set('user_picture_file_size', $test_size); + + $pic_path = $this->saveUserPicture($image); + + // Test that the upload failed and that the correct reason was cited. + $text = t('The specified file %filename could not be uploaded.', array('%filename' => $image->filename)); + $this->assertRaw($text, t('Upload failed.')); + $text = t('The file is %filesize exceeding the maximum file size of %maxsize.', array('%filesize' => format_size(filesize($image->uri)), '%maxsize' => format_size($test_size * 1024))); + $this->assertRaw($text, t('File size cited as reason for failure.')); + + // Check if file is not uploaded. + $this->assertFalse(is_file($pic_path), t('File was not uploaded.')); + } + } + + /** + * Do the test: + * Picture is valid (proper size and dimension) + * + * results: The image should be uploaded + */ + function testPictureIsValid() { + if ($this->_directory_test) { + $this->drupalLogin($this->user); + + $image = current($this->drupalGetTestFiles('image')); + $info = image_get_info($image->uri); + + // Set new variables: valid dimensions, valid filesize (0 = no limit). + $test_dim = ($info['width'] + 10) . 'x' . ($info['height'] + 10); + variable_set('user_picture_dimensions', $test_dim); + variable_set('user_picture_file_size', 0); + + $pic_path = $this->saveUserPicture($image); + + // Check if image is displayed in user's profile page. + $this->drupalGet('user'); + $this->assertRaw(file_uri_target($pic_path), t("Image is displayed in user's profile page")); + + // Check if file is located in proper directory. + $this->assertTrue(is_file($pic_path), t('File is located in proper directory')); + + // Set new picture dimensions. + $test_dim = ($info['width'] + 5) . 'x' . ($info['height'] + 5); + variable_set('user_picture_dimensions', $test_dim); + + $pic_path2 = $this->saveUserPicture($image); + $this->assertNotEqual($pic_path, $pic_path2, t('Filename of second picture is different.')); + } + } + + /** + * Test HTTP schema working with user pictures. + */ + function testExternalPicture() { + $this->drupalLogin($this->user); + // Set the default picture to an URI with a HTTP schema. + $images = $this->drupalGetTestFiles('image'); + $image = $images[0]; + $pic_path = file_create_url($image->uri); + variable_set('user_picture_default', $pic_path); + + // Check if image is displayed in user's profile page. + $this->drupalGet('user'); + + // Get the user picture image via xpath. + $elements = $this->xpath('//div[@class="user-picture"]/img'); + $this->assertEqual(count($elements), 1, t("There is exactly one user picture on the user's profile page")); + $this->assertEqual($pic_path, (string) $elements[0]['src'], t("User picture source is correct.")); + } + + function saveUserPicture($image) { + $edit = array('files[picture_upload]' => drupal_realpath($image->uri)); + $this->drupalPost('user/' . $this->user->uid . '/edit', $edit, t('Save')); + + // Load actual user data from database. + $account = user_load($this->user->uid, TRUE); + return isset($account->picture) ? $account->picture->uri : NULL; + } +} + + +class UserPermissionsTestCase extends DrupalWebTestCase { + protected $admin_user; + protected $rid; + + public static function getInfo() { + return array( + 'name' => 'Role permissions', + 'description' => 'Verify that role permissions can be added and removed via the permissions page.', + 'group' => 'User' + ); + } + + function setUp() { + parent::setUp(); + + $this->admin_user = $this->drupalCreateUser(array('administer permissions', 'access user profiles', 'administer site configuration', 'administer modules', 'administer users')); + + // Find the new role ID - it must be the maximum. + $all_rids = array_keys($this->admin_user->roles); + sort($all_rids); + $this->rid = array_pop($all_rids); + } + + /** + * Change user permissions and check user_access(). + */ + function testUserPermissionChanges() { + $this->drupalLogin($this->admin_user); + $rid = $this->rid; + $account = $this->admin_user; + + // Add a permission. + $this->assertFalse(user_access('administer nodes', $account), t('User does not have "administer nodes" permission.')); + $edit = array(); + $edit[$rid . '[administer nodes]'] = TRUE; + $this->drupalPost('admin/people/permissions', $edit, t('Save permissions')); + $this->assertText(t('The changes have been saved.'), t('Successful save message displayed.')); + drupal_static_reset('user_access'); + drupal_static_reset('user_role_permissions'); + $this->assertTrue(user_access('administer nodes', $account), t('User now has "administer nodes" permission.')); + + // Remove a permission. + $this->assertTrue(user_access('access user profiles', $account), t('User has "access user profiles" permission.')); + $edit = array(); + $edit[$rid . '[access user profiles]'] = FALSE; + $this->drupalPost('admin/people/permissions', $edit, t('Save permissions')); + $this->assertText(t('The changes have been saved.'), t('Successful save message displayed.')); + drupal_static_reset('user_access'); + drupal_static_reset('user_role_permissions'); + $this->assertFalse(user_access('access user profiles', $account), t('User no longer has "access user profiles" permission.')); + } + + /** + * Test assigning of permissions for the administrator role. + */ + function testAdministratorRole() { + $this->drupalLogin($this->admin_user); + $this->drupalGet('admin/config/people/accounts'); + + // Set the user's role to be the administrator role. + $edit = array(); + $edit['user_admin_role'] = $this->rid; + $this->drupalPost('admin/config/people/accounts', $edit, t('Save configuration')); + + // Enable aggregator module and ensure the 'administer news feeds' + // permission is assigned by default. + $edit = array(); + $edit['modules[Core][aggregator][enable]'] = TRUE; + $this->drupalPost('admin/modules', $edit, t('Save configuration')); + $this->assertTrue(user_access('administer news feeds', $this->admin_user), t('The permission was automatically assigned to the administrator role')); + } + + /** + * Verify proper permission changes by user_role_change_permissions(). + */ + function testUserRoleChangePermissions() { + $rid = $this->rid; + $account = $this->admin_user; + + // Verify current permissions. + $this->assertFalse(user_access('administer nodes', $account), t('User does not have "administer nodes" permission.')); + $this->assertTrue(user_access('access user profiles', $account), t('User has "access user profiles" permission.')); + $this->assertTrue(user_access('administer site configuration', $account), t('User has "administer site configuration" permission.')); + + // Change permissions. + $permissions = array( + 'administer nodes' => 1, + 'access user profiles' => 0, + ); + user_role_change_permissions($rid, $permissions); + + // Verify proper permission changes. + $this->assertTrue(user_access('administer nodes', $account), t('User now has "administer nodes" permission.')); + $this->assertFalse(user_access('access user profiles', $account), t('User no longer has "access user profiles" permission.')); + $this->assertTrue(user_access('administer site configuration', $account), t('User still has "administer site configuration" permission.')); + } +} + +class UserAdminTestCase extends DrupalWebTestCase { + public static function getInfo() { + return array( + 'name' => 'User administration', + 'description' => 'Test user administration page functionality.', + 'group' => 'User' + ); + } + + /** + * Registers a user and deletes it. + */ + function testUserAdmin() { + + $user_a = $this->drupalCreateUser(array()); + $user_b = $this->drupalCreateUser(array('administer taxonomy')); + $user_c = $this->drupalCreateUser(array('administer taxonomy')); + + // Create admin user to delete registered user. + $admin_user = $this->drupalCreateUser(array('administer users')); + $this->drupalLogin($admin_user); + $this->drupalGet('admin/people'); + $this->assertText($user_a->name, t('Found user A on admin users page')); + $this->assertText($user_b->name, t('Found user B on admin users page')); + $this->assertText($user_c->name, t('Found user C on admin users page')); + $this->assertText($admin_user->name, t('Found Admin user on admin users page')); + + // Test for existence of edit link in table. + $link = l(t('edit'), "user/$user_a->uid/edit", array('query' => array('destination' => 'admin/people'))); + $this->assertRaw($link, t('Found user A edit link on admin users page')); + + // Filter the users by permission 'administer taxonomy'. + $edit = array(); + $edit['permission'] = 'administer taxonomy'; + $this->drupalPost('admin/people', $edit, t('Filter')); + + // Check if the correct users show up. + $this->assertNoText($user_a->name, t('User A not on filtered by perm admin users page')); + $this->assertText($user_b->name, t('Found user B on filtered by perm admin users page')); + $this->assertText($user_c->name, t('Found user C on filtered by perm admin users page')); + + // Filter the users by role. Grab the system-generated role name for User C. + $edit['role'] = max(array_flip($user_c->roles)); + $this->drupalPost('admin/people', $edit, t('Refine')); + + // Check if the correct users show up when filtered by role. + $this->assertNoText($user_a->name, t('User A not on filtered by role on admin users page')); + $this->assertNoText($user_b->name, t('User B not on filtered by role on admin users page')); + $this->assertText($user_c->name, t('User C on filtered by role on admin users page')); + + // Test blocking of a user. + $account = user_load($user_c->uid); + $this->assertEqual($account->status, 1, 'User C not blocked'); + $edit = array(); + $edit['operation'] = 'block'; + $edit['accounts[' . $account->uid . ']'] = TRUE; + $this->drupalPost('admin/people', $edit, t('Update')); + $account = user_load($user_c->uid, TRUE); + $this->assertEqual($account->status, 0, 'User C blocked'); + + // Test unblocking of a user from /admin/people page and sending of activation mail + $editunblock = array(); + $editunblock['operation'] = 'unblock'; + $editunblock['accounts[' . $account->uid . ']'] = TRUE; + $this->drupalPost('admin/people', $editunblock, t('Update')); + $account = user_load($user_c->uid, TRUE); + $this->assertEqual($account->status, 1, 'User C unblocked'); + $this->assertMail("to", $account->mail, "Activation mail sent to user C"); + + // Test blocking and unblocking another user from /user/[uid]/edit form and sending of activation mail + $user_d = $this->drupalCreateUser(array()); + $account1 = user_load($user_d->uid, TRUE); + $this->drupalPost('user/' . $account1->uid . '/edit', array('status' => 0), t('Save')); + $account1 = user_load($user_d->uid, TRUE); + $this->assertEqual($account1->status, 0, 'User D blocked'); + $this->drupalPost('user/' . $account1->uid . '/edit', array('status' => TRUE), t('Save')); + $account1 = user_load($user_d->uid, TRUE); + $this->assertEqual($account1->status, 1, 'User D unblocked'); + $this->assertMail("to", $account1->mail, "Activation mail sent to user D"); + } +} + +/** + * Tests for user-configurable time zones. + */ +class UserTimeZoneFunctionalTest extends DrupalWebTestCase { + public static function getInfo() { + return array( + 'name' => 'User time zones', + 'description' => 'Set a user time zone and verify that dates are displayed in local time.', + 'group' => 'User', + ); + } + + /** + * Tests the display of dates and time when user-configurable time zones are set. + */ + function testUserTimeZone() { + // Setup date/time settings for Los Angeles time. + variable_set('date_default_timezone', 'America/Los_Angeles'); + variable_set('configurable_timezones', 1); + variable_set('date_format_medium', 'Y-m-d H:i T'); + + // Create a user account and login. + $web_user = $this->drupalCreateUser(); + $this->drupalLogin($web_user); + + // Create some nodes with different authored-on dates. + // Two dates in PST (winter time): + $date1 = '2007-03-09 21:00:00 -0800'; + $date2 = '2007-03-11 01:00:00 -0800'; + // One date in PDT (summer time): + $date3 = '2007-03-20 21:00:00 -0700'; + $node1 = $this->drupalCreateNode(array('created' => strtotime($date1), 'type' => 'article')); + $node2 = $this->drupalCreateNode(array('created' => strtotime($date2), 'type' => 'article')); + $node3 = $this->drupalCreateNode(array('created' => strtotime($date3), 'type' => 'article')); + + // Confirm date format and time zone. + $this->drupalGet("node/$node1->nid"); + $this->assertText('2007-03-09 21:00 PST', t('Date should be PST.')); + $this->drupalGet("node/$node2->nid"); + $this->assertText('2007-03-11 01:00 PST', t('Date should be PST.')); + $this->drupalGet("node/$node3->nid"); + $this->assertText('2007-03-20 21:00 PDT', t('Date should be PDT.')); + + // Change user time zone to Santiago time. + $edit = array(); + $edit['mail'] = $web_user->mail; + $edit['timezone'] = 'America/Santiago'; + $this->drupalPost("user/$web_user->uid/edit", $edit, t('Save')); + $this->assertText(t('The changes have been saved.'), t('Time zone changed to Santiago time.')); + + // Confirm date format and time zone. + $this->drupalGet("node/$node1->nid"); + $this->assertText('2007-03-10 02:00 CLST', t('Date should be Chile summer time; five hours ahead of PST.')); + $this->drupalGet("node/$node2->nid"); + $this->assertText('2007-03-11 05:00 CLT', t('Date should be Chile time; four hours ahead of PST')); + $this->drupalGet("node/$node3->nid"); + $this->assertText('2007-03-21 00:00 CLT', t('Date should be Chile time; three hours ahead of PDT.')); + } +} + +/** + * Test user autocompletion. + */ +class UserAutocompleteTestCase extends DrupalWebTestCase { + public static function getInfo() { + return array( + 'name' => 'User autocompletion', + 'description' => 'Test user autocompletion functionality.', + 'group' => 'User' + ); + } + + function setUp() { + parent::setUp(); + + // Set up two users with different permissions to test access. + $this->unprivileged_user = $this->drupalCreateUser(); + $this->privileged_user = $this->drupalCreateUser(array('access user profiles')); + } + + /** + * Tests access to user autocompletion and verify the correct results. + */ + function testUserAutocomplete() { + // Check access from unprivileged user, should be denied. + $this->drupalLogin($this->unprivileged_user); + $this->drupalGet('user/autocomplete/' . $this->unprivileged_user->name[0]); + $this->assertResponse(403, t('Autocompletion access denied to user without permission.')); + + // Check access from privileged user. + $this->drupalLogout(); + $this->drupalLogin($this->privileged_user); + $this->drupalGet('user/autocomplete/' . $this->unprivileged_user->name[0]); + $this->assertResponse(200, t('Autocompletion access allowed.')); + + // Using first letter of the user's name, make sure the user's full name is in the results. + $this->assertRaw($this->unprivileged_user->name, t('User name found in autocompletion results.')); + } +} + + +/** + * Test user-links in secondary menu. + */ +class UserAccountLinksUnitTests extends DrupalWebTestCase { + public static function getInfo() { + return array( + 'name' => 'User account links', + 'description' => 'Test user-account links.', + 'group' => 'User' + ); + } + + /** + * Test the user login block. + */ + function testSecondaryMenu() { + // Create a regular user. + $user = $this->drupalCreateUser(array()); + + // Log in and get the homepage. + $this->drupalLogin($user); + $this->drupalGet('<front>'); + + // For a logged-in user, expect the secondary menu to have links for "My + // account" and "Log out". + $link = $this->xpath('//ul[@id=:menu_id]/li/a[contains(@href, :href) and text()=:text]', array( + ':menu_id' => 'secondary-menu-links', + ':href' => 'user', + ':text' => 'My account', + )); + $this->assertEqual(count($link), 1, 'My account link is in secondary menu.'); + + $link = $this->xpath('//ul[@id=:menu_id]/li/a[contains(@href, :href) and text()=:text]', array( + ':menu_id' => 'secondary-menu-links', + ':href' => 'user/logout', + ':text' => 'Log out', + )); + $this->assertEqual(count($link), 1, 'Log out link is in secondary menu.'); + + // Log out and get the homepage. + $this->drupalLogout(); + $this->drupalGet('<front>'); + + // For a logged-out user, expect no secondary links. + $element = $this->xpath('//ul[@id=:menu_id]', array(':menu_id' => 'secondary-menu-links')); + $this->assertEqual(count($element), 0, 'No secondary-menu for logged-out users.'); + } +} + +/** + * Test user blocks. + */ +class UserBlocksUnitTests extends DrupalWebTestCase { + public static function getInfo() { + return array( + 'name' => 'User blocks', + 'description' => 'Test user blocks.', + 'group' => 'User' + ); + } + + /** + * Test the user login block. + */ + function testUserLoginBlock() { + // Create a user with some permission that anonymous users lack. + $user = $this->drupalCreateUser(array('administer permissions')); + + // Log in using the block. + $edit = array(); + $edit['name'] = $user->name; + $edit['pass'] = $user->pass_raw; + $this->drupalPost('admin/people/permissions', $edit, t('Log in')); + $this->assertNoText(t('User login'), t('Logged in.')); + + // Check that we are still on the same page. + $this->assertEqual(url('admin/people/permissions', array('absolute' => TRUE)), $this->getUrl(), t('Still on the same page after login for access denied page')); + + // Now, log out and repeat with a non-403 page. + $this->drupalLogout(); + $this->drupalPost('filter/tips', $edit, t('Log in')); + $this->assertNoText(t('User login'), t('Logged in.')); + $this->assertPattern('!<title.*?' . t('Compose tips') . '.*?</title>!', t('Still on the same page after login for allowed page')); + } + + /** + * Test the Who's Online block. + */ + function testWhosOnlineBlock() { + // Generate users and make sure there are no current user sessions. + $user1 = $this->drupalCreateUser(array()); + $user2 = $this->drupalCreateUser(array()); + $user3 = $this->drupalCreateUser(array()); + $this->assertEqual(db_query("SELECT COUNT(*) FROM {sessions}")->fetchField(), 0, t('Sessions table is empty.')); + + // Insert a user with two sessions. + $this->insertSession(array('uid' => $user1->uid)); + $this->insertSession(array('uid' => $user1->uid)); + $this->assertEqual(db_query("SELECT COUNT(*) FROM {sessions} WHERE uid = :uid", array(':uid' => $user1->uid))->fetchField(), 2, t('Duplicate user session has been inserted.')); + + // Insert a user with only one session. + $this->insertSession(array('uid' => $user2->uid, 'timestamp' => REQUEST_TIME + 1)); + + // Insert an inactive logged-in user who should not be seen in the block. + $this->insertSession(array('uid' => $user3->uid, 'timestamp' => (REQUEST_TIME - variable_get('user_block_seconds_online', 900) - 1))); + + // Insert two anonymous user sessions. + $this->insertSession(); + $this->insertSession(); + + // Test block output. + $block = user_block_view('online'); + $this->drupalSetContent($block['content']); + $this->assertRaw(t('2 users'), t('Correct number of online users (2 users).')); + $this->assertText($user1->name, t('Active user 1 found in online list.')); + $this->assertText($user2->name, t('Active user 2 found in online list.')); + $this->assertNoText($user3->name, t("Inactive user not found in online list.")); + $this->assertTrue(strpos($this->drupalGetContent(), $user1->name) > strpos($this->drupalGetContent(), $user2->name), t('Online users are ordered correctly.')); + } + + /** + * Insert a user session into the {sessions} table. This function is used + * since we cannot log in more than one user at the same time in tests. + */ + private function insertSession(array $fields = array()) { + $fields += array( + 'uid' => 0, + 'sid' => drupal_hash_base64(uniqid(mt_rand(), TRUE)), + 'timestamp' => REQUEST_TIME, + ); + db_insert('sessions') + ->fields($fields) + ->execute(); + $this->assertEqual(db_query("SELECT COUNT(*) FROM {sessions} WHERE uid = :uid AND sid = :sid AND timestamp = :timestamp", array(':uid' => $fields['uid'], ':sid' => $fields['sid'], ':timestamp' => $fields['timestamp']))->fetchField(), 1, t('Session record inserted.')); + } +} + +/** + * Test case to test user_save() behaviour. + */ +class UserSaveTestCase extends DrupalWebTestCase { + + public static function getInfo() { + return array( + 'name' => 'User save test', + 'description' => 'Test user_save() for arbitrary new uid.', + 'group' => 'User', + ); + } + + /** + * Test creating a user with arbitrary uid. + */ + function testUserImport() { + // User ID must be a number that is not in the database. + $max_uid = db_query('SELECT MAX(uid) FROM {users}')->fetchField(); + $test_uid = $max_uid + mt_rand(1000, 1000000); + $test_name = $this->randomName(); + + // Create the base user, based on drupalCreateUser(). + $user = array( + 'name' => $test_name, + 'uid' => $test_uid, + 'mail' => $test_name . '@example.com', + 'is_new' => TRUE, + 'pass' => user_password(), + 'status' => 1, + ); + $user_by_return = user_save(drupal_anonymous_user(), $user); + $this->assertTrue($user_by_return, t('Loading user by return of user_save().')); + + // Test if created user exists. + $user_by_uid = user_load($test_uid); + $this->assertTrue($user_by_uid, t('Loading user by uid.')); + + $user_by_name = user_load_by_name($test_name); + $this->assertTrue($user_by_name, t('Loading user by name.')); + } +} + +/** + * Test the create user administration page. + */ +class UserCreateTestCase extends DrupalWebTestCase { + + public static function getInfo() { + return array( + 'name' => 'User create', + 'description' => 'Test the create user administration page.', + 'group' => 'User', + ); + } + + /** + * Create a user through the administration interface and ensure that it + * displays in the user list. + */ + protected function testUserAdd() { + $user = $this->drupalCreateUser(array('administer users')); + $this->drupalLogin($user); + + foreach (array(FALSE, TRUE) as $notify) { + $edit = array( + 'name' => $this->randomName(), + 'mail' => $this->randomName() . '@example.com', + 'pass[pass1]' => $pass = $this->randomString(), + 'pass[pass2]' => $pass, + 'notify' => $notify, + ); + $this->drupalPost('admin/people/create', $edit, t('Create new account')); + + if ($notify) { + $this->assertText(t('A welcome message with further instructions has been e-mailed to the new user @name.', array('@name' => $edit['name'])), 'User created'); + $this->assertEqual(count($this->drupalGetMails()), 1, 'Notification e-mail sent'); + } + else { + $this->assertText(t('Created a new user account for @name. No e-mail has been sent.', array('@name' => $edit['name'])), 'User created'); + $this->assertEqual(count($this->drupalGetMails()), 0, 'Notification e-mail not sent'); + } + + $this->drupalGet('admin/people'); + $this->assertText($edit['name'], 'User found in list of users'); + } + } +} + +/** + * Test case to test user_save() behaviour. + */ +class UserEditTestCase extends DrupalWebTestCase { + + public static function getInfo() { + return array( + 'name' => 'User edit', + 'description' => 'Test user edit page.', + 'group' => 'User', + ); + } + + /** + * Test user edit page. + */ + function testUserEdit() { + // Test user edit functionality with user pictures disabled. + variable_set('user_pictures', 0); + $user1 = $this->drupalCreateUser(array('change own username')); + $user2 = $this->drupalCreateUser(array()); + $this->drupalLogin($user1); + + // Test that error message appears when attempting to use a non-unique user name. + $edit['name'] = $user2->name; + $this->drupalPost("user/$user1->uid/edit", $edit, t('Save')); + $this->assertRaw(t('The name %name is already taken.', array('%name' => $edit['name']))); + + // Repeat the test with user pictures enabled, which modifies the form. + variable_set('user_pictures', 1); + $this->drupalPost("user/$user1->uid/edit", $edit, t('Save')); + $this->assertRaw(t('The name %name is already taken.', array('%name' => $edit['name']))); + + // Check that filling out a single password field does not validate. + $edit = array(); + $edit['pass[pass1]'] = ''; + $edit['pass[pass2]'] = $this->randomName(); + $this->drupalPost("user/$user1->uid/edit", $edit, t('Save')); + $this->assertText(t("The specified passwords do not match."), t('Typing mismatched passwords displays an error message.')); + + $edit['pass[pass1]'] = $this->randomName(); + $edit['pass[pass2]'] = ''; + $this->drupalPost("user/$user1->uid/edit", $edit, t('Save')); + $this->assertText(t("The specified passwords do not match."), t('Typing mismatched passwords displays an error message.')); + + // Test that the error message appears when attempting to change the mail or + // pass without the current password. + $edit = array(); + $edit['mail'] = $this->randomName() . '@new.example.com'; + $this->drupalPost("user/$user1->uid/edit", $edit, t('Save')); + $this->assertRaw(t("Your current password is missing or incorrect; it's required to change the %name.", array('%name' => t('E-mail address')))); + + $edit['current_pass'] = $user1->pass_raw; + $this->drupalPost("user/$user1->uid/edit", $edit, t('Save')); + $this->assertRaw(t("The changes have been saved.")); + + // Test that the user must enter current password before changing passwords. + $edit = array(); + $edit['pass[pass1]'] = $new_pass = $this->randomName(); + $edit['pass[pass2]'] = $new_pass; + $this->drupalPost("user/$user1->uid/edit", $edit, t('Save')); + $this->assertRaw(t("Your current password is missing or incorrect; it's required to change the %name.", array('%name' => t('Password')))); + + // Try again with the current password. + $edit['current_pass'] = $user1->pass_raw; + $this->drupalPost("user/$user1->uid/edit", $edit, t('Save')); + $this->assertRaw(t("The changes have been saved.")); + + // Make sure the user can log in with their new password. + $this->drupalLogout(); + $user1->pass_raw = $new_pass; + $this->drupalLogin($user1); + $this->drupalLogout(); + } +} + +/** + * Test case for user signatures. + */ +class UserSignatureTestCase extends DrupalWebTestCase { + public static function getInfo() { + return array( + 'name' => 'User signatures', + 'description' => 'Test user signatures.', + 'group' => 'User', + ); + } + + function setUp() { + parent::setUp('comment'); + + // Enable user signatures. + variable_set('user_signatures', 1); + + // Prefetch text formats. + $this->full_html_format = filter_format_load('full_html'); + $this->plain_text_format = filter_format_load('plain_text'); + + // Create regular and administrative users. + $this->web_user = $this->drupalCreateUser(array()); + $admin_permissions = array('administer comments'); + foreach (filter_formats() as $format) { + if ($permission = filter_permission_name($format)) { + $admin_permissions[] = $permission; + } + } + $this->admin_user = $this->drupalCreateUser($admin_permissions); + } + + /** + * Test that a user can change their signature format and that it is respected + * upon display. + */ + function testUserSignature() { + // Create a new node with comments on. + $node = $this->drupalCreateNode(array('comment' => COMMENT_NODE_OPEN)); + + // Verify that user signature field is not displayed on registration form. + $this->drupalGet('user/register'); + $this->assertNoText(t('Signature')); + + // Log in as a regular user and create a signature. + $this->drupalLogin($this->web_user); + $signature_text = "<h1>" . $this->randomName() . "</h1>"; + $edit = array( + 'signature[value]' => $signature_text, + 'signature[format]' => $this->plain_text_format->format, + ); + $this->drupalPost('user/' . $this->web_user->uid . '/edit', $edit, t('Save')); + + // Verify that values were stored. + $this->assertFieldByName('signature[value]', $edit['signature[value]'], 'Submitted signature text found.'); + $this->assertFieldByName('signature[format]', $edit['signature[format]'], 'Submitted signature format found.'); + + // Create a comment. + $langcode = LANGUAGE_NONE; + $edit = array(); + $edit['subject'] = $this->randomName(8); + $edit['comment_body[' . $langcode . '][0][value]'] = $this->randomName(16); + $this->drupalPost('comment/reply/' . $node->nid, $edit, t('Preview')); + $this->drupalPost(NULL, array(), t('Save')); + + // Get the comment ID. (This technique is the same one used in the Comment + // module's CommentHelperCase test case.) + preg_match('/#comment-([0-9]+)/', $this->getURL(), $match); + $comment_id = $match[1]; + + // Log in as an administrator and edit the comment to use Full HTML, so + // that the comment text itself is not filtered at all. + $this->drupalLogin($this->admin_user); + $edit['comment_body[' . $langcode . '][0][format]'] = $this->full_html_format->format; + $this->drupalPost('comment/' . $comment_id . '/edit', $edit, t('Save')); + + // Assert that the signature did not make it through unfiltered. + $this->drupalGet('node/' . $node->nid); + $this->assertNoRaw($signature_text, 'Unfiltered signature text not found.'); + $this->assertRaw(check_markup($signature_text, $this->plain_text_format->format), 'Filtered signature text found.'); + } +} + +/* + * Test that a user, having editing their own account, can still log in. + */ +class UserEditedOwnAccountTestCase extends DrupalWebTestCase { + + public static function getInfo() { + return array( + 'name' => 'User edited own account', + 'description' => 'Test user edited own account can still log in.', + 'group' => 'User', + ); + } + + function testUserEditedOwnAccount() { + // Change account setting 'Who can register accounts?' to Administrators + // only. + variable_set('user_register', USER_REGISTER_ADMINISTRATORS_ONLY); + + // Create a new user account and log in. + $account = $this->drupalCreateUser(array('change own username')); + $this->drupalLogin($account); + + // Change own username. + $edit = array(); + $edit['name'] = $this->randomName(); + $this->drupalPost('user/' . $account->uid . '/edit', $edit, t('Save')); + + // Log out. + $this->drupalLogout(); + + // Set the new name on the user account and attempt to log back in. + $account->name = $edit['name']; + $this->drupalLogin($account); + } +} + +/** + * Test case to test adding, editing and deleting roles. + */ +class UserRoleAdminTestCase extends DrupalWebTestCase { + + public static function getInfo() { + return array( + 'name' => 'User role administration', + 'description' => 'Test adding, editing and deleting user roles and changing role weights.', + 'group' => 'User', + ); + } + + function setUp() { + parent::setUp(); + $this->admin_user = $this->drupalCreateUser(array('administer permissions', 'administer users')); + } + + /** + * Test adding, renaming and deleting roles. + */ + function testRoleAdministration() { + $this->drupalLogin($this->admin_user); + + // Test adding a role. (In doing so, we use a role name that happens to + // correspond to an integer, to test that the role administration pages + // correctly distinguish between role names and IDs.) + $role_name = '123'; + $edit = array('name' => $role_name); + $this->drupalPost('admin/people/permissions/roles', $edit, t('Add role')); + $this->assertText(t('The role has been added.'), t('The role has been added.')); + $role = user_role_load_by_name($role_name); + $this->assertTrue(is_object($role), t('The role was successfully retrieved from the database.')); + + // Try adding a duplicate role. + $this->drupalPost(NULL, $edit, t('Add role')); + $this->assertRaw(t('The role name %name already exists. Choose another role name.', array('%name' => $role_name)), t('Duplicate role warning displayed.')); + + // Test renaming a role. + $old_name = $role_name; + $role_name = '456'; + $edit = array('name' => $role_name); + $this->drupalPost("admin/people/permissions/roles/edit/{$role->rid}", $edit, t('Save role')); + $this->assertText(t('The role has been renamed.'), t('The role has been renamed.')); + $this->assertFalse(user_role_load_by_name($old_name), t('The role can no longer be retrieved from the database using its old name.')); + $this->assertTrue(is_object(user_role_load_by_name($role_name)), t('The role can be retrieved from the database using its new name.')); + + // Test deleting a role. + $this->drupalPost("admin/people/permissions/roles/edit/{$role->rid}", NULL, t('Delete role')); + $this->drupalPost(NULL, NULL, t('Delete')); + $this->assertText(t('The role has been deleted.'), t('The role has been deleted')); + $this->assertNoLinkByHref("admin/people/permissions/roles/edit/{$role->rid}", t('Role edit link removed.')); + $this->assertFalse(user_role_load_by_name($role_name), t('A deleted role can no longer be loaded.')); + + // Make sure that the system-defined roles cannot be edited via the user + // interface. + $this->drupalGet('admin/people/permissions/roles/edit/' . DRUPAL_ANONYMOUS_RID); + $this->assertResponse(403, t('Access denied when trying to edit the built-in anonymous role.')); + $this->drupalGet('admin/people/permissions/roles/edit/' . DRUPAL_AUTHENTICATED_RID); + $this->assertResponse(403, t('Access denied when trying to edit the built-in authenticated role.')); + } + + /** + * Test user role weight change operation. + */ + function testRoleWeightChange() { + $this->drupalLogin($this->admin_user); + + // Pick up a random role and get its weight. + $rid = array_rand(user_roles()); + $role = user_role_load($rid); + $old_weight = $role->weight; + + // Change the role weight and submit the form. + $edit = array('roles['. $rid .'][weight]' => $old_weight + 1); + $this->drupalPost('admin/people/permissions/roles', $edit, t('Save order')); + $this->assertText(t('The role settings have been updated.'), t('The role settings form submitted successfully.')); + + // Retrieve the saved role and compare its weight. + $role = user_role_load($rid); + $new_weight = $role->weight; + $this->assertTrue(($old_weight + 1) == $new_weight, t('Role weight updated successfully.')); + } +} + +/** + * Test user token replacement in strings. + */ +class UserTokenReplaceTestCase extends DrupalWebTestCase { + public static function getInfo() { + return array( + 'name' => 'User token replacement', + 'description' => 'Generates text using placeholders for dummy content to check user token replacement.', + 'group' => 'User', + ); + } + + /** + * Creates a user, then tests the tokens generated from it. + */ + function testUserTokenReplacement() { + global $language; + $url_options = array( + 'absolute' => TRUE, + 'language' => $language, + ); + + // Create two users and log them in one after another. + $user1 = $this->drupalCreateUser(array()); + $user2 = $this->drupalCreateUser(array()); + $this->drupalLogin($user1); + $this->drupalLogout(); + $this->drupalLogin($user2); + + $account = user_load($user1->uid); + $global_account = user_load($GLOBALS['user']->uid); + + // Generate and test sanitized tokens. + $tests = array(); + $tests['[user:uid]'] = $account->uid; + $tests['[user:name]'] = check_plain(format_username($account)); + $tests['[user:mail]'] = check_plain($account->mail); + $tests['[user:url]'] = url("user/$account->uid", $url_options); + $tests['[user:edit-url]'] = url("user/$account->uid/edit", $url_options); + $tests['[user:last-login]'] = format_date($account->login, 'medium', '', NULL, $language->language); + $tests['[user:last-login:short]'] = format_date($account->login, 'short', '', NULL, $language->language); + $tests['[user:created]'] = format_date($account->created, 'medium', '', NULL, $language->language); + $tests['[user:created:short]'] = format_date($account->created, 'short', '', NULL, $language->language); + $tests['[current-user:name]'] = check_plain(format_username($global_account)); + + // Test to make sure that we generated something for each token. + $this->assertFalse(in_array(0, array_map('strlen', $tests)), t('No empty tokens generated.')); + + foreach ($tests as $input => $expected) { + $output = token_replace($input, array('user' => $account), array('language' => $language)); + $this->assertEqual($output, $expected, t('Sanitized user token %token replaced.', array('%token' => $input))); + } + + // Generate and test unsanitized tokens. + $tests['[user:name]'] = format_username($account); + $tests['[user:mail]'] = $account->mail; + $tests['[current-user:name]'] = format_username($global_account); + + foreach ($tests as $input => $expected) { + $output = token_replace($input, array('user' => $account), array('language' => $language, 'sanitize' => FALSE)); + $this->assertEqual($output, $expected, t('Unsanitized user token %token replaced.', array('%token' => $input))); + } + } +} + +/** + * Test user search. + */ +class UserUserSearchTestCase extends DrupalWebTestCase { + public static function getInfo() { + return array( + 'name' => 'User search', + 'description' => 'Testing that only user with the right permission can see the email address in the user search.', + 'group' => 'User', + ); + } + + function testUserSearch() { + $user1 = $this->drupalCreateUser(array('access user profiles', 'search content', 'use advanced search')); + $this->drupalLogin($user1); + $keys = $user1->mail; + $edit = array('keys' => $keys); + $this->drupalPost('search/user/', $edit, t('Search')); + $this->assertNoText($keys); + $this->drupalLogout(); + + $user2 = $this->drupalCreateUser(array('administer users', 'access user profiles', 'search content', 'use advanced search')); + $this->drupalLogin($user2); + $keys = $user2->mail; + $edit = array('keys' => $keys); + $this->drupalPost('search/user/', $edit, t('Search')); + $this->assertText($keys); + $this->drupalLogout(); + } +} + + +/** + * Test role assignment. + */ +class UserRolesAssignmentTestCase extends DrupalWebTestCase { + protected $admin_user; + + public static function getInfo() { + return array( + 'name' => t('Role assignment'), + 'description' => t('Tests that users can be assigned and unassigned roles.'), + 'group' => t('User') + ); + } + + function setUp() { + parent::setUp(); + $this->admin_user = $this->drupalCreateUser(array('administer permissions', 'administer users')); + $this->drupalLogin($this->admin_user); + } + + /** + * Tests that a user can be assigned a role and that the role can be removed + * again. + */ + function testAssignAndRemoveRole() { + $rid = $this->drupalCreateRole(array('administer content types')); + $account = $this->drupalCreateUser(); + + // Assign the role to the user. + $this->drupalPost('user/' . $account->uid . '/edit', array("roles[$rid]" => $rid), t('Save')); + $this->assertText(t('The changes have been saved.')); + $this->assertFieldChecked('edit-roles-' . $rid, t('Role is assigned.')); + $this->userLoadAndCheckRoleAssigned($account, $rid); + + // Remove the role from the user. + $this->drupalPost('user/' . $account->uid . '/edit', array("roles[$rid]" => FALSE), t('Save')); + $this->assertText(t('The changes have been saved.')); + $this->assertNoFieldChecked('edit-roles-' . $rid, t('Role is removed from user.')); + $this->userLoadAndCheckRoleAssigned($account, $rid, FALSE); + } + + /** + * Tests that when creating a user the role can be assigned. And that it can + * be removed again. + */ + function testCreateUserWithRole() { + $rid = $this->drupalCreateRole(array('administer content types')); + // Create a new user and add the role at the same time. + $edit = array( + 'name' => $this->randomName(), + 'mail' => $this->randomName() . '@example.com', + 'pass[pass1]' => $pass = $this->randomString(), + 'pass[pass2]' => $pass, + "roles[$rid]" => $rid, + ); + $this->drupalPost('admin/people/create', $edit, t('Create new account')); + $this->assertText(t('Created a new user account for !name.', array('!name' => $edit['name']))); + // Get the newly added user. + $account = user_load_by_name($edit['name']); + + $this->drupalGet('user/' . $account->uid . '/edit'); + $this->assertFieldChecked('edit-roles-' . $rid, t('Role is assigned.')); + $this->userLoadAndCheckRoleAssigned($account, $rid); + + // Remove the role again. + $this->drupalPost('user/' . $account->uid . '/edit', array("roles[$rid]" => FALSE), t('Save')); + $this->assertText(t('The changes have been saved.')); + $this->assertNoFieldChecked('edit-roles-' . $rid, t('Role is removed from user.')); + $this->userLoadAndCheckRoleAssigned($account, $rid, FALSE); + } + + /** + * Check role on user object. + * + * @param object $account User. + * @param integer $rid Role id. + * @param bool $is_assigned True if the role should present on the account. + */ + private function userLoadAndCheckRoleAssigned($account, $rid, $is_assigned = TRUE) { + $account = user_load($account->uid, TRUE); + if ($is_assigned) { + $this->assertTrue(array_key_exists($rid, $account->roles), t('The role is present in the user object.')); + } + else { + $this->assertFalse(array_key_exists($rid, $account->roles), t('The role is not present in the user object.')); + } + } +} + + +/** + * Unit test for authmap assignment. + */ +class UserAuthmapAssignmentTestCase extends DrupalWebTestCase { + public static function getInfo() { + return array( + 'name' => t('Authmap assignment'), + 'description' => t('Tests that users can be assigned and unassigned authmaps.'), + 'group' => t('User') + ); + } + + /** + * Test authmap assignment and retrieval. + */ + function testAuthmapAssignment() { + $account = $this->drupalCreateUser(); + + // Assign authmaps to the user. + $authmaps = array( + 'authname_poll' => 'external username one', + 'authname_book' => 'external username two', + ); + user_set_authmaps($account, $authmaps); + + // Test for expected authmaps. + $expected_authmaps = array( + 'external username one' => array( + 'poll' => 'external username one', + ), + 'external username two' => array( + 'book' => 'external username two', + ), + ); + foreach ($expected_authmaps as $authname => $expected_output) { + $this->assertIdentical(user_get_authmaps($authname), $expected_output, t('Authmap for authname %authname was set correctly.', array('%authname' => $authname))); + } + + // Remove authmap for module poll, add authmap for module blog. + $authmaps = array( + 'authname_poll' => NULL, + 'authname_blog' => 'external username three', + ); + user_set_authmaps($account, $authmaps); + + // Assert that external username one does not have authmaps. + $remove_username = 'external username one'; + unset($expected_authmaps[$remove_username]); + $this->assertFalse(user_get_authmaps($remove_username), t('Authmap for %authname was removed.', array('%authname' => $remove_username))); + + // Assert that a new authmap was created for external username three, and + // existing authmaps for external username two were unchanged. + $expected_authmaps['external username three'] = array('blog' => 'external username three'); + foreach ($expected_authmaps as $authname => $expected_output) { + $this->assertIdentical(user_get_authmaps($authname), $expected_output, t('Authmap for authname %authname was set correctly.', array('%authname' => $authname))); + } + } +} + +/** + * Tests user_validate_current_pass on a custom form. + */ +class UserValidateCurrentPassCustomForm extends DrupalWebTestCase { + + public static function getInfo() { + return array( + 'name' => 'User validate current pass custom form', + 'description' => 'Test that user_validate_current_pass is usable on a custom form.', + 'group' => 'User', + ); + } + + /** + * User with permission to view content. + */ + protected $accessUser; + + /** + * User permission to administer users. + */ + protected $adminUser; + + function setUp() { + parent::setUp('user_form_test'); + // Create two users + $this->accessUser = $this->drupalCreateUser(array('access content')); + $this->adminUser = $this->drupalCreateUser(array('administer users')); + } + + /** + * Tests that user_validate_current_pass can be reused on a custom form. + */ + function testUserValidateCurrentPassCustomForm() { + $this->drupalLogin($this->adminUser); + + // Submit the custom form with the admin user using the access user's password. + $edit = array(); + $edit['user_form_test_field'] = $this->accessUser->name; + $edit['current_pass'] = $this->accessUser->pass_raw; + $this->drupalPost('user_form_test_current_password/' . $this->accessUser->uid, $edit, t('Test')); + $this->assertText(t('The password has been validated and the form submitted successfully.')); + } +} + +/** + * Test user entity callbacks. + */ +class UserEntityCallbacksTestCase extends DrupalWebTestCase { + public static function getInfo() { + return array( + 'name' => 'User entity callback tests', + 'description' => 'Tests specific parts of the user entity like the URI callback and the label callback.', + 'group' => 'User' + ); + } + + function setUp() { + parent::setUp('user'); + + $this->account = $this->drupalCreateUser(); + $this->anonymous = drupal_anonymous_user(); + } + + /** + * Test label callback. + */ + function testLabelCallback() { + $this->assertEqual(entity_label('user', $this->account), $this->account->name, t('The username should be used as label')); + + // Setup a random anonymous name to be sure the name is used. + $name = $this->randomName(); + variable_set('anonymous', $name); + $this->assertEqual(entity_label('user', $this->anonymous), $name, t('The variable anonymous should be used for name of uid 0')); + } + + /** + * Test URI callback. + */ + function testUriCallback() { + $uri = entity_uri('user', $this->account); + $this->assertEqual('user/' . $this->account->uid, $uri['path'], t('Correct user URI.')); + } +} diff --git a/core/modules/user/user.tokens.inc b/core/modules/user/user.tokens.inc new file mode 100644 index 00000000000..8dcea4b597e --- /dev/null +++ b/core/modules/user/user.tokens.inc @@ -0,0 +1,131 @@ +<?php + +/** + * @file + * Builds placeholder replacement tokens for user-related data. + */ + +/** + * Implements hook_token_info(). + */ +function user_token_info() { + $types['user'] = array( + 'name' => t('Users'), + 'description' => t('Tokens related to individual user accounts.'), + 'needs-data' => 'user', + ); + $types['current-user'] = array( + 'name' => t('Current user'), + 'description' => t('Tokens related to the currently logged in user.'), + 'type' => 'user', + ); + + $user['uid'] = array( + 'name' => t('User ID'), + 'description' => t("The unique ID of the user account."), + ); + $user['name'] = array( + 'name' => t("Name"), + 'description' => t("The login name of the user account."), + ); + $user['mail'] = array( + 'name' => t("Email"), + 'description' => t("The email address of the user account."), + ); + $user['url'] = array( + 'name' => t("URL"), + 'description' => t("The URL of the account profile page."), + ); + $user['edit-url'] = array( + 'name' => t("Edit URL"), + 'description' => t("The URL of the account edit page."), + ); + + $user['last-login'] = array( + 'name' => t("Last login"), + 'description' => t("The date the user last logged in to the site."), + 'type' => 'date', + ); + $user['created'] = array( + 'name' => t("Created"), + 'description' => t("The date the user account was created."), + 'type' => 'date', + ); + + return array( + 'types' => $types, + 'tokens' => array('user' => $user), + ); +} + +/** + * Implements hook_tokens(). + */ +function user_tokens($type, $tokens, array $data = array(), array $options = array()) { + $url_options = array('absolute' => TRUE); + if (isset($options['language'])) { + $url_options['language'] = $options['language']; + $language_code = $options['language']->language; + } + else { + $language_code = NULL; + } + $sanitize = !empty($options['sanitize']); + + $replacements = array(); + + if ($type == 'user' && !empty($data['user'])) { + $account = $data['user']; + foreach ($tokens as $name => $original) { + switch ($name) { + // Basic user account information. + case 'uid': + // In the case of hook user_presave uid is not set yet. + $replacements[$original] = !empty($account->uid) ? $account->uid : t('not yet assigned'); + break; + + case 'name': + $name = format_username($account); + $replacements[$original] = $sanitize ? check_plain($name) : $name; + break; + + case 'mail': + $replacements[$original] = $sanitize ? check_plain($account->mail) : $account->mail; + break; + + case 'url': + $replacements[$original] = !empty($account->uid) ? url("user/$account->uid", $url_options) : t('not yet assigned'); + break; + + case 'edit-url': + $replacements[$original] = !empty($account->uid) ? url("user/$account->uid/edit", $url_options) : t('not yet assigned'); + break; + + // These tokens are default variations on the chained tokens handled below. + case 'last-login': + $replacements[$original] = !empty($account->login) ? format_date($account->login, 'medium', '', NULL, $language_code) : t('never'); + break; + + case 'created': + // In the case of user_presave the created date may not yet be set. + $replacements[$original] = !empty($account->created) ? format_date($account->created, 'medium', '', NULL, $language_code) : t('not yet created'); + break; + } + } + + if ($login_tokens = token_find_with_prefix($tokens, 'last-login')) { + $replacements += token_generate('date', $login_tokens, array('date' => $account->login), $options); + } + + if ($registered_tokens = token_find_with_prefix($tokens, 'created')) { + $replacements += token_generate('date', $registered_tokens, array('date' => $account->created), $options); + } + } + + if ($type == 'current-user') { + $account = user_load($GLOBALS['user']->uid); + $replacements += token_generate('user', $tokens, array('user' => $account), $options); + } + + return $replacements; +} |