user.module

  1. drupal
    1. 4.6 modules/user.module
    2. 4.7 modules/user.module
    3. 5 modules/user/user.module
    4. 6 modules/user/user.module
    5. 7 modules/user/user.module
    6. 8 core/modules/user/user.module

Enables the user registration and login system.

Constants

NameDescription
EMAIL_MAX_LENGTHMaximum length of user e-mail text field.
USERNAME_MAX_LENGTHMaximum length of username text field.
USER_REGISTER_ADMINISTRATORS_ONLYOnly administrators can create user accounts.
USER_REGISTER_VISITORSVisitors can create their own accounts.
USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVALVisitors can create accounts, but they don't become active without administrative approval.

Functions & methods

NameDescription
template_preprocess_usernamePreprocesses variables for theme_username().
template_preprocess_user_pictureProcess variables for user-picture.tpl.php.
template_process_usernameProcesses variables for theme_username().
theme_usernameReturns HTML for a username, potentially linked to the user's page.
theme_user_listReturns HTML for a list of users.
theme_user_signatureReturns HTML for a user signature.
user_accessDetermine whether the user has a given privilege.
user_account_formHelper function to add default user account fields to user registration and edit form.
user_account_form_validateForm validation handler for user_account_form().
user_action_infoImplements hook_action_info().
user_admin_pathsImplements hook_admin_paths().
user_authenticateTry to validate the user's login credentials locally.
user_block_configureImplements hook_block_configure().
user_block_infoImplements hook_block_info().
user_block_saveImplements hook_block_save().
user_block_user_actionBlocks the current user.
user_block_viewImplements hook_block_view().
user_build_contentBuilds a structured array representing the profile content.
user_build_filter_queryExtends a query object for user administration filters based on session.
user_cancelCancel a user account.
user_cancel_accessMenu access callback; limit access to account cancellation pages.
user_cancel_urlGenerates a URL to confirm an account cancellation request.
user_comment_viewImplements hook_comment_view().
user_cookie_deleteDelete a visitor information cookie.
user_cookie_saveSaves visitor information as a cookie so it can be reused.
user_deleteDelete a user.
user_delete_multipleDelete multiple user accounts.
user_edit_accessAccess callback for user account editing.
user_entity_infoImplements hook_entity_info().
user_external_loadFetches a user object based on an external authentication source.
user_external_login_registerHelper 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.
user_field_extra_fieldsImplements hook_field_extra_fields().
user_field_info_alterImplements hook_field_info_alter().
user_file_downloadImplements hook_file_download().
user_file_download_accessImplements hook_file_download_access().
user_file_moveImplements hook_file_move().
user_file_predeleteImplements hook_file_predelete().
user_filtersList user administration filters that can be applied.
user_format_nameFormat a username.
user_form_field_ui_field_edit_form_alterImplements hook_form_FORM_ID_alter().
user_form_field_ui_field_edit_form_submitAdditional submit handler for the 'Edit field instance' form.
user_form_process_password_confirmForm element process handler for client-side password validation.
user_get_authmapsDiscover which external authentication module(s) authenticated a username.
user_helpImplement hook_help().
user_image_style_deleteImplements hook_image_style_delete().
user_image_style_saveImplements hook_image_style_save().
user_is_anonymous
user_is_blockedChecks for usernames blocked by user administration.
user_is_logged_in
user_labelEntity label callback.
user_loadLoads a user object.
user_load_by_mailFetches a user object by email address.
user_load_by_nameFetches a user object by account name.
user_load_multipleLoads multiple users based on certain conditions.
user_loginForm builder; the main user login form.
user_login_authenticate_validateA 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.
user_login_block
user_login_default_validatorsSet 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…
user_login_destinationHelper function to rewrite the destination to avoid redirecting to login page after login.
user_login_finalizeFinalize the login process. Must be called when logging in a user.
user_login_final_validateThe final validation handler on the login form.
user_login_name_validateA FAPI validate handler. Sets an error if supplied username has been blocked.
user_login_submitSubmit 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.
user_mailImplements hook_mail().
user_mail_tokensToken callback to add unsafe tokens for user mails.
user_menuImplements hook_menu().
user_menu_link_alterImplements hook_menu_link_alter().
user_menu_site_status_alterImplements hook_menu_site_status_alter().
user_menu_titleMenu item title callback for the 'user' path.
user_modules_installedImplements hook_modules_installed().
user_modules_uninstalledImplements hook_modules_uninstalled().
user_module_invokeInvokes a user hook in every module.
user_multiple_cancel_confirm
user_multiple_cancel_confirm_submitSubmit handler for mass-account cancellation form.
user_multiple_role_editCallback function for admin mass adding/deleting a user role.
user_node_loadImplements hook_node_load().
user_page_titleMenu item title callback - use the user name.
user_passwordGenerate a random alphanumeric password.
user_pass_rehashCreates a unique hash value for use in time-dependent per-user URLs.
user_pass_reset_urlGenerates a unique URL for a user to login and reset their password.
user_permissionImplements hook_permission().
user_permission_get_modulesDetermine the modules that permissions belong to.
user_preferred_languageGet 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…
user_preprocess_blockImplements hook_preprocess_HOOK() for block.tpl.php.
user_rdf_mappingImplements hook_rdf_mapping().
user_register_access
user_register_formForm builder; the user registration form.
user_register_submitSubmit handler for the user registration form.
user_register_validateValidation function for the user registration form.
user_rolesRetrieve an array of roles matching specified conditions.
user_role_change_permissionsChange permissions for a user role.
user_role_deleteDelete a user role from database.
user_role_edit_accessMenu access callback for user role editing.
user_role_grant_permissionsGrant permissions to a user role.
user_role_loadFetches a user role by role ID.
user_role_load_by_nameFetches a user role by role name.
user_role_permissionsDetermine the permissions for one or more roles.
user_role_revoke_permissionsRevoke permissions from a user role.
user_role_saveSave a user role to the database.
user_search_accessImplements hook_search_access().
user_search_executeImplements hook_search_execute().
user_search_infoImplements hook_search_info().
user_set_authmapsSave mappings of which external authentication module(s) authenticated a user. Maps external usernames to user ids in the users table.
user_themeImplements hook_theme().
user_translated_menu_link_alterImplements hook_translated_menu_link_alter().
user_uid_only_optional_to_argReturns $arg or the user ID of the current user if $arg is '%' or empty.
user_uid_optional_loadLoad either a specified or the current user account.
user_uid_optional_to_argReturns $arg or the user ID of the current user if $arg is '%' or empty.
user_uriEntity uri callback.
user_user_operationsImplements hook_user_operations().
user_user_operations_blockCallback function for admin mass blocking users.
user_user_operations_unblockCallback function for admin mass unblocking users.
user_user_viewImplements hook_user_view().
user_validate_current_passForm validation handler for the current password on the user_account_form().
user_validate_nameVerify the syntax of the given name.
user_validate_pictureValidates an image uploaded by a user.
user_viewGenerate an array for rendering the given user.
user_view_accessUser view access callback.
user_view_pagePage callback wrapper for user_view().
_user_cancelLast batch processing step for cancelling a user account.
_user_language_selector_langcode_valueSets the value of the user register and profile forms' langcode element.
_user_mail_notifyConditionally create and send a notification email when a certain operation happens on the given user account.
_user_mail_textReturns a mail string for a variable name.

File

