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

Enables the user registration and login system.

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

Functions

Namesort descending Description
template_preprocess_user_picture Process variables for user-picture.tpl.php.
theme_user_list Make a list of users.
theme_user_signature Theme output of user signature.
user_access Determine whether the user has a given privilege.
user_action_info Implementation of hook_action_info().
user_authenticate Try to log in the user locally.
user_authenticate_finalize Finalize the login process. Must be called when logging in a user.
user_block Implementation of hook_block().
user_block_ip_action Implementation of a Drupal action. Adds an access rule that blocks the user's IP address.
user_block_user_action Implementation of a Drupal action. Blocks the current user.
user_build_content Builds a structured array representing the profile content.
user_build_filter_query Build query for user administration filters based on session.
user_category_load Return a user object after checking if any profile category in the path exists.
user_comment Implementation of hook_comment().
user_delete Delete a user.
user_delete_access Menu access callback; limit access to account deletion pages.
user_edit_access Access callback for user account editing.
user_edit_form
user_elements Implementation of hook_elements().
user_external_load
user_external_login Perform standard Drupal login operations for a user object.
user_external_login_register Helper 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_download Implementation of hook_file_download().
user_filters List user administration filters that can be applied.
user_forms Implementation of hook_forms().
user_get_authmaps Discover which external authentication module(s) authenticated a username.
user_help Implementation of hook_help().
user_hook_info Implementation of hook_hook_info().
user_init Implementation of hook_init().
user_is_anonymous
user_is_blocked Checks for usernames blocked by user administration.
user_is_logged_in
user_load Fetch a user object.
user_load_self
user_login Form builder; the main user login form.
user_login_authenticate_validate A 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_validators Set 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_destination Prepare a destination query string for use in combination with drupal_goto().
user_login_final_validate A validate handler on the login form. Should be the last validator. Sets an error if user has not been authenticated yet.
user_login_name_validate A FAPI validate handler. Sets an error if supplied username has been blocked or denied access.
user_login_submit Submit handler for the login form. Redirects the user to a page.
user_mail Implementation of hook_mail().
user_mail_tokens Return an array of token to value mappings for user e-mail messages.
user_menu Implementation of hook_menu().
user_module_invoke Invokes hook_user() in every module.
user_multiple_delete_confirm
user_multiple_delete_confirm_submit
user_multiple_role_edit Callback function for admin mass adding/deleting a user role.
user_page_title Menu item title callback - use the user name if it's not the current user.
user_password Generate a random alphanumeric password.
user_pass_rehash
user_pass_reset_url Generates a unique URL for a user to login and reset their password.
user_perm Implementation of hook_perm().
user_preferred_language Get the language object preferred by the user. This user preference can be set on the user account editing page, and is only available if there are more than one languages enabled on the site. If the user did not choose a preferred language, or is the…
user_register Form builder; The user registration form.
user_register_access
user_register_submit Submit handler for the user registration form.
user_register_validate
user_roles Retrieve an array of roles matching specified conditions.
user_save Save changes to a user account or add a new user.
user_search Implementation of hook_search().
user_set_authmaps Save mappings of which external authentication module(s) authenticated a user. Maps external usernames to user ids in the users table.
user_theme Implementation of hook_theme().
user_uid_optional_load Load either a specified or the current user account.
user_uid_optional_to_arg Returns the user id of the currently logged in user.
user_user Implementation of hook_user().
user_user_operations Implementation of hook_user_operations().
user_user_operations_block Callback function for admin mass blocking users.
user_user_operations_unblock Callback function for admin mass unblocking users.
user_validate_mail
user_validate_name Verify the syntax of the given name.
user_validate_picture
user_view_access
_user_categories Retrieve a list of all user setting/information categories and sort them by weight.
_user_edit_submit
_user_edit_validate
_user_forms Retrieve a list of all form elements for the specified category.
_user_mail_notify Conditionally create and send a notification email when a certain operation happens on the given user account.
_user_mail_text Returns a mail string for a variable name.
_user_password_dynamic_validation Add javascript and string translations for dynamic password validation (strength and confirmation checking).
_user_sort

Constants