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_LENGTH
USERNAME_MAX_LENGTH

Functions & methods

NameDescription
template_preprocess_user_pictureProcess variables for user-picture.tpl.php.
theme_user_listMake a list of users.
theme_user_signatureTheme output of user signature.
user_accessDetermine whether the user has a given privilege.
user_action_infoImplementation of hook_action_info().
user_authenticateTry to log in the user locally.
user_authenticate_finalizeFinalize the login process. Must be called when logging in a user.
user_blockImplementation of hook_block().
user_block_ip_actionImplementation of a Drupal action. Adds an access rule that blocks the user's IP address.
user_block_user_actionImplementation of a Drupal action. Blocks the current user.
user_build_contentBuilds a structured array representing the profile content.
user_build_filter_queryBuild query for user administration filters based on session.
user_category_loadReturn a user object after checking if any profile category in the path exists.
user_commentImplementation of hook_comment().
user_deleteDelete a user.
user_delete_accessMenu access callback; limit access to account deletion pages.
user_edit_accessAccess callback for user account editing.
user_edit_form
user_elementsImplementation of hook_elements().
user_external_load
user_external_loginPerform standard Drupal login operations for a user object.
user_external_login_registerHelper function for authentication modules. Either login in or registers the current user, based on username. Either way, the global $user object is populated based on $name.
user_fields
user_file_downloadImplementation of hook_file_download().
user_filtersList user administration filters that can be applied.
user_formsImplementation of hook_forms().
user_get_authmapsDiscover which external authentication module(s) authenticated a username.
user_helpImplementation of hook_help().
user_hook_infoImplementation of hook_hook_info().
user_initImplementation of hook_init().
user_is_anonymous
user_is_blockedChecks for usernames blocked by user administration.
user_is_logged_in
user_loadFetch a user object.
user_load_self
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, sets the global $user object.
user_login_block
user_login_default_validatorsSet up a series for validators which check for blocked/denied 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…
user_login_destinationPrepare a destination query string for use in combination with drupal_goto().
user_login_final_validateA validate handler on the login form. Should be the last validator. Sets an error if user has not been authenticated yet.
user_login_name_validateA FAPI validate handler. Sets an error if supplied username has been blocked or denied access.
user_login_submitSubmit handler for the login form. Redirects the user to a page.
user_mailImplementation of hook_mail().
user_mail_tokensReturn an array of token to value mappings for user e-mail messages.
user_menuImplementation of hook_menu().
user_module_invokeInvokes hook_user() in every module.
user_multiple_delete_confirm
user_multiple_delete_confirm_submit
user_multiple_role_editCallback function for admin mass adding/deleting a user role.
user_page_titleMenu item title callback - use the user name if it's not the current user.
user_passwordGenerate a random alphanumeric password.
user_pass_rehash
user_pass_reset_urlGenerates a unique URL for a user to login and reset their password.
user_permImplementation of hook_perm().
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_registerForm builder; The user registration form.
user_register_access
user_register_submitSubmit handler for the user registration form.
user_register_validate
user_rolesRetrieve an array of roles matching specified conditions.
user_saveSave changes to a user account or add a new user.
user_searchImplementation of hook_search().
user_set_authmapsSave mappings of which external authentication module(s) authenticated a user. Maps external usernames to user ids in the users table.
user_themeImplementation of hook_theme().
user_uid_optional_loadLoad either a specified or the current user account.
user_uid_optional_to_argReturns the user id of the currently logged in user.
user_userImplementation of hook_user().
user_user_operationsImplementation of hook_user_operations().
user_user_operations_blockCallback function for admin mass blocking users.
user_user_operations_unblockCallback function for admin mass unblocking users.
user_validate_mail
user_validate_nameVerify the syntax of the given name.
user_validate_picture
user_view_access
_user_categoriesRetrieve a list of all user setting/information categories and sort them by weight.
_user_edit_submit
_user_edit_validate
_user_formsRetrieve a list of all form elements for the specified category.
_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.
_user_password_dynamic_validationAdd javascript and string translations for dynamic password validation (strength and confirmation checking).
_user_sort

File