core/modules/user/user.module
View source
  1. <?php
  2. use DrupalCoreDatabaseQuerySelectInterface;
  3. /**
  4. * @file
  5. * Enables the user registration and login system.
  6. */
  7. /**
  8. * Maximum length of username text field.
  9. */
  10. const USERNAME_MAX_LENGTH = 60;
  11. /**
  12. * Maximum length of user e-mail text field.
  13. */
  14. const EMAIL_MAX_LENGTH = 254;
  15. /**
  16. * Only administrators can create user accounts.
  17. */
  18. const USER_REGISTER_ADMINISTRATORS_ONLY = 0;
  19. /**
  20. * Visitors can create their own accounts.
  21. */
  22. const USER_REGISTER_VISITORS = 1;
  23. /**
  24. * Visitors can create accounts, but they don't become active without
  25. * administrative approval.
  26. */
  27. const USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL = 2;
  28. /**
  29. * Implement hook_help().
  30. */
  31. function user_help($path, $arg) {
  32. global $user;
  33. switch ($path) {
  34. case 'admin/help#user':
  35. $output = '';
  36. $output .= '<h3>' . t('About') . '</h3>';
  37. $output .= '<p>' . t('The User module allows users to register, log in, and log out. It also allows users with proper permissions to manage user roles (used to classify users) and permissions associated with those roles. For more information, see the online handbook entry for <a href="@user">User module</a>.', array('@user' => 'http://drupal.org/documentation/modules/user')) . '</p>';
  38. $output .= '<h3>' . t('Uses') . '</h3>';
  39. $output .= '<dl>';
  40. $output .= '<dt>' . t('Creating and managing users') . '</dt>';
  41. $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>';
  42. $output .= '<dt>' . t('User roles and permissions') . '</dt>';
  43. $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>';
  44. $output .= '<dt>' . t('Account settings') . '</dt>';
  45. $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>';
  46. $output .= '</dl>';
  47. return $output;
  48. case 'admin/people/create':
  49. return '<p>' . t("This web page allows administrators to register new users. Users' e-mail addresses and usernames must be unique.") . '</p>';
  50. case 'admin/people/permissions':
  51. 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>';
  52. case 'admin/people/permissions/roles':
  53. $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>';
  54. $output .= '<p>' . t('Drupal has three special user roles:') . '</p>';
  55. $output .= '<ul>';
  56. $output .= '<li>' . t("Anonymous user: this role is used for users that don't have a user account or that are not authenticated.") . '</li>';
  57. $output .= '<li>' . t('Authenticated user: this role is automatically granted to all logged in users.') . '</li>';
  58. $output .= '<li>' . t('Administrator role: this role is automatically granted all new permissions when you install a new module. Configure which role is the administrator role on the <a href="@account_settings">Account settings page</a>.', array('@account_settings' => url('admin/config/people/accounts'))) . '</li>';
  59. $output .= '</ul>';
  60. return $output;
  61. case 'admin/config/people/accounts/fields':
  62. return '<p>' . t('This form lets administrators add, edit, and arrange fields for storing user data.') . '</p>';
  63. case 'admin/config/people/accounts/display':
  64. return '<p>' . t('This form lets administrators configure how fields should be displayed when rendering a user profile page.') . '</p>';
  65. case 'admin/people/search':
  66. 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>';
  67. }
  68. }
  69. /**
  70. * Invokes a user hook in every module.
  71. *
  72. * We cannot use module_invoke() for this, because the arguments need to
  73. * be passed by reference.
  74. *
  75. * @param $type
  76. * A text string that controls which user hook to invoke. Valid choices are:
  77. * - login: Invokes hook_user_login().
  78. * @param $edit
  79. * An associative array variable containing form values to be passed
  80. * as the first parameter of the hook function.
  81. * @param $account
  82. * The user account object to be passed as the second parameter of the hook
  83. * function.
  84. */
  85. function user_module_invoke($type, &$edit, $account) {
  86. foreach (module_implements('user_' . $type) as $module) {
  87. $function = $module . '_user_' . $type;
  88. $function($edit, $account);
  89. }
  90. }
  91. /**
  92. * Implements hook_theme().
  93. */
  94. function user_theme() {
  95. return array(
  96. 'user_picture' => array(
  97. 'variables' => array('account' => NULL),
  98. 'template' => 'user-picture',
  99. ),
  100. 'user_profile' => array(
  101. 'render element' => 'elements',
  102. 'template' => 'user-profile',
  103. 'file' => 'user.pages.inc',
  104. ),
  105. 'user_list' => array(
  106. 'variables' => array('users' => NULL, 'title' => NULL),
  107. ),
  108. 'user_admin_permissions' => array(
  109. 'render element' => 'form',
  110. 'file' => 'user.admin.inc',
  111. ),
  112. 'user_admin_roles' => array(
  113. 'render element' => 'form',
  114. 'file' => 'user.admin.inc',
  115. ),
  116. 'user_permission_description' => array(
  117. 'variables' => array('permission_item' => NULL, 'hide' => NULL),
  118. 'file' => 'user.admin.inc',
  119. ),
  120. 'user_signature' => array(
  121. 'variables' => array('signature' => NULL),
  122. ),
  123. 'username' => array(
  124. 'variables' => array('account' => NULL),
  125. ),
  126. );
  127. }
  128. /**
  129. * Implements hook_entity_info().
  130. */
  131. function user_entity_info() {
  132. return array(
  133. 'user' => array(
  134. 'label' => t('User'),
  135. 'controller class' => 'Drupal\user\UserStorageController',
  136. 'base table' => 'users',
  137. 'uri callback' => 'user_uri',
  138. 'label callback' => 'user_label',
  139. 'fieldable' => TRUE,
  140. 'entity class' => 'Drupal\user\User',
  141. 'entity keys' => array(
  142. 'id' => 'uid',
  143. ),
  144. 'bundles' => array(
  145. 'user' => array(
  146. 'label' => t('User'),
  147. 'admin' => array(
  148. 'path' => 'admin/config/people/accounts',
  149. 'access arguments' => array('administer users'),
  150. ),
  151. ),
  152. ),
  153. 'view modes' => array(
  154. 'full' => array(
  155. 'label' => t('User account'),
  156. 'custom settings' => FALSE,
  157. ),
  158. ),
  159. ),
  160. );
  161. }
  162. /**
  163. * Entity uri callback.
  164. */
  165. function user_uri($user) {
  166. return array(
  167. 'path' => 'user/' . $user->uid,
  168. );
  169. }
  170. /**
  171. * Entity label callback.
  172. *
  173. * @param $entity_type
  174. * The entity type.
  175. * @param $entity
  176. * The entity object.
  177. *
  178. * @return
  179. * The name of the user.
  180. *
  181. * @see user_format_name()
  182. */
  183. function user_label($entity_type, $entity) {
  184. return user_format_name($entity);
  185. }
  186. /**
  187. * Implements hook_field_info_alter().
  188. */
  189. function user_field_info_alter(&$info) {
  190. // Add the 'user_register_form' instance setting to all field types.
  191. foreach ($info as $field_type => &$field_type_info) {
  192. $field_type_info += array('instance_settings' => array());
  193. $field_type_info['instance_settings'] += array(
  194. 'user_register_form' => FALSE,
  195. );
  196. }
  197. }
  198. /**
  199. * Implements hook_field_extra_fields().
  200. */
  201. function user_field_extra_fields() {
  202. $return['user']['user'] = array(
  203. 'form' => array(
  204. 'account' => array(
  205. 'label' => t('User name and password'),
  206. 'description' => t('User module account form elements.'),
  207. 'weight' => -10,
  208. ),
  209. 'timezone' => array(
  210. 'label' => t('Timezone'),
  211. 'description' => t('User module timezone form element.'),
  212. 'weight' => 6,
  213. ),
  214. ),
  215. 'display' => array(
  216. 'member_for' => array(
  217. 'label' => t('Member for'),
  218. 'description' => t('User module \'member for\' view element.'),
  219. 'weight' => 5,
  220. ),
  221. ),
  222. );
  223. return $return;
  224. }
  225. /**
  226. * Fetches a user object based on an external authentication source.
  227. *
  228. * @param string $authname
  229. * The external authentication username.
  230. *
  231. * @return
  232. * A fully-loaded user object if the user is found or FALSE if not found.
  233. */
  234. function user_external_load($authname) {
  235. $uid = db_query("SELECT uid FROM {authmap} WHERE authname = :authname", array(':authname' => $authname))->fetchField();
  236. if ($uid) {
  237. return user_load($uid);
  238. }
  239. else {
  240. return FALSE;
  241. }
  242. }
  243. /**
  244. * Loads multiple users based on certain conditions.
  245. *
  246. * This function should be used whenever you need to load more than one user
  247. * from the database. Users are loaded into memory and will not require
  248. * database access if loaded again during the same page request.
  249. *
  250. * @param array|bool $uids
  251. * An array of user IDs, or FALSE to load all users.
  252. * @param array $conditions
  253. * (deprecated) An associative array of conditions on the {users}
  254. * table, where the keys are the database fields and the values are the
  255. * values those fields must have. Instead, it is preferable to use
  256. * EntityFieldQuery to retrieve a list of entity IDs loadable by
  257. * this function.
  258. * @param bool $reset
  259. * A boolean indicating that the internal cache should be reset. Use this if
  260. * loading a user object which has been altered during the page request.
  261. *
  262. * @return array
  263. * An array of user objects, indexed by uid.
  264. *
  265. * @see entity_load_multiple()
  266. * @see user_load()
  267. * @see user_load_by_mail()
  268. * @see user_load_by_name()
  269. * @see EntityFieldQuery
  270. *
  271. * @todo Remove $conditions in Drupal 8.
  272. */
  273. function user_load_multiple($uids = array(), array $conditions = array(), $reset = FALSE) {
  274. return entity_load_multiple('user', $uids, $conditions, $reset);
  275. }
  276. /**
  277. * Loads a user object.
  278. *
  279. * Drupal has a global $user object, which represents the currently-logged-in
  280. * user. So to avoid confusion and to avoid clobbering the global $user object,
  281. * it is a good idea to assign the result of this function to a different local
  282. * variable, generally $account. If you actually do want to act as the user you
  283. * are loading, it is essential to call drupal_save_session(FALSE); first.
  284. * See
  285. * @link http://drupal.org/node/218104 Safely impersonating another user @endlink
  286. * for more information.
  287. *
  288. * @param int $uid
  289. * Integer specifying the user ID to load.
  290. * @param bool $reset
  291. * TRUE to reset the internal cache and load from the database; FALSE
  292. * (default) to load from the internal cache, if set.
  293. *
  294. * @return object
  295. * A fully-loaded user object upon successful user load, or FALSE if the user
  296. * cannot be loaded.
  297. *
  298. * @see user_load_multiple()
  299. */
  300. function user_load($uid, $reset = FALSE) {
  301. return entity_load('user', $uid, $reset);
  302. }
  303. /**
  304. * Fetches a user object by email address.
  305. *
  306. * @param string $mail
  307. * String with the account's e-mail address.
  308. * @return object|bool
  309. * A fully-loaded $user object upon successful user load or FALSE if user
  310. * cannot be loaded.
  311. *
  312. * @see user_load_multiple()
  313. */
  314. function user_load_by_mail($mail) {
  315. $users = entity_load_multiple('user', FALSE, array('mail' => $mail));
  316. return reset($users);
  317. }
  318. /**
  319. * Fetches a user object by account name.
  320. *
  321. * @param string $name
  322. * String with the account's user name.
  323. * @return object|bool
  324. * A fully-loaded $user object upon successful user load or FALSE if user
  325. * cannot be loaded.
  326. *
  327. * @see user_load_multiple()
  328. */
  329. function user_load_by_name($name) {
  330. $users = entity_load_multiple('user', FALSE, array('name' => $name));
  331. return reset($users);
  332. }
  333. /**
  334. * Verify the syntax of the given name.
  335. */
  336. function user_validate_name($name) {
  337. if (!$name) {
  338. return t('You must enter a username.');
  339. }
  340. if (substr($name, 0, 1) == ' ') {
  341. return t('The username cannot begin with a space.');
  342. }
  343. if (substr($name, -1) == ' ') {
  344. return t('The username cannot end with a space.');
  345. }
  346. if (strpos($name, ' ') !== FALSE) {
  347. return t('The username cannot contain multiple spaces in a row.');
  348. }
  349. if (preg_match('/[^\x{80}-\x{F7} a-z0-9@_.\'-]/i', $name)) {
  350. return t('The username contains an illegal character.');
  351. }
  352. if (preg_match('/[\x{80}-\x{A0}' . // Non-printable ISO-8859-1 + NBSP
  353. '\x{AD}' . // Soft-hyphen
  354. '\x{2000}-\x{200F}' . // Various space characters
  355. '\x{2028}-\x{202F}' . // Bidirectional text overrides
  356. '\x{205F}-\x{206F}' . // Various text hinting characters
  357. '\x{FEFF}' . // Byte order mark
  358. '\x{FF01}-\x{FF60}' . // Full-width latin
  359. '\x{FFF9}-\x{FFFD}' . // Replacement characters
  360. '\x{0}-\x{1F}]/u', // NULL byte and control characters
  361. $name)) {
  362. return t('The username contains an illegal character.');
  363. }
  364. if (drupal_strlen($name) > USERNAME_MAX_LENGTH) {
  365. return t('The username %name is too long: it must be %max characters or less.', array('%name' => $name, '%max' => USERNAME_MAX_LENGTH));
  366. }
  367. }
  368. /**
  369. * Validates an image uploaded by a user.
  370. *
  371. * @see user_account_form()
  372. */
  373. function user_validate_picture(&$form, &$form_state) {
  374. // If required, validate the uploaded picture.
  375. $validators = array(
  376. 'file_validate_is_image' => array(),
  377. 'file_validate_image_resolution' => array(variable_get('user_picture_dimensions', '85x85')),
  378. 'file_validate_size' => array(variable_get('user_picture_file_size', '30') * 1024),
  379. );
  380. // Save the file as a temporary file.
  381. $file = file_save_upload('picture_upload', $validators);
  382. if ($file === FALSE) {
  383. 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'))));
  384. }
  385. elseif ($file !== NULL) {
  386. $form_state['values']['picture_upload'] = $file;
  387. }
  388. }
  389. /**
  390. * Generate a random alphanumeric password.
  391. */
  392. function user_password($length = 10) {
  393. // This variable contains the list of allowable characters for the
  394. // password. Note that the number 0 and the letter 'O' have been
  395. // removed to avoid confusion between the two. The same is true
  396. // of 'I', 1, and 'l'.
  397. $allowable_characters = 'abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789';
  398. // Zero-based count of characters in the allowable list:
  399. $len = strlen($allowable_characters) - 1;
  400. // Declare the password as a blank string.
  401. $pass = '';
  402. // Loop the number of times specified by $length.
  403. for ($i = 0; $i < $length; $i++) {
  404. // Each iteration, pick a random character from the
  405. // allowable string and append it to the password:
  406. $pass .= $allowable_characters[mt_rand(0, $len)];
  407. }
  408. return $pass;
  409. }
  410. /**
  411. * Determine the permissions for one or more roles.
  412. *
  413. * @param $roles
  414. * An array whose keys are the role IDs of interest, such as $user->roles.
  415. *
  416. * @return
  417. * An array indexed by role ID. Each value is an array whose keys are the
  418. * permission strings for the given role ID.
  419. */
  420. function user_role_permissions($roles = array()) {
  421. $cache = &drupal_static(__FUNCTION__, array());
  422. $role_permissions = $fetch = array();
  423. if ($roles) {
  424. foreach ($roles as $rid => $name) {
  425. if (isset($cache[$rid])) {
  426. $role_permissions[$rid] = $cache[$rid];
  427. }
  428. else {
  429. // Add this rid to the list of those needing to be fetched.
  430. $fetch[] = $rid;
  431. // Prepare in case no permissions are returned.
  432. $cache[$rid] = array();
  433. }
  434. }
  435. if ($fetch) {
  436. // Get from the database permissions that were not in the static variable.
  437. // Only role IDs with at least one permission assigned will return rows.
  438. $result = db_query("SELECT rid, permission FROM {role_permission} WHERE rid IN (:fetch)", array(':fetch' => $fetch));
  439. foreach ($result as $row) {
  440. $cache[$row->rid][$row->permission] = TRUE;
  441. }
  442. foreach ($fetch as $rid) {
  443. // For every rid, we know we at least assigned an empty array.
  444. $role_permissions[$rid] = $cache[$rid];
  445. }
  446. }
  447. }
  448. return $role_permissions;
  449. }
  450. /**
  451. * Determine whether the user has a given privilege.
  452. *
  453. * @param $string
  454. * The permission, such as "administer nodes", being checked for.
  455. * @param $account
  456. * (optional) The account to check, if not given use currently logged in user.
  457. *
  458. * @return
  459. * Boolean TRUE if the current user has the requested permission.
  460. *
  461. * All permission checks in Drupal should go through this function. This
  462. * way, we guarantee consistent behavior, and ensure that the superuser
  463. * can perform all actions.
  464. */
  465. function user_access($string, $account = NULL) {
  466. global $user;
  467. if (!isset($account)) {
  468. $account = $user;
  469. }
  470. // User #1 has all privileges:
  471. if ($account->uid == 1) {
  472. return TRUE;
  473. }
  474. // To reduce the number of SQL queries, we cache the user's permissions
  475. // in a static variable.
  476. // Use the advanced drupal_static() pattern, since this is called very often.
  477. static $drupal_static_fast;
  478. if (!isset($drupal_static_fast)) {
  479. $drupal_static_fast['perm'] = &drupal_static(__FUNCTION__);
  480. }
  481. $perm = &$drupal_static_fast['perm'];
  482. if (!isset($perm[$account->uid])) {
  483. $role_permissions = user_role_permissions($account->roles);
  484. $perms = array();
  485. foreach ($role_permissions as $one_role) {
  486. $perms += $one_role;
  487. }
  488. $perm[$account->uid] = $perms;
  489. }
  490. return isset($perm[$account->uid][$string]);
  491. }
  492. /**
  493. * Checks for usernames blocked by user administration.
  494. *
  495. * @return boolean TRUE for blocked users, FALSE for active.
  496. */
  497. function user_is_blocked($name) {
  498. return db_select('users')
  499. ->fields('users', array('name'))
  500. ->condition('name', db_like($name), 'LIKE')
  501. ->condition('status', 0)
  502. ->execute()->fetchObject();
  503. }
  504. /**
  505. * Implements hook_permission().
  506. */
  507. function user_permission() {
  508. return array(
  509. 'administer permissions' => array(
  510. 'title' => t('Administer permissions'),
  511. 'restrict access' => TRUE,
  512. ),
  513. 'administer users' => array(
  514. 'title' => t('Administer users'),
  515. 'restrict access' => TRUE,
  516. ),
  517. 'access user profiles' => array(
  518. 'title' => t('View user profiles'),
  519. ),
  520. 'change own username' => array(
  521. 'title' => t('Change own username'),
  522. ),
  523. 'cancel account' => array(
  524. 'title' => t('Cancel own user account'),
  525. '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'))),
  526. ),
  527. 'select account cancellation method' => array(
  528. 'title' => t('Select method for cancelling own account'),
  529. 'restrict access' => TRUE,
  530. ),
  531. );
  532. }
  533. /**
  534. * Implements hook_file_download().
  535. *
  536. * Ensure that user pictures (avatars) are always downloadable.
  537. */
  538. function user_file_download($uri) {
  539. if (strpos(file_uri_target($uri), variable_get('user_picture_path', 'pictures') . '/picture-') === 0) {
  540. $info = image_get_info($uri);
  541. return array('Content-Type' => $info['mime_type']);
  542. }
  543. }
  544. /**
  545. * Implements hook_file_move().
  546. */
  547. function user_file_move($file, $source) {
  548. // If a user's picture is replaced with a new one, update the record in
  549. // the users table.
  550. if (isset($file->fid) && isset($source->fid) && $file->fid != $source->fid) {
  551. db_update('users')
  552. ->fields(array(
  553. 'picture' => $file->fid,
  554. ))
  555. ->condition('picture', $source->fid)
  556. ->execute();
  557. }
  558. }
  559. /**
  560. * Implements hook_file_predelete().
  561. */
  562. function user_file_predelete($file) {
  563. // Remove any references to the file.
  564. db_update('users')
  565. ->fields(array('picture' => 0))
  566. ->condition('picture', $file->fid)
  567. ->execute();
  568. }
  569. /**
  570. * Implements hook_search_info().
  571. */
  572. function user_search_info() {
  573. return array(
  574. 'title' => 'Users',
  575. );
  576. }
  577. /**
  578. * Implements hook_search_access().
  579. */
  580. function user_search_access() {
  581. return user_access('access user profiles');
  582. }
  583. /**
  584. * Implements hook_search_execute().
  585. */
  586. function user_search_execute($keys = NULL, $conditions = NULL) {
  587. $find = array();
  588. // Replace wildcards with MySQL/PostgreSQL wildcards.
  589. $keys = preg_replace('!\*+!', '%', $keys);
  590. $query = db_select('users')->extend('PagerDefault');
  591. $query->fields('users', array('uid'));
  592. if (user_access('administer users')) {
  593. // Administrators can also search in the otherwise private email field.
  594. $query->fields('users', array('mail'));
  595. $query->condition(db_or()->
  596. condition('name', '%' . db_like($keys) . '%', 'LIKE')->
  597. condition('mail', '%' . db_like($keys) . '%', 'LIKE'));
  598. }
  599. else {
  600. $query->condition('name', '%' . db_like($keys) . '%', 'LIKE');
  601. }
  602. $uids = $query
  603. ->limit(15)
  604. ->execute()
  605. ->fetchCol();
  606. $accounts = user_load_multiple($uids);
  607. $results = array();
  608. foreach ($accounts as $account) {
  609. $result = array(
  610. 'title' => user_format_name($account),
  611. 'link' => url('user/' . $account->uid, array('absolute' => TRUE)),
  612. );
  613. if (user_access('administer users')) {
  614. $result['title'] .= ' (' . $account->mail . ')';
  615. }
  616. $results[] = $result;
  617. }
  618. return $results;
  619. }
  620. /**
  621. * Implements hook_user_view().
  622. */
  623. function user_user_view($account) {
  624. $account->content['user_picture'] = array(
  625. '#markup' => theme('user_picture', array('account' => $account)),
  626. '#weight' => -10,
  627. );
  628. $account->content['member_for'] = array(
  629. '#type' => 'item',
  630. '#title' => t('Member for'),
  631. '#markup' => format_interval(REQUEST_TIME - $account->created),
  632. '#weight' => 5,
  633. );
  634. }
  635. /**
  636. * Helper function to add default user account fields to user registration and edit form.
  637. *
  638. * @see user_account_form_validate()
  639. * @see user_validate_current_pass()
  640. * @see user_validate_picture()
  641. * @see user_validate_mail()
  642. */
  643. function user_account_form(&$form, &$form_state) {
  644. global $user, $language_interface;
  645. $account = $form['#user'];
  646. $register = ($form['#user']->uid > 0 ? FALSE : TRUE);
  647. $admin = user_access('administer users');
  648. $form['#validate'][] = 'user_account_form_validate';
  649. // Account information.
  650. $form['account'] = array(
  651. '#type' => 'container',
  652. '#weight' => -10,
  653. );
  654. // Only show name field on registration form or user can change own username.
  655. $form['account']['name'] = array(
  656. '#type' => 'textfield',
  657. '#title' => t('Username'),
  658. '#maxlength' => USERNAME_MAX_LENGTH,
  659. '#description' => t('Spaces are allowed; punctuation is not allowed except for periods, hyphens, apostrophes, and underscores.'),
  660. '#required' => TRUE,
  661. '#attributes' => array('class' => array('username'), 'autocomplete' => 'off'),
  662. '#default_value' => (!$register ? $account->name : ''),
  663. '#access' => ($register || ($user->uid == $account->uid && user_access('change own username')) || $admin),
  664. '#weight' => -10,
  665. );
  666. // The mail field is NOT required if account originally had no mail set
  667. // and the user performing the edit has 'administer users' permission.
  668. // This allows users without e-mail address to be edited and deleted.
  669. $form['account']['mail'] = array(
  670. '#type' => 'email',
  671. '#title' => t('E-mail address'),
  672. '#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.'),
  673. '#required' => !(empty($account->mail) && user_access('administer users')),
  674. '#default_value' => (!$register ? $account->mail : ''),
  675. '#attributes' => array('autocomplete' => 'off'),
  676. );
  677. // Display password field only for existing users or when user is allowed to
  678. // assign a password during registration.
  679. if (!$register) {
  680. $form['account']['pass'] = array(
  681. '#type' => 'password_confirm',
  682. '#size' => 25,
  683. '#description' => t('To change the current user password, enter the new password in both fields.'),
  684. );
  685. // To skip the current password field, the user must have logged in via a
  686. // one-time link and have the token in the URL.
  687. $pass_reset = isset($_SESSION['pass_reset_' . $account->uid]) && isset($_GET['pass-reset-token']) && ($_GET['pass-reset-token'] == $_SESSION['pass_reset_' . $account->uid]);
  688. $protected_values = array();
  689. $current_pass_description = '';
  690. // The user may only change their own password without their current
  691. // password if they logged in via a one-time login link.
  692. if (!$pass_reset) {
  693. $protected_values['mail'] = $form['account']['mail']['#title'];
  694. $protected_values['pass'] = t('Password');
  695. $request_new = l(t('Request new password'), 'user/password', array('attributes' => array('title' => t('Request new password via e-mail.'))));
  696. $current_pass_description = t('Required if you want to change the %mail or %pass below. !request_new.', array('%mail' => $protected_values['mail'], '%pass' => $protected_values['pass'], '!request_new' => $request_new));
  697. }
  698. // The user must enter their current password to change to a new one.
  699. if ($user->uid == $account->uid) {
  700. $form['account']['current_pass_required_values'] = array(
  701. '#type' => 'value',
  702. '#value' => $protected_values,
  703. );
  704. $form['account']['current_pass'] = array(
  705. '#type' => 'password',
  706. '#title' => t('Current password'),
  707. '#size' => 25,
  708. '#access' => !empty($protected_values),
  709. '#description' => $current_pass_description,
  710. '#weight' => -5,
  711. '#attributes' => array('autocomplete' => 'off'),
  712. );
  713. $form['#validate'][] = 'user_validate_current_pass';
  714. }
  715. }
  716. elseif (!variable_get('user_email_verification', TRUE) || $admin) {
  717. $form['account']['pass'] = array(
  718. '#type' => 'password_confirm',
  719. '#size' => 25,
  720. '#description' => t('Provide a password for the new account in both fields.'),
  721. '#required' => TRUE,
  722. );
  723. }
  724. if ($admin) {
  725. $status = isset($account->status) ? $account->status : 1;
  726. }
  727. else {
  728. $status = $register ? variable_get('user_register', USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL) == USER_REGISTER_VISITORS : $account->status;
  729. }
  730. $form['account']['status'] = array(
  731. '#type' => 'radios',
  732. '#title' => t('Status'),
  733. '#default_value' => $status,
  734. '#options' => array(t('Blocked'), t('Active')),
  735. '#access' => $admin,
  736. );
  737. $roles = array_map('check_plain', user_roles(TRUE));
  738. // The disabled checkbox subelement for the 'authenticated user' role
  739. // must be generated separately and added to the checkboxes element,
  740. // because of a limitation in Form API not supporting a single disabled
  741. // checkbox within a set of checkboxes.
  742. // @todo This should be solved more elegantly. See issue #119038.
  743. $checkbox_authenticated = array(
  744. '#type' => 'checkbox',
  745. '#title' => $roles[DRUPAL_AUTHENTICATED_RID],
  746. '#default_value' => TRUE,
  747. '#disabled' => TRUE,
  748. );
  749. unset($roles[DRUPAL_AUTHENTICATED_RID]);
  750. $form['account']['roles'] = array(
  751. '#type' => 'checkboxes',
  752. '#title' => t('Roles'),
  753. '#default_value' => (!$register && isset($account->roles) ? array_keys($account->roles) : array()),
  754. '#options' => $roles,
  755. '#access' => $roles && user_access('administer permissions'),
  756. DRUPAL_AUTHENTICATED_RID => $checkbox_authenticated,
  757. );
  758. $form['account']['notify'] = array(
  759. '#type' => 'checkbox',
  760. '#title' => t('Notify user of new account'),
  761. '#access' => $register && $admin,
  762. );
  763. // Signature.
  764. $form['signature_settings'] = array(
  765. '#type' => 'fieldset',
  766. '#title' => t('Signature settings'),
  767. '#weight' => 1,
  768. '#access' => (!$register && variable_get('user_signatures', 0)),
  769. );
  770. $form['signature_settings']['signature'] = array(
  771. '#type' => 'text_format',
  772. '#title' => t('Signature'),
  773. '#default_value' => isset($account->signature) ? $account->signature : '',
  774. '#description' => t('Your signature will be publicly displayed at the end of your comments.'),
  775. '#format' => isset($account->signature_format) ? $account->signature_format : NULL,
  776. );
  777. // Picture/avatar.
  778. $form['picture'] = array(
  779. '#type' => 'fieldset',
  780. '#title' => t('Picture'),
  781. '#weight' => 1,
  782. '#access' => (!$register && variable_get('user_pictures', 0)),
  783. );
  784. $form['picture']['picture'] = array(
  785. '#type' => 'value',
  786. '#value' => isset($account->picture) ? $account->picture : NULL,
  787. );
  788. $form['picture']['picture_current'] = array(
  789. '#markup' => theme('user_picture', array('account' => $account)),
  790. );
  791. $form['picture']['picture_delete'] = array(
  792. '#type' => 'checkbox',
  793. '#title' => t('Delete picture'),
  794. '#access' => !empty($account->picture->fid),
  795. '#description' => t('Check this box to delete your current picture.'),
  796. );
  797. $form['picture']['picture_upload'] = array(
  798. '#type' => 'file',
  799. '#title' => t('Upload picture'),
  800. '#size' => 48,
  801. '#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', '')),
  802. );
  803. $form['#validate'][] = 'user_validate_picture';
  804. if (module_exists('language') && language_multilingual()) {
  805. $languages = language_list();
  806. // If the user is being created, we set the user language to the page language.
  807. $user_preferred_language = $register ? $language_interface : user_preferred_language($account);
  808. $names = array();
  809. foreach ($languages as $langcode => $item) {
  810. $names[$langcode] = $item->name;
  811. }
  812. // Is default the interface language?
  813. $interface_language_is_default = language_negotiation_method_get_first(LANGUAGE_TYPE_INTERFACE) != LANGUAGE_NEGOTIATION_DEFAULT;
  814. $form['language'] = array(
  815. '#type' => 'fieldset',
  816. '#title' => t('Language settings'),
  817. // Display language selector when either creating a user on the admin
  818. // interface or editing a user account.
  819. '#access' => !$register || user_access('administer users'),
  820. );
  821. $form['language']['preferred_langcode'] = array(
  822. '#type' => (count($names) <= 5 ? 'radios' : 'select'),
  823. '#title' => t('Language'),
  824. '#default_value' => $user_preferred_language->langcode,
  825. '#options' => $names,
  826. '#description' => $interface_language_is_default ? t("This account's preferred language for e-mails and site presentation.") : t("This account's preferred language for e-mails."),
  827. );
  828. }
  829. else {
  830. $form['language'] = array(
  831. '#type' => 'container',
  832. );
  833. $form['language']['preferred_langcode'] = array(
  834. '#type' => 'value',
  835. '#value' => language_default()->langcode,
  836. );
  837. }
  838. // User entities contain both a langcode property (for identifying the
  839. // language of the entity data) and a preferred_langcode property (see above).
  840. // Rather than provide a UI forcing the user to choose both separately,
  841. // assume that the user profile data is in the user's preferred language. This
  842. // element provides that synchronization. For use-cases where this
  843. // synchronization is not desired, a module can alter or remove this element.
  844. $form['language']['langcode'] = array(
  845. '#type' => 'value',
  846. '#value_callback' => '_user_language_selector_langcode_value',
  847. // For the synchronization to work, this element must have a larger weight
  848. // than the preferred_langcode element. Set a large weight here in case
  849. // a module alters the weight of the other element.
  850. '#weight' => 100,
  851. );
  852. }
  853. /**
  854. * Sets the value of the user register and profile forms' langcode element.
  855. */
  856. function _user_language_selector_langcode_value($element, $input, &$form_state) {
  857. // Only add to the description if the form element have a description.
  858. if (isset($form_state['complete_form']['language']['preferred_langcode']['#description'])) {
  859. $form_state['complete_form']['language']['preferred_langcode']['#description'] .= ' ' . t("This is also assumed to be the primary language of this account's profile information.");
  860. }
  861. return $form_state['values']['preferred_langcode'];
  862. }
  863. /**
  864. * Form validation handler for the current password on the user_account_form().
  865. *
  866. * @see user_account_form()
  867. */
  868. function user_validate_current_pass(&$form, &$form_state) {
  869. $account = $form['#user'];
  870. foreach ($form_state['values']['current_pass_required_values'] as $key => $name) {
  871. // This validation only works for required textfields (like mail) or
  872. // form values like password_confirm that have their own validation
  873. // that prevent them from being empty if they are changed.
  874. if ((strlen(trim($form_state['values'][$key])) > 0) && ($form_state['values'][$key] != $account->$key)) {
  875. require_once DRUPAL_ROOT . '/' . variable_get('password_inc', 'core/includes/password.inc');
  876. $current_pass_failed = empty($form_state['values']['current_pass']) || !user_check_password($form_state['values']['current_pass'], $account);
  877. if ($current_pass_failed) {
  878. form_set_error('current_pass', t("Your current password is missing or incorrect; it's required to change the %name.", array('%name' => $name)));
  879. form_set_error($key);
  880. }
  881. // We only need to check the password once.
  882. break;
  883. }
  884. }
  885. }
  886. /**
  887. * Form validation handler for user_account_form().
  888. *
  889. * @see user_account_form()
  890. */
  891. function user_account_form_validate($form, &$form_state) {
  892. $account = $form['#user'];
  893. // Validate new or changing username.
  894. if (isset($form_state['values']['name'])) {
  895. if ($error = user_validate_name($form_state['values']['name'])) {
  896. form_set_error('name', $error);
  897. }
  898. // Cast the user ID as an integer. It might have been set to NULL, which
  899. // could lead to unexpected results.
  900. else {
  901. $name_taken = (bool) db_select('users')
  902. ->fields('users', array('uid'))
  903. ->condition('uid', (int) $account->uid, '<>')
  904. ->condition('name', db_like($form_state['values']['name']), 'LIKE')
  905. ->range(0, 1)
  906. ->execute()
  907. ->fetchField();
  908. if ($name_taken) {
  909. form_set_error('name', t('The name %name is already taken.', array('%name' => $form_state['values']['name'])));
  910. }
  911. }
  912. }
  913. $mail = $form_state['values']['mail'];
  914. if (!empty($mail)) {
  915. $mail_taken = (bool) db_select('users')
  916. ->fields('users', array('uid'))
  917. ->condition('uid', (int) $account->uid, '<>')
  918. ->condition('mail', db_like($mail), 'LIKE')
  919. ->range(0, 1)
  920. ->execute()
  921. ->fetchField();
  922. if ($mail_taken) {
  923. // Format error message dependent on whether the user is logged in or not.
  924. if ($GLOBALS['user']->uid) {
  925. form_set_error('mail', t('The e-mail address %email is already taken.', array('%email' => $mail)));
  926. }
  927. else {
  928. form_set_error('mail', t('The e-mail address %email is already registered. <a href="@password">Have you forgotten your password?</a>', array('%email' => $mail, '@password' => url('user/password'))));
  929. }
  930. }
  931. }
  932. // Make sure the signature isn't longer than the size of the database field.
  933. // Signatures are disabled by default, so make sure it exists first.
  934. if (isset($form_state['values']['signature'])) {
  935. // Move text format for user signature into 'signature_format'.
  936. $form_state['values']['signature_format'] = $form_state['values']['signature']['format'];
  937. // Move text value for user signature into 'signature'.
  938. $form_state['values']['signature'] = $form_state['values']['signature']['value'];
  939. $user_schema = drupal_get_schema('users');
  940. if (drupal_strlen($form_state['values']['signature']) > $user_schema['fields']['signature']['length']) {
  941. form_set_error('signature', t('The signature is too long: it must be %max characters or less.', array('%max' => $user_schema['fields']['signature']['length'])));
  942. }
  943. }
  944. }
  945. function user_login_block($form) {
  946. $form['#action'] = url(current_path(), array('query' => drupal_get_destination(), 'external' => FALSE));
  947. $form['#id'] = 'user-login-form';
  948. $form['#validate'] = user_login_default_validators();
  949. $form['#submit'][] = 'user_login_submit';
  950. $form['name'] = array('#type' => 'textfield',
  951. '#title' => t('Username'),
  952. '#maxlength' => USERNAME_MAX_LENGTH,
  953. '#size' => 15,
  954. '#required' => TRUE,
  955. );
  956. $form['pass'] = array('#type' => 'password',
  957. '#title' => t('Password'),
  958. '#maxlength' => 60,
  959. '#size' => 15,
  960. '#required' => TRUE,
  961. );
  962. $form['actions'] = array('#type' => 'actions');
  963. $form['actions']['submit'] = array('#type' => 'submit',
  964. '#value' => t('Log in'),
  965. );
  966. $items = array();
  967. if (variable_get('user_register', USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL)) {
  968. $items[] = l(t('Create new account'), 'user/register', array('attributes' => array('title' => t('Create a new user account.'))));
  969. }
  970. $items[] = l(t('Request new password'), 'user/password', array('attributes' => array('title' => t('Request new password via e-mail.'))));
  971. $form['links'] = array('#theme' => 'item_list', '#items' => $items);
  972. return $form;
  973. }
  974. /**
  975. * Implements hook_block_info().
  976. */
  977. function user_block_info() {
  978. global $user;
  979. $blocks['login']['info'] = t('User login');
  980. // Not worth caching.
  981. $blocks['login']['cache'] = DRUPAL_NO_CACHE;
  982. $blocks['new']['info'] = t('Who\'s new');
  983. $blocks['new']['properties']['administrative'] = TRUE;
  984. // Too dynamic to cache.
  985. $blocks['online']['info'] = t('Who\'s online');
  986. $blocks['online']['cache'] = DRUPAL_NO_CACHE;
  987. $blocks['online']['properties']['administrative'] = TRUE;
  988. return $blocks;
  989. }
  990. /**
  991. * Implements hook_block_configure().
  992. */
  993. function user_block_configure($delta = '') {
  994. global $user;
  995. switch ($delta) {
  996. case 'new':
  997. $form['user_block_whois_new_count'] = array(
  998. '#type' => 'select',
  999. '#title' => t('Number of users to display'),
  1000. '#default_value' => variable_get('user_block_whois_new_count', 5),
  1001. '#options' => drupal_map_assoc(array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)),
  1002. );
  1003. return $form;
  1004. case 'online':
  1005. $period = drupal_map_assoc(array(30, 60, 120, 180, 300, 600, 900, 1800, 2700, 3600, 5400, 7200, 10800, 21600, 43200, 86400), 'format_interval');
  1006. $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.'));
  1007. $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.'));
  1008. return $form;
  1009. }
  1010. }
  1011. /**
  1012. * Implements hook_block_save().
  1013. */
  1014. function user_block_save($delta = '', $edit = array()) {
  1015. global $user;
  1016. switch ($delta) {
  1017. case 'new':
  1018. variable_set('user_block_whois_new_count', $edit['user_block_whois_new_count']);
  1019. break;
  1020. case 'online':
  1021. variable_set('user_block_seconds_online', $edit['user_block_seconds_online']);
  1022. variable_set('user_block_max_list_count', $edit['user_block_max_list_count']);
  1023. break;
  1024. }
  1025. }
  1026. /**
  1027. * Implements hook_block_view().
  1028. */
  1029. function user_block_view($delta = '') {
  1030. global $user;
  1031. $block = array();
  1032. switch ($delta) {
  1033. case 'login':
  1034. // For usability's sake, avoid showing two login forms on one page.
  1035. if (!$user->uid && !(arg(0) == 'user' && !is_numeric(arg(1)))) {
  1036. $block['subject'] = t('User login');
  1037. $block['content'] = drupal_get_form('user_login_block');
  1038. }
  1039. return $block;
  1040. case 'new':
  1041. if (user_access('access content')) {
  1042. // Retrieve a list of new users who have subsequently accessed the site successfully.
  1043. $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();
  1044. $output = theme('user_list', array('users' => $items));
  1045. $block['subject'] = t('Who\'s new');
  1046. $block['content'] = $output;
  1047. }
  1048. return $block;
  1049. case 'online':
  1050. if (user_access('access content')) {
  1051. // Count users active within the defined period.
  1052. $interval = REQUEST_TIME - variable_get('user_block_seconds_online', 900);
  1053. // Perform database queries to gather online user lists. We use s.timestamp
  1054. // rather than u.access because it is much faster.
  1055. $authenticated_count = db_query("SELECT COUNT(DISTINCT s.uid) FROM {sessions} s WHERE s.timestamp >= :timestamp AND s.uid > 0", array(':timestamp' => $interval))->fetchField();
  1056. $output = '<p>' . format_plural($authenticated_count, 'There is currently 1 user online.', 'There are currently @count users online.') . '</p>';
  1057. // Display a list of currently online users.
  1058. $max_users = variable_get('user_block_max_list_count', 10);
  1059. if ($authenticated_count && $max_users) {
  1060. $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();
  1061. $output .= theme('user_list', array('users' => $items));
  1062. }
  1063. $block['subject'] = t('Who\'s online');
  1064. $block['content'] = $output;
  1065. }
  1066. return $block;
  1067. }
  1068. }
  1069. /**
  1070. * Implements hook_preprocess_HOOK() for block.tpl.php.
  1071. */
  1072. function user_preprocess_block(&$variables) {
  1073. if ($variables['block']->module == 'user') {
  1074. switch ($variables['block']->delta) {
  1075. case 'login':
  1076. $variables['attributes_array']['role'] = 'form';
  1077. break;
  1078. case 'new':
  1079. $variables['attributes_array']['role'] = 'complementary';
  1080. break;
  1081. case 'online':
  1082. $variables['attributes_array']['role'] = 'complementary';
  1083. break;
  1084. }
  1085. }
  1086. }
  1087. /**
  1088. * Format a username.
  1089. *
  1090. * By default, the passed-in object's 'name' property is used if it exists, or
  1091. * else, the site-defined value for the 'anonymous' variable. However, a module
  1092. * may override this by implementing
  1093. * hook_user_format_name_alter(&$name, $account).
  1094. *
  1095. * @see hook_user_format_name_alter()
  1096. *
  1097. * @param $account
  1098. * The account object for the user whose name is to be formatted.
  1099. *
  1100. * @return
  1101. * An unsanitized string with the username to display. The code receiving
  1102. * this result must ensure that check_plain() is called on it before it is
  1103. * printed to the page.
  1104. */
  1105. function user_format_name($account) {
  1106. $name = !empty($account->name) ? $account->name : variable_get('anonymous', t('Anonymous'));
  1107. drupal_alter('user_format_name', $name, $account);
  1108. return $name;
  1109. }
  1110. /**
  1111. * Process variables for user-picture.tpl.php.
  1112. *
  1113. * The $variables array contains the following arguments:
  1114. * - $account: A user, node or comment object with 'name', 'uid' and 'picture'
  1115. * fields.
  1116. *
  1117. * @see user-picture.tpl.php
  1118. */
  1119. function template_preprocess_user_picture(&$variables) {
  1120. $variables['user_picture'] = '';
  1121. if (variable_get('user_pictures', 0)) {
  1122. $account = $variables['account'];
  1123. if (!empty($account->picture)) {
  1124. // @TODO: Ideally this function would only be passed file objects, but
  1125. // since there's a lot of legacy code that JOINs the {users} table to
  1126. // {node} or {comments} and passes the results into this function if we
  1127. // a numeric value in the picture field we'll assume it's a file id
  1128. // and load it for them. Once we've got user_load_multiple() and
  1129. // comment_load_multiple() functions the user module will be able to load
  1130. // the picture files in mass during the object's load process.
  1131. if (is_numeric($account->picture)) {
  1132. $account->picture = file_load($account->picture);
  1133. }
  1134. if (!empty($account->picture->uri)) {
  1135. $filepath = $account->picture->uri;
  1136. }
  1137. }
  1138. elseif (variable_get('user_picture_default', '')) {
  1139. $filepath = variable_get('user_picture_default', '');
  1140. }
  1141. if (isset($filepath)) {
  1142. $alt = t("@user's picture", array('@user' => user_format_name($account)));
  1143. // If the image does not have a valid Drupal scheme (for eg. HTTP),
  1144. // don't load image styles.
  1145. if (module_exists('image') && file_valid_uri($filepath) && $style = variable_get('user_picture_style', '')) {
  1146. $variables['user_picture'] = theme('image_style', array('style_name' => $style, 'uri' => $filepath, 'alt' => $alt, 'title' => $alt));
  1147. }
  1148. else {
  1149. $variables['user_picture'] = theme('image', array('uri' => $filepath, 'alt' => $alt, 'title' => $alt));
  1150. }
  1151. if (!empty($account->uid) && user_access('access user profiles')) {
  1152. $attributes = array('attributes' => array('title' => t('View user profile.')), 'html' => TRUE);
  1153. $variables['user_picture'] = l($variables['user_picture'], "user/$account->uid", $attributes);
  1154. }
  1155. }
  1156. }
  1157. }
  1158. /**
  1159. * Preprocesses variables for theme_username().
  1160. *
  1161. * Modules that make any changes to variables like 'name' or 'extra' must insure
  1162. * that the final string is safe to include directly in the output by using
  1163. * check_plain() or filter_xss().
  1164. *
  1165. * @see template_process_username()
  1166. */
  1167. function template_preprocess_username(&$variables) {
  1168. $account = $variables['account'];
  1169. $variables['extra'] = '';
  1170. if (empty($account->uid)) {
  1171. $variables['uid'] = 0;
  1172. if (theme_get_setting('toggle_comment_user_verification')) {
  1173. $variables['extra'] = ' (' . t('not verified') . ')';
  1174. }
  1175. }
  1176. else {
  1177. $variables['uid'] = (int) $account->uid;
  1178. }
  1179. // Set the name to a formatted name that is safe for printing and
  1180. // that won't break tables by being too long. Keep an unshortened,
  1181. // unsanitized version, in case other preprocess functions want to implement
  1182. // their own shortening logic or add markup. If they do so, they must ensure
  1183. // that $variables['name'] is safe for printing.
  1184. $name = $variables['name_raw'] = user_format_name($account);
  1185. if (drupal_strlen($name) > 20) {
  1186. $name = drupal_substr($name, 0, 15) . '...';
  1187. }
  1188. $variables['name'] = check_plain($name);
  1189. $variables['profile_access'] = user_access('access user profiles');
  1190. // Populate link path and attributes if appropriate.
  1191. if ($variables['uid'] && $variables['profile_access']) {
  1192. // We are linking to a local user.
  1193. $variables['link_attributes']['title'] = t('View user profile.');
  1194. $variables['link_path'] = 'user/' . $variables['uid'];
  1195. }
  1196. elseif (!empty($account->homepage)) {
  1197. // Like the 'class' attribute, the 'rel' attribute can hold a
  1198. // space-separated set of values, so initialize it as an array to make it
  1199. // easier for other preprocess functions to append to it.
  1200. $variables['link_attributes']['rel'] = 'nofollow';
  1201. $variables['link_path'] = $account->homepage;
  1202. $variables['homepage'] = $account->homepage;
  1203. }
  1204. // We do not want the l() function to check_plain() a second time.
  1205. $variables['link_options']['html'] = TRUE;
  1206. // Set a default class.
  1207. $variables['attributes_array'] = array('class' => array('username'));
  1208. }
  1209. /**
  1210. * Processes variables for theme_username().
  1211. *
  1212. * @see template_preprocess_username()
  1213. */
  1214. function template_process_username(&$variables) {
  1215. // Finalize the link_options array for passing to the l() function.
  1216. // This is done in the process phase so that attributes may be added by
  1217. // modules or the theme during the preprocess phase.
  1218. if (isset($variables['link_path'])) {
  1219. // $variables['attributes_array'] contains attributes that should be applied
  1220. // regardless of whether a link is being rendered or not.
  1221. // $variables['link_attributes'] contains attributes that should only be
  1222. // applied if a link is being rendered. Preprocess functions are encouraged
  1223. // to use the former unless they want to add attributes on the link only.
  1224. // If a link is being rendered, these need to be merged. Some attributes are
  1225. // themselves arrays, so the merging needs to be recursive.
  1226. $variables['link_options']['attributes'] = array_merge_recursive($variables['link_attributes'], $variables['attributes_array']);
  1227. }
  1228. }
  1229. /**
  1230. * Returns HTML for a username, potentially linked to the user's page.
  1231. *
  1232. * @param $variables
  1233. * An associative array containing:
  1234. * - account: The user object to format.
  1235. * - name: The user's name, sanitized.
  1236. * - extra: Additional text to append to the user's name, sanitized.
  1237. * - link_path: The path or URL of the user's profile page, home page, or
  1238. * other desired page to link to for more information about the user.
  1239. * - link_options: An array of options to pass to the l() function's $options
  1240. * parameter if linking the user's name to the user's page.
  1241. * - attributes_array: An array of attributes to pass to the
  1242. * drupal_attributes() function if not linking to the user's page.
  1243. *
  1244. * @see template_preprocess_username()
  1245. * @see template_process_username()
  1246. */
  1247. function theme_username($variables) {
  1248. if (isset($variables['link_path'])) {
  1249. // We have a link path, so we should generate a link using l().
  1250. // Additional classes may be added as array elements like
  1251. // $variables['link_options']['attributes']['class'][] = 'myclass';
  1252. $output = l($variables['name'] . $variables['extra'], $variables['link_path'], $variables['link_options']);
  1253. }
  1254. else {
  1255. // Modules may have added important attributes so they must be included
  1256. // in the output. Additional classes may be added as array elements like
  1257. // $variables['attributes_array']['class'][] = 'myclass';
  1258. $output = '<span' . drupal_attributes($variables['attributes_array']) . '>' . $variables['name'] . $variables['extra'] . '</span>';
  1259. }
  1260. return $output;
  1261. }
  1262. /**
  1263. * Returns HTML for a list of users.
  1264. *
  1265. * @param $variables
  1266. * An associative array containing:
  1267. * - users: An array with user objects. Should contain at least the name and
  1268. * uid.
  1269. * - title: (optional) Title to pass on to theme_item_list().
  1270. *
  1271. * @ingroup themeable
  1272. */
  1273. function theme_user_list($variables) {
  1274. $users = $variables['users'];
  1275. $title = $variables['title'];
  1276. $items = array();
  1277. if (!empty($users)) {
  1278. foreach ($users as $user) {
  1279. $items[] = theme('username', array('account' => $user));
  1280. }
  1281. }
  1282. return theme('item_list', array('items' => $items, 'title' => $title));
  1283. }
  1284. function user_is_anonymous() {
  1285. // Menu administrators can see items for anonymous when administering.
  1286. return !$GLOBALS['user']->uid || !empty($GLOBALS['menu_admin']);
  1287. }
  1288. function user_is_logged_in() {
  1289. return (bool) $GLOBALS['user']->uid;
  1290. }
  1291. function user_register_access() {
  1292. return user_is_anonymous() && variable_get('user_register', USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL);
  1293. }
  1294. /**
  1295. * User view access callback.
  1296. *
  1297. * @param $account
  1298. * Can either be a full user object or a $uid.
  1299. */
  1300. function user_view_access($account) {
  1301. $uid = is_object($account) ? $account->uid : (int) $account;
  1302. // Never allow access to view the anonymous user account.
  1303. if ($uid) {
  1304. // Admins can view all, users can view own profiles at all times.
  1305. if ($GLOBALS['user']->uid == $uid || user_access('administer users')) {
  1306. return TRUE;
  1307. }
  1308. elseif (user_access('access user profiles')) {
  1309. // At this point, load the complete account object.
  1310. if (!is_object($account)) {
  1311. $account = user_load($uid);
  1312. }
  1313. return (is_object($account) && $account->status);
  1314. }
  1315. }
  1316. return FALSE;
  1317. }
  1318. /**
  1319. * Access callback for user account editing.
  1320. */
  1321. function user_edit_access($account) {
  1322. return (($GLOBALS['user']->uid == $account->uid) || user_access('administer users')) && $account->uid > 0;
  1323. }
  1324. /**
  1325. * Menu access callback; limit access to account cancellation pages.
  1326. *
  1327. * Limit access to users with the 'cancel account' permission or administrative
  1328. * users, and prevent the anonymous user from cancelling the account.
  1329. */
  1330. function user_cancel_access($account) {
  1331. return ((($GLOBALS['user']->uid == $account->uid) && user_access('cancel account')) || user_access('administer users')) && $account->uid > 0;
  1332. }
  1333. /**
  1334. * Implements hook_menu().
  1335. */
  1336. function user_menu() {
  1337. $items['user/autocomplete'] = array(
  1338. 'title' => 'User autocomplete',
  1339. 'page callback' => 'user_autocomplete',
  1340. 'access callback' => 'user_access',
  1341. 'access arguments' => array('access user profiles'),
  1342. 'type' => MENU_CALLBACK,
  1343. 'file' => 'user.pages.inc',
  1344. );
  1345. // Registration and login pages.
  1346. $items['user'] = array(
  1347. 'title' => 'User account',
  1348. 'title callback' => 'user_menu_title',
  1349. 'page callback' => 'user_page',
  1350. 'access callback' => TRUE,
  1351. 'file' => 'user.pages.inc',
  1352. 'weight' => -10,
  1353. 'menu_name' => 'user-menu',
  1354. );
  1355. $items['user/login'] = array(
  1356. 'title' => 'Log in',
  1357. 'access callback' => 'user_is_anonymous',
  1358. 'type' => MENU_DEFAULT_LOCAL_TASK,
  1359. );
  1360. $items['user/register'] = array(
  1361. 'title' => 'Create new account',
  1362. 'page callback' => 'drupal_get_form',
  1363. 'page arguments' => array('user_register_form'),
  1364. 'access callback' => 'user_register_access',
  1365. 'type' => MENU_LOCAL_TASK,
  1366. );
  1367. $items['user/password'] = array(
  1368. 'title' => 'Request new password',
  1369. 'page callback' => 'drupal_get_form',
  1370. 'page arguments' => array('user_pass'),
  1371. 'access callback' => TRUE,
  1372. 'type' => MENU_LOCAL_TASK,
  1373. 'file' => 'user.pages.inc',
  1374. );
  1375. $items['user/reset/%/%/%'] = array(
  1376. 'title' => 'Reset password',
  1377. 'page callback' => 'drupal_get_form',
  1378. 'page arguments' => array('user_pass_reset', 2, 3, 4),
  1379. 'access callback' => TRUE,
  1380. 'type' => MENU_CALLBACK,
  1381. 'file' => 'user.pages.inc',
  1382. );
  1383. $items['user/logout'] = array(
  1384. 'title' => 'Log out',
  1385. 'access callback' => 'user_is_logged_in',
  1386. 'page callback' => 'user_logout',
  1387. 'weight' => 10,
  1388. 'menu_name' => 'user-menu',
  1389. 'file' => 'user.pages.inc',
  1390. );
  1391. // User listing pages.
  1392. $items['admin/people'] = array(
  1393. 'title' => 'People',
  1394. 'description' => 'Manage user accounts, roles, and permissions.',
  1395. 'page callback' => 'user_admin',
  1396. 'page arguments' => array('list'),
  1397. 'access arguments' => array('administer users'),
  1398. 'position' => 'left',
  1399. 'weight' => -4,
  1400. 'file' => 'user.admin.inc',
  1401. );
  1402. $items['admin/people/people'] = array(
  1403. 'title' => 'List',
  1404. 'description' => 'Find and manage people interacting with your site.',
  1405. 'access arguments' => array('administer users'),
  1406. 'type' => MENU_DEFAULT_LOCAL_TASK,
  1407. 'weight' => -10,
  1408. 'file' => 'user.admin.inc',
  1409. );
  1410. // Permissions and role forms.
  1411. $items['admin/people/permissions'] = array(
  1412. 'title' => 'Permissions',
  1413. 'description' => 'Determine access to features by selecting permissions for roles.',
  1414. 'page callback' => 'drupal_get_form',
  1415. 'page arguments' => array('user_admin_permissions'),
  1416. 'access arguments' => array('administer permissions'),
  1417. 'file' => 'user.admin.inc',
  1418. 'type' => MENU_LOCAL_TASK,
  1419. );
  1420. $items['admin/people/permissions/list'] = array(
  1421. 'title' => 'Permissions',
  1422. 'description' => 'Determine access to features by selecting permissions for roles.',
  1423. 'type' => MENU_DEFAULT_LOCAL_TASK,
  1424. 'weight' => -8,
  1425. );
  1426. $items['admin/people/permissions/roles'] = array(
  1427. 'title' => 'Roles',
  1428. 'description' => 'List, edit, or add user roles.',
  1429. 'page callback' => 'drupal_get_form',
  1430. 'page arguments' => array('user_admin_roles'),
  1431. 'access arguments' => array('administer permissions'),
  1432. 'file' => 'user.admin.inc',
  1433. 'type' => MENU_LOCAL_TASK,
  1434. 'weight' => -5,
  1435. );
  1436. $items['admin/people/permissions/roles/edit/%user_role'] = array(
  1437. 'title' => 'Edit role',
  1438. 'page arguments' => array('user_admin_role', 5),
  1439. 'access callback' => 'user_role_edit_access',
  1440. 'access arguments' => array(5),
  1441. );
  1442. $items['admin/people/permissions/roles/delete/%user_role'] = array(
  1443. 'title' => 'Delete role',
  1444. 'page callback' => 'drupal_get_form',
  1445. 'page arguments' => array('user_admin_role_delete_confirm', 5),
  1446. 'access callback' => 'user_role_edit_access',
  1447. 'access arguments' => array(5),
  1448. 'file' => 'user.admin.inc',
  1449. );
  1450. $items['admin/people/create'] = array(
  1451. 'title' => 'Add user',
  1452. 'page arguments' => array('create'),
  1453. 'access arguments' => array('administer users'),
  1454. 'type' => MENU_LOCAL_ACTION,
  1455. );
  1456. // Administration pages.
  1457. $items['admin/config/people'] = array(
  1458. 'title' => 'People',
  1459. 'description' => 'Configure user accounts.',
  1460. 'position' => 'left',
  1461. 'weight' => -20,
  1462. 'page callback' => 'system_admin_menu_block_page',
  1463. 'access arguments' => array('access administration pages'),
  1464. 'file' => 'system.admin.inc',
  1465. 'file path' => drupal_get_path('module', 'system'),
  1466. );
  1467. $items['admin/config/people/accounts'] = array(
  1468. 'title' => 'Account settings',
  1469. 'description' => 'Configure default behavior of users, including registration requirements, e-mails, fields, and user pictures.',
  1470. 'page callback' => 'drupal_get_form',
  1471. 'page arguments' => array('user_admin_settings'),
  1472. 'access arguments' => array('administer users'),
  1473. 'file' => 'user.admin.inc',
  1474. 'weight' => -10,
  1475. );
  1476. $items['admin/config/people/accounts/settings'] = array(
  1477. 'title' => 'Settings',
  1478. 'type' => MENU_DEFAULT_LOCAL_TASK,
  1479. 'weight' => -10,
  1480. );
  1481. $items['user/%user'] = array(
  1482. 'title' => 'My account',
  1483. 'title callback' => 'user_page_title',
  1484. 'title arguments' => array(1),
  1485. 'page callback' => 'user_view_page',
  1486. 'page arguments' => array(1),
  1487. 'access callback' => 'user_view_access',
  1488. 'access arguments' => array(1),
  1489. // By assigning a different menu name, this item (and all registered child
  1490. // paths) are no longer considered as children of 'user'. When accessing the
  1491. // user account pages, the preferred menu link that is used to build the
  1492. // active trail (breadcrumb) will be found in this menu (unless there is
  1493. // more specific link), so the link to 'user' will not be in the breadcrumb.
  1494. 'menu_name' => 'navigation',
  1495. );
  1496. $items['user/%user/view'] = array(
  1497. 'title' => 'View',
  1498. 'type' => MENU_DEFAULT_LOCAL_TASK,
  1499. 'weight' => -10,
  1500. );
  1501. $items['user/%user/cancel'] = array(
  1502. 'title' => 'Cancel account',
  1503. 'page callback' => 'drupal_get_form',
  1504. 'page arguments' => array('user_cancel_confirm_form', 1),
  1505. 'access callback' => 'user_cancel_access',
  1506. 'access arguments' => array(1),
  1507. 'file' => 'user.pages.inc',
  1508. );
  1509. $items['user/%user/cancel/confirm/%/%'] = array(
  1510. 'title' => 'Confirm account cancellation',
  1511. 'page callback' => 'user_cancel_confirm',
  1512. 'page arguments' => array(1, 4, 5),
  1513. 'access callback' => 'user_cancel_access',
  1514. 'access arguments' => array(1),
  1515. 'file' => 'user.pages.inc',
  1516. );
  1517. $items['user/%user/edit'] = array(
  1518. 'title' => 'Edit',
  1519. 'page callback' => 'drupal_get_form',
  1520. 'page arguments' => array('user_profile_form', 1),
  1521. 'access callback' => 'user_edit_access',
  1522. 'access arguments' => array(1),
  1523. 'type' => MENU_LOCAL_TASK,
  1524. 'file' => 'user.pages.inc',
  1525. );
  1526. return $items;
  1527. }
  1528. /**
  1529. * Implements hook_menu_site_status_alter().
  1530. */
  1531. function user_menu_site_status_alter(&$menu_site_status, $path) {
  1532. if ($menu_site_status == MENU_SITE_OFFLINE) {
  1533. // If the site is offline, log out unprivileged users.
  1534. if (user_is_logged_in() && !user_access('access site in maintenance mode')) {
  1535. module_load_include('pages.inc', 'user', 'user');
  1536. user_logout();
  1537. }
  1538. if (user_is_anonymous()) {
  1539. switch ($path) {
  1540. case 'user':
  1541. // Forward anonymous user to login page.
  1542. drupal_goto('user/login');
  1543. case 'user/login':
  1544. case 'user/password':
  1545. // Disable offline mode.
  1546. $menu_site_status = MENU_SITE_ONLINE;
  1547. break;
  1548. default:
  1549. if (strpos($path, 'user/reset/') === 0) {
  1550. // Disable offline mode.
  1551. $menu_site_status = MENU_SITE_ONLINE;
  1552. }
  1553. break;
  1554. }
  1555. }
  1556. }
  1557. if (user_is_logged_in()) {
  1558. if ($path == 'user/login') {
  1559. // If user is logged in, redirect to 'user' instead of giving 403.
  1560. drupal_goto('user');
  1561. }
  1562. if ($path == 'user/register') {
  1563. // Authenticated user should be redirected to user edit page.
  1564. drupal_goto('user/' . $GLOBALS['user']->uid . '/edit');
  1565. }
  1566. }
  1567. }
  1568. /**
  1569. * Implements hook_menu_link_alter().
  1570. */
  1571. function user_menu_link_alter(&$link) {
  1572. // The path 'user' must be accessible for anonymous users, but only visible
  1573. // for authenticated users. Authenticated users should see "My account", but
  1574. // anonymous users should not see it at all. Therefore, invoke
  1575. // user_translated_menu_link_alter() to conditionally hide the link.
  1576. if ($link['link_path'] == 'user' && $link['module'] == 'system') {
  1577. $link['options']['alter'] = TRUE;
  1578. }
  1579. // Force the Logout link to appear on the top-level of 'user-menu' menu by
  1580. // default (i.e., unless it has been customized).
  1581. if ($link['link_path'] == 'user/logout' && $link['module'] == 'system' && empty($link['customized'])) {
  1582. $link['plid'] = 0;
  1583. }
  1584. }
  1585. /**
  1586. * Implements hook_translated_menu_link_alter().
  1587. */
  1588. function user_translated_menu_link_alter(&$link) {
  1589. // Hide the "User account" link for anonymous users.
  1590. if ($link['link_path'] == 'user' && $link['module'] == 'system' && user_is_anonymous()) {
  1591. $link['hidden'] = 1;
  1592. }
  1593. }
  1594. /**
  1595. * Implements hook_admin_paths().
  1596. */
  1597. function user_admin_paths() {
  1598. $paths = array(
  1599. 'user/*/cancel' => TRUE,
  1600. 'user/*/edit' => TRUE,
  1601. 'user/*/edit/*' => TRUE,
  1602. );
  1603. return $paths;
  1604. }
  1605. /**
  1606. * Returns $arg or the user ID of the current user if $arg is '%' or empty.
  1607. *
  1608. * Deprecated. Use %user_uid_optional instead.
  1609. *
  1610. * @todo D8: Remove.
  1611. */
  1612. function user_uid_only_optional_to_arg($arg) {
  1613. return user_uid_optional_to_arg($arg);
  1614. }
  1615. /**
  1616. * Load either a specified or the current user account.
  1617. *
  1618. * @param $uid
  1619. * An optional user ID of the user to load. If not provided, the current
  1620. * user's ID will be used.
  1621. * @return
  1622. * A fully-loaded $user object upon successful user load, FALSE if user
  1623. * cannot be loaded.
  1624. *
  1625. * @see user_load()
  1626. * @todo rethink the naming of this in Drupal 8.
  1627. */
  1628. function user_uid_optional_load($uid = NULL) {
  1629. if (!isset($uid)) {
  1630. $uid = $GLOBALS['user']->uid;
  1631. }
  1632. return user_load($uid);
  1633. }
  1634. /**
  1635. * Returns $arg or the user ID of the current user if $arg is '%' or empty.
  1636. *
  1637. * @todo rethink the naming of this in Drupal 8.
  1638. */
  1639. function user_uid_optional_to_arg($arg) {
  1640. // Give back the current user uid when called from eg. tracker, aka.
  1641. // with an empty arg. Also use the current user uid when called from
  1642. // the menu with a % for the current account link.
  1643. return empty($arg) || $arg == '%' ? $GLOBALS['user']->uid : $arg;
  1644. }
  1645. /**
  1646. * Menu item title callback for the 'user' path.
  1647. *
  1648. * Anonymous users should see "User account", but authenticated users are
  1649. * expected to see "My account".
  1650. */
  1651. function user_menu_title() {
  1652. return user_is_logged_in() ? t('My account') : t('User account');
  1653. }
  1654. /**
  1655. * Menu item title callback - use the user name.
  1656. */
  1657. function user_page_title($account) {
  1658. return is_object($account) ? user_format_name($account) : '';
  1659. }
  1660. /**
  1661. * Discover which external authentication module(s) authenticated a username.
  1662. *
  1663. * @param $authname
  1664. * A username used by an external authentication module.
  1665. * @return
  1666. * An associative array with module as key and username as value.
  1667. */
  1668. function user_get_authmaps($authname = NULL) {
  1669. $authmaps = db_query("SELECT module, authname FROM {authmap} WHERE authname = :authname", array(':authname' => $authname))->fetchAllKeyed();
  1670. return count($authmaps) ? $authmaps : 0;
  1671. }
  1672. /**
  1673. * Save mappings of which external authentication module(s) authenticated
  1674. * a user. Maps external usernames to user ids in the users table.
  1675. *
  1676. * @param $account
  1677. * A user object.
  1678. * @param $authmaps
  1679. * An associative array with a compound key and the username as the value.
  1680. * The key is made up of 'authname_' plus the name of the external authentication
  1681. * module.
  1682. * @see user_external_login_register()
  1683. */
  1684. function user_set_authmaps($account, $authmaps) {
  1685. foreach ($authmaps as $key => $value) {
  1686. $module = explode('_', $key, 2);
  1687. if ($value) {
  1688. db_merge('authmap')
  1689. ->key(array(
  1690. 'uid' => $account->uid,
  1691. 'module' => $module[1],
  1692. ))
  1693. ->fields(array('authname' => $value))
  1694. ->execute();
  1695. }
  1696. else {
  1697. db_delete('authmap')
  1698. ->condition('uid', $account->uid)
  1699. ->condition('module', $module[1])
  1700. ->execute();
  1701. }
  1702. }
  1703. }
  1704. /**
  1705. * Form builder; the main user login form.
  1706. *
  1707. * @ingroup forms
  1708. */
  1709. function user_login($form, &$form_state) {
  1710. global $user;
  1711. // If we are already logged on, go to the user page instead.
  1712. if ($user->uid) {
  1713. drupal_goto('user/' . $user->uid);
  1714. }
  1715. // Display login form:
  1716. $form['name'] = array('#type' => 'textfield',
  1717. '#title' => t('Username'),
  1718. '#size' => 60,
  1719. '#maxlength' => USERNAME_MAX_LENGTH,
  1720. '#required' => TRUE,
  1721. );
  1722. $form['name']['#description'] = t('Enter your @s username.', array('@s' => variable_get('site_name', 'Drupal')));
  1723. $form['pass'] = array('#type' => 'password',
  1724. '#title' => t('Password'),
  1725. '#description' => t('Enter the password that accompanies your username.'),
  1726. '#required' => TRUE,
  1727. );
  1728. $form['#validate'] = user_login_default_validators();
  1729. $form['actions'] = array('#type' => 'actions');
  1730. $form['actions']['submit'] = array('#type' => 'submit', '#value' => t('Log in'));
  1731. return $form;
  1732. }
  1733. /**
  1734. * Set up a series for validators which check for blocked users,
  1735. * then authenticate against local database, then return an error if
  1736. * authentication fails. Distributed authentication modules are welcome
  1737. * to use hook_form_alter() to change this series in order to
  1738. * authenticate against their user database instead of the local users
  1739. * table. If a distributed authentication module is successful, it
  1740. * should set $form_state['uid'] to a user ID.
  1741. *
  1742. * We use three validators instead of one since external authentication
  1743. * modules usually only need to alter the second validator.
  1744. *
  1745. * @see user_login_name_validate()
  1746. * @see user_login_authenticate_validate()
  1747. * @see user_login_final_validate()
  1748. * @return array
  1749. * A simple list of validate functions.
  1750. */
  1751. function user_login_default_validators() {
  1752. return array('user_login_name_validate', 'user_login_authenticate_validate', 'user_login_final_validate');
  1753. }
  1754. /**
  1755. * A FAPI validate handler. Sets an error if supplied username has been blocked.
  1756. */
  1757. function user_login_name_validate($form, &$form_state) {
  1758. if (isset($form_state['values']['name']) && user_is_blocked($form_state['values']['name'])) {
  1759. // Blocked in user administration.
  1760. form_set_error('name', t('The username %name has not been activated or is blocked.', array('%name' => $form_state['values']['name'])));
  1761. }
  1762. }
  1763. /**
  1764. * A validate handler on the login form. Check supplied username/password
  1765. * against local users table. If successful, $form_state['uid']
  1766. * is set to the matching user ID.
  1767. */
  1768. function user_login_authenticate_validate($form, &$form_state) {
  1769. $password = trim($form_state['values']['pass']);
  1770. if (!empty($form_state['values']['name']) && !empty($password)) {
  1771. // Do not allow any login from the current user's IP if the limit has been
  1772. // reached. Default is 50 failed attempts allowed in one hour. This is
  1773. // independent of the per-user limit to catch attempts from one IP to log
  1774. // in to many different user accounts. We have a reasonably high limit
  1775. // since there may be only one apparent IP for all users at an institution.
  1776. if (!flood_is_allowed('failed_login_attempt_ip', variable_get('user_failed_login_ip_limit', 50), variable_get('user_failed_login_ip_window', 3600))) {
  1777. $form_state['flood_control_triggered'] = 'ip';
  1778. return;
  1779. }
  1780. $account = db_query("SELECT * FROM {users} WHERE name = :name AND status = 1", array(':name' => $form_state['values']['name']))->fetchObject();
  1781. if ($account) {
  1782. if (variable_get('user_failed_login_identifier_uid_only', FALSE)) {
  1783. // Register flood events based on the uid only, so they apply for any
  1784. // IP address. This is the most secure option.
  1785. $identifier = $account->uid;
  1786. }
  1787. else {
  1788. // The default identifier is a combination of uid and IP address. This
  1789. // is less secure but more resistant to denial-of-service attacks that
  1790. // could lock out all users with public user names.
  1791. $identifier = $account->uid . '-' . ip_address();
  1792. }
  1793. $form_state['flood_control_user_identifier'] = $identifier;
  1794. // Don't allow login if the limit for this user has been reached.
  1795. // Default is to allow 5 failed attempts every 6 hours.
  1796. 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)) {
  1797. $form_state['flood_control_triggered'] = 'user';
  1798. return;
  1799. }
  1800. }
  1801. // We are not limited by flood control, so try to authenticate.
  1802. // Set $form_state['uid'] as a flag for user_login_final_validate().
  1803. $form_state['uid'] = user_authenticate($form_state['values']['name'], $password);
  1804. }
  1805. }
  1806. /**
  1807. * The final validation handler on the login form.
  1808. *
  1809. * Sets a form error if user has not been authenticated, or if too many
  1810. * logins have been attempted. This validation function should always
  1811. * be the last one.
  1812. */
  1813. function user_login_final_validate($form, &$form_state) {
  1814. if (empty($form_state['uid'])) {
  1815. // Always register an IP-based failed login event.
  1816. flood_register_event('failed_login_attempt_ip', variable_get('user_failed_login_ip_window', 3600));
  1817. // Register a per-user failed login event.
  1818. if (isset($form_state['flood_control_user_identifier'])) {
  1819. flood_register_event('failed_login_attempt_user', variable_get('user_failed_login_user_window', 21600), $form_state['flood_control_user_identifier']);
  1820. }
  1821. if (isset($form_state['flood_control_triggered'])) {
  1822. if ($form_state['flood_control_triggered'] == 'user') {
  1823. 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'))));
  1824. }
  1825. else {
  1826. // We did not find a uid, so the limit is IP-based.
  1827. 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'))));
  1828. }
  1829. }
  1830. else {
  1831. form_set_error('name', t('Sorry, unrecognized username or password. <a href="@password">Have you forgotten your password?</a>', array('@password' => url('user/password'))));
  1832. watchdog('user', 'Login attempt failed for %user.', array('%user' => $form_state['values']['name']));
  1833. }
  1834. }
  1835. elseif (isset($form_state['flood_control_user_identifier'])) {
  1836. // Clear past failures for this user so as not to block a user who might
  1837. // log in and out more than once in an hour.
  1838. flood_clear_event('failed_login_attempt_user', $form_state['flood_control_user_identifier']);
  1839. }
  1840. }
  1841. /**
  1842. * Try to validate the user's login credentials locally.
  1843. *
  1844. * @param $name
  1845. * User name to authenticate.
  1846. * @param $password
  1847. * A plain-text password, such as trimmed text from form values.
  1848. * @return
  1849. * The user's uid on success, or FALSE on failure to authenticate.
  1850. */
  1851. function user_authenticate($name, $password) {
  1852. $uid = FALSE;
  1853. if (!empty($name) && !empty($password)) {
  1854. $account = user_load_by_name($name);
  1855. if ($account) {
  1856. // Allow alternate password hashing schemes.
  1857. require_once DRUPAL_ROOT . '/' . variable_get('password_inc', 'core/includes/password.inc');
  1858. if (user_check_password($password, $account)) {
  1859. // Successful authentication.
  1860. $uid = $account->uid;
  1861. // Update user to new password scheme if needed.
  1862. if (user_needs_new_hash($account)) {
  1863. $account->pass = $password;
  1864. $account->save();
  1865. }
  1866. }
  1867. }
  1868. }
  1869. return $uid;
  1870. }
  1871. /**
  1872. * Finalize the login process. Must be called when logging in a user.
  1873. *
  1874. * The function records a watchdog message about the new session, saves the
  1875. * login timestamp, calls hook_user op 'login' and generates a new session. *
  1876. */
  1877. function user_login_finalize(&$edit = array()) {
  1878. global $user;
  1879. watchdog('user', 'Session opened for %name.', array('%name' => $user->name));
  1880. // Update the user table timestamp noting user has logged in.
  1881. // This is also used to invalidate one-time login links.
  1882. $user->login = REQUEST_TIME;
  1883. db_update('users')
  1884. ->fields(array('login' => $user->login))
  1885. ->condition('uid', $user->uid)
  1886. ->execute();
  1887. // Regenerate the session ID to prevent against session fixation attacks.
  1888. // This is called before hook_user in case one of those functions fails
  1889. // or incorrectly does a redirect which would leave the old session in place.
  1890. drupal_session_regenerate();
  1891. user_module_invoke('login', $edit, $user);
  1892. }
  1893. /**
  1894. * Submit handler for the login form. Load $user object and perform standard login
  1895. * tasks. The user is then redirected to the My Account page. Setting the
  1896. * destination in the query string overrides the redirect.
  1897. */
  1898. function user_login_submit($form, &$form_state) {
  1899. global $user;
  1900. $user = user_load($form_state['uid']);
  1901. $form_state['redirect'] = 'user/' . $user->uid;
  1902. user_login_finalize($form_state);
  1903. }
  1904. /**
  1905. * Helper function for authentication modules. Either logs in or registers
  1906. * the current user, based on username. Either way, the global $user object is
  1907. * populated and login tasks are performed.
  1908. */
  1909. function user_external_login_register($name, $module) {
  1910. $account = user_external_load($name);
  1911. if (!$account) {
  1912. // Register this new user.
  1913. $account = entity_create('user', array(
  1914. 'name' => $name,
  1915. 'pass' => user_password(),
  1916. 'init' => $name,
  1917. 'status' => 1,
  1918. 'access' => REQUEST_TIME
  1919. ));
  1920. $status = $account->save();
  1921. // Terminate if an error occurred while saving the account.
  1922. if ($status != SAVED_NEW) {
  1923. drupal_set_message(t("Error saving user account."), 'error');
  1924. return;
  1925. }
  1926. user_set_authmaps($account, array("authname_$module" => $name));
  1927. }
  1928. // Log user in.
  1929. $form_state['uid'] = $account->uid;
  1930. user_login_submit(array(), $form_state);
  1931. }
  1932. /**
  1933. * Generates a unique URL for a user to login and reset their password.
  1934. *
  1935. * @param object $account
  1936. * An object containing the user account.
  1937. *
  1938. * @return
  1939. * A unique URL that provides a one-time log in for the user, from which
  1940. * they can change their password.
  1941. */
  1942. function user_pass_reset_url($account) {
  1943. $timestamp = REQUEST_TIME;
  1944. return url("user/reset/$account->uid/$timestamp/" . user_pass_rehash($account->pass, $timestamp, $account->login), array('absolute' => TRUE));
  1945. }
  1946. /**
  1947. * Generates a URL to confirm an account cancellation request.
  1948. *
  1949. * @param object $account
  1950. * The user account object, which must contain at least the following
  1951. * properties:
  1952. * - uid: The user uid number.
  1953. * - pass: The hashed user password string.
  1954. * - login: The user login name.
  1955. *
  1956. * @return
  1957. * A unique URL that may be used to confirm the cancellation of the user
  1958. * account.
  1959. *
  1960. * @see user_mail_tokens()
  1961. * @see user_cancel_confirm()
  1962. */
  1963. function user_cancel_url($account) {
  1964. $timestamp = REQUEST_TIME;
  1965. return url("user/$account->uid/cancel/confirm/$timestamp/" . user_pass_rehash($account->pass, $timestamp, $account->login), array('absolute' => TRUE));
  1966. }
  1967. /**
  1968. * Creates a unique hash value for use in time-dependent per-user URLs.
  1969. *
  1970. * This hash is normally used to build a unique and secure URL that is sent to
  1971. * the user by email for purposes such as resetting the user's password. In
  1972. * order to validate the URL, the same hash can be generated again, from the
  1973. * same information, and compared to the hash value from the URL. The URL
  1974. * normally contains both the time stamp and the numeric user ID. The login
  1975. * name and hashed password are retrieved from the database as necessary. For a
  1976. * usage example, see user_cancel_url() and user_cancel_confirm().
  1977. *
  1978. * @param $password
  1979. * The hashed user account password value.
  1980. * @param $timestamp
  1981. * A unix timestamp.
  1982. * @param $login
  1983. * The user account login name.
  1984. *
  1985. * @return
  1986. * A string that is safe for use in URLs and SQL statements.
  1987. */
  1988. function user_pass_rehash($password, $timestamp, $login) {
  1989. return drupal_hmac_base64($timestamp . $login, drupal_get_hash_salt() . $password);
  1990. }
  1991. /**
  1992. * Cancel a user account.
  1993. *
  1994. * Since the user cancellation process needs to be run in a batch, either
  1995. * Form API will invoke it, or batch_process() needs to be invoked after calling
  1996. * this function and should define the path to redirect to.
  1997. *
  1998. * @param $edit
  1999. * An array of submitted form values.
  2000. * @param $uid
  2001. * The user ID of the user account to cancel.
  2002. * @param $method
  2003. * The account cancellation method to use.
  2004. *
  2005. * @see _user_cancel()
  2006. */
  2007. function user_cancel($edit, $uid, $method) {
  2008. global $user;
  2009. $account = user_load($uid);
  2010. if (!$account) {
  2011. drupal_set_message(t('The user account %id does not exist.', array('%id' => $uid)), 'error');
  2012. watchdog('user', 'Attempted to cancel non-existing user account: %id.', array('%id' => $uid), WATCHDOG_ERROR);
  2013. return;
  2014. }
  2015. // Initialize batch (to set title).
  2016. $batch = array(
  2017. 'title' => t('Cancelling account'),
  2018. 'operations' => array(),
  2019. );
  2020. batch_set($batch);
  2021. // When the 'user_cancel_delete' method is used, user_delete() is called,
  2022. // which invokes hook_user_predelete() and hook_user_delete(). Modules
  2023. // should use those hooks to respond to the account deletion.
  2024. if ($method != 'user_cancel_delete') {
  2025. // Allow modules to add further sets to this batch.
  2026. module_invoke_all('user_cancel', $edit, $account, $method);
  2027. }
  2028. // Finish the batch and actually cancel the account.
  2029. $batch = array(
  2030. 'title' => t('Cancelling user account'),
  2031. 'operations' => array(
  2032. array('_user_cancel', array($edit, $account, $method)),
  2033. ),
  2034. );
  2035. batch_set($batch);
  2036. // Batch processing is either handled via Form API or has to be invoked
  2037. // manually.
  2038. }
  2039. /**
  2040. * Last batch processing step for cancelling a user account.
  2041. *
  2042. * Since batch and session API require a valid user account, the actual
  2043. * cancellation of a user account needs to happen last.
  2044. *
  2045. * @see user_cancel()
  2046. */
  2047. function _user_cancel($edit, $account, $method) {
  2048. global $user;
  2049. switch ($method) {
  2050. case 'user_cancel_block':
  2051. case 'user_cancel_block_unpublish':
  2052. default:
  2053. // Send account blocked notification if option was checked.
  2054. if (!empty($edit['user_cancel_notify'])) {
  2055. _user_mail_notify('status_blocked', $account);
  2056. }
  2057. $account->status = 0;
  2058. $account->save();
  2059. drupal_set_message(t('%name has been disabled.', array('%name' => $account->name)));
  2060. watchdog('user', 'Blocked user: %name %email.', array('%name' => $account->name, '%email' => '<' . $account->mail . '>'), WATCHDOG_NOTICE);
  2061. break;
  2062. case 'user_cancel_reassign':
  2063. case 'user_cancel_delete':
  2064. // Send account canceled notification if option was checked.
  2065. if (!empty($edit['user_cancel_notify'])) {
  2066. _user_mail_notify('status_canceled', $account);
  2067. }
  2068. user_delete($account->uid);
  2069. drupal_set_message(t('%name has been deleted.', array('%name' => $account->name)));
  2070. watchdog('user', 'Deleted user: %name %email.', array('%name' => $account->name, '%email' => '<' . $account->mail . '>'), WATCHDOG_NOTICE);
  2071. break;
  2072. }
  2073. // After cancelling account, ensure that user is logged out.
  2074. if ($account->uid == $user->uid) {
  2075. // Destroy the current session, and reset $user to the anonymous user.
  2076. session_destroy();
  2077. }
  2078. // Clear the cache for anonymous users.
  2079. cache_clear_all();
  2080. }
  2081. /**
  2082. * Delete a user.
  2083. *
  2084. * @param $uid
  2085. * A user ID.
  2086. */
  2087. function user_delete($uid) {
  2088. user_delete_multiple(array($uid));
  2089. }
  2090. /**
  2091. * Delete multiple user accounts.
  2092. *
  2093. * @param $uids
  2094. * An array of user IDs.
  2095. *
  2096. * @see hook_user_predelete()
  2097. * @see hook_user_delete()
  2098. */
  2099. function user_delete_multiple(array $uids) {
  2100. if (!empty($uids)) {
  2101. $accounts = user_load_multiple($uids, array());
  2102. $transaction = db_transaction();
  2103. try {
  2104. foreach ($accounts as $uid => $account) {
  2105. // Allow modules to act prior to user deletion.
  2106. module_invoke_all('user_predelete', $account);
  2107. module_invoke_all('entity_predelete', $account, 'user');
  2108. field_attach_delete('user', $account);
  2109. drupal_session_destroy_uid($account->uid);
  2110. }
  2111. db_delete('users')
  2112. ->condition('uid', $uids, 'IN')
  2113. ->execute();
  2114. db_delete('users_roles')
  2115. ->condition('uid', $uids, 'IN')
  2116. ->execute();
  2117. db_delete('authmap')
  2118. ->condition('uid', $uids, 'IN')
  2119. ->execute();
  2120. // Allow modules to respond to user deletion.
  2121. module_invoke_all('user_delete', $account);
  2122. module_invoke_all('entity_delete', $account, 'user');
  2123. }
  2124. catch (Exception $e) {
  2125. $transaction->rollback();
  2126. watchdog_exception('user', $e);
  2127. throw $e;
  2128. }
  2129. entity_get_controller('user')->resetCache();
  2130. }
  2131. }
  2132. /**
  2133. * Page callback wrapper for user_view().
  2134. */
  2135. function user_view_page($account) {
  2136. // An administrator may try to view a non-existent account,
  2137. // so we give them a 404 (versus a 403 for non-admins).
  2138. return is_object($account) ? user_view($account) : MENU_NOT_FOUND;
  2139. }
  2140. /**
  2141. * Generate an array for rendering the given user.
  2142. *
  2143. * When viewing a user profile, the $page array contains:
  2144. *
  2145. * - $page['content']['user_picture']:
  2146. * User's rendered picture.
  2147. * - $page['content']['member_for']:
  2148. * Contains the default "Member for" profile data for a user.
  2149. * - $page['content']['#account']:
  2150. * The user account of the profile being viewed.
  2151. *
  2152. * To theme user profiles, copy modules/user/user-profile.tpl.php
  2153. * to your theme directory, and edit it as instructed in that file's comments.
  2154. *
  2155. * @param $account
  2156. * A user object.
  2157. * @param $view_mode
  2158. * View mode, e.g. 'full'.
  2159. * @param $langcode
  2160. * (optional) A language code to use for rendering. Defaults to the global
  2161. * content language of the current request.
  2162. *
  2163. * @return
  2164. * An array as expected by drupal_render().
  2165. */
  2166. function user_view($account, $view_mode = 'full', $langcode = NULL) {
  2167. if (!isset($langcode)) {
  2168. $langcode = $GLOBALS['language_content']->langcode;
  2169. }
  2170. // Retrieve all profile fields and attach to $account->content.
  2171. user_build_content($account, $view_mode, $langcode);
  2172. $build = $account->content;
  2173. // We don't need duplicate rendering info in account->content.
  2174. unset($account->content);
  2175. $build += array(
  2176. '#theme' => 'user_profile',
  2177. '#account' => $account,
  2178. '#view_mode' => $view_mode,
  2179. '#language' => $langcode,
  2180. );
  2181. // Allow modules to modify the structured user.
  2182. $type = 'user';
  2183. drupal_alter(array('user_view', 'entity_view'), $build, $type);
  2184. return $build;
  2185. }
  2186. /**
  2187. * Builds a structured array representing the profile content.
  2188. *
  2189. * @param $account
  2190. * A user object.
  2191. * @param $view_mode
  2192. * View mode, e.g. 'full'.
  2193. * @param $langcode
  2194. * (optional) A language code to use for rendering. Defaults to the global
  2195. * content language of the current request.
  2196. */
  2197. function user_build_content($account, $view_mode = 'full', $langcode = NULL) {
  2198. if (!isset($langcode)) {
  2199. $langcode = $GLOBALS['language_content']->langcode;
  2200. }
  2201. // Remove previously built content, if exists.
  2202. $account->content = array();
  2203. // Build fields content.
  2204. field_attach_prepare_view('user', array($account->uid => $account), $view_mode, $langcode);
  2205. entity_prepare_view('user', array($account->uid => $account), $langcode);
  2206. $account->content += field_attach_view('user', $account, $view_mode, $langcode);
  2207. // Populate $account->content with a render() array.
  2208. module_invoke_all('user_view', $account, $view_mode, $langcode);
  2209. module_invoke_all('entity_view', $account, 'user', $view_mode, $langcode);
  2210. }
  2211. /**
  2212. * Implements hook_mail().
  2213. */
  2214. function user_mail($key, &$message, $params) {
  2215. $language = $message['language'];
  2216. $variables = array('user' => $params['account']);
  2217. $message['subject'] .= _user_mail_text($key . '_subject', $language, $variables);
  2218. $message['body'][] = _user_mail_text($key . '_body', $language, $variables);
  2219. }
  2220. /**
  2221. * Returns a mail string for a variable name.
  2222. *
  2223. * Used by user_mail() and the settings forms to retrieve strings.
  2224. */
  2225. function _user_mail_text($key, $language = NULL, $variables = array(), $replace = TRUE) {
  2226. $langcode = isset($language) ? $language->langcode : NULL;
  2227. if ($admin_setting = variable_get('user_mail_' . $key, FALSE)) {
  2228. // An admin setting overrides the default string.
  2229. $text = $admin_setting;
  2230. }
  2231. else {
  2232. // No override, return default string.
  2233. switch ($key) {
  2234. case 'register_no_approval_required_subject':
  2235. $text = t('Account details for [user:name] at [site:name]', array(), array('langcode' => $langcode));
  2236. break;
  2237. case 'register_no_approval_required_body':
  2238. $text = t("[user:name],
  2239. Thank you for registering at [site:name]. You may now log in by clicking this link or copying and pasting it to your browser:
  2240. [user:one-time-login-url]
  2241. This link can only be used once to log in and will lead you to a page where you can set your password.
  2242. After setting your password, you will be able to log in at [site:login-url] in the future using:
  2243. username: [user:name]
  2244. password: Your password
  2245. -- [site:name] team", array(), array('langcode' => $langcode));
  2246. break;
  2247. case 'register_admin_created_subject':
  2248. $text = t('An administrator created an account for you at [site:name]', array(), array('langcode' => $langcode));
  2249. break;
  2250. case 'register_admin_created_body':
  2251. $text = t("[user:name],
  2252. 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:
  2253. [user:one-time-login-url]
  2254. This link can only be used once to log in and will lead you to a page where you can set your password.
  2255. After setting your password, you will be able to log in at [site:login-url] in the future using:
  2256. username: [user:name]
  2257. password: Your password
  2258. -- [site:name] team", array(), array('langcode' => $langcode));
  2259. break;
  2260. case 'register_pending_approval_subject':
  2261. case 'register_pending_approval_admin_subject':
  2262. $text = t('Account details for [user:name] at [site:name] (pending admin approval)', array(), array('langcode' => $langcode));
  2263. break;
  2264. case 'register_pending_approval_body':
  2265. $text = t("[user:name],
  2266. 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.
  2267. -- [site:name] team", array(), array('langcode' => $langcode));
  2268. break;
  2269. case 'register_pending_approval_admin_body':
  2270. $text = t("[user:name] has applied for an account.
  2271. [user:edit-url]", array(), array('langcode' => $langcode));
  2272. break;
  2273. case 'password_reset_subject':
  2274. $text = t('Replacement login information for [user:name] at [site:name]', array(), array('langcode' => $langcode));
  2275. break;
  2276. case 'password_reset_body':
  2277. $text = t("[user:name],
  2278. A request to reset the password for your account has been made at [site:name].
  2279. You may now log in by clicking this link or copying and pasting it to your browser:
  2280. [user:one-time-login-url]
  2281. 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.
  2282. -- [site:name] team", array(), array('langcode' => $langcode));
  2283. break;
  2284. case 'status_activated_subject':
  2285. $text = t('Account details for [user:name] at [site:name] (approved)', array(), array('langcode' => $langcode));
  2286. break;
  2287. case 'status_activated_body':
  2288. $text = t("[user:name],
  2289. Your account at [site:name] has been activated.
  2290. You may now log in by clicking this link or copying and pasting it into your browser:
  2291. [user:one-time-login-url]
  2292. This link can only be used once to log in and will lead you to a page where you can set your password.
  2293. After setting your password, you will be able to log in at [site:login-url] in the future using:
  2294. username: [user:name]
  2295. password: Your password
  2296. -- [site:name] team", array(), array('langcode' => $langcode));
  2297. break;
  2298. case 'status_blocked_subject':
  2299. $text = t('Account details for [user:name] at [site:name] (blocked)', array(), array('langcode' => $langcode));
  2300. break;
  2301. case 'status_blocked_body':
  2302. $text = t("[user:name],
  2303. Your account on [site:name] has been blocked.
  2304. -- [site:name] team", array(), array('langcode' => $langcode));
  2305. break;
  2306. case 'cancel_confirm_subject':
  2307. $text = t('Account cancellation request for [user:name] at [site:name]', array(), array('langcode' => $langcode));
  2308. break;
  2309. case 'cancel_confirm_body':
  2310. $text = t("[user:name],
  2311. A request to cancel your account has been made at [site:name].
  2312. You may now cancel your account on [site:url-brief] by clicking this link or copying and pasting it into your browser:
  2313. [user:cancel-url]
  2314. NOTE: The cancellation of your account is not reversible.
  2315. This link expires in one day and nothing will happen if it is not used.
  2316. -- [site:name] team", array(), array('langcode' => $langcode));
  2317. break;
  2318. case 'status_canceled_subject':
  2319. $text = t('Account details for [user:name] at [site:name] (canceled)', array(), array('langcode' => $langcode));
  2320. break;
  2321. case 'status_canceled_body':
  2322. $text = t("[user:name],
  2323. Your account on [site:name] has been canceled.
  2324. -- [site:name] team", array(), array('langcode' => $langcode));
  2325. break;
  2326. }
  2327. }
  2328. if ($replace) {
  2329. // We do not sanitize the token replacement, since the output of this
  2330. // replacement is intended for an e-mail message, not a web browser.
  2331. return token_replace($text, $variables, array('language' => $language, 'callback' => 'user_mail_tokens', 'sanitize' => FALSE, 'clear' => TRUE));
  2332. }
  2333. return $text;
  2334. }
  2335. /**
  2336. * Token callback to add unsafe tokens for user mails.
  2337. *
  2338. * This function is used by the token_replace() call at the end of
  2339. * _user_mail_text() to set up some additional tokens that can be
  2340. * used in email messages generated by user_mail().
  2341. *
  2342. * @param $replacements
  2343. * An associative array variable containing mappings from token names to
  2344. * values (for use with strtr()).
  2345. * @param $data
  2346. * An associative array of token replacement values. If the 'user' element
  2347. * exists, it must contain a user account object with the following
  2348. * properties:
  2349. * - login: The account login name.
  2350. * - pass: The hashed account login password.
  2351. * @param $options
  2352. * Unused parameter required by the token_replace() function.
  2353. */
  2354. function user_mail_tokens(&$replacements, $data, $options) {
  2355. if (isset($data['user'])) {
  2356. $replacements['[user:one-time-login-url]'] = user_pass_reset_url($data['user']);
  2357. $replacements['[user:cancel-url]'] = user_cancel_url($data['user']);
  2358. }
  2359. }
  2360. /*** Administrative features ***********************************************/
  2361. /**
  2362. * Retrieve an array of roles matching specified conditions.
  2363. *
  2364. * @param $membersonly
  2365. * Set this to TRUE to exclude the 'anonymous' role.
  2366. * @param $permission
  2367. * A string containing a permission. If set, only roles containing that
  2368. * permission are returned.
  2369. *
  2370. * @return
  2371. * An associative array with the role id as the key and the role name as
  2372. * value.
  2373. */
  2374. function user_roles($membersonly = FALSE, $permission = NULL) {
  2375. $user_roles = &drupal_static(__FUNCTION__);
  2376. // Do not cache roles for specific permissions. This data is not requested
  2377. // frequently enough to justify the additional memory use.
  2378. if (empty($permission)) {
  2379. $cid = $membersonly ? DRUPAL_AUTHENTICATED_RID : DRUPAL_ANONYMOUS_RID;
  2380. if (isset($user_roles[$cid])) {
  2381. return $user_roles[$cid];
  2382. }
  2383. }
  2384. $query = db_select('role', 'r');
  2385. $query->addTag('translatable');
  2386. $query->fields('r', array('rid', 'name'));
  2387. $query->orderBy('weight');
  2388. $query->orderBy('name');
  2389. if (!empty($permission)) {
  2390. $query->innerJoin('role_permission', 'p', 'r.rid = p.rid');
  2391. $query->condition('p.permission', $permission);
  2392. }
  2393. $result = $query->execute();
  2394. $roles = array();
  2395. foreach ($result as $role) {
  2396. switch ($role->rid) {
  2397. // We only translate the built in role names
  2398. case DRUPAL_ANONYMOUS_RID:
  2399. if (!$membersonly) {
  2400. $roles[$role->rid] = t($role->name);
  2401. }
  2402. break;
  2403. case DRUPAL_AUTHENTICATED_RID:
  2404. $roles[$role->rid] = t($role->name);
  2405. break;
  2406. default:
  2407. $roles[$role->rid] = $role->name;
  2408. }
  2409. }
  2410. if (empty($permission)) {
  2411. $user_roles[$cid] = $roles;
  2412. return $user_roles[$cid];
  2413. }
  2414. return $roles;
  2415. }
  2416. /**
  2417. * Fetches a user role by role ID.
  2418. *
  2419. * @param $rid
  2420. * An integer representing the role ID.
  2421. *
  2422. * @return
  2423. * A fully-loaded role object if a role with the given ID exists, or FALSE
  2424. * otherwise.
  2425. *
  2426. * @see user_role_load_by_name()
  2427. */
  2428. function user_role_load($rid) {
  2429. return db_select('role', 'r')
  2430. ->fields('r')
  2431. ->condition('rid', $rid)
  2432. ->execute()
  2433. ->fetchObject();
  2434. }
  2435. /**
  2436. * Fetches a user role by role name.
  2437. *
  2438. * @param $role_name
  2439. * A string representing the role name.
  2440. *
  2441. * @return
  2442. * A fully-loaded role object if a role with the given name exists, or FALSE
  2443. * otherwise.
  2444. *
  2445. * @see user_role_load()
  2446. */
  2447. function user_role_load_by_name($role_name) {
  2448. return db_select('role', 'r')
  2449. ->fields('r')
  2450. ->condition('name', $role_name)
  2451. ->execute()
  2452. ->fetchObject();
  2453. }
  2454. /**
  2455. * Save a user role to the database.
  2456. *
  2457. * @param $role
  2458. * A role object to modify or add. If $role->rid is not specified, a new
  2459. * role will be created.
  2460. * @return
  2461. * Status constant indicating if role was created or updated.
  2462. * Failure to write the user role record will return FALSE. Otherwise.
  2463. * SAVED_NEW or SAVED_UPDATED is returned depending on the operation
  2464. * performed.
  2465. */
  2466. function user_role_save($role) {
  2467. if ($role->name) {
  2468. // Prevent leading and trailing spaces in role names.
  2469. $role->name = trim($role->name);
  2470. }
  2471. if (!isset($role->weight)) {
  2472. // Set a role weight to make this new role last.
  2473. $query = db_select('role');
  2474. $query->addExpression('MAX(weight)');
  2475. $role->weight = $query->execute()->fetchField() + 1;
  2476. }
  2477. // Let modules modify the user role before it is saved to the database.
  2478. module_invoke_all('user_role_presave', $role);
  2479. if (!empty($role->rid) && $role->name) {
  2480. $status = drupal_write_record('role', $role, 'rid');
  2481. module_invoke_all('user_role_update', $role);
  2482. }
  2483. else {
  2484. $status = drupal_write_record('role', $role);
  2485. module_invoke_all('user_role_insert', $role);
  2486. }
  2487. // Clear the user access cache.
  2488. drupal_static_reset('user_access');
  2489. drupal_static_reset('user_role_permissions');
  2490. return $status;
  2491. }
  2492. /**
  2493. * Delete a user role from database.
  2494. *
  2495. * @param $role
  2496. * A string with the role name, or an integer with the role ID.
  2497. */
  2498. function user_role_delete($role) {
  2499. if (is_int($role)) {
  2500. $role = user_role_load($role);
  2501. }
  2502. else {
  2503. $role = user_role_load_by_name($role);
  2504. }
  2505. db_delete('role')
  2506. ->condition('rid', $role->rid)
  2507. ->execute();
  2508. db_delete('role_permission')
  2509. ->condition('rid', $role->rid)
  2510. ->execute();
  2511. // Update the users who have this role set:
  2512. db_delete('users_roles')
  2513. ->condition('rid', $role->rid)
  2514. ->execute();
  2515. module_invoke_all('user_role_delete', $role);
  2516. // Clear the user access cache.
  2517. drupal_static_reset('user_access');
  2518. drupal_static_reset('user_role_permissions');
  2519. }
  2520. /**
  2521. * Menu access callback for user role editing.
  2522. */
  2523. function user_role_edit_access($role) {
  2524. // Prevent the system-defined roles from being altered or removed.
  2525. if ($role->rid == DRUPAL_ANONYMOUS_RID || $role->rid == DRUPAL_AUTHENTICATED_RID) {
  2526. return FALSE;
  2527. }
  2528. return user_access('administer permissions');
  2529. }
  2530. /**
  2531. * Determine the modules that permissions belong to.
  2532. *
  2533. * @return
  2534. * An associative array in the format $permission => $module.
  2535. */
  2536. function user_permission_get_modules() {
  2537. $permissions = array();
  2538. foreach (module_implements('permission') as $module) {
  2539. $perms = module_invoke($module, 'permission');
  2540. foreach ($perms as $key => $value) {
  2541. $permissions[$key] = $module;
  2542. }
  2543. }
  2544. return $permissions;
  2545. }
  2546. /**
  2547. * Change permissions for a user role.
  2548. *
  2549. * This function may be used to grant and revoke multiple permissions at once.
  2550. * For example, when a form exposes checkboxes to configure permissions for a
  2551. * role, the form submit handler may directly pass the submitted values for the
  2552. * checkboxes form element to this function.
  2553. *
  2554. * @param $rid
  2555. * The ID of a user role to alter.
  2556. * @param $permissions
  2557. * An associative array, where the key holds the permission name and the value
  2558. * determines whether to grant or revoke that permission. Any value that
  2559. * evaluates to TRUE will cause the permission to be granted. Any value that
  2560. * evaluates to FALSE will cause the permission to be revoked.
  2561. * @code
  2562. * array(
  2563. * 'administer nodes' => 0, // Revoke 'administer nodes'
  2564. * 'administer blocks' => FALSE, // Revoke 'administer blocks'
  2565. * 'access user profiles' => 1, // Grant 'access user profiles'
  2566. * 'access content' => TRUE, // Grant 'access content'
  2567. * 'access comments' => 'access comments', // Grant 'access comments'
  2568. * )
  2569. * @endcode
  2570. * Existing permissions are not changed, unless specified in $permissions.
  2571. *
  2572. * @see user_role_grant_permissions()
  2573. * @see user_role_revoke_permissions()
  2574. */
  2575. function user_role_change_permissions($rid, array $permissions = array()) {
  2576. // Grant new permissions for the role.
  2577. $grant = array_filter($permissions);
  2578. if (!empty($grant)) {
  2579. user_role_grant_permissions($rid, array_keys($grant));
  2580. }
  2581. // Revoke permissions for the role.
  2582. $revoke = array_diff_assoc($permissions, $grant);
  2583. if (!empty($revoke)) {
  2584. user_role_revoke_permissions($rid, array_keys($revoke));
  2585. }
  2586. }
  2587. /**
  2588. * Grant permissions to a user role.
  2589. *
  2590. * @param $rid
  2591. * The ID of a user role to alter.
  2592. * @param $permissions
  2593. * A list of permission names to grant.
  2594. *
  2595. * @see user_role_change_permissions()
  2596. * @see user_role_revoke_permissions()
  2597. */
  2598. function user_role_grant_permissions($rid, array $permissions = array()) {
  2599. $modules = user_permission_get_modules();
  2600. // Grant new permissions for the role.
  2601. foreach ($permissions as $name) {
  2602. db_merge('role_permission')
  2603. ->key(array(
  2604. 'rid' => $rid,
  2605. 'permission' => $name,
  2606. ))
  2607. ->fields(array(
  2608. 'module' => $modules[$name],
  2609. ))
  2610. ->execute();
  2611. }
  2612. // Clear the user access cache.
  2613. drupal_static_reset('user_access');
  2614. drupal_static_reset('user_role_permissions');
  2615. }
  2616. /**
  2617. * Revoke permissions from a user role.
  2618. *
  2619. * @param $rid
  2620. * The ID of a user role to alter.
  2621. * @param $permissions
  2622. * A list of permission names to revoke.
  2623. *
  2624. * @see user_role_change_permissions()
  2625. * @see user_role_grant_permissions()
  2626. */
  2627. function user_role_revoke_permissions($rid, array $permissions = array()) {
  2628. // Revoke permissions for the role.
  2629. db_delete('role_permission')
  2630. ->condition('rid', $rid)
  2631. ->condition('permission', $permissions, 'IN')
  2632. ->execute();
  2633. // Clear the user access cache.
  2634. drupal_static_reset('user_access');
  2635. drupal_static_reset('user_role_permissions');
  2636. }
  2637. /**
  2638. * Implements hook_user_operations().
  2639. */
  2640. function user_user_operations($form = array(), $form_state = array()) {
  2641. $operations = array(
  2642. 'unblock' => array(
  2643. 'label' => t('Unblock the selected users'),
  2644. 'callback' => 'user_user_operations_unblock',
  2645. ),
  2646. 'block' => array(
  2647. 'label' => t('Block the selected users'),
  2648. 'callback' => 'user_user_operations_block',
  2649. ),
  2650. 'cancel' => array(
  2651. 'label' => t('Cancel the selected user accounts'),
  2652. ),
  2653. );
  2654. if (user_access('administer permissions')) {
  2655. $roles = user_roles(TRUE);
  2656. unset($roles[DRUPAL_AUTHENTICATED_RID]); // Can't edit authenticated role.
  2657. $add_roles = array();
  2658. foreach ($roles as $key => $value) {
  2659. $add_roles['add_role-' . $key] = $value;
  2660. }
  2661. $remove_roles = array();
  2662. foreach ($roles as $key => $value) {
  2663. $remove_roles['remove_role-' . $key] = $value;
  2664. }
  2665. if (count($roles)) {
  2666. $role_operations = array(
  2667. t('Add a role to the selected users') => array(
  2668. 'label' => $add_roles,
  2669. ),
  2670. t('Remove a role from the selected users') => array(
  2671. 'label' => $remove_roles,
  2672. ),
  2673. );
  2674. $operations += $role_operations;
  2675. }
  2676. }
  2677. // If the form has been posted, we need to insert the proper data for
  2678. // role editing if necessary.
  2679. if (!empty($form_state['submitted'])) {
  2680. $operation_rid = explode('-', $form_state['values']['operation']);
  2681. $operation = $operation_rid[0];
  2682. if ($operation == 'add_role' || $operation == 'remove_role') {
  2683. $rid = $operation_rid[1];
  2684. if (user_access('administer permissions')) {
  2685. $operations[$form_state['values']['operation']] = array(
  2686. 'callback' => 'user_multiple_role_edit',
  2687. 'callback arguments' => array($operation, $rid),
  2688. );
  2689. }
  2690. else {
  2691. watchdog('security', 'Detected malicious attempt to alter protected user fields.', array(), WATCHDOG_WARNING);
  2692. return;
  2693. }
  2694. }
  2695. }
  2696. return $operations;
  2697. }
  2698. /**
  2699. * Callback function for admin mass unblocking users.
  2700. */
  2701. function user_user_operations_unblock($accounts) {
  2702. $accounts = user_load_multiple($accounts);
  2703. foreach ($accounts as $account) {
  2704. // Skip unblocking user if they are already unblocked.
  2705. if ($account !== FALSE && $account->status == 0) {
  2706. $account->status = 1;
  2707. $account->save();
  2708. }
  2709. }
  2710. }
  2711. /**
  2712. * Callback function for admin mass blocking users.
  2713. */
  2714. function user_user_operations_block($accounts) {
  2715. $accounts = user_load_multiple($accounts);
  2716. foreach ($accounts as $account) {
  2717. // Skip blocking user if they are already blocked.
  2718. if ($account !== FALSE && $account->status == 1) {
  2719. // For efficiency manually save the original account before applying any
  2720. // changes.
  2721. $account->original = clone $account;
  2722. $account->status = 0;
  2723. $account->save();
  2724. }
  2725. }
  2726. }
  2727. /**
  2728. * Callback function for admin mass adding/deleting a user role.
  2729. */
  2730. function user_multiple_role_edit($accounts, $operation, $rid) {
  2731. $role_name = db_query('SELECT name FROM {role} WHERE rid = :rid', array(':rid' => $rid))->fetchField();
  2732. switch ($operation) {
  2733. case 'add_role':
  2734. $accounts = user_load_multiple($accounts);
  2735. foreach ($accounts as $account) {
  2736. // Skip adding the role to the user if they already have it.
  2737. if ($account !== FALSE && !isset($account->roles[$rid])) {
  2738. $roles = $account->roles + array($rid => $role_name);
  2739. // For efficiency manually save the original account before applying
  2740. // any changes.
  2741. $account->original = clone $account;
  2742. $account->roles = $roles;
  2743. $account->save();
  2744. }
  2745. }
  2746. break;
  2747. case 'remove_role':
  2748. $accounts = user_load_multiple($accounts);
  2749. foreach ($accounts as $account) {
  2750. // Skip removing the role from the user if they already don't have it.
  2751. if ($account !== FALSE && isset($account->roles[$rid])) {
  2752. $roles = array_diff($account->roles, array($rid => $role_name));
  2753. // For efficiency manually save the original account before applying
  2754. // any changes.
  2755. $account->original = clone $account;
  2756. $account->roles = $roles;
  2757. $account->save();
  2758. }
  2759. }
  2760. break;
  2761. }
  2762. }
  2763. function user_multiple_cancel_confirm($form, &$form_state) {
  2764. $edit = $form_state['input'];
  2765. $form['accounts'] = array('#prefix' => '<ul>', '#suffix' => '</ul>', '#tree' => TRUE);
  2766. $accounts = user_load_multiple(array_keys(array_filter($edit['accounts'])));
  2767. foreach ($accounts as $uid => $account) {
  2768. // Prevent user 1 from being canceled.
  2769. if ($uid <= 1) {
  2770. continue;
  2771. }
  2772. $form['accounts'][$uid] = array(
  2773. '#type' => 'hidden',
  2774. '#value' => $uid,
  2775. '#prefix' => '<li>',
  2776. '#suffix' => check_plain($account->name) . "</li>\n",
  2777. );
  2778. }
  2779. // Output a notice that user 1 cannot be canceled.
  2780. if (isset($accounts[1])) {
  2781. $redirect = (count($accounts) == 1);
  2782. $message = t('The user account %name cannot be cancelled.', array('%name' => $accounts[1]->name));
  2783. drupal_set_message($message, $redirect ? 'error' : 'warning');
  2784. // If only user 1 was selected, redirect to the overview.
  2785. if ($redirect) {
  2786. drupal_goto('admin/people');
  2787. }
  2788. }
  2789. $form['operation'] = array('#type' => 'hidden', '#value' => 'cancel');
  2790. module_load_include('inc', 'user', 'user.pages');
  2791. $form['user_cancel_method'] = array(
  2792. '#type' => 'item',
  2793. '#title' => t('When cancelling these accounts'),
  2794. );
  2795. $form['user_cancel_method'] += user_cancel_methods();
  2796. // Remove method descriptions.
  2797. foreach (element_children($form['user_cancel_method']) as $element) {
  2798. unset($form['user_cancel_method'][$element]['#description']);
  2799. }
  2800. // Allow to send the account cancellation confirmation mail.
  2801. $form['user_cancel_confirm'] = array(
  2802. '#type' => 'checkbox',
  2803. '#title' => t('Require e-mail confirmation to cancel account.'),
  2804. '#default_value' => FALSE,
  2805. '#description' => t('When enabled, the user must confirm the account cancellation via e-mail.'),
  2806. );
  2807. // Also allow to send account canceled notification mail, if enabled.
  2808. $form['user_cancel_notify'] = array(
  2809. '#type' => 'checkbox',
  2810. '#title' => t('Notify user when account is canceled.'),
  2811. '#default_value' => FALSE,
  2812. '#access' => variable_get('user_mail_status_canceled_notify', FALSE),
  2813. '#description' => t('When enabled, the user will receive an e-mail notification after the account has been cancelled.'),
  2814. );
  2815. return confirm_form($form,
  2816. t('Are you sure you want to cancel these user accounts?'),
  2817. 'admin/people', t('This action cannot be undone.'),
  2818. t('Cancel accounts'), t('Cancel'));
  2819. }
  2820. /**
  2821. * Submit handler for mass-account cancellation form.
  2822. *
  2823. * @see user_multiple_cancel_confirm()
  2824. * @see user_cancel_confirm_form_submit()
  2825. */
  2826. function user_multiple_cancel_confirm_submit($form, &$form_state) {
  2827. global $user;
  2828. if ($form_state['values']['confirm']) {
  2829. foreach ($form_state['values']['accounts'] as $uid => $value) {
  2830. // Prevent programmatic form submissions from cancelling user 1.
  2831. if ($uid <= 1) {
  2832. continue;
  2833. }
  2834. // Prevent user administrators from deleting themselves without confirmation.
  2835. if ($uid == $user->uid) {
  2836. $admin_form_state = $form_state;
  2837. unset($admin_form_state['values']['user_cancel_confirm']);
  2838. // The $user global is not a complete user entity, so load the full
  2839. // entity.
  2840. $admin_form_state['values']['_account'] = user_load($user->uid);
  2841. user_cancel_confirm_form_submit(array(), $admin_form_state);
  2842. }
  2843. else {
  2844. user_cancel($form_state['values'], $uid, $form_state['values']['user_cancel_method']);
  2845. }
  2846. }
  2847. }
  2848. $form_state['redirect'] = 'admin/people';
  2849. }
  2850. /**
  2851. * List user administration filters that can be applied.
  2852. */
  2853. function user_filters() {
  2854. // Regular filters
  2855. $filters = array();
  2856. $roles = user_roles(TRUE);
  2857. unset($roles[DRUPAL_AUTHENTICATED_RID]); // Don't list authorized role.
  2858. if (count($roles)) {
  2859. $filters['role'] = array(
  2860. 'title' => t('role'),
  2861. 'field' => 'ur.rid',
  2862. 'options' => array(
  2863. '[any]' => t('any'),
  2864. ) + $roles,
  2865. );
  2866. }
  2867. $options = array();
  2868. foreach (module_implements('permission') as $module) {
  2869. $function = $module . '_permission';
  2870. if ($permissions = $function('permission')) {
  2871. asort($permissions);
  2872. foreach ($permissions as $permission => $description) {
  2873. $options[t('@module module', array('@module' => $module))][$permission] = t($permission);
  2874. }
  2875. }
  2876. }
  2877. ksort($options);
  2878. $filters['permission'] = array(
  2879. 'title' => t('permission'),
  2880. 'options' => array(
  2881. '[any]' => t('any'),
  2882. ) + $options,
  2883. );
  2884. $filters['status'] = array(
  2885. 'title' => t('status'),
  2886. 'field' => 'u.status',
  2887. 'options' => array(
  2888. '[any]' => t('any'),
  2889. 1 => t('active'),
  2890. 0 => t('blocked'),
  2891. ),
  2892. );
  2893. return $filters;
  2894. }
  2895. /**
  2896. * Extends a query object for user administration filters based on session.
  2897. *
  2898. * @param $query
  2899. * Query object that should be filtered.
  2900. */
  2901. function user_build_filter_query(SelectInterface $query) {
  2902. $filters = user_filters();
  2903. // Extend Query with filter conditions.
  2904. foreach (isset($_SESSION['user_overview_filter']) ? $_SESSION['user_overview_filter'] : array() as $filter) {
  2905. list($key, $value) = $filter;
  2906. // This checks to see if this permission filter is an enabled permission for
  2907. // the authenticated role. If so, then all users would be listed, and we can
  2908. // skip adding it to the filter query.
  2909. if ($key == 'permission') {
  2910. $account = entity_create('user', array());
  2911. $account->uid = 'user_filter';
  2912. $account->roles = array(DRUPAL_AUTHENTICATED_RID => 1);
  2913. if (user_access($value, $account)) {
  2914. continue;
  2915. }
  2916. $users_roles_alias = $query->join('users_roles', 'ur', '%alias.uid = u.uid');
  2917. $permission_alias = $query->join('role_permission', 'p', $users_roles_alias . '.rid = %alias.rid');
  2918. $query->condition($permission_alias . '.permission', $value);
  2919. }
  2920. elseif ($key == 'role') {
  2921. $users_roles_alias = $query->join('users_roles', 'ur', '%alias.uid = u.uid');
  2922. $query->condition($users_roles_alias . '.rid' , $value);
  2923. }
  2924. else {
  2925. $query->condition($filters[$key]['field'], $value);
  2926. }
  2927. }
  2928. }
  2929. /**
  2930. * Implements hook_comment_view().
  2931. */
  2932. function user_comment_view($comment) {
  2933. if (variable_get('user_signatures', 0) && !empty($comment->signature)) {
  2934. // @todo This alters and replaces the original object value, so a
  2935. // hypothetical process of loading, viewing, and saving will hijack the
  2936. // stored data. Consider renaming to $comment->signature_safe or similar
  2937. // here and elsewhere in Drupal 8.
  2938. $comment->signature = check_markup($comment->signature, $comment->signature_format, '', TRUE);
  2939. }
  2940. else {
  2941. $comment->signature = '';
  2942. }
  2943. }
  2944. /**
  2945. * Returns HTML for a user signature.
  2946. *
  2947. * @param $variables
  2948. * An associative array containing:
  2949. * - signature: The user's signature.
  2950. *
  2951. * @ingroup themeable
  2952. */
  2953. function theme_user_signature($variables) {
  2954. $signature = $variables['signature'];
  2955. $output = '';
  2956. if ($signature) {
  2957. $output .= '<div class="clear">';
  2958. $output .= '<div>—</div>';
  2959. $output .= $signature;
  2960. $output .= '</div>';
  2961. }
  2962. return $output;
  2963. }
  2964. /**
  2965. * Get the language object preferred by the user. This user preference can
  2966. * be set on the user account editing page, and is only available if there
  2967. * are more than one languages enabled on the site. If the user did not
  2968. * choose a preferred language, or is the anonymous user, the $default
  2969. * value, or if it is not set, the site default language will be returned.
  2970. *
  2971. * @param $account
  2972. * User account to look up language for.
  2973. * @param $default
  2974. * Optional default language object to return if the account
  2975. * has no valid language.
  2976. */
  2977. function user_preferred_language($account, $default = NULL) {
  2978. $language_list = language_list();
  2979. if (!empty($account->preferred_langcode) && isset($language_list[$account->preferred_langcode])) {
  2980. return $language_list[$account->preferred_langcode];
  2981. }
  2982. else {
  2983. return $default ? $default : language_default();
  2984. }
  2985. }
  2986. /**
  2987. * Conditionally create and send a notification email when a certain
  2988. * operation happens on the given user account.
  2989. *
  2990. * @see user_mail_tokens()
  2991. * @see drupal_mail()
  2992. *
  2993. * @param $op
  2994. * The operation being performed on the account. Possible values:
  2995. * - 'register_admin_created': Welcome message for user created by the admin.
  2996. * - 'register_no_approval_required': Welcome message when user
  2997. * self-registers.
  2998. * - 'register_pending_approval': Welcome message, user pending admin
  2999. * approval.
  3000. * - 'password_reset': Password recovery request.
  3001. * - 'status_activated': Account activated.
  3002. * - 'status_blocked': Account blocked.
  3003. * - 'cancel_confirm': Account cancellation request.
  3004. * - 'status_canceled': Account canceled.
  3005. *
  3006. * @param $account
  3007. * The user object of the account being notified. Must contain at
  3008. * least the fields 'uid', 'name', and 'mail'.
  3009. * @param $language
  3010. * Optional language to use for the notification, overriding account language.
  3011. *
  3012. * @return
  3013. * The return value from drupal_mail_system()->mail(), if ends up being
  3014. * called.
  3015. */
  3016. function _user_mail_notify($op, $account, $language = NULL) {
  3017. // By default, we always notify except for canceled and blocked.
  3018. $default_notify = ($op != 'status_canceled' && $op != 'status_blocked');
  3019. $notify = variable_get('user_mail_' . $op . '_notify', $default_notify);
  3020. if ($notify) {
  3021. $params['account'] = $account;
  3022. $language = $language ? $language : user_preferred_language($account);
  3023. $mail = drupal_mail('user', $op, $account->mail, $language, $params);
  3024. if ($op == 'register_pending_approval') {
  3025. // If a user registered requiring admin approval, notify the admin, too.
  3026. // We use the site default language for this.
  3027. drupal_mail('user', 'register_pending_approval_admin', variable_get('site_mail', ini_get('sendmail_from')), language_default(), $params);
  3028. }
  3029. }
  3030. return empty($mail) ? NULL : $mail['result'];
  3031. }
  3032. /**
  3033. * Form element process handler for client-side password validation.
  3034. *
  3035. * This #process handler is automatically invoked for 'password_confirm' form
  3036. * elements to add the JavaScript and string translations for dynamic password
  3037. * validation.
  3038. *
  3039. * @see system_element_info()
  3040. */
  3041. function user_form_process_password_confirm($element) {
  3042. global $user;
  3043. $js_settings = array(
  3044. 'password' => array(
  3045. 'strengthTitle' => t('Password strength:'),
  3046. 'hasWeaknesses' => t('To make your password stronger:'),
  3047. 'tooShort' => t('Make it at least 6 characters'),
  3048. 'addLowerCase' => t('Add lowercase letters'),
  3049. 'addUpperCase' => t('Add uppercase letters'),
  3050. 'addNumbers' => t('Add numbers'),
  3051. 'addPunctuation' => t('Add punctuation'),
  3052. 'sameAsUsername' => t('Make it different from your username'),
  3053. 'confirmSuccess' => t('yes'),
  3054. 'confirmFailure' => t('no'),
  3055. 'weak' => t('Weak'),
  3056. 'fair' => t('Fair'),
  3057. 'good' => t('Good'),
  3058. 'strong' => t('Strong'),
  3059. 'confirmTitle' => t('Passwords match:'),
  3060. 'username' => (isset($user->name) ? $user->name : ''),
  3061. ),
  3062. );
  3063. $element['#attached']['js'][] = drupal_get_path('module', 'user') . '/user.js';
  3064. // Ensure settings are only added once per page.
  3065. static $already_added = FALSE;
  3066. if (!$already_added) {
  3067. $already_added = TRUE;
  3068. $element['#attached']['js'][] = array('data' => $js_settings, 'type' => 'setting');
  3069. }
  3070. return $element;
  3071. }
  3072. /**
  3073. * Implements hook_node_load().
  3074. */
  3075. function user_node_load($nodes, $types) {
  3076. // Build an array of all uids for node authors, keyed by nid.
  3077. $uids = array();
  3078. foreach ($nodes as $nid => $node) {
  3079. $uids[$nid] = $node->uid;
  3080. }
  3081. // Fetch name, picture, and data for these users.
  3082. $user_fields = db_query("SELECT uid, name, picture, data FROM {users} WHERE uid IN (:uids)", array(':uids' => $uids))->fetchAllAssoc('uid');
  3083. // Add these values back into the node objects.
  3084. foreach ($uids as $nid => $uid) {
  3085. $nodes[$nid]->name = $user_fields[$uid]->name;
  3086. $nodes[$nid]->picture = $user_fields[$uid]->picture;
  3087. $nodes[$nid]->data = $user_fields[$uid]->data;
  3088. }
  3089. }
  3090. /**
  3091. * Implements hook_image_style_delete().
  3092. */
  3093. function user_image_style_delete($style) {
  3094. // If a style is deleted, update the variables.
  3095. // Administrators choose a replacement style when deleting.
  3096. user_image_style_save($style);
  3097. }
  3098. /**
  3099. * Implements hook_image_style_save().
  3100. */
  3101. function user_image_style_save($style) {
  3102. // If a style is renamed, update the variables that use it.
  3103. if (isset($style['old_name']) && $style['old_name'] == variable_get('user_picture_style', '')) {
  3104. variable_set('user_picture_style', $style['name']);
  3105. }
  3106. }
  3107. /**
  3108. * Implements hook_action_info().
  3109. */
  3110. function user_action_info() {
  3111. return array(
  3112. 'user_block_user_action' => array(
  3113. 'label' => t('Block current user'),
  3114. 'type' => 'user',
  3115. 'configurable' => FALSE,
  3116. 'triggers' => array('any'),
  3117. ),
  3118. );
  3119. }
  3120. /**
  3121. * Blocks the current user.
  3122. *
  3123. * @ingroup actions
  3124. */
  3125. function user_block_user_action(&$entity, $context = array()) {
  3126. // First priority: If there is a $entity->uid, block that user.
  3127. // This is most likely a user object or the author if a node or comment.
  3128. if (isset($entity->uid)) {
  3129. $uid = $entity->uid;
  3130. }
  3131. elseif (isset($context['uid'])) {
  3132. $uid = $context['uid'];
  3133. }
  3134. // If neither of those are valid, then block the current user.
  3135. else {
  3136. $uid = $GLOBALS['user']->uid;
  3137. }
  3138. $account = user_load($uid);
  3139. $account->status = 0;
  3140. $account->save();
  3141. watchdog('action', 'Blocked user %name.', array('%name' => $account->name));
  3142. }
  3143. /**
  3144. * Implements hook_form_FORM_ID_alter().
  3145. *
  3146. * Add a checkbox for the 'user_register_form' instance settings on the 'Edit
  3147. * field instance' form.
  3148. */
  3149. function user_form_field_ui_field_edit_form_alter(&$form, &$form_state, $form_id) {
  3150. $instance = $form['#instance'];
  3151. if ($instance['entity_type'] == 'user') {
  3152. $form['instance']['settings']['user_register_form'] = array(
  3153. '#type' => 'checkbox',
  3154. '#title' => t('Display on user registration form.'),
  3155. '#description' => t("This is compulsory for 'required' fields."),
  3156. // Field instances created in D7 beta releases before the setting was
  3157. // introduced might be set as 'required' and 'not shown on user_register
  3158. // form'. We make sure the checkbox comes as 'checked' for those.
  3159. '#default_value' => $instance['settings']['user_register_form'] || $instance['required'],
  3160. // Display just below the 'required' checkbox.
  3161. '#weight' => $form['instance']['required']['#weight'] + .1,
  3162. // Disabled when the 'required' checkbox is checked.
  3163. '#states' => array(
  3164. 'enabled' => array('input[name="instance[required]"]' => array('checked' => FALSE)),
  3165. ),
  3166. // Checked when the 'required' checkbox is checked. This is done through
  3167. // a custom behavior, since the #states system would also synchronize on
  3168. // uncheck.
  3169. '#attached' => array(
  3170. 'js' => array(drupal_get_path('module', 'user') . '/user.js'),
  3171. ),
  3172. );
  3173. array_unshift($form['#submit'], 'user_form_field_ui_field_edit_form_submit');
  3174. }
  3175. }
  3176. /**
  3177. * Additional submit handler for the 'Edit field instance' form.
  3178. *
  3179. * Make sure the 'user_register_form' setting is set for required fields.
  3180. */
  3181. function user_form_field_ui_field_edit_form_submit($form, &$form_state) {
  3182. $instance = $form_state['values']['instance'];
  3183. if (!empty($instance['required'])) {
  3184. form_set_value($form['instance']['settings']['user_register_form'], 1, $form_state);
  3185. }
  3186. }
  3187. /**
  3188. * Form builder; the user registration form.
  3189. *
  3190. * @ingroup forms
  3191. * @see user_account_form()
  3192. * @see user_account_form_validate()
  3193. * @see user_register_submit()
  3194. */
  3195. function user_register_form($form, &$form_state) {
  3196. global $user;
  3197. $admin = user_access('administer users');
  3198. // Pass access information to the submit handler. Running an access check
  3199. // inside the submit function interferes with form processing and breaks
  3200. // hook_form_alter().
  3201. $form['administer_users'] = array(
  3202. '#type' => 'value',
  3203. '#value' => $admin,
  3204. );
  3205. // If we aren't admin but already logged on, go to the user page instead.
  3206. if (!$admin && $user->uid) {
  3207. drupal_goto('user/' . $user->uid);
  3208. }
  3209. $form['#user'] = entity_create('user', array());
  3210. $form['#attached']['library'][] = array('system', 'jquery.cookie');
  3211. $form['#attributes']['class'][] = 'user-info-from-cookie';
  3212. // Start with the default user account fields.
  3213. user_account_form($form, $form_state);
  3214. // Attach field widgets, and hide the ones where the 'user_register_form'
  3215. // setting is not on.
  3216. field_attach_form('user', $form['#user'], $form, $form_state);
  3217. foreach (field_info_instances('user', 'user') as $field_name => $instance) {
  3218. if (empty($instance['settings']['user_register_form'])) {
  3219. $form[$field_name]['#access'] = FALSE;
  3220. }
  3221. }
  3222. if ($admin) {
  3223. // Redirect back to page which initiated the create request;
  3224. // usually admin/people/create.
  3225. $form_state['redirect'] = current_path();
  3226. }
  3227. $form['actions'] = array('#type' => 'actions');
  3228. $form['actions']['submit'] = array(
  3229. '#type' => 'submit',
  3230. '#value' => t('Create new account'),
  3231. );
  3232. $form['#validate'][] = 'user_register_validate';
  3233. // Add the final user registration form submit handler.
  3234. $form['#submit'][] = 'user_register_submit';
  3235. return $form;
  3236. }
  3237. /**
  3238. * Validation function for the user registration form.
  3239. */
  3240. function user_register_validate($form, &$form_state) {
  3241. entity_form_field_validate('user', $form, $form_state);
  3242. }
  3243. /**
  3244. * Submit handler for the user registration form.
  3245. *
  3246. * This function is shared by the installation form and the normal registration form,
  3247. * which is why it can't be in the user.pages.inc file.
  3248. *
  3249. * @see user_register_form()
  3250. */
  3251. function user_register_submit($form, &$form_state) {
  3252. $admin = $form_state['values']['administer_users'];
  3253. if (!variable_get('user_email_verification', TRUE) || $admin) {
  3254. $pass = $form_state['values']['pass'];
  3255. }
  3256. else {
  3257. $pass = user_password();
  3258. }
  3259. $notify = !empty($form_state['values']['notify']);
  3260. // Remove unneeded values.
  3261. form_state_values_clean($form_state);
  3262. $form_state['values']['pass'] = $pass;
  3263. $form_state['values']['init'] = $form_state['values']['mail'];
  3264. $account = $form['#user'];
  3265. entity_form_submit_build_entity('user', $account, $form, $form_state);
  3266. $status = $account->save();
  3267. // Terminate if an error occurred while saving the account.
  3268. if ($status =! SAVED_NEW) {
  3269. drupal_set_message(t("Error saving user account."), 'error');
  3270. $form_state['redirect'] = '';
  3271. return;
  3272. }
  3273. $form_state['user'] = $account;
  3274. $form_state['values']['uid'] = $account->uid;
  3275. 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'));
  3276. // Add plain text password into user account to generate mail tokens.
  3277. $account->password = $pass;
  3278. // New administrative account without notification.
  3279. $uri = entity_uri('user', $account);
  3280. if ($admin && !$notify) {
  3281. 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)));
  3282. }
  3283. // No e-mail verification required; log in user immediately.
  3284. elseif (!$admin && !variable_get('user_email_verification', TRUE) && $account->status) {
  3285. _user_mail_notify('register_no_approval_required', $account);
  3286. $form_state['uid'] = $account->uid;
  3287. user_login_submit(array(), $form_state);
  3288. drupal_set_message(t('Registration successful. You are now logged in.'));
  3289. $form_state['redirect'] = '';
  3290. }
  3291. // No administrator approval required.
  3292. elseif ($account->status || $notify) {
  3293. if (empty($account->mail) && $notify) {
  3294. drupal_set_message(t('The new user <a href="@url">%name</a> was created without an email address, so no welcome message was sent.', array('@url' => url($uri['path'], $uri['options']), '%name' => $account->name)));
  3295. }
  3296. else {
  3297. $op = $notify ? 'register_admin_created' : 'register_no_approval_required';
  3298. _user_mail_notify($op, $account);
  3299. if ($notify) {
  3300. 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)));
  3301. }
  3302. else {
  3303. drupal_set_message(t('A welcome message with further instructions has been sent to your e-mail address.'));
  3304. $form_state['redirect'] = '';
  3305. }
  3306. }
  3307. }
  3308. // Administrator approval required.
  3309. else {
  3310. _user_mail_notify('register_pending_approval', $account);
  3311. 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.'));
  3312. $form_state['redirect'] = '';
  3313. }
  3314. }
  3315. /**
  3316. * Implements hook_modules_installed().
  3317. */
  3318. function user_modules_installed($modules) {
  3319. // Assign all available permissions to the administrator role.
  3320. $rid = variable_get('user_admin_role', 0);
  3321. if ($rid) {
  3322. $permissions = array();
  3323. foreach ($modules as $module) {
  3324. if ($module_permissions = module_invoke($module, 'permission')) {
  3325. $permissions = array_merge($permissions, array_keys($module_permissions));
  3326. }
  3327. }
  3328. if (!empty($permissions)) {
  3329. user_role_grant_permissions($rid, $permissions);
  3330. }
  3331. }
  3332. }
  3333. /**
  3334. * Implements hook_modules_uninstalled().
  3335. */
  3336. function user_modules_uninstalled($modules) {
  3337. db_delete('role_permission')
  3338. ->condition('module', $modules, 'IN')
  3339. ->execute();
  3340. }
  3341. /**
  3342. * Helper function to rewrite the destination to avoid redirecting to login page after login.
  3343. *
  3344. * Third-party authentication modules may use this function to determine the
  3345. * proper destination after a user has been properly logged in.
  3346. */
  3347. function user_login_destination() {
  3348. $destination = drupal_get_destination();
  3349. if ($destination['destination'] == 'user/login') {
  3350. $destination['destination'] = 'user';
  3351. }
  3352. return $destination;
  3353. }
  3354. /**
  3355. * Saves visitor information as a cookie so it can be reused.
  3356. *
  3357. * @param $values
  3358. * An array of key/value pairs to be saved into a cookie.
  3359. */
  3360. function user_cookie_save(array $values) {
  3361. foreach ($values as $field => $value) {
  3362. // Set cookie for 365 days.
  3363. setrawcookie('Drupal.visitor.' . $field, rawurlencode($value), REQUEST_TIME + 31536000, '/');
  3364. }
  3365. }
  3366. /**
  3367. * Delete a visitor information cookie.
  3368. *
  3369. * @param $cookie_name
  3370. * A cookie name such as 'homepage'.
  3371. */
  3372. function user_cookie_delete($cookie_name) {
  3373. setrawcookie('Drupal.visitor.' . $cookie_name, '', REQUEST_TIME - 3600, '/');
  3374. }
  3375. /**
  3376. * Implements hook_rdf_mapping().
  3377. */
  3378. function user_rdf_mapping() {
  3379. return array(
  3380. array(
  3381. 'type' => 'user',
  3382. 'bundle' => RDF_DEFAULT_BUNDLE,
  3383. 'mapping' => array(
  3384. 'rdftype' => array('sioc:UserAccount'),
  3385. 'name' => array(
  3386. 'predicates' => array('foaf:name'),
  3387. ),
  3388. 'homepage' => array(
  3389. 'predicates' => array('foaf:page'),
  3390. 'type' => 'rel',
  3391. ),
  3392. ),
  3393. ),
  3394. );
  3395. }
  3396. /**
  3397. * Implements hook_file_download_access().
  3398. */
  3399. function user_file_download_access($field, $entity_type, $entity) {
  3400. if ($entity_type == 'user') {
  3401. return user_view_access($entity);
  3402. }
  3403. }
Login or register to post comments