modules/user/user.module
View source
  1. <?php
  2. /**
  3. * @file
  4. * Enables the user registration and login system.
  5. */
  6. define('USERNAME_MAX_LENGTH', 60);
  7. define('EMAIL_MAX_LENGTH', 64);
  8. /**
  9. * Invokes hook_user() in every module.
  10. *
  11. * We cannot use module_invoke() for this, because the arguments need to
  12. * be passed by reference.
  13. *
  14. * @param $op
  15. * The operation to be passed as the first parameter of the hook function.
  16. * @param $edit
  17. * An associative array variable containing form values to be passed
  18. * as the second parameter of the hook function.
  19. * @param $account
  20. * The user account object to be passed as the third parameter of the hook
  21. * function.
  22. * @param $category
  23. * The category of user information being acted upon.
  24. */
  25. function user_module_invoke($op, &$edit, &$account, $category = NULL) {
  26. foreach (module_list() as $module) {
  27. $function = $module .'_user';
  28. if (function_exists($function)) {
  29. $function($op, $edit, $account, $category);
  30. }
  31. }
  32. }
  33. /**
  34. * Implementation of hook_theme().
  35. */
  36. function user_theme() {
  37. return array(
  38. 'user_picture' => array(
  39. 'arguments' => array('account' => NULL),
  40. 'template' => 'user-picture',
  41. ),
  42. 'user_profile' => array(
  43. 'arguments' => array('account' => NULL),
  44. 'template' => 'user-profile',
  45. 'file' => 'user.pages.inc',
  46. ),
  47. 'user_profile_category' => array(
  48. 'arguments' => array('element' => NULL),
  49. 'template' => 'user-profile-category',
  50. 'file' => 'user.pages.inc',
  51. ),
  52. 'user_profile_item' => array(
  53. 'arguments' => array('element' => NULL),
  54. 'template' => 'user-profile-item',
  55. 'file' => 'user.pages.inc',
  56. ),
  57. 'user_list' => array(
  58. 'arguments' => array('users' => NULL, 'title' => NULL),
  59. ),
  60. 'user_admin_perm' => array(
  61. 'arguments' => array('form' => NULL),
  62. 'file' => 'user.admin.inc',
  63. ),
  64. 'user_admin_new_role' => array(
  65. 'arguments' => array('form' => NULL),
  66. 'file' => 'user.admin.inc',
  67. ),
  68. 'user_admin_account' => array(
  69. 'arguments' => array('form' => NULL),
  70. 'file' => 'user.admin.inc',
  71. ),
  72. 'user_filter_form' => array(
  73. 'arguments' => array('form' => NULL),
  74. 'file' => 'user.admin.inc',
  75. ),
  76. 'user_filters' => array(
  77. 'arguments' => array('form' => NULL),
  78. 'file' => 'user.admin.inc',
  79. ),
  80. 'user_signature' => array(
  81. 'arguments' => array('signature' => NULL),
  82. ),
  83. );
  84. }
  85. function user_external_load($authname) {
  86. $result = db_query("SELECT uid FROM {authmap} WHERE authname = '%s'", $authname);
  87. if ($user = db_fetch_array($result)) {
  88. return user_load($user);
  89. }
  90. else {
  91. return 0;
  92. }
  93. }
  94. /**
  95. * Perform standard Drupal login operations for a user object.
  96. *
  97. * The user object must already be authenticated. This function verifies
  98. * that the user account is not blocked/denied and then performs the login,
  99. * updates the login timestamp in the database, invokes hook_user('login'),
  100. * and regenerates the session.
  101. *
  102. * @param $account
  103. * An authenticated user object to be set as the currently logged
  104. * in user.
  105. * @param $edit
  106. * The array of form values submitted by the user, if any.
  107. * This array is passed to hook_user op login.
  108. * @return boolean
  109. * TRUE if the login succeeds, FALSE otherwise.
  110. */
  111. function user_external_login($account, $edit = array()) {
  112. $form = drupal_get_form('user_login');
  113. $state['values'] = $edit;
  114. if (empty($state['values']['name'])) {
  115. $state['values']['name'] = $account->name;
  116. }
  117. // Check if user is blocked or denied by access rules.
  118. user_login_name_validate($form, $state, (array)$account);
  119. if (form_get_errors()) {
  120. // Invalid login.
  121. return FALSE;
  122. }
  123. // Valid login.
  124. global $user;
  125. $user = $account;
  126. user_authenticate_finalize($state['values']);
  127. return TRUE;
  128. }
  129. /**
  130. * Fetch a user object.
  131. *
  132. * @param $user_info
  133. * Information about the user to load, consisting of one of the following:
  134. * - An associative array whose keys are fields in the {users} table (such as
  135. * uid, name, pass, mail, status) and whose values are the field's value.
  136. * - A numeric user ID.
  137. *
  138. * @return
  139. * A fully-loaded $user object upon successful user load or FALSE if user
  140. * cannot be loaded.
  141. */
  142. function user_load($user_info = array()) {
  143. // Dynamically compose a SQL query:
  144. $query = array();
  145. $params = array();
  146. if (is_numeric($user_info)) {
  147. $user_info = array('uid' => $user_info);
  148. }
  149. elseif (!is_array($user_info)) {
  150. return FALSE;
  151. }
  152. foreach ($user_info as $key => $value) {
  153. if ($key == 'uid' || $key == 'status') {
  154. $query[] = "$key = %d";
  155. $params[] = $value;
  156. }
  157. else if ($key == 'pass') {
  158. $query[] = "pass = '%s'";
  159. $params[] = md5($value);
  160. }
  161. else {
  162. $query[]= "LOWER($key) = LOWER('%s')";
  163. $params[] = $value;
  164. }
  165. }
  166. $result = db_query('SELECT * FROM {users} u WHERE '. implode(' AND ', $query), $params);
  167. if ($user = db_fetch_object($result)) {
  168. $user = drupal_unpack($user);
  169. $user->roles = array();
  170. if ($user->uid) {
  171. $user->roles[DRUPAL_AUTHENTICATED_RID] = 'authenticated user';
  172. }
  173. else {
  174. $user->roles[DRUPAL_ANONYMOUS_RID] = 'anonymous user';
  175. }
  176. $result = db_query('SELECT r.rid, r.name FROM {role} r INNER JOIN {users_roles} ur ON ur.rid = r.rid WHERE ur.uid = %d', $user->uid);
  177. while ($role = db_fetch_object($result)) {
  178. $user->roles[$role->rid] = $role->name;
  179. }
  180. user_module_invoke('load', $user_info, $user);
  181. }
  182. else {
  183. $user = FALSE;
  184. }
  185. return $user;
  186. }
  187. /**
  188. * Save changes to a user account or add a new user.
  189. *
  190. * @param $account
  191. * The user object for to modify or add. If you want to modify an existing
  192. * user account, you will need to ensure that (a) $account is an object, and
  193. * (b) you have set $account->uid to the numeric user ID of the user account
  194. * you wish to modify. Pass in NULL or any non-object to add a new user.
  195. * @param $array
  196. * (optional) An array of fields and values to save. For example,
  197. * array('name' => 'My name'); Keys that do not belong to columns
  198. * in the user-related tables are added to the a serialized array
  199. * in the 'data' column and will be loaded in the $user->data array by
  200. * user_load(). Setting a field to NULL deletes it from the data column,
  201. * if you are modifying an existing user account.
  202. * @param $category
  203. * (optional) The category for storing profile information in.
  204. *
  205. * @return
  206. * A fully-loaded $user object upon successful save or FALSE if the save failed.
  207. */
  208. function user_save($account, $array = array(), $category = 'account') {
  209. // Dynamically compose a SQL query:
  210. $user_fields = user_fields();
  211. if (is_object($account) && $account->uid) {
  212. user_module_invoke('update', $array, $account, $category);
  213. $query = '';
  214. $data = unserialize(db_result(db_query('SELECT data FROM {users} WHERE uid = %d', $account->uid)));
  215. // Consider users edited by an administrator as logged in, if they haven't
  216. // already, so anonymous users can view the profile (if allowed).
  217. if (empty($array['access']) && empty($account->access) && user_access('administer users')) {
  218. $array['access'] = time();
  219. }
  220. foreach ($array as $key => $value) {
  221. if ($key == 'pass' && !empty($value)) {
  222. $query .= "$key = '%s', ";
  223. $v[] = md5($value);
  224. }
  225. else if ((substr($key, 0, 4) !== 'auth') && ($key != 'pass')) {
  226. if (in_array($key, $user_fields)) {
  227. // Save standard fields.
  228. $query .= "$key = '%s', ";
  229. $v[] = $value;
  230. }
  231. else if ($key != 'roles') {
  232. // Roles is a special case: it used below.
  233. if ($value === NULL) {
  234. unset($data[$key]);
  235. }
  236. elseif (!empty($key)) {
  237. $data[$key] = $value;
  238. }
  239. }
  240. }
  241. }
  242. $query .= "data = '%s' ";
  243. $v[] = serialize($data);
  244. $success = db_query("UPDATE {users} SET $query WHERE uid = %d", array_merge($v, array($account->uid)));
  245. if (!$success) {
  246. // The query failed - better to abort the save than risk further data loss.
  247. return FALSE;
  248. }
  249. // Reload user roles if provided.
  250. if (isset($array['roles']) && is_array($array['roles'])) {
  251. db_query('DELETE FROM {users_roles} WHERE uid = %d', $account->uid);
  252. foreach (array_keys($array['roles']) as $rid) {
  253. if (!in_array($rid, array(DRUPAL_ANONYMOUS_RID, DRUPAL_AUTHENTICATED_RID))) {
  254. db_query('INSERT INTO {users_roles} (uid, rid) VALUES (%d, %d)', $account->uid, $rid);
  255. }
  256. }
  257. }
  258. // Delete a blocked user's sessions to kick them if they are online.
  259. if (isset($array['status']) && $array['status'] == 0) {
  260. sess_destroy_uid($account->uid);
  261. }
  262. // If the password changed, delete all open sessions and recreate
  263. // the current one.
  264. if (!empty($array['pass'])) {
  265. sess_destroy_uid($account->uid);
  266. if ($account->uid == $GLOBALS['user']->uid) {
  267. sess_regenerate();
  268. }
  269. }
  270. // Refresh user object.
  271. $user = user_load(array('uid' => $account->uid));
  272. // Send emails after we have the new user object.
  273. if (isset($array['status']) && $array['status'] != $account->status) {
  274. // The user's status is changing; conditionally send notification email.
  275. $op = $array['status'] == 1 ? 'status_activated' : 'status_blocked';
  276. _user_mail_notify($op, $user);
  277. }
  278. user_module_invoke('after_update', $array, $user, $category);
  279. }
  280. else {
  281. // Allow 'created' to be set by the caller.
  282. if (!isset($array['created'])) {
  283. $array['created'] = time();
  284. }
  285. // Consider users created by an administrator as already logged in, so
  286. // anonymous users can view the profile (if allowed).
  287. if (empty($array['access']) && user_access('administer users')) {
  288. $array['access'] = time();
  289. }
  290. // Note: we wait to save the data column to prevent module-handled
  291. // fields from being saved there. We cannot invoke hook_user('insert') here
  292. // because we don't have a fully initialized user object yet.
  293. foreach ($array as $key => $value) {
  294. switch ($key) {
  295. case 'pass':
  296. $fields[] = $key;
  297. $values[] = md5($value);
  298. $s[] = "'%s'";
  299. break;
  300. case 'mode': case 'sort': case 'timezone':
  301. case 'threshold': case 'created': case 'access':
  302. case 'login': case 'status':
  303. $fields[] = $key;
  304. $values[] = $value;
  305. $s[] = "%d";
  306. break;
  307. default:
  308. if (substr($key, 0, 4) !== 'auth' && in_array($key, $user_fields)) {
  309. $fields[] = $key;
  310. $values[] = $value;
  311. $s[] = "'%s'";
  312. }
  313. break;
  314. }
  315. }
  316. $success = db_query('INSERT INTO {users} ('. implode(', ', $fields) .') VALUES ('. implode(', ', $s) .')', $values);
  317. if (!$success) {
  318. // On a failed INSERT some other existing user's uid may be returned.
  319. // We must abort to avoid overwriting their account.
  320. return FALSE;
  321. }
  322. // Build the initial user object.
  323. $array['uid'] = db_last_insert_id('users', 'uid');
  324. $user = user_load(array('uid' => $array['uid']));
  325. user_module_invoke('insert', $array, $user, $category);
  326. // Build and save the serialized data field now.
  327. $data = array();
  328. foreach ($array as $key => $value) {
  329. if ((substr($key, 0, 4) !== 'auth') && ($key != 'roles') && (!in_array($key, $user_fields)) && ($value !== NULL)) {
  330. $data[$key] = $value;
  331. }
  332. }
  333. db_query("UPDATE {users} SET data = '%s' WHERE uid = %d", serialize($data), $user->uid);
  334. // Save user roles (delete just to be safe).
  335. if (isset($array['roles']) && is_array($array['roles'])) {
  336. db_query('DELETE FROM {users_roles} WHERE uid = %d', $array['uid']);
  337. foreach (array_keys($array['roles']) as $rid) {
  338. if (!in_array($rid, array(DRUPAL_ANONYMOUS_RID, DRUPAL_AUTHENTICATED_RID))) {
  339. db_query('INSERT INTO {users_roles} (uid, rid) VALUES (%d, %d)', $array['uid'], $rid);
  340. }
  341. }
  342. }
  343. // Build the finished user object.
  344. $user = user_load(array('uid' => $array['uid']));
  345. }
  346. // Save distributed authentication mappings.
  347. $authmaps = array();
  348. foreach ($array as $key => $value) {
  349. if (substr($key, 0, 4) == 'auth') {
  350. $authmaps[$key] = $value;
  351. }
  352. }
  353. if (sizeof($authmaps) > 0) {
  354. user_set_authmaps($user, $authmaps);
  355. }
  356. return $user;
  357. }
  358. /**
  359. * Verify the syntax of the given name.
  360. */
  361. function user_validate_name($name) {
  362. if (!strlen($name)) {
  363. return t('You must enter a username.');
  364. }
  365. if (substr($name, 0, 1) == ' ') {
  366. return t('The username cannot begin with a space.');
  367. }
  368. if (substr($name, -1) == ' ') {
  369. return t('The username cannot end with a space.');
  370. }
  371. if (strpos($name, ' ') !== FALSE) {
  372. return t('The username cannot contain multiple spaces in a row.');
  373. }
  374. if (preg_match('/[^\x{80}-\x{F7} a-z0-9@_.\'-]/i', $name)) {
  375. return t('The username contains an illegal character.');
  376. }
  377. if (preg_match('/[\x{80}-\x{A0}'. // Non-printable ISO-8859-1 + NBSP
  378. '\x{AD}'. // Soft-hyphen
  379. '\x{2000}-\x{200F}'. // Various space characters
  380. '\x{2028}-\x{202F}'. // Bidirectional text overrides
  381. '\x{205F}-\x{206F}'. // Various text hinting characters
  382. '\x{FEFF}'. // Byte order mark
  383. '\x{FF01}-\x{FF60}'. // Full-width latin
  384. '\x{FFF9}-\x{FFFD}'. // Replacement characters
  385. '\x{0}-\x{1F}]/u', // NULL byte and control characters
  386. $name)) {
  387. return t('The username contains an illegal character.');
  388. }
  389. if (drupal_strlen($name) > USERNAME_MAX_LENGTH) {
  390. return t('The username %name is too long: it must be %max characters or less.', array('%name' => $name, '%max' => USERNAME_MAX_LENGTH));
  391. }
  392. }
  393. function user_validate_mail($mail) {
  394. if (!$mail) return t('You must enter an e-mail address.');
  395. if (!valid_email_address($mail)) {
  396. return t('The e-mail address %mail is not valid.', array('%mail' => $mail));
  397. }
  398. }
  399. function user_validate_picture(&$form, &$form_state) {
  400. // If required, validate the uploaded picture.
  401. $validators = array(
  402. 'file_validate_is_image' => array(),
  403. 'file_validate_image_resolution' => array(variable_get('user_picture_dimensions', '85x85')),
  404. 'file_validate_size' => array(variable_get('user_picture_file_size', '30') * 1024),
  405. );
  406. if ($file = file_save_upload('picture_upload', $validators)) {
  407. // Remove the old picture.
  408. if (isset($form_state['values']['_account']->picture) && file_exists($form_state['values']['_account']->picture)) {
  409. file_delete($form_state['values']['_account']->picture);
  410. }
  411. // The image was saved using file_save_upload() and was added to the
  412. // files table as a temporary file. We'll make a copy and let the garbage
  413. // collector delete the original upload.
  414. $info = image_get_info($file->filepath);
  415. $destination = variable_get('user_picture_path', 'pictures') .'/picture-'. $form['#uid'] .'.'. $info['extension'];
  416. if (file_copy($file, $destination, FILE_EXISTS_REPLACE)) {
  417. $form_state['values']['picture'] = $file->filepath;
  418. }
  419. else {
  420. 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'))));
  421. }
  422. }
  423. }
  424. /**
  425. * Generate a random alphanumeric password.
  426. */
  427. function user_password($length = 10) {
  428. // This variable contains the list of allowable characters for the
  429. // password. Note that the number 0 and the letter 'O' have been
  430. // removed to avoid confusion between the two. The same is true
  431. // of 'I', 1, and 'l'.
  432. $allowable_characters = 'abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789';
  433. // Zero-based count of characters in the allowable list:
  434. $len = strlen($allowable_characters) - 1;
  435. // Declare the password as a blank string.
  436. $pass = '';
  437. // Loop the number of times specified by $length.
  438. for ($i = 0; $i < $length; $i++) {
  439. // Each iteration, pick a random character from the
  440. // allowable string and append it to the password:
  441. $pass .= $allowable_characters[mt_rand(0, $len)];
  442. }
  443. return $pass;
  444. }
  445. /**
  446. * Determine whether the user has a given privilege.
  447. *
  448. * @param $string
  449. * The permission, such as "administer nodes", being checked for.
  450. * @param $account
  451. * (optional) The account to check, if not given use currently logged in user.
  452. * @param $reset
  453. * (optional) Resets the user's permissions cache, which will result in a
  454. * recalculation of the user's permissions. This is necessary to support
  455. * dynamically added user roles.
  456. *
  457. * @return
  458. * Boolean TRUE if the current user has the requested permission.
  459. *
  460. * All permission checks in Drupal should go through this function. This
  461. * way, we guarantee consistent behavior, and ensure that the superuser
  462. * can perform all actions.
  463. */
  464. function user_access($string, $account = NULL, $reset = FALSE) {
  465. global $user;
  466. static $perm = array();
  467. if ($reset) {
  468. $perm = array();
  469. }
  470. if (!isset($account)) {
  471. $account = $user;
  472. }
  473. // User #1 has all privileges:
  474. if ($account->uid == 1) {
  475. return TRUE;
  476. }
  477. // To reduce the number of SQL queries, we cache the user's permissions
  478. // in a static variable.
  479. if (!isset($perm[$account->uid])) {
  480. $result = db_query("SELECT p.perm FROM {role} r INNER JOIN {permission} p ON p.rid = r.rid WHERE r.rid IN (". db_placeholders($account->roles) .")", array_keys($account->roles));
  481. $perms = array();
  482. while ($row = db_fetch_object($result)) {
  483. $perms += array_flip(explode(', ', $row->perm));
  484. }
  485. $perm[$account->uid] = $perms;
  486. }
  487. return isset($perm[$account->uid][$string]);
  488. }
  489. /**
  490. * Checks for usernames blocked by user administration.
  491. *
  492. * @return boolean TRUE for blocked users, FALSE for active.
  493. */
  494. function user_is_blocked($name) {
  495. $deny = db_fetch_object(db_query("SELECT name FROM {users} WHERE status = 0 AND name = LOWER('%s')", $name));
  496. return $deny;
  497. }
  498. function user_fields() {
  499. static $fields;
  500. if (!$fields) {
  501. $result = db_query('SELECT * FROM {users} WHERE uid = 1');
  502. if ($field = db_fetch_array($result)) {
  503. $fields = array_keys($field);
  504. }
  505. else {
  506. // Make sure we return the default fields at least.
  507. $fields = array('uid', 'name', 'pass', 'mail', 'picture', 'mode', 'sort', 'threshold', 'theme', 'signature', 'signature_format', 'created', 'access', 'login', 'status', 'timezone', 'language', 'init', 'data');
  508. }
  509. }
  510. return $fields;
  511. }
  512. /**
  513. * Implementation of hook_perm().
  514. */
  515. function user_perm() {
  516. return array('administer permissions', 'administer users', 'access user profiles', 'change own username');
  517. }
  518. /**
  519. * Implementation of hook_file_download().
  520. *
  521. * Ensure that user pictures (avatars) are always downloadable.
  522. */
  523. function user_file_download($file) {
  524. if (strpos($file, variable_get('user_picture_path', 'pictures') .'/picture-') === 0) {
  525. $info = image_get_info(file_create_path($file));
  526. return array('Content-type: '. $info['mime_type']);
  527. }
  528. }
  529. /**
  530. * Implementation of hook_search().
  531. */
  532. function user_search($op = 'search', $keys = NULL, $skip_access_check = FALSE) {
  533. switch ($op) {
  534. case 'name':
  535. if ($skip_access_check || user_access('access user profiles')) {
  536. return t('Users');
  537. }
  538. case 'search':
  539. if (user_access('access user profiles')) {
  540. $find = array();
  541. // Replace wildcards with MySQL/PostgreSQL wildcards.
  542. $keys = preg_replace('!\*+!', '%', $keys);
  543. if (user_access('administer users')) {
  544. // Administrators can also search in the otherwise private email field.
  545. $result = pager_query("SELECT name, uid, mail FROM {users} WHERE LOWER(name) LIKE LOWER('%%%s%%') OR LOWER(mail) LIKE LOWER('%%%s%%')", 15, 0, NULL, $keys, $keys);
  546. while ($account = db_fetch_object($result)) {
  547. $find[] = array('title' => $account->name .' ('. $account->mail .')', 'link' => url('user/'. $account->uid, array('absolute' => TRUE)));
  548. }
  549. }
  550. else {
  551. $result = pager_query("SELECT name, uid FROM {users} WHERE LOWER(name) LIKE LOWER('%%%s%%')", 15, 0, NULL, $keys);
  552. while ($account = db_fetch_object($result)) {
  553. $find[] = array('title' => $account->name, 'link' => url('user/'. $account->uid, array('absolute' => TRUE)));
  554. }
  555. }
  556. return $find;
  557. }
  558. }
  559. }
  560. /**
  561. * Implementation of hook_elements().
  562. */
  563. function user_elements() {
  564. return array(
  565. 'user_profile_category' => array(),
  566. 'user_profile_item' => array(),
  567. );
  568. }
  569. /**
  570. * Implementation of hook_user().
  571. */
  572. function user_user($type, &$edit, &$account, $category = NULL) {
  573. if ($type == 'view') {
  574. $account->content['user_picture'] = array(
  575. '#value' => theme('user_picture', $account),
  576. '#weight' => -10,
  577. );
  578. if (!isset($account->content['summary'])) {
  579. $account->content['summary'] = array();
  580. }
  581. $account->content['summary'] += array(
  582. '#type' => 'user_profile_category',
  583. '#attributes' => array('class' => 'user-member'),
  584. '#weight' => 5,
  585. '#title' => t('History'),
  586. );
  587. $account->content['summary']['member_for'] = array(
  588. '#type' => 'user_profile_item',
  589. '#title' => t('Member for'),
  590. '#value' => format_interval(time() - $account->created),
  591. );
  592. }
  593. if ($type == 'form' && $category == 'account') {
  594. $form_state = array();
  595. return user_edit_form($form_state, (isset($account->uid) ? $account->uid : FALSE), $edit);
  596. }
  597. if ($type == 'validate' && $category == 'account') {
  598. return _user_edit_validate((isset($account->uid) ? $account->uid : FALSE), $edit);
  599. }
  600. if ($type == 'submit' && $category == 'account') {
  601. return _user_edit_submit((isset($account->uid) ? $account->uid : FALSE), $edit);
  602. }
  603. if ($type == 'categories') {
  604. return array(array('name' => 'account', 'title' => t('Account settings'), 'weight' => 1));
  605. }
  606. }
  607. function user_login_block() {
  608. $form = array(
  609. '#action' => url($_GET['q'], array('query' => drupal_get_destination())),
  610. '#id' => 'user-login-form',
  611. '#validate' => user_login_default_validators(),
  612. '#submit' => array('user_login_submit'),
  613. );
  614. $form['name'] = array('#type' => 'textfield',
  615. '#title' => t('Username'),
  616. '#maxlength' => USERNAME_MAX_LENGTH,
  617. '#size' => 15,
  618. '#required' => TRUE,
  619. );
  620. $form['pass'] = array('#type' => 'password',
  621. '#title' => t('Password'),
  622. '#maxlength' => 60,
  623. '#size' => 15,
  624. '#required' => TRUE,
  625. );
  626. $form['submit'] = array('#type' => 'submit',
  627. '#value' => t('Log in'),
  628. );
  629. $items = array();
  630. if (variable_get('user_register', 1)) {
  631. $items[] = l(t('Create new account'), 'user/register', array('attributes' => array('title' => t('Create a new user account.'))));
  632. }
  633. $items[] = l(t('Request new password'), 'user/password', array('attributes' => array('title' => t('Request new password via e-mail.'))));
  634. $form['links'] = array('#value' => theme('item_list', $items));
  635. return $form;
  636. }
  637. /**
  638. * Implementation of hook_block().
  639. */
  640. function user_block($op = 'list', $delta = 0, $edit = array()) {
  641. global $user;
  642. if ($op == 'list') {
  643. $blocks[0]['info'] = t('User login');
  644. // Not worth caching.
  645. $blocks[0]['cache'] = BLOCK_NO_CACHE;
  646. $blocks[1]['info'] = t('Navigation');
  647. // Menu blocks can't be cached because each menu item can have
  648. // a custom access callback. menu.inc manages its own caching.
  649. $blocks[1]['cache'] = BLOCK_NO_CACHE;
  650. $blocks[2]['info'] = t('Who\'s new');
  651. // Too dynamic to cache.
  652. $blocks[3]['info'] = t('Who\'s online');
  653. $blocks[3]['cache'] = BLOCK_NO_CACHE;
  654. return $blocks;
  655. }
  656. else if ($op == 'configure' && $delta == 2) {
  657. $form['user_block_whois_new_count'] = array(
  658. '#type' => 'select',
  659. '#title' => t('Number of users to display'),
  660. '#default_value' => variable_get('user_block_whois_new_count', 5),
  661. '#options' => drupal_map_assoc(array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)),
  662. );
  663. return $form;
  664. }
  665. else if ($op == 'configure' && $delta == 3) {
  666. $period = drupal_map_assoc(array(30, 60, 120, 180, 300, 600, 900, 1800, 2700, 3600, 5400, 7200, 10800, 21600, 43200, 86400), 'format_interval');
  667. $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.'));
  668. $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.'));
  669. return $form;
  670. }
  671. else if ($op == 'save' && $delta == 2) {
  672. variable_set('user_block_whois_new_count', $edit['user_block_whois_new_count']);
  673. }
  674. else if ($op == 'save' && $delta == 3) {
  675. variable_set('user_block_seconds_online', $edit['user_block_seconds_online']);
  676. variable_set('user_block_max_list_count', $edit['user_block_max_list_count']);
  677. }
  678. else if ($op == 'view') {
  679. $block = array();
  680. switch ($delta) {
  681. case 0:
  682. // For usability's sake, avoid showing two login forms on one page.
  683. if (!$user->uid && !(arg(0) == 'user' && !is_numeric(arg(1)))) {
  684. $block['subject'] = t('User login');
  685. $block['content'] = drupal_get_form('user_login_block');
  686. }
  687. return $block;
  688. case 1:
  689. if ($menu = menu_tree()) {
  690. $block['subject'] = $user->uid ? check_plain($user->name) : t('Navigation');
  691. $block['content'] = $menu;
  692. }
  693. return $block;
  694. case 2:
  695. if (user_access('access content')) {
  696. // Retrieve a list of new users who have subsequently accessed the site successfully.
  697. $result = 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));
  698. while ($account = db_fetch_object($result)) {
  699. $items[] = $account;
  700. }
  701. $output = theme('user_list', $items);
  702. $block['subject'] = t('Who\'s new');
  703. $block['content'] = $output;
  704. }
  705. return $block;
  706. case 3:
  707. if (user_access('access content')) {
  708. // Count users active within the defined period.
  709. $interval = time() - variable_get('user_block_seconds_online', 900);
  710. // Perform database queries to gather online user lists. We use s.timestamp
  711. // rather than u.access because it is much faster.
  712. $anonymous_count = sess_count($interval);
  713. $authenticated_count = db_result(db_query('SELECT COUNT(DISTINCT s.uid) FROM {sessions} s WHERE s.timestamp >= %d AND s.uid > 0', $interval));
  714. // Format the output with proper grammar.
  715. if ($anonymous_count == 1 && $authenticated_count == 1) {
  716. $output = t('There is currently %members and %visitors online.', array('%members' => format_plural($authenticated_count, '1 user', '@count users'), '%visitors' => format_plural($anonymous_count, '1 guest', '@count guests')));
  717. }
  718. else {
  719. $output = t('There are currently %members and %visitors online.', array('%members' => format_plural($authenticated_count, '1 user', '@count users'), '%visitors' => format_plural($anonymous_count, '1 guest', '@count guests')));
  720. }
  721. // Display a list of currently online users.
  722. $max_users = variable_get('user_block_max_list_count', 10);
  723. if ($authenticated_count && $max_users) {
  724. $authenticated_users = db_query_range('SELECT u.uid, u.name, MAX(s.timestamp) AS timestamp FROM {users} u INNER JOIN {sessions} s ON u.uid = s.uid WHERE s.timestamp >= %d AND s.uid > 0 GROUP BY u.uid, u.name ORDER BY s.timestamp DESC', $interval, 0, $max_users);
  725. while ($account = db_fetch_object($authenticated_users)) {
  726. $items[] = $account;
  727. }
  728. $output .= theme('user_list', $items, t('Online users'));
  729. }
  730. $block['subject'] = t('Who\'s online');
  731. $block['content'] = $output;
  732. }
  733. return $block;
  734. }
  735. }
  736. }
  737. /**
  738. * Process variables for user-picture.tpl.php.
  739. *
  740. * The $variables array contains the following arguments:
  741. * - $account
  742. *
  743. * @see user-picture.tpl.php
  744. */
  745. function template_preprocess_user_picture(&$variables) {
  746. $variables['picture'] = '';
  747. if (variable_get('user_pictures', 0)) {
  748. $account = $variables['account'];
  749. if (!empty($account->picture) && file_exists($account->picture)) {
  750. $picture = file_create_url($account->picture);
  751. }
  752. else if (variable_get('user_picture_default', '')) {
  753. $picture = variable_get('user_picture_default', '');
  754. }
  755. if (isset($picture)) {
  756. $alt = t("@user's picture", array('@user' => $account->name ? $account->name : variable_get('anonymous', t('Anonymous'))));
  757. $variables['picture'] = theme('image', $picture, $alt, $alt, '', FALSE);
  758. if (!empty($account->uid) && user_access('access user profiles')) {
  759. $attributes = array('attributes' => array('title' => t('View user profile.')), 'html' => TRUE);
  760. $variables['picture'] = l($variables['picture'], "user/$account->uid", $attributes);
  761. }
  762. }
  763. }
  764. }
  765. /**
  766. * Make a list of users.
  767. *
  768. * @param $users
  769. * An array with user objects. Should contain at least the name and uid.
  770. * @param $title
  771. * (optional) Title to pass on to theme_item_list().
  772. *
  773. * @ingroup themeable
  774. */
  775. function theme_user_list($users, $title = NULL) {
  776. if (!empty($users)) {
  777. foreach ($users as $user) {
  778. $items[] = theme('username', $user);
  779. }
  780. }
  781. return theme('item_list', $items, $title);
  782. }
  783. function user_is_anonymous() {
  784. // Menu administrators can see items for anonymous when administering.
  785. return !$GLOBALS['user']->uid || !empty($GLOBALS['menu_admin']);
  786. }
  787. function user_is_logged_in() {
  788. return (bool)$GLOBALS['user']->uid;
  789. }
  790. function user_register_access() {
  791. return user_is_anonymous() && variable_get('user_register', 1);
  792. }
  793. function user_view_access($account) {
  794. return $account && $account->uid &&
  795. (
  796. // Always let users view their own profile.
  797. ($GLOBALS['user']->uid == $account->uid) ||
  798. // Administrators can view all accounts.
  799. user_access('administer users') ||
  800. // The user is not blocked and logged in at least once.
  801. ($account->access && $account->status && user_access('access user profiles'))
  802. );
  803. }
  804. /**
  805. * Access callback for user account editing.
  806. */
  807. function user_edit_access($account) {
  808. return (($GLOBALS['user']->uid == $account->uid) || user_access('administer users')) && $account->uid > 0;
  809. }
  810. function user_load_self($arg) {
  811. $arg[1] = user_load($GLOBALS['user']->uid);
  812. return $arg;
  813. }
  814. /**
  815. * Implementation of hook_menu().
  816. */
  817. function user_menu() {
  818. $items['user/autocomplete'] = array(
  819. 'title' => 'User autocomplete',
  820. 'page callback' => 'user_autocomplete',
  821. 'access callback' => 'user_access',
  822. 'access arguments' => array('access user profiles'),
  823. 'type' => MENU_CALLBACK,
  824. 'file' => 'user.pages.inc',
  825. );
  826. // Registration and login pages.
  827. $items['user'] = array(
  828. 'title' => 'User account',
  829. 'page callback' => 'user_page',
  830. 'access callback' => TRUE,
  831. 'type' => MENU_CALLBACK,
  832. 'file' => 'user.pages.inc',
  833. );
  834. $items['user/login'] = array(
  835. 'title' => 'Log in',
  836. 'access callback' => 'user_is_anonymous',
  837. 'type' => MENU_DEFAULT_LOCAL_TASK,
  838. );
  839. $items['user/register'] = array(
  840. 'title' => 'Create new account',
  841. 'page callback' => 'drupal_get_form',
  842. 'page arguments' => array('user_register'),
  843. 'access callback' => 'user_register_access',
  844. 'type' => MENU_LOCAL_TASK,
  845. 'file' => 'user.pages.inc',
  846. );
  847. $items['user/password'] = array(
  848. 'title' => 'Request new password',
  849. 'page callback' => 'drupal_get_form',
  850. 'page arguments' => array('user_pass'),
  851. 'access callback' => 'user_is_anonymous',
  852. 'type' => MENU_LOCAL_TASK,
  853. 'file' => 'user.pages.inc',
  854. );
  855. $items['user/reset/%/%/%'] = array(
  856. 'title' => 'Reset password',
  857. 'page callback' => 'drupal_get_form',
  858. 'page arguments' => array('user_pass_reset', 2, 3, 4),
  859. 'access callback' => TRUE,
  860. 'type' => MENU_CALLBACK,
  861. 'file' => 'user.pages.inc',
  862. );
  863. // Admin user pages.
  864. $items['admin/user'] = array(
  865. 'title' => 'User management',
  866. 'description' => "Manage your site's users, groups and access to site features.",
  867. 'position' => 'left',
  868. 'page callback' => 'system_admin_menu_block_page',
  869. 'access arguments' => array('access administration pages'),
  870. 'file' => 'system.admin.inc',
  871. 'file path' => drupal_get_path('module', 'system'),
  872. );
  873. $items['admin/user/user'] = array(
  874. 'title' => 'Users',
  875. 'description' => 'List, add, and edit users.',
  876. 'page callback' => 'user_admin',
  877. 'page arguments' => array('list'),
  878. 'access arguments' => array('administer users'),
  879. 'file' => 'user.admin.inc',
  880. );
  881. $items['admin/user/user/list'] = array(
  882. 'title' => 'List',
  883. 'type' => MENU_DEFAULT_LOCAL_TASK,
  884. 'weight' => -10,
  885. );
  886. $items['admin/user/user/create'] = array(
  887. 'title' => 'Add user',
  888. 'page arguments' => array('create'),
  889. 'access arguments' => array('administer users'),
  890. 'type' => MENU_LOCAL_TASK,
  891. 'file' => 'user.admin.inc',
  892. );
  893. $items['admin/user/settings'] = array(
  894. 'title' => 'User settings',
  895. 'description' => 'Configure default behavior of users, including registration requirements, e-mails, and user pictures.',
  896. 'page callback' => 'drupal_get_form',
  897. 'page arguments' => array('user_admin_settings'),
  898. 'access arguments' => array('administer users'),
  899. 'file' => 'user.admin.inc',
  900. );
  901. // Admin access pages.
  902. $items['admin/user/permissions'] = array(
  903. 'title' => 'Permissions',
  904. 'description' => 'Determine access to features by selecting permissions for roles.',
  905. 'page callback' => 'drupal_get_form',
  906. 'page arguments' => array('user_admin_perm'),
  907. 'access arguments' => array('administer permissions'),
  908. 'file' => 'user.admin.inc',
  909. );
  910. $items['admin/user/roles'] = array(
  911. 'title' => 'Roles',
  912. 'description' => 'List, edit, or add user roles.',
  913. 'page callback' => 'drupal_get_form',
  914. 'page arguments' => array('user_admin_new_role'),
  915. 'access arguments' => array('administer permissions'),
  916. 'file' => 'user.admin.inc',
  917. );
  918. $items['admin/user/roles/edit'] = array(
  919. 'title' => 'Edit role',
  920. 'page arguments' => array('user_admin_role'),
  921. 'access arguments' => array('administer permissions'),
  922. 'type' => MENU_CALLBACK,
  923. 'file' => 'user.admin.inc',
  924. );
  925. $items['admin/user/rules'] = array(
  926. 'title' => 'Access rules',
  927. 'description' => 'List and create rules to disallow usernames, e-mail addresses, and IP addresses.',
  928. 'page callback' => 'user_admin_access',
  929. 'access arguments' => array('administer permissions'),
  930. 'file' => 'user.admin.inc',
  931. );
  932. $items['admin/user/rules/list'] = array(
  933. 'title' => 'List',
  934. 'type' => MENU_DEFAULT_LOCAL_TASK,
  935. 'weight' => -10,
  936. );
  937. $items['admin/user/rules/add'] = array(
  938. 'title' => 'Add rule',
  939. 'page callback' => 'user_admin_access_add',
  940. 'access arguments' => array('administer permissions'),
  941. 'type' => MENU_LOCAL_TASK,
  942. 'file' => 'user.admin.inc',
  943. );
  944. $items['admin/user/rules/check'] = array(
  945. 'title' => 'Check rules',
  946. 'page callback' => 'user_admin_access_check',
  947. 'access arguments' => array('administer permissions'),
  948. 'type' => MENU_LOCAL_TASK,
  949. 'file' => 'user.admin.inc',
  950. );
  951. $items['admin/user/rules/edit'] = array(
  952. 'title' => 'Edit rule',
  953. 'page callback' => 'user_admin_access_edit',
  954. 'access arguments' => array('administer permissions'),
  955. 'type' => MENU_CALLBACK,
  956. 'file' => 'user.admin.inc',
  957. );
  958. $items['admin/user/rules/delete'] = array(
  959. 'title' => 'Delete rule',
  960. 'page callback' => 'drupal_get_form',
  961. 'page arguments' => array('user_admin_access_delete_confirm'),
  962. 'access arguments' => array('administer permissions'),
  963. 'type' => MENU_CALLBACK,
  964. 'file' => 'user.admin.inc',
  965. );
  966. $items['logout'] = array(
  967. 'title' => 'Log out',
  968. 'access callback' => 'user_is_logged_in',
  969. 'page callback' => 'user_logout',
  970. 'weight' => 10,
  971. 'file' => 'user.pages.inc',
  972. );
  973. $items['user/%user_uid_optional'] = array(
  974. 'title' => 'My account',
  975. 'title callback' => 'user_page_title',
  976. 'title arguments' => array(1),
  977. 'page callback' => 'user_view',
  978. 'page arguments' => array(1),
  979. 'access callback' => 'user_view_access',
  980. 'access arguments' => array(1),
  981. 'parent' => '',
  982. 'file' => 'user.pages.inc',
  983. );
  984. $items['user/%user/view'] = array(
  985. 'title' => 'View',
  986. 'type' => MENU_DEFAULT_LOCAL_TASK,
  987. 'weight' => -10,
  988. );
  989. $items['user/%user/delete'] = array(
  990. 'title' => 'Delete',
  991. 'page callback' => 'drupal_get_form',
  992. 'page arguments' => array('user_confirm_delete', 1),
  993. 'access callback' => 'user_delete_access',
  994. 'access arguments' => array(1),
  995. 'type' => MENU_CALLBACK,
  996. 'file' => 'user.pages.inc',
  997. );
  998. $items['user/%user_category/edit'] = array(
  999. 'title' => 'Edit',
  1000. 'page callback' => 'user_edit',
  1001. 'page arguments' => array(1),
  1002. 'access callback' => 'user_edit_access',
  1003. 'access arguments' => array(1),
  1004. 'type' => MENU_LOCAL_TASK,
  1005. 'load arguments' => array('%map', '%index'),
  1006. 'file' => 'user.pages.inc',
  1007. );
  1008. $items['user/%user_category/edit/account'] = array(
  1009. 'title' => 'Account',
  1010. 'type' => MENU_DEFAULT_LOCAL_TASK,
  1011. 'load arguments' => array('%map', '%index'),
  1012. );
  1013. $empty_account = new stdClass();
  1014. if (($categories = _user_categories($empty_account)) && (count($categories) > 1)) {
  1015. foreach ($categories as $key => $category) {
  1016. // 'account' is already handled by the MENU_DEFAULT_LOCAL_TASK.
  1017. if ($category['name'] != 'account') {
  1018. $items['user/%user_category/edit/'. $category['name']] = array(
  1019. 'title callback' => 'check_plain',
  1020. 'title arguments' => array($category['title']),
  1021. 'page callback' => 'user_edit',
  1022. 'page arguments' => array(1, 3),
  1023. 'access callback' => isset($category['access callback']) ? $category['access callback'] : 'user_edit_access',
  1024. 'access arguments' => isset($category['access arguments']) ? $category['access arguments'] : array(1),
  1025. 'type' => MENU_LOCAL_TASK,
  1026. 'weight' => $category['weight'],
  1027. 'load arguments' => array('%map', '%index'),
  1028. 'tab_parent' => 'user/%/edit',
  1029. 'file' => 'user.pages.inc',
  1030. );
  1031. }
  1032. }
  1033. }
  1034. return $items;
  1035. }
  1036. /**
  1037. * Implementation of hook_init().
  1038. */
  1039. function user_init() {
  1040. drupal_add_css(drupal_get_path('module', 'user') .'/user.css', 'module');
  1041. }
  1042. /**
  1043. * Load either a specified or the current user account.
  1044. *
  1045. * @param $uid
  1046. * An optional user ID of the user to load. If not provided, the current
  1047. * user's ID will be used.
  1048. * @return
  1049. * A fully-loaded $user object upon successful user load, FALSE if user
  1050. * cannot be loaded.
  1051. *
  1052. * @see user_load()
  1053. */
  1054. function user_uid_optional_load($uid = NULL) {
  1055. if (!isset($uid)) {
  1056. $uid = $GLOBALS['user']->uid;
  1057. }
  1058. return user_load($uid);
  1059. }
  1060. /**
  1061. * Return a user object after checking if any profile category in the path exists.
  1062. */
  1063. function user_category_load($uid, &$map, $index) {
  1064. static $user_categories, $accounts;
  1065. // Cache $account - this load function will get called for each profile tab.
  1066. if (!isset($accounts[$uid])) {
  1067. $accounts[$uid] = user_load($uid);
  1068. }
  1069. $valid = TRUE;
  1070. if (($account = $accounts[$uid]) && isset($map[$index + 1]) && $map[$index + 1] == 'edit') {
  1071. // Since the path is like user/%/edit/category_name, the category name will
  1072. // be at a position 2 beyond the index corresponding to the % wildcard.
  1073. $category_index = $index + 2;
  1074. // Valid categories may contain slashes, and hence need to be imploded.
  1075. $category_path = implode('/', array_slice($map, $category_index));
  1076. if ($category_path) {
  1077. // Check that the requested category exists.
  1078. $valid = FALSE;
  1079. if (!isset($user_categories)) {
  1080. $empty_account = new stdClass();
  1081. $user_categories = _user_categories($empty_account);
  1082. }
  1083. foreach ($user_categories as $category) {
  1084. if ($category['name'] == $category_path) {
  1085. $valid = TRUE;
  1086. // Truncate the map array in case the category name had slashes.
  1087. $map = array_slice($map, 0, $category_index);
  1088. // Assign the imploded category name to the last map element.
  1089. $map[$category_index] = $category_path;
  1090. break;
  1091. }
  1092. }
  1093. }
  1094. }
  1095. return $valid ? $account : FALSE;
  1096. }
  1097. /**
  1098. * Returns the user id of the currently logged in user.
  1099. */
  1100. function user_uid_optional_to_arg($arg) {
  1101. // Give back the current user uid when called from eg. tracker, aka.
  1102. // with an empty arg. Also use the current user uid when called from
  1103. // the menu with a % for the current account link.
  1104. return empty($arg) || $arg == '%' ? $GLOBALS['user']->uid : $arg;
  1105. }
  1106. /**
  1107. * Menu item title callback - use the user name if it's not the current user.
  1108. */
  1109. function user_page_title($account) {
  1110. if ($account->uid == $GLOBALS['user']->uid) {
  1111. return t('My account');
  1112. }
  1113. return $account->name;
  1114. }
  1115. /**
  1116. * Discover which external authentication module(s) authenticated a username.
  1117. *
  1118. * @param $authname
  1119. * A username used by an external authentication module.
  1120. * @return
  1121. * An associative array with module as key and username as value.
  1122. */
  1123. function user_get_authmaps($authname = NULL) {
  1124. $result = db_query("SELECT authname, module FROM {authmap} WHERE authname = '%s'", $authname);
  1125. $authmaps = array();
  1126. $has_rows = FALSE;
  1127. while ($authmap = db_fetch_object($result)) {
  1128. $authmaps[$authmap->module] = $authmap->authname;
  1129. $has_rows = TRUE;
  1130. }
  1131. return $has_rows ? $authmaps : 0;
  1132. }
  1133. /**
  1134. * Save mappings of which external authentication module(s) authenticated
  1135. * a user. Maps external usernames to user ids in the users table.
  1136. *
  1137. * @param $account
  1138. * A user object.
  1139. * @param $authmaps
  1140. * An associative array with a compound key and the username as the value.
  1141. * The key is made up of 'authname_' plus the name of the external authentication
  1142. * module.
  1143. * @see user_external_login_register()
  1144. */
  1145. function user_set_authmaps($account, $authmaps) {
  1146. foreach ($authmaps as $key => $value) {
  1147. $module = explode('_', $key, 2);
  1148. if ($value) {
  1149. db_query("UPDATE {authmap} SET authname = '%s' WHERE uid = %d AND module = '%s'", $value, $account->uid, $module[1]);
  1150. if (!db_affected_rows()) {
  1151. @db_query("INSERT INTO {authmap} (authname, uid, module) VALUES ('%s', %d, '%s')", $value, $account->uid, $module[1]);
  1152. }
  1153. }
  1154. else {
  1155. db_query("DELETE FROM {authmap} WHERE uid = %d AND module = '%s'", $account->uid, $module[1]);
  1156. }
  1157. }
  1158. }
  1159. /**
  1160. * Form builder; the main user login form.
  1161. *
  1162. * @ingroup forms
  1163. */
  1164. function user_login(&$form_state) {
  1165. global $user;
  1166. // If we are already logged on, go to the user page instead.
  1167. if ($user->uid) {
  1168. drupal_goto('user/'. $user->uid);
  1169. }
  1170. // Display login form:
  1171. $form['name'] = array('#type' => 'textfield',
  1172. '#title' => t('Username'),
  1173. '#size' => 60,
  1174. '#maxlength' => USERNAME_MAX_LENGTH,
  1175. '#required' => TRUE,
  1176. );
  1177. $form['name']['#description'] = t('Enter your @s username.', array('@s' => variable_get('site_name', 'Drupal')));
  1178. $form['pass'] = array('#type' => 'password',
  1179. '#title' => t('Password'),
  1180. '#description' => t('Enter the password that accompanies your username.'),
  1181. '#required' => TRUE,
  1182. );
  1183. $form['#validate'] = user_login_default_validators();
  1184. $form['submit'] = array('#type' => 'submit', '#value' => t('Log in'), '#weight' => 2);
  1185. return $form;
  1186. }
  1187. /**
  1188. * Set up a series for validators which check for blocked/denied users,
  1189. * then authenticate against local database, then return an error if
  1190. * authentication fails. Distributed authentication modules are welcome
  1191. * to use hook_form_alter() to change this series in order to
  1192. * authenticate against their user database instead of the local users
  1193. * table.
  1194. *
  1195. * We use three validators instead of one since external authentication
  1196. * modules usually only need to alter the second validator.
  1197. *
  1198. * @see user_login_name_validate()
  1199. * @see user_login_authenticate_validate()
  1200. * @see user_login_final_validate()
  1201. * @return array
  1202. * A simple list of validate functions.
  1203. */
  1204. function user_login_default_validators() {
  1205. return array('user_login_name_validate', 'user_login_authenticate_validate', 'user_login_final_validate');
  1206. }
  1207. /**
  1208. * A FAPI validate handler. Sets an error if supplied username has been blocked
  1209. * or denied access.
  1210. */
  1211. function user_login_name_validate($form, &$form_state) {
  1212. if (isset($form_state['values']['name'])) {
  1213. if (user_is_blocked($form_state['values']['name'])) {
  1214. // blocked in user administration
  1215. form_set_error('name', t('The username %name has not been activated or is blocked.', array('%name' => $form_state['values']['name'])));
  1216. }
  1217. else if (drupal_is_denied('user', $form_state['values']['name'])) {
  1218. // denied by access controls
  1219. form_set_error('name', t('The name %name is a reserved username.', array('%name' => $form_state['values']['name'])));
  1220. }
  1221. }
  1222. }
  1223. /**
  1224. * A validate handler on the login form. Check supplied username/password
  1225. * against local users table. If successful, sets the global $user object.
  1226. */
  1227. function user_login_authenticate_validate($form, &$form_state) {
  1228. user_authenticate($form_state['values']);
  1229. }
  1230. /**
  1231. * A validate handler on the login form. Should be the last validator. Sets an
  1232. * error if user has not been authenticated yet.
  1233. */
  1234. function user_login_final_validate($form, &$form_state) {
  1235. global $user;
  1236. if (!$user->uid) {
  1237. form_set_error('name', t('Sorry, unrecognized username or password. <a href="@password">Have you forgotten your password?</a>', array('@password' => url('user/password'))));
  1238. }
  1239. }
  1240. /**
  1241. * Try to log in the user locally.
  1242. *
  1243. * @param $form_values
  1244. * Form values with at least 'name' and 'pass' keys, as well as anything else
  1245. * which should be passed along to hook_user op 'login'.
  1246. *
  1247. * @return
  1248. * A $user object, if successful.
  1249. */
  1250. function user_authenticate($form_values = array()) {
  1251. global $user;
  1252. // Load the account to check if the e-mail is denied by an access rule.
  1253. // Doing this check here saves us a user_load() in user_login_name_validate()
  1254. // and introduces less code change for a security fix.
  1255. $account = user_load(array('name' => $form_values['name'], 'pass' => trim($form_values['pass']), 'status' => 1));
  1256. if ($account && drupal_is_denied('mail', $account->mail)) {
  1257. form_set_error('name', t('The name %name is registered using a reserved e-mail address and therefore could not be logged in.', array('%name' => $account->name)));
  1258. }
  1259. // Name and pass keys are required.
  1260. // The user is about to be logged in, so make sure no error was previously
  1261. // encountered in the validation process.
  1262. if (!form_get_errors() && !empty($form_values['name']) && !empty($form_values['pass']) && $account) {
  1263. $user = $account;
  1264. user_authenticate_finalize($form_values);
  1265. return $user;
  1266. }
  1267. else {
  1268. watchdog('user', 'Login attempt failed for %user.', array('%user' => $form_values['name']));
  1269. }
  1270. }
  1271. /**
  1272. * Finalize the login process. Must be called when logging in a user.
  1273. *
  1274. * The function records a watchdog message about the new session, saves the
  1275. * login timestamp, calls hook_user op 'login' and generates a new session.
  1276. *
  1277. * $param $edit
  1278. * This array is passed to hook_user op login.
  1279. */
  1280. function user_authenticate_finalize(&$edit) {
  1281. global $user;
  1282. watchdog('user', 'Session opened for %name.', array('%name' => $user->name));
  1283. // Update the user table timestamp noting user has logged in.
  1284. // This is also used to invalidate one-time login links.
  1285. $user->login = time();
  1286. db_query("UPDATE {users} SET login = %d WHERE uid = %d", $user->login, $user->uid);
  1287. // Regenerate the session ID to prevent against session fixation attacks.
  1288. sess_regenerate();
  1289. user_module_invoke('login', $edit, $user);
  1290. }
  1291. /**
  1292. * Submit handler for the login form. Redirects the user to a page.
  1293. *
  1294. * The user is redirected to the My Account page. Setting the destination in
  1295. * the query string (as done by the user login block) overrides the redirect.
  1296. */
  1297. function user_login_submit($form, &$form_state) {
  1298. global $user;
  1299. if ($user->uid) {
  1300. $form_state['redirect'] = 'user/'. $user->uid;
  1301. return;
  1302. }
  1303. }
  1304. /**
  1305. * Helper function for authentication modules. Either login in or registers
  1306. * the current user, based on username. Either way, the global $user object is
  1307. * populated based on $name.
  1308. */
  1309. function user_external_login_register($name, $module) {
  1310. global $user;
  1311. $existing_user = user_load(array('name' => $name));
  1312. if (isset($existing_user->uid)) {
  1313. $user = $existing_user;
  1314. }
  1315. else {
  1316. // Register this new user.
  1317. $userinfo = array(
  1318. 'name' => $name,
  1319. 'pass' => user_password(),
  1320. 'init' => $name,
  1321. 'status' => 1,
  1322. "authname_$module" => $name,
  1323. 'access' => time()
  1324. );
  1325. $account = user_save('', $userinfo);
  1326. // Terminate if an error occured during user_save().
  1327. if (!$account) {
  1328. drupal_set_message(t("Error saving user account."), 'error');
  1329. return;
  1330. }
  1331. $user = $account;
  1332. watchdog('user', 'New external user: %name using module %module.', array('%name' => $name, '%module' => $module), WATCHDOG_NOTICE, l(t('edit'), 'user/'. $user->uid .'/edit'));
  1333. }
  1334. }
  1335. /**
  1336. * Generates a unique URL for a user to login and reset their password.
  1337. *
  1338. * @param object $account
  1339. * An object containing the user account.
  1340. *
  1341. * @return
  1342. * A unique URL that provides a one-time log in for the user, from which
  1343. * they can change their password.
  1344. */
  1345. function user_pass_reset_url($account) {
  1346. $timestamp = time();
  1347. return url("user/reset/$account->uid/$timestamp/". user_pass_rehash($account->pass, $timestamp, $account->login), array('absolute' => TRUE));
  1348. }
  1349. function user_pass_rehash($password, $timestamp, $login) {
  1350. return md5($timestamp . $password . $login);
  1351. }
  1352. function user_edit_form(&$form_state, $uid, $edit, $register = FALSE) {
  1353. _user_password_dynamic_validation();
  1354. $admin = user_access('administer users');
  1355. // Account information:
  1356. $form['account'] = array('#type' => 'fieldset',
  1357. '#title' => t('Account information'),
  1358. '#weight' => -10,
  1359. );
  1360. // Only show name field when: registration page; or user is editing own account and can change username; or an admin user.
  1361. if ($register || ($GLOBALS['user']->uid == $uid && user_access('change own username')) || $admin) {
  1362. $form['account']['name'] = array('#type' => 'textfield',
  1363. '#title' => t('Username'),
  1364. '#default_value' => $edit['name'],
  1365. '#maxlength' => USERNAME_MAX_LENGTH,
  1366. '#description' => t('Spaces are allowed; punctuation is not allowed except for periods, hyphens, and underscores.'),
  1367. '#required' => TRUE,
  1368. );
  1369. }
  1370. $form['account']['mail'] = array('#type' => 'textfield',
  1371. '#title' => t('E-mail address'),
  1372. '#default_value' => $edit['mail'],
  1373. '#maxlength' => EMAIL_MAX_LENGTH,
  1374. '#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.'),
  1375. '#required' => TRUE,
  1376. );
  1377. if (!$register) {
  1378. $form['account']['pass'] = array('#type' => 'password_confirm',
  1379. '#description' => t('To change the current user password, enter the new password in both fields.'),
  1380. '#size' => 25,
  1381. );
  1382. }
  1383. elseif (!variable_get('user_email_verification', TRUE) || $admin) {
  1384. $form['account']['pass'] = array(
  1385. '#type' => 'password_confirm',
  1386. '#description' => t('Provide a password for the new account in both fields.'),
  1387. '#required' => TRUE,
  1388. '#size' => 25,
  1389. );
  1390. }
  1391. if ($admin) {
  1392. $form['account']['status'] = array(
  1393. '#type' => 'radios',
  1394. '#title' => t('Status'),
  1395. '#default_value' => isset($edit['status']) ? $edit['status'] : 1,
  1396. '#options' => array(t('Blocked'), t('Active'))
  1397. );
  1398. }
  1399. if (user_access('administer permissions')) {
  1400. $roles = user_roles(TRUE);
  1401. // The disabled checkbox subelement for the 'authenticated user' role
  1402. // must be generated separately and added to the checkboxes element,
  1403. // because of a limitation in D6 FormAPI not supporting a single disabled
  1404. // checkbox within a set of checkboxes.
  1405. // TODO: This should be solved more elegantly. See issue #119038.
  1406. $checkbox_authenticated = array(
  1407. '#type' => 'checkbox',
  1408. '#title' => $roles[DRUPAL_AUTHENTICATED_RID],
  1409. '#default_value' => TRUE,
  1410. '#disabled' => TRUE,
  1411. );
  1412. unset($roles[DRUPAL_AUTHENTICATED_RID]);
  1413. if ($roles) {
  1414. $default = empty($edit['roles']) ? array() : array_keys($edit['roles']);
  1415. $form['account']['roles'] = array(
  1416. '#type' => 'checkboxes',
  1417. '#title' => t('Roles'),
  1418. '#default_value' => $default,
  1419. '#options' => $roles,
  1420. DRUPAL_AUTHENTICATED_RID => $checkbox_authenticated,
  1421. );
  1422. }
  1423. }
  1424. // Signature:
  1425. if (variable_get('user_signatures', 0) && module_exists('comment') && !$register) {
  1426. $form['signature_settings'] = array(
  1427. '#type' => 'fieldset',
  1428. '#title' => t('Signature settings'),
  1429. '#weight' => 1,
  1430. );
  1431. $form['signature_settings']['signature'] = array(
  1432. '#type' => 'textarea',
  1433. '#title' => t('Signature'),
  1434. '#default_value' => $edit['signature'],
  1435. '#description' => t('Your signature will be publicly displayed at the end of your comments.'),
  1436. );
  1437. // Prevent a "validation error" message when the user attempts to save with a default value they
  1438. // do not have access to.
  1439. if (!filter_access($edit['signature_format']) && empty($_POST)) {
  1440. drupal_set_message(t("The signature input format has been set to a format you don't have access to. It will be changed to a format you have access to when you save this page."));
  1441. $edit['signature_format'] = FILTER_FORMAT_DEFAULT;
  1442. }
  1443. $form['signature_settings']['signature_format'] = filter_form($edit['signature_format'], NULL, array('signature_format'));
  1444. }
  1445. // Picture/avatar:
  1446. if (variable_get('user_pictures', 0) && !$register) {
  1447. $form['picture'] = array('#type' => 'fieldset', '#title' => t('Picture'), '#weight' => 1);
  1448. $picture = theme('user_picture', (object)$edit);
  1449. if ($edit['picture']) {
  1450. $form['picture']['current_picture'] = array('#value' => $picture);
  1451. $form['picture']['picture_delete'] = array('#type' => 'checkbox', '#title' => t('Delete picture'), '#description' => t('Check this box to delete your current picture.'));
  1452. }
  1453. else {
  1454. $form['picture']['picture_delete'] = array('#type' => 'hidden');
  1455. }
  1456. $form['picture']['picture_upload'] = array('#type' => 'file', '#title' => t('Upload picture'), '#size' => 48, '#description' => t('Your virtual face or picture. Maximum dimensions are %dimensions and the maximum size is %size kB.', array('%dimensions' => variable_get('user_picture_dimensions', '85x85'), '%size' => variable_get('user_picture_file_size', '30'))) .' '. variable_get('user_picture_guidelines', ''));
  1457. $form['#validate'][] = 'user_profile_form_validate';
  1458. $form['#validate'][] = 'user_validate_picture';
  1459. }
  1460. $form['#uid'] = $uid;
  1461. return $form;
  1462. }
  1463. function _user_edit_validate($uid, &$edit) {
  1464. // Validate the username when: new user account; or user is editing own account and can change username; or an admin user.
  1465. if (!$uid || ($GLOBALS['user']->uid == $uid && user_access('change own username')) || user_access('administer users')) {
  1466. if ($error = user_validate_name($edit['name'])) {
  1467. form_set_error('name', $error);
  1468. }
  1469. else if (db_result(db_query("SELECT COUNT(*) FROM {users} WHERE uid != %d AND LOWER(name) = LOWER('%s')", $uid, $edit['name'])) > 0) {
  1470. form_set_error('name', t('The name %name is already taken.', array('%name' => $edit['name'])));
  1471. }
  1472. else if (drupal_is_denied('user', $edit['name'])) {
  1473. form_set_error('name', t('The name %name has been denied access.', array('%name' => $edit['name'])));
  1474. }
  1475. }
  1476. // Validate the e-mail address:
  1477. if ($error = user_validate_mail($edit['mail'])) {
  1478. form_set_error('mail', $error);
  1479. }
  1480. else if (db_result(db_query("SELECT COUNT(*) FROM {users} WHERE uid != %d AND LOWER(mail) = LOWER('%s')", $uid, $edit['mail'])) > 0) {
  1481. form_set_error('mail', t('The e-mail address %email is already registered. <a href="@password">Have you forgotten your password?</a>', array('%email' => $edit['mail'], '@password' => url('user/password'))));
  1482. }
  1483. else if (drupal_is_denied('mail', $edit['mail'])) {
  1484. form_set_error('mail', t('The e-mail address %email has been denied access.', array('%email' => $edit['mail'])));
  1485. }
  1486. }
  1487. function _user_edit_submit($uid, &$edit) {
  1488. $account = user_load($uid);
  1489. // Delete picture if requested, and if no replacement picture was given.
  1490. if (!empty($edit['picture_delete'])) {
  1491. if ($account->picture && file_exists($account->picture)) {
  1492. file_delete($account->picture);
  1493. }
  1494. $edit['picture'] = '';
  1495. }
  1496. if (isset($edit['roles'])) {
  1497. $edit['roles'] = array_filter($edit['roles']);
  1498. }
  1499. }
  1500. /**
  1501. * Delete a user.
  1502. *
  1503. * @param $edit An array of submitted form values.
  1504. * @param $uid The user ID of the user to delete.
  1505. */
  1506. function user_delete($edit, $uid) {
  1507. $account = user_load(array('uid' => $uid));
  1508. sess_destroy_uid($uid);
  1509. _user_mail_notify('status_deleted', $account);
  1510. db_query('DELETE FROM {users} WHERE uid = %d', $uid);
  1511. db_query('DELETE FROM {users_roles} WHERE uid = %d', $uid);
  1512. db_query('DELETE FROM {authmap} WHERE uid = %d', $uid);
  1513. $variables = array('%name' => $account->name, '%email' => '<'. $account->mail .'>');
  1514. watchdog('user', 'Deleted user: %name %email.', $variables, WATCHDOG_NOTICE);
  1515. user_module_invoke('delete', $edit, $account);
  1516. }
  1517. /**
  1518. * Builds a structured array representing the profile content.
  1519. *
  1520. * @param $account
  1521. * A user object.
  1522. *
  1523. * @return
  1524. * A structured array containing the individual elements of the profile.
  1525. */
  1526. function user_build_content(&$account) {
  1527. $edit = NULL;
  1528. user_module_invoke('view', $edit, $account);
  1529. // Allow modules to modify the fully-built profile.
  1530. drupal_alter('profile', $account);
  1531. return $account->content;
  1532. }
  1533. /**
  1534. * Implementation of hook_mail().
  1535. */
  1536. function user_mail($key, &$message, $params) {
  1537. $language = $message['language'];
  1538. $variables = user_mail_tokens($params['account'], $language);
  1539. $message['subject'] .= _user_mail_text($key .'_subject', $language, $variables);
  1540. $message['body'][] = _user_mail_text($key .'_body', $language, $variables);
  1541. }
  1542. /**
  1543. * Returns a mail string for a variable name.
  1544. *
  1545. * Used by user_mail() and the settings forms to retrieve strings.
  1546. */
  1547. function _user_mail_text($key, $language = NULL, $variables = array()) {
  1548. $langcode = isset($language) ? $language->language : NULL;
  1549. if ($admin_setting = variable_get('user_mail_'. $key, FALSE)) {
  1550. // An admin setting overrides the default string.
  1551. return strtr($admin_setting, $variables);
  1552. }
  1553. else {
  1554. // No override, return default string.
  1555. switch ($key) {
  1556. case 'register_no_approval_required_subject':
  1557. return t('Account details for !username at !site', $variables, $langcode);
  1558. case 'register_no_approval_required_body':
  1559. return t("!username,\n\nThank you for registering at !site. You may now log in to !login_uri using the following username and password:\n\nusername: !username\npassword: !password\n\nYou may also log in by clicking on this link or copying and pasting it in your browser:\n\n!login_url\n\nThis is a one-time login, so it can be used only once.\n\nAfter logging in, you will be redirected to !edit_uri so you can change your password.\n\n\n-- !site team", $variables, $langcode);
  1560. case 'register_admin_created_subject':
  1561. return t('An administrator created an account for you at !site', $variables, $langcode);
  1562. case 'register_admin_created_body':
  1563. return t("!username,\n\nA site administrator at !site has created an account for you. You may now log in to !login_uri using the following username and password:\n\nusername: !username\npassword: !password\n\nYou may also log in by clicking on this link or copying and pasting it in your browser:\n\n!login_url\n\nThis is a one-time login, so it can be used only once.\n\nAfter logging in, you will be redirected to !edit_uri so you can change your password.\n\n\n-- !site team", $variables, $langcode);
  1564. case 'register_pending_approval_subject':
  1565. case 'register_pending_approval_admin_subject':
  1566. return t('Account details for !username at !site (pending admin approval)', $variables, $langcode);
  1567. case 'register_pending_approval_body':
  1568. return t("!username,\n\nThank you for registering at !site. 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.\n\n\n-- !site team", $variables, $langcode);
  1569. case 'register_pending_approval_admin_body':
  1570. return t("!username has applied for an account.\n\n!edit_uri", $variables, $langcode);
  1571. case 'password_reset_subject':
  1572. return t('Replacement login information for !username at !site', $variables, $langcode);
  1573. case 'password_reset_body':
  1574. return t("!username,\n\nA request to reset the password for your account has been made at !site.\n\nYou may now log in to !uri_brief by clicking on this link or copying and pasting it in your browser:\n\n!login_url\n\nThis is a one-time login, so it can be used only once. It expires after one day and nothing will happen if it's not used.\n\nAfter logging in, you will be redirected to !edit_uri so you can change your password.", $variables, $langcode);
  1575. case 'status_activated_subject':
  1576. return t('Account details for !username at !site (approved)', $variables, $langcode);
  1577. case 'status_activated_body':
  1578. return t("!username,\n\nYour account at !site has been activated.\n\nYou may now log in by clicking on this link or copying and pasting it in your browser:\n\n!login_url\n\nThis is a one-time login, so it can be used only once.\n\nAfter logging in, you will be redirected to !edit_uri so you can change your password.\n\nOnce you have set your own password, you will be able to log in to !login_uri in the future using:\n\nusername: !username\n", $variables, $langcode);
  1579. case 'status_blocked_subject':
  1580. return t('Account details for !username at !site (blocked)', $variables, $langcode);
  1581. case 'status_blocked_body':
  1582. return t("!username,\n\nYour account on !site has been blocked.", $variables, $langcode);
  1583. case 'status_deleted_subject':
  1584. return t('Account details for !username at !site (deleted)', $variables, $langcode);
  1585. case 'status_deleted_body':
  1586. return t("!username,\n\nYour account on !site has been deleted.", $variables, $langcode);
  1587. }
  1588. }
  1589. }
  1590. /*** Administrative features ***********************************************/
  1591. /**
  1592. * Retrieve an array of roles matching specified conditions.
  1593. *
  1594. * @param $membersonly
  1595. * Set this to TRUE to exclude the 'anonymous' role.
  1596. * @param $permission
  1597. * A string containing a permission. If set, only roles containing that
  1598. * permission are returned.
  1599. *
  1600. * @return
  1601. * An associative array with the role id as the key and the role name as
  1602. * value.
  1603. */
  1604. function user_roles($membersonly = FALSE, $permission = NULL) {
  1605. // System roles take the first two positions.
  1606. $roles = array(
  1607. DRUPAL_ANONYMOUS_RID => NULL,
  1608. DRUPAL_AUTHENTICATED_RID => NULL,
  1609. );
  1610. if (!empty($permission)) {
  1611. $result = db_query("SELECT r.* FROM {role} r INNER JOIN {permission} p ON r.rid = p.rid WHERE p.perm LIKE '%%%s%%' ORDER BY r.name", $permission);
  1612. }
  1613. else {
  1614. $result = db_query('SELECT * FROM {role} ORDER BY name');
  1615. }
  1616. while ($role = db_fetch_object($result)) {
  1617. switch ($role->rid) {
  1618. // We only translate the built in role names
  1619. case DRUPAL_ANONYMOUS_RID:
  1620. if (!$membersonly) {
  1621. $roles[$role->rid] = t($role->name);
  1622. }
  1623. break;
  1624. case DRUPAL_AUTHENTICATED_RID:
  1625. $roles[$role->rid] = t($role->name);
  1626. break;
  1627. default:
  1628. $roles[$role->rid] = $role->name;
  1629. }
  1630. }
  1631. // Filter to remove unmatched system roles.
  1632. return array_filter($roles);
  1633. }
  1634. /**
  1635. * Implementation of hook_user_operations().
  1636. */
  1637. function user_user_operations($form_state = array()) {
  1638. $operations = array(
  1639. 'unblock' => array(
  1640. 'label' => t('Unblock the selected users'),
  1641. 'callback' => 'user_user_operations_unblock',
  1642. ),
  1643. 'block' => array(
  1644. 'label' => t('Block the selected users'),
  1645. 'callback' => 'user_user_operations_block',
  1646. ),
  1647. 'delete' => array(
  1648. 'label' => t('Delete the selected users'),
  1649. ),
  1650. );
  1651. if (user_access('administer permissions')) {
  1652. $roles = user_roles(TRUE);
  1653. unset($roles[DRUPAL_AUTHENTICATED_RID]); // Can't edit authenticated role.
  1654. $add_roles = array();
  1655. foreach ($roles as $key => $value) {
  1656. $add_roles['add_role-'. $key] = $value;
  1657. }
  1658. $remove_roles = array();
  1659. foreach ($roles as $key => $value) {
  1660. $remove_roles['remove_role-'. $key] = $value;
  1661. }
  1662. if (count($roles)) {
  1663. $role_operations = array(
  1664. t('Add a role to the selected users') => array(
  1665. 'label' => $add_roles,
  1666. ),
  1667. t('Remove a role from the selected users') => array(
  1668. 'label' => $remove_roles,
  1669. ),
  1670. );
  1671. $operations += $role_operations;
  1672. }
  1673. }
  1674. // If the form has been posted, we need to insert the proper data for
  1675. // role editing if necessary.
  1676. if (!empty($form_state['submitted'])) {
  1677. $operation_rid = explode('-', $form_state['values']['operation']);
  1678. $operation = $operation_rid[0];
  1679. if ($operation == 'add_role' || $operation == 'remove_role') {
  1680. $rid = $operation_rid[1];
  1681. if (user_access('administer permissions')) {
  1682. $operations[$form_state['values']['operation']] = array(
  1683. 'callback' => 'user_multiple_role_edit',
  1684. 'callback arguments' => array($operation, $rid),
  1685. );
  1686. }
  1687. else {
  1688. watchdog('security', 'Detected malicious attempt to alter protected user fields.', array(), WATCHDOG_WARNING);
  1689. return;
  1690. }
  1691. }
  1692. }
  1693. return $operations;
  1694. }
  1695. /**
  1696. * Callback function for admin mass unblocking users.
  1697. */
  1698. function user_user_operations_unblock($accounts) {
  1699. foreach ($accounts as $uid) {
  1700. $account = user_load(array('uid' => (int)$uid));
  1701. // Skip unblocking user if they are already unblocked.
  1702. if ($account !== FALSE && $account->status == 0) {
  1703. user_save($account, array('status' => 1));
  1704. }
  1705. }
  1706. }
  1707. /**
  1708. * Callback function for admin mass blocking users.
  1709. */
  1710. function user_user_operations_block($accounts) {
  1711. foreach ($accounts as $uid) {
  1712. $account = user_load(array('uid' => (int)$uid));
  1713. // Skip blocking user if they are already blocked.
  1714. if ($account !== FALSE && $account->status == 1) {
  1715. user_save($account, array('status' => 0));
  1716. }
  1717. }
  1718. }
  1719. /**
  1720. * Callback function for admin mass adding/deleting a user role.
  1721. */
  1722. function user_multiple_role_edit($accounts, $operation, $rid) {
  1723. // The role name is not necessary as user_save() will reload the user
  1724. // object, but some modules' hook_user() may look at this first.
  1725. $role_name = db_result(db_query('SELECT name FROM {role} WHERE rid = %d', $rid));
  1726. switch ($operation) {
  1727. case 'add_role':
  1728. foreach ($accounts as $uid) {
  1729. $account = user_load(array('uid' => (int)$uid));
  1730. // Skip adding the role to the user if they already have it.
  1731. if ($account !== FALSE && !isset($account->roles[$rid])) {
  1732. $roles = $account->roles + array($rid => $role_name);
  1733. user_save($account, array('roles' => $roles));
  1734. }
  1735. }
  1736. break;
  1737. case 'remove_role':
  1738. foreach ($accounts as $uid) {
  1739. $account = user_load(array('uid' => (int)$uid));
  1740. // Skip removing the role from the user if they already don't have it.
  1741. if ($account !== FALSE && isset($account->roles[$rid])) {
  1742. $roles = array_diff($account->roles, array($rid => $role_name));
  1743. user_save($account, array('roles' => $roles));
  1744. }
  1745. }
  1746. break;
  1747. }
  1748. }
  1749. function user_multiple_delete_confirm(&$form_state) {
  1750. $edit = $form_state['post'];
  1751. $form['accounts'] = array('#prefix' => '<ul>', '#suffix' => '</ul>', '#tree' => TRUE);
  1752. // array_filter() returns only elements with TRUE values.
  1753. foreach (array_filter($edit['accounts']) as $uid => $value) {
  1754. $user = db_result(db_query('SELECT name FROM {users} WHERE uid = %d', $uid));
  1755. $form['accounts'][$uid] = array('#type' => 'hidden', '#value' => $uid, '#prefix' => '<li>', '#suffix' => check_plain($user) ."</li>\n");
  1756. }
  1757. $form['operation'] = array('#type' => 'hidden', '#value' => 'delete');
  1758. return confirm_form($form,
  1759. t('Are you sure you want to delete these users?'),
  1760. 'admin/user/user', t('This action cannot be undone.'),
  1761. t('Delete all'), t('Cancel'));
  1762. }
  1763. function user_multiple_delete_confirm_submit($form, &$form_state) {
  1764. if ($form_state['values']['confirm']) {
  1765. foreach ($form_state['values']['accounts'] as $uid => $value) {
  1766. user_delete($form_state['values'], $uid);
  1767. }
  1768. drupal_set_message(t('The users have been deleted.'));
  1769. }
  1770. $form_state['redirect'] = 'admin/user/user';
  1771. return;
  1772. }
  1773. /**
  1774. * Implementation of hook_help().
  1775. */
  1776. function user_help($path, $arg) {
  1777. global $user;
  1778. switch ($path) {
  1779. case 'admin/help#user':
  1780. $output = '<p>'. t('The user module allows users to register, login, and log out. Users benefit from being able to sign on because it associates content they create with their account and allows various permissions to be set for their roles. The user module supports user roles which establish fine grained permissions allowing each role to do only what the administrator wants them to. Each user is assigned to one or more roles. By default there are two roles <em>anonymous</em> - a user who has not logged in, and <em>authenticated</em> a user who has signed up and who has been authorized.') .'</p>';
  1781. $output .= '<p>'. t("Users can use their own name or handle and can specify personal configuration settings through their individual <em>My account</em> page. Users must authenticate by supplying a local username and password or through their OpenID, an optional and secure method for logging into many websites with a single username and password. In some configurations, users may authenticate using a username and password from another Drupal site, or through some other site-specific mechanism.") .'</p>';
  1782. $output .= '<p>'. t('A visitor accessing your website is assigned a unique ID, or session ID, which is stored in a cookie. The cookie does not contain personal information, but acts as a key to retrieve information from your site. Users should have cookies enabled in their web browser when using your site.') .'</p>';
  1783. $output .= '<p>'. t('For more information, see the online handbook entry for <a href="@user">User module</a>.', array('@user' => 'http://drupal.org/handbook/modules/user/')) .'</p>';
  1784. return $output;
  1785. case 'admin/user/user':
  1786. return '<p>'. t('Drupal allows users to register, login, log out, maintain user profiles, etc. Users of the site may not use their own names to post content until they have signed up for a user account.') .'</p>';
  1787. case 'admin/user/user/create':
  1788. case 'admin/user/user/account/create':
  1789. return '<p>'. t("This web page allows administrators to register new users. Users' e-mail addresses and usernames must be unique.") .'</p>';
  1790. case 'admin/user/rules':
  1791. return '<p>'. t('Set up username and e-mail address access rules for new <em>and</em> existing accounts (currently logged in accounts will not be logged out). If a username or e-mail address for an account matches any deny rule, but not an allow rule, then the account will not be allowed to be created or to log in. A host rule is effective for every page view, not just registrations.') .'</p>';
  1792. case 'admin/user/permissions':
  1793. return '<p>'. t('Permissions let you control what users can do on your site. Each user role (defined on the <a href="@role">user roles page</a>) has its own set of permissions. For example, you could give users classified as "Administrators" permission to "administer nodes" but deny this power to ordinary, "authenticated" users. You can use permissions to reveal new features to privileged users (those with subscriptions, for example). Permissions also allow trusted users to share the administrative burden of running a busy site.', array('@role' => url('admin/user/roles'))) .'</p>';
  1794. case 'admin/user/roles':
  1795. return t('<p>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 in <a href="@permissions">user permissions</a>. Examples of roles include: anonymous user, authenticated user, moderator, administrator and so on. In this area you will define the <em>role names</em> of the various roles. To delete a role choose "edit".</p><p>By default, Drupal comes with two user roles:</p>
  1796. <ul>
  1797. <li>Anonymous user: this role is used for users that don\'t have a user account or that are not authenticated.</li>
  1798. <li>Authenticated user: this role is automatically granted to all logged in users.</li>
  1799. </ul>', array('@permissions' => url('admin/user/permissions')));
  1800. case 'admin/user/search':
  1801. 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>';
  1802. }
  1803. }
  1804. /**
  1805. * Retrieve a list of all user setting/information categories and sort them by weight.
  1806. */
  1807. function _user_categories($account) {
  1808. $categories = array();
  1809. // Only variables can be passed by reference workaround.
  1810. $null = NULL;
  1811. foreach (module_list() as $module) {
  1812. $function = $module .'_user';
  1813. // $null and $account need to be passed by reference.
  1814. if (function_exists($function) && ($data = $function('categories', $null, $account, ''))) {
  1815. $categories = array_merge($data, $categories);
  1816. }
  1817. }
  1818. usort($categories, '_user_sort');
  1819. return $categories;
  1820. }
  1821. function _user_sort($a, $b) {
  1822. $a = (array)$a + array('weight' => 0, 'title' => '');
  1823. $b = (array)$b + array('weight' => 0, 'title' => '');
  1824. return $a['weight'] < $b['weight'] ? -1 : ($a['weight'] > $b['weight'] ? 1 : ($a['title'] < $b['title'] ? -1 : 1));
  1825. }
  1826. /**
  1827. * List user administration filters that can be applied.
  1828. */
  1829. function user_filters() {
  1830. // Regular filters
  1831. $filters = array();
  1832. $roles = user_roles(TRUE);
  1833. unset($roles[DRUPAL_AUTHENTICATED_RID]); // Don't list authorized role.
  1834. if (count($roles)) {
  1835. $filters['role'] = array(
  1836. 'title' => t('role'),
  1837. 'where' => "ur.rid = %d",
  1838. 'options' => $roles,
  1839. 'join' => '',
  1840. );
  1841. }
  1842. $options = array();
  1843. foreach (module_list() as $module) {
  1844. if ($permissions = module_invoke($module, 'perm')) {
  1845. asort($permissions);
  1846. foreach ($permissions as $permission) {
  1847. $options[t('@module module', array('@module' => $module))][$permission] = t($permission);
  1848. }
  1849. }
  1850. }
  1851. ksort($options);
  1852. $filters['permission'] = array(
  1853. 'title' => t('permission'),
  1854. 'join' => 'LEFT JOIN {permission} p ON ur.rid = p.rid',
  1855. 'where' => " ((p.perm IS NOT NULL AND p.perm LIKE '%%%s%%') OR u.uid = 1) ",
  1856. 'options' => $options,
  1857. );
  1858. $filters['status'] = array(
  1859. 'title' => t('status'),
  1860. 'where' => 'u.status = %d',
  1861. 'join' => '',
  1862. 'options' => array(1 => t('active'), 0 => t('blocked')),
  1863. );
  1864. return $filters;
  1865. }
  1866. /**
  1867. * Build query for user administration filters based on session.
  1868. */
  1869. function user_build_filter_query() {
  1870. $filters = user_filters();
  1871. // Build query
  1872. $where = $args = $join = array();
  1873. foreach ($_SESSION['user_overview_filter'] as $filter) {
  1874. list($key, $value) = $filter;
  1875. // This checks to see if this permission filter is an enabled permission for
  1876. // the authenticated role. If so, then all users would be listed, and we can
  1877. // skip adding it to the filter query.
  1878. if ($key == 'permission') {
  1879. $account = new stdClass();
  1880. $account->uid = 'user_filter';
  1881. $account->roles = array(DRUPAL_AUTHENTICATED_RID => 1);
  1882. if (user_access($value, $account)) {
  1883. continue;
  1884. }
  1885. }
  1886. $where[] = $filters[$key]['where'];
  1887. $args[] = $value;
  1888. $join[] = $filters[$key]['join'];
  1889. }
  1890. $where = !empty($where) ? 'AND '. implode(' AND ', $where) : '';
  1891. $join = !empty($join) ? ' '. implode(' ', array_unique($join)) : '';
  1892. return array('where' => $where,
  1893. 'join' => $join,
  1894. 'args' => $args,
  1895. );
  1896. }
  1897. /**
  1898. * Implementation of hook_forms().
  1899. */
  1900. function user_forms() {
  1901. $forms['user_admin_access_add_form']['callback'] = 'user_admin_access_form';
  1902. $forms['user_admin_access_edit_form']['callback'] = 'user_admin_access_form';
  1903. $forms['user_admin_new_role']['callback'] = 'user_admin_role';
  1904. return $forms;
  1905. }
  1906. /**
  1907. * Implementation of hook_comment().
  1908. */
  1909. function user_comment(&$comment, $op) {
  1910. // Validate signature.
  1911. if ($op == 'view') {
  1912. if (variable_get('user_signatures', 0) && !empty($comment->signature)) {
  1913. $comment->signature = check_markup($comment->signature, $comment->signature_format, FALSE);
  1914. }
  1915. else {
  1916. $comment->signature = '';
  1917. }
  1918. }
  1919. }
  1920. /**
  1921. * Theme output of user signature.
  1922. *
  1923. * @ingroup themeable
  1924. */
  1925. function theme_user_signature($signature) {
  1926. $output = '';
  1927. if ($signature) {
  1928. $output .= '<div class="clear">';
  1929. $output .= '<div>—</div>';
  1930. $output .= $signature;
  1931. $output .= '</div>';
  1932. }
  1933. return $output;
  1934. }
  1935. /**
  1936. * Return an array of token to value mappings for user e-mail messages.
  1937. *
  1938. * @param $account
  1939. * The user object of the account being notified. Must contain at
  1940. * least the fields 'uid', 'name', 'pass', 'login', and 'mail'.
  1941. * @param $language
  1942. * Language object to generate the tokens with.
  1943. * @return
  1944. * Array of mappings from token names to values (for use with strtr()).
  1945. */
  1946. function user_mail_tokens($account, $language) {
  1947. global $base_url;
  1948. $tokens = array(
  1949. '!username' => $account->name,
  1950. '!site' => variable_get('site_name', 'Drupal'),
  1951. '!login_url' => user_pass_reset_url($account),
  1952. '!uri' => $base_url,
  1953. '!uri_brief' => preg_replace('!^https?://!', '', $base_url),
  1954. '!mailto' => $account->mail,
  1955. '!date' => format_date(time(), 'medium', '', NULL, $language->language),
  1956. '!login_uri' => url('user', array('absolute' => TRUE, 'language' => $language)),
  1957. '!edit_uri' => url('user/'. $account->uid .'/edit', array('absolute' => TRUE, 'language' => $language)),
  1958. );
  1959. if (!empty($account->password)) {
  1960. $tokens['!password'] = $account->password;
  1961. }
  1962. return $tokens;
  1963. }
  1964. /**
  1965. * Get the language object preferred by the user. This user preference can
  1966. * be set on the user account editing page, and is only available if there
  1967. * are more than one languages enabled on the site. If the user did not
  1968. * choose a preferred language, or is the anonymous user, the $default
  1969. * value, or if it is not set, the site default language will be returned.
  1970. *
  1971. * @param $account
  1972. * User account to look up language for.
  1973. * @param $default
  1974. * Optional default language object to return if the account
  1975. * has no valid language.
  1976. */
  1977. function user_preferred_language($account, $default = NULL) {
  1978. $language_list = language_list();
  1979. if (!empty($account->language) && isset($language_list[$account->language])) {
  1980. return $language_list[$account->language];
  1981. }
  1982. else {
  1983. return $default ? $default : language_default();
  1984. }
  1985. }
  1986. /**
  1987. * Conditionally create and send a notification email when a certain
  1988. * operation happens on the given user account.
  1989. *
  1990. * @see user_mail_tokens()
  1991. * @see drupal_mail()
  1992. *
  1993. * @param $op
  1994. * The operation being performed on the account. Possible values:
  1995. * - 'register_admin_created': Welcome message for user created by the admin.
  1996. * - 'register_no_approval_required': Welcome message when user
  1997. * self-registers.
  1998. * - 'register_pending_approval': Welcome message, user pending admin
  1999. * approval.
  2000. * - 'password_reset': Password recovery request.
  2001. * - 'status_activated': Account activated.
  2002. * - 'status_blocked': Account blocked.
  2003. * - 'status_deleted': Account deleted.
  2004. *
  2005. * @param $account
  2006. * The user object of the account being notified. Must contain at
  2007. * least the fields 'uid', 'name', and 'mail'.
  2008. * @param $language
  2009. * Optional language to use for the notification, overriding account language.
  2010. *
  2011. * @return
  2012. * The return value from drupal_mail_send(), if ends up being called.
  2013. */
  2014. function _user_mail_notify($op, $account, $language = NULL) {
  2015. // By default, we always notify except for deleted and blocked.
  2016. $default_notify = ($op != 'status_deleted' && $op != 'status_blocked');
  2017. $notify = variable_get('user_mail_'. $op .'_notify', $default_notify);
  2018. if ($notify) {
  2019. $params['account'] = $account;
  2020. $language = $language ? $language : user_preferred_language($account);
  2021. $mail = drupal_mail('user', $op, $account->mail, $language, $params);
  2022. if ($op == 'register_pending_approval') {
  2023. // If a user registered requiring admin approval, notify the admin, too.
  2024. // We use the site default language for this.
  2025. drupal_mail('user', 'register_pending_approval_admin', variable_get('site_mail', ini_get('sendmail_from')), language_default(), $params);
  2026. }
  2027. }
  2028. return empty($mail) ? NULL : $mail['result'];
  2029. }
  2030. /**
  2031. * Add javascript and string translations for dynamic password validation
  2032. * (strength and confirmation checking).
  2033. *
  2034. * This is an internal function that makes it easier to manage the translation
  2035. * strings that need to be passed to the javascript code.
  2036. */
  2037. function _user_password_dynamic_validation() {
  2038. static $complete = FALSE;
  2039. global $user;
  2040. // Only need to do once per page.
  2041. if (!$complete) {
  2042. drupal_add_js(drupal_get_path('module', 'user') .'/user.js', 'module');
  2043. drupal_add_js(array(
  2044. 'password' => array(
  2045. 'strengthTitle' => t('Password strength:'),
  2046. 'lowStrength' => t('Low'),
  2047. 'mediumStrength' => t('Medium'),
  2048. 'highStrength' => t('High'),
  2049. 'tooShort' => t('It is recommended to choose a password that contains at least six characters. It should include numbers, punctuation, and both upper and lowercase letters.'),
  2050. 'needsMoreVariation' => t('The password does not include enough variation to be secure. Try:'),
  2051. 'addLetters' => t('Adding both upper and lowercase letters.'),
  2052. 'addNumbers' => t('Adding numbers.'),
  2053. 'addPunctuation' => t('Adding punctuation.'),
  2054. 'sameAsUsername' => t('It is recommended to choose a password different from the username.'),
  2055. 'confirmSuccess' => t('Yes'),
  2056. 'confirmFailure' => t('No'),
  2057. 'confirmTitle' => t('Passwords match:'),
  2058. 'username' => (isset($user->name) ? $user->name : ''))),
  2059. 'setting');
  2060. $complete = TRUE;
  2061. }
  2062. }
  2063. /**
  2064. * Implementation of hook_hook_info().
  2065. */
  2066. function user_hook_info() {
  2067. return array(
  2068. 'user' => array(
  2069. 'user' => array(
  2070. 'insert' => array(
  2071. 'runs when' => t('After a user account has been created'),
  2072. ),
  2073. 'update' => array(
  2074. 'runs when' => t("After a user's profile has been updated"),
  2075. ),
  2076. 'delete' => array(
  2077. 'runs when' => t('After a user has been deleted')
  2078. ),
  2079. 'login' => array(
  2080. 'runs when' => t('After a user has logged in')
  2081. ),
  2082. 'logout' => array(
  2083. 'runs when' => t('After a user has logged out')
  2084. ),
  2085. 'view' => array(
  2086. 'runs when' => t("When a user's profile is being viewed")
  2087. ),
  2088. ),
  2089. ),
  2090. );
  2091. }
  2092. /**
  2093. * Implementation of hook_action_info().
  2094. */
  2095. function user_action_info() {
  2096. return array(
  2097. 'user_block_user_action' => array(
  2098. 'description' => t('Block current user'),
  2099. 'type' => 'user',
  2100. 'configurable' => FALSE,
  2101. 'hooks' => array(),
  2102. ),
  2103. 'user_block_ip_action' => array(
  2104. 'description' => t('Ban IP address of current user'),
  2105. 'type' => 'user',
  2106. 'configurable' => FALSE,
  2107. 'hooks' => array(),
  2108. ),
  2109. );
  2110. }
  2111. /**
  2112. * Implementation of a Drupal action.
  2113. * Blocks the current user.
  2114. */
  2115. function user_block_user_action(&$object, $context = array()) {
  2116. if (isset($object->uid)) {
  2117. $uid = $object->uid;
  2118. }
  2119. elseif (isset($context['uid'])) {
  2120. $uid = $context['uid'];
  2121. }
  2122. else {
  2123. global $user;
  2124. $uid = $user->uid;
  2125. }
  2126. db_query("UPDATE {users} SET status = 0 WHERE uid = %d", $uid);
  2127. sess_destroy_uid($uid);
  2128. watchdog('action', 'Blocked user %name.', array('%name' => check_plain($user->name)));
  2129. }
  2130. /**
  2131. * Implementation of a Drupal action.
  2132. * Adds an access rule that blocks the user's IP address.
  2133. */
  2134. function user_block_ip_action() {
  2135. $ip = ip_address();
  2136. db_query("INSERT INTO {access} (mask, type, status) VALUES ('%s', '%s', %d)", $ip, 'host', 0);
  2137. watchdog('action', 'Banned IP address %ip', array('%ip' => $ip));
  2138. }
  2139. /**
  2140. * Submit handler for the user registration form.
  2141. *
  2142. * This function is shared by the installation form and the normal registration form,
  2143. * which is why it can't be in the user.pages.inc file.
  2144. */
  2145. function user_register_submit($form, &$form_state) {
  2146. global $base_url;
  2147. $admin = user_access('administer users');
  2148. $mail = $form_state['values']['mail'];
  2149. $name = $form_state['values']['name'];
  2150. if (!variable_get('user_email_verification', TRUE) || $admin) {
  2151. $pass = $form_state['values']['pass'];
  2152. }
  2153. else {
  2154. $pass = user_password();
  2155. };
  2156. $notify = isset($form_state['values']['notify']) ? $form_state['values']['notify'] : NULL;
  2157. $from = variable_get('site_mail', ini_get('sendmail_from'));
  2158. if (isset($form_state['values']['roles'])) {
  2159. // Remove unset roles.
  2160. $roles = array_filter($form_state['values']['roles']);
  2161. }
  2162. else {
  2163. $roles = array();
  2164. }
  2165. if (!$admin && array_intersect(array_keys($form_state['values']), array('uid', 'roles', 'init', 'session', 'status'))) {
  2166. watchdog('security', 'Detected malicious attempt to alter protected user fields.', array(), WATCHDOG_WARNING);
  2167. $form_state['redirect'] = 'user/register';
  2168. return;
  2169. }
  2170. // The unset below is needed to prevent these form values from being saved as
  2171. // user data.
  2172. unset($form_state['values']['form_token'], $form_state['values']['submit'], $form_state['values']['op'], $form_state['values']['notify'], $form_state['values']['form_id'], $form_state['values']['affiliates'], $form_state['values']['destination']);
  2173. $merge_data = array('pass' => $pass, 'init' => $mail, 'roles' => $roles);
  2174. if (!$admin) {
  2175. // Set the user's status because it was not displayed in the form.
  2176. $merge_data['status'] = variable_get('user_register', 1) == 1;
  2177. }
  2178. $account = user_save('', array_merge($form_state['values'], $merge_data));
  2179. // Terminate if an error occured during user_save().
  2180. if (!$account) {
  2181. drupal_set_message(t("Error saving user account."), 'error');
  2182. $form_state['redirect'] = '';
  2183. return;
  2184. }
  2185. $form_state['user'] = $account;
  2186. watchdog('user', 'New user: %name (%email).', array('%name' => $name, '%email' => $mail), WATCHDOG_NOTICE, l(t('edit'), 'user/'. $account->uid .'/edit'));
  2187. // The first user may login immediately, and receives a customized welcome e-mail.
  2188. if ($account->uid == 1) {
  2189. drupal_set_message(t('Welcome to Drupal. You are now logged in as user #1, which gives you full control over your website.'));
  2190. if (variable_get('user_email_verification', TRUE)) {
  2191. drupal_set_message(t('</p><p> Your password is <strong>%pass</strong>. You may change your password below.</p>', array('%pass' => $pass)));
  2192. }
  2193. user_authenticate(array_merge($form_state['values'], $merge_data));
  2194. $form_state['redirect'] = 'user/1/edit';
  2195. return;
  2196. }
  2197. else {
  2198. // Add plain text password into user account to generate mail tokens.
  2199. $account->password = $pass;
  2200. if ($admin && !$notify) {
  2201. drupal_set_message(t('Created a new user account for <a href="@url">%name</a>. No e-mail has been sent.', array('@url' => url("user/$account->uid"), '%name' => $account->name)));
  2202. }
  2203. else if (!variable_get('user_email_verification', TRUE) && $account->status && !$admin) {
  2204. // No e-mail verification is required, create new user account, and login
  2205. // user immediately.
  2206. _user_mail_notify('register_no_approval_required', $account);
  2207. if (user_authenticate(array_merge($form_state['values'], $merge_data))) {
  2208. drupal_set_message(t('Registration successful. You are now logged in.'));
  2209. }
  2210. $form_state['redirect'] = '';
  2211. return;
  2212. }
  2213. else if ($account->status || $notify) {
  2214. // Create new user account, no administrator approval required.
  2215. $op = $notify ? 'register_admin_created' : 'register_no_approval_required';
  2216. _user_mail_notify($op, $account);
  2217. if ($notify) {
  2218. drupal_set_message(t('Password and further instructions have been e-mailed to the new user <a href="@url">%name</a>.', array('@url' => url("user/$account->uid"), '%name' => $account->name)));
  2219. }
  2220. else {
  2221. drupal_set_message(t('Your password and further instructions have been sent to your e-mail address.'));
  2222. $form_state['redirect'] = '';
  2223. return;
  2224. }
  2225. }
  2226. else {
  2227. // Create new user account, administrator approval required.
  2228. _user_mail_notify('register_pending_approval', $account);
  2229. 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.'));
  2230. $form_state['redirect'] = '';
  2231. return;
  2232. }
  2233. }
  2234. }
  2235. /**
  2236. * Form builder; The user registration form.
  2237. *
  2238. * @ingroup forms
  2239. * @see user_register_validate()
  2240. * @see user_register_submit()
  2241. */
  2242. function user_register() {
  2243. global $user;
  2244. $admin = user_access('administer users');
  2245. // If we aren't admin but already logged on, go to the user page instead.
  2246. if (!$admin && $user->uid) {
  2247. drupal_goto('user/'. $user->uid);
  2248. }
  2249. $form = array();
  2250. // Display the registration form.
  2251. if (!$admin) {
  2252. $form['user_registration_help'] = array(
  2253. '#value' => filter_xss_admin(variable_get('user_registration_help', '')),
  2254. // Ensure that user registration help appears above profile fields.
  2255. '#weight' => -20,
  2256. );
  2257. }
  2258. // Merge in the default user edit fields.
  2259. $form = array_merge($form, user_edit_form($form_state, NULL, NULL, TRUE));
  2260. if ($admin) {
  2261. $form['account']['notify'] = array(
  2262. '#type' => 'checkbox',
  2263. '#title' => t('Notify user of new account')
  2264. );
  2265. // Redirect back to page which initiated the create request;
  2266. // usually admin/user/user/create.
  2267. $form['destination'] = array('#type' => 'hidden', '#value' => $_GET['q']);
  2268. }
  2269. // Create a dummy variable for pass-by-reference parameters.
  2270. $null = NULL;
  2271. $extra = _user_forms($null, NULL, NULL, 'register');
  2272. // Remove form_group around default fields if there are no other groups.
  2273. if (!$extra) {
  2274. foreach (array('name', 'mail', 'pass', 'status', 'roles', 'notify') as $key) {
  2275. if (isset($form['account'][$key])) {
  2276. $form[$key] = $form['account'][$key];
  2277. }
  2278. }
  2279. unset($form['account']);
  2280. }
  2281. else {
  2282. $form = array_merge($form, $extra);
  2283. }
  2284. if (variable_get('configurable_timezones', 1)) {
  2285. // Override field ID, so we only change timezone on user registration,
  2286. // and never touch it on user edit pages.
  2287. $form['timezone'] = array(
  2288. '#type' => 'hidden',
  2289. '#default_value' => variable_get('date_default_timezone', NULL),
  2290. '#id' => 'edit-user-register-timezone',
  2291. );
  2292. // Add the JavaScript callback to automatically set the timezone.
  2293. drupal_add_js('
  2294. // Global Killswitch
  2295. if (Drupal.jsEnabled) {
  2296. $(document).ready(function() {
  2297. Drupal.setDefaultTimezone();
  2298. });
  2299. }', 'inline');
  2300. }
  2301. $form['submit'] = array('#type' => 'submit', '#value' => t('Create new account'), '#weight' => 30);
  2302. $form['#validate'][] = 'user_register_validate';
  2303. return $form;
  2304. }
  2305. function user_register_validate($form, &$form_state) {
  2306. $account = (object) $form_state['values'];
  2307. user_module_invoke('validate', $form_state['values'], $account, 'account');
  2308. }
  2309. /**
  2310. * Retrieve a list of all form elements for the specified category.
  2311. */
  2312. function _user_forms(&$edit, $account, $category, $hook = 'form') {
  2313. $groups = array();
  2314. foreach (module_list() as $module) {
  2315. $function = $module .'_user';
  2316. // $edit and $account need to be passed by reference.
  2317. if (function_exists($function) && ($data = $function($hook, $edit, $account, $category))) {
  2318. $groups = array_merge_recursive($data, $groups);
  2319. }
  2320. }
  2321. uasort($groups, '_user_sort');
  2322. return empty($groups) ? FALSE : $groups;
  2323. }
  2324. /**
  2325. * Prepare a destination query string for use in combination with drupal_goto().
  2326. *
  2327. * Used to direct the user back to the referring page after completing
  2328. * the openid login. This function prevents the login page from being
  2329. * returned because that page will give an access denied message to an
  2330. * authenticated user.
  2331. *
  2332. * @see drupal_get_destination()
  2333. */
  2334. function user_login_destination() {
  2335. $destination = drupal_get_destination();
  2336. return $destination == 'destination=user%2Flogin' ? 'destination=user' : $destination;
  2337. }
  2338. /**
  2339. * Menu access callback; limit access to account deletion pages.
  2340. *
  2341. * Limit access to administrative users, and prevent the anonymous user account
  2342. * from being deleted.
  2343. */
  2344. function user_delete_access($account) {
  2345. return user_access('administer users') && $account->uid > 0;
  2346. }
Login or register to post comments