user.pages.inc 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  1. <?php
  2. /**
  3. * @file
  4. * User page callback file for the user module.
  5. */
  6. /**
  7. * Menu callback; Retrieve a JSON object containing autocomplete suggestions for existing users.
  8. */
  9. function user_autocomplete($string = '') {
  10. $matches = array();
  11. if ($string) {
  12. $result = db_select('users')->fields('users', array('name'))->condition('name', db_like($string) . '%', 'LIKE')->range(0, 10)->execute();
  13. foreach ($result as $user) {
  14. $matches[$user->name] = check_plain($user->name);
  15. }
  16. }
  17. drupal_json_output($matches);
  18. }
  19. /**
  20. * Form builder; Request a password reset.
  21. *
  22. * @ingroup forms
  23. * @see user_pass_validate()
  24. * @see user_pass_submit()
  25. */
  26. function user_pass() {
  27. global $user;
  28. $form['name'] = array(
  29. '#type' => 'textfield',
  30. '#title' => t('Username or e-mail address'),
  31. '#size' => 60,
  32. '#maxlength' => max(USERNAME_MAX_LENGTH, EMAIL_MAX_LENGTH),
  33. '#required' => TRUE,
  34. '#default_value' => isset($_GET['name']) ? $_GET['name'] : '',
  35. );
  36. // Allow logged in users to request this also.
  37. if ($user->uid > 0) {
  38. $form['name']['#type'] = 'value';
  39. $form['name']['#value'] = $user->mail;
  40. $form['mail'] = array(
  41. '#prefix' => '<p>',
  42. '#markup' => t('Password reset instructions will be mailed to %email. You must log out to use the password reset link in the e-mail.', array('%email' => $user->mail)),
  43. '#suffix' => '</p>',
  44. );
  45. }
  46. $form['actions'] = array('#type' => 'actions');
  47. $form['actions']['submit'] = array('#type' => 'submit', '#value' => t('E-mail new password'));
  48. return $form;
  49. }
  50. function user_pass_validate($form, &$form_state) {
  51. $name = trim($form_state['values']['name']);
  52. // Try to load by email.
  53. $users = user_load_multiple(array(), array('mail' => $name, 'status' => '1'));
  54. $account = reset($users);
  55. if (!$account) {
  56. // No success, try to load by name.
  57. $users = user_load_multiple(array(), array('name' => $name, 'status' => '1'));
  58. $account = reset($users);
  59. }
  60. if (isset($account->uid)) {
  61. form_set_value(array('#parents' => array('account')), $account, $form_state);
  62. }
  63. else {
  64. form_set_error('name', t('Sorry, %name is not recognized as a user name or an e-mail address.', array('%name' => $name)));
  65. }
  66. }
  67. function user_pass_submit($form, &$form_state) {
  68. global $language;
  69. $account = $form_state['values']['account'];
  70. // Mail one time login URL and instructions using current language.
  71. $mail = _user_mail_notify('password_reset', $account, $language);
  72. if (!empty($mail)) {
  73. watchdog('user', 'Password reset instructions mailed to %name at %email.', array('%name' => $account->name, '%email' => $account->mail));
  74. drupal_set_message(t('Further instructions have been sent to your e-mail address.'));
  75. }
  76. $form_state['redirect'] = 'user';
  77. return;
  78. }
  79. /**
  80. * Menu callback; process one time login link and redirects to the user page on success.
  81. */
  82. function user_pass_reset($form, &$form_state, $uid, $timestamp, $hashed_pass, $action = NULL) {
  83. global $user;
  84. // When processing the one-time login link, we have to make sure that a user
  85. // isn't already logged in.
  86. if ($user->uid) {
  87. // The existing user is already logged in.
  88. if ($user->uid == $uid) {
  89. drupal_set_message(t('You are logged in as %user. <a href="!user_edit">Change your password.</a>', array('%user' => $user->name, '!user_edit' => url("user/$user->uid/edit"))));
  90. }
  91. // A different user is already logged in on the computer.
  92. else {
  93. $reset_link_account = user_load($uid);
  94. if (!empty($reset_link_account)) {
  95. drupal_set_message(t('Another user (%other_user) is already logged into the site on this computer, but you tried to use a one-time link for user %resetting_user. Please <a href="!logout">logout</a> and try using the link again.',
  96. array('%other_user' => $user->name, '%resetting_user' => $reset_link_account->name, '!logout' => url('user/logout'))));
  97. } else {
  98. // Invalid one-time link specifies an unknown user.
  99. drupal_set_message(t('The one-time login link you clicked is invalid.'));
  100. }
  101. }
  102. drupal_goto();
  103. }
  104. else {
  105. // Time out, in seconds, until login URL expires. Defaults to 24 hours =
  106. // 86400 seconds.
  107. $timeout = variable_get('user_password_reset_timeout', 86400);
  108. $current = REQUEST_TIME;
  109. // Some redundant checks for extra security ?
  110. $users = user_load_multiple(array($uid), array('status' => '1'));
  111. if ($timestamp <= $current && $account = reset($users)) {
  112. // No time out for first time login.
  113. if ($account->login && $current - $timestamp > $timeout) {
  114. drupal_set_message(t('You have tried to use a one-time login link that has expired. Please request a new one using the form below.'));
  115. drupal_goto('user/password');
  116. }
  117. elseif ($account->uid && $timestamp >= $account->login && $timestamp <= $current && $hashed_pass == user_pass_rehash($account->pass, $timestamp, $account->login)) {
  118. // First stage is a confirmation form, then login
  119. if ($action == 'login') {
  120. // Set the new user.
  121. $user = $account;
  122. // user_login_finalize() also updates the login timestamp of the
  123. // user, which invalidates further use of the one-time login link.
  124. user_login_finalize();
  125. watchdog('user', 'User %name used one-time login link at time %timestamp.', array('%name' => $account->name, '%timestamp' => $timestamp));
  126. drupal_set_message(t('You have just used your one-time login link. It is no longer necessary to use this link to log in. Please change your password.'));
  127. // Let the user's password be changed without the current password check.
  128. $token = drupal_hash_base64(drupal_random_bytes(55));
  129. $_SESSION['pass_reset_' . $user->uid] = $token;
  130. drupal_goto('user/' . $user->uid . '/edit', array('query' => array('pass-reset-token' => $token)));
  131. }
  132. else {
  133. $form['message'] = array('#markup' => t('<p>This is a one-time login for %user_name and will expire on %expiration_date.</p><p>Click on this button to log in to the site and change your password.</p>', array('%user_name' => $account->name, '%expiration_date' => format_date($timestamp + $timeout))));
  134. $form['help'] = array('#markup' => '<p>' . t('This login can be used only once.') . '</p>');
  135. $form['actions'] = array('#type' => 'actions');
  136. $form['actions']['submit'] = array('#type' => 'submit', '#value' => t('Log in'));
  137. $form['#action'] = url("user/reset/$uid/$timestamp/$hashed_pass/login");
  138. return $form;
  139. }
  140. }
  141. else {
  142. drupal_set_message(t('You have tried to use a one-time login link that has either been used or is no longer valid. Please request a new one using the form below.'));
  143. drupal_goto('user/password');
  144. }
  145. }
  146. else {
  147. // Deny access, no more clues.
  148. // Everything will be in the watchdog's URL for the administrator to check.
  149. drupal_access_denied();
  150. }
  151. }
  152. }
  153. /**
  154. * Menu callback; logs the current user out, and redirects to the home page.
  155. */
  156. function user_logout() {
  157. global $user;
  158. watchdog('user', 'Session closed for %name.', array('%name' => $user->name));
  159. module_invoke_all('user_logout', $user);
  160. // Destroy the current session, and reset $user to the anonymous user.
  161. session_destroy();
  162. drupal_goto();
  163. }
  164. /**
  165. * Process variables for user-profile.tpl.php.
  166. *
  167. * The $variables array contains the following arguments:
  168. * - $account
  169. *
  170. * @see user-profile.tpl.php
  171. */
  172. function template_preprocess_user_profile(&$variables) {
  173. $account = $variables['elements']['#account'];
  174. // Helpful $user_profile variable for templates.
  175. foreach (element_children($variables['elements']) as $key) {
  176. $variables['user_profile'][$key] = $variables['elements'][$key];
  177. }
  178. // Preprocess fields.
  179. field_attach_preprocess('user', $account, $variables['elements'], $variables);
  180. }
  181. /**
  182. * Process variables for user-profile-item.tpl.php.
  183. *
  184. * The $variables array contains the following arguments:
  185. * - $element
  186. *
  187. * @see user-profile-item.tpl.php
  188. */
  189. function template_preprocess_user_profile_item(&$variables) {
  190. $variables['title'] = $variables['element']['#title'];
  191. $variables['value'] = $variables['element']['#markup'];
  192. $variables['attributes'] = '';
  193. if (isset($variables['element']['#attributes'])) {
  194. $variables['attributes'] = drupal_attributes($variables['element']['#attributes']);
  195. }
  196. }
  197. /**
  198. * Process variables for user-profile-category.tpl.php.
  199. *
  200. * The $variables array contains the following arguments:
  201. * - $element
  202. *
  203. * @see user-profile-category.tpl.php
  204. */
  205. function template_preprocess_user_profile_category(&$variables) {
  206. $variables['title'] = check_plain($variables['element']['#title']);
  207. $variables['profile_items'] = $variables['element']['#children'];
  208. $variables['attributes'] = '';
  209. if (isset($variables['element']['#attributes'])) {
  210. $variables['attributes'] = drupal_attributes($variables['element']['#attributes']);
  211. }
  212. }
  213. /**
  214. * Form builder; edit a user account or one of their profile categories.
  215. *
  216. * @ingroup forms
  217. * @see user_account_form()
  218. * @see user_account_form_validate()
  219. * @see user_profile_form_validate()
  220. * @see user_profile_form_submit()
  221. * @see user_cancel_confirm_form_submit()
  222. */
  223. function user_profile_form($form, &$form_state, $account, $category = 'account') {
  224. global $user;
  225. // During initial form build, add the entity to the form state for use during
  226. // form building and processing. During a rebuild, use what is in the form
  227. // state.
  228. if (!isset($form_state['user'])) {
  229. $form_state['user'] = $account;
  230. }
  231. else {
  232. $account = $form_state['user'];
  233. }
  234. // @todo Legacy support. Modules are encouraged to access the entity using
  235. // $form_state. Remove in Drupal 8.
  236. $form['#user'] = $account;
  237. $form['#user_category'] = $category;
  238. if ($category == 'account') {
  239. user_account_form($form, $form_state);
  240. // Attach field widgets.
  241. $langcode = entity_language('user', $account);
  242. field_attach_form('user', $account, $form, $form_state, $langcode);
  243. }
  244. $form['actions'] = array('#type' => 'actions');
  245. $form['actions']['submit'] = array(
  246. '#type' => 'submit',
  247. '#value' => t('Save'),
  248. );
  249. if ($category == 'account') {
  250. $form['actions']['cancel'] = array(
  251. '#type' => 'submit',
  252. '#value' => t('Cancel account'),
  253. '#submit' => array('user_edit_cancel_submit'),
  254. '#access' => $account->uid > 1 && (($account->uid == $user->uid && user_access('cancel account')) || user_access('administer users')),
  255. );
  256. }
  257. $form['#validate'][] = 'user_profile_form_validate';
  258. // Add the final user profile form submit handler.
  259. $form['#submit'][] = 'user_profile_form_submit';
  260. return $form;
  261. }
  262. /**
  263. * Validation function for the user account and profile editing form.
  264. */
  265. function user_profile_form_validate($form, &$form_state) {
  266. entity_form_field_validate('user', $form, $form_state);
  267. }
  268. /**
  269. * Submit function for the user account and profile editing form.
  270. */
  271. function user_profile_form_submit($form, &$form_state) {
  272. $account = $form_state['user'];
  273. $category = $form['#user_category'];
  274. // Remove unneeded values.
  275. form_state_values_clean($form_state);
  276. // Before updating the account entity, keep an unchanged copy for use with
  277. // user_save() later. This is necessary for modules implementing the user
  278. // hooks to be able to react on changes by comparing the values of $account
  279. // and $edit.
  280. $account_unchanged = clone $account;
  281. entity_form_submit_build_entity('user', $account, $form, $form_state);
  282. // Populate $edit with the properties of $account, which have been edited on
  283. // this form by taking over all values, which appear in the form values too.
  284. $edit = array_intersect_key((array) $account, $form_state['values']);
  285. user_save($account_unchanged, $edit, $category);
  286. $form_state['values']['uid'] = $account->uid;
  287. if ($category == 'account' && !empty($edit['pass'])) {
  288. // Remove the password reset tag since a new password was saved.
  289. unset($_SESSION['pass_reset_'. $account->uid]);
  290. }
  291. // Clear the page cache because pages can contain usernames and/or profile information:
  292. cache_clear_all();
  293. drupal_set_message(t('The changes have been saved.'));
  294. }
  295. /**
  296. * Submit function for the 'Cancel account' button on the user edit form.
  297. */
  298. function user_edit_cancel_submit($form, &$form_state) {
  299. $destination = array();
  300. if (isset($_GET['destination'])) {
  301. $destination = drupal_get_destination();
  302. unset($_GET['destination']);
  303. }
  304. // Note: We redirect from user/uid/edit to user/uid/cancel to make the tabs disappear.
  305. $form_state['redirect'] = array("user/" . $form['#user']->uid . "/cancel", array('query' => $destination));
  306. }
  307. /**
  308. * Form builder; confirm form for cancelling user account.
  309. *
  310. * @ingroup forms
  311. * @see user_edit_cancel_submit()
  312. */
  313. function user_cancel_confirm_form($form, &$form_state, $account) {
  314. global $user;
  315. $form['_account'] = array('#type' => 'value', '#value' => $account);
  316. // Display account cancellation method selection, if allowed.
  317. $default_method = variable_get('user_cancel_method', 'user_cancel_block');
  318. $admin_access = user_access('administer users');
  319. $can_select_method = $admin_access || user_access('select account cancellation method');
  320. $form['user_cancel_method'] = array(
  321. '#type' => 'item',
  322. '#title' => ($account->uid == $user->uid ? t('When cancelling your account') : t('When cancelling the account')),
  323. '#access' => $can_select_method,
  324. );
  325. $form['user_cancel_method'] += user_cancel_methods();
  326. // Allow user administrators to skip the account cancellation confirmation
  327. // mail (by default), as long as they do not attempt to cancel their own
  328. // account.
  329. $override_access = $admin_access && ($account->uid != $user->uid);
  330. $form['user_cancel_confirm'] = array(
  331. '#type' => 'checkbox',
  332. '#title' => t('Require e-mail confirmation to cancel account.'),
  333. '#default_value' => ($override_access ? FALSE : TRUE),
  334. '#access' => $override_access,
  335. '#description' => t('When enabled, the user must confirm the account cancellation via e-mail.'),
  336. );
  337. // Also allow to send account canceled notification mail, if enabled.
  338. $default_notify = variable_get('user_mail_status_canceled_notify', FALSE);
  339. $form['user_cancel_notify'] = array(
  340. '#type' => 'checkbox',
  341. '#title' => t('Notify user when account is canceled.'),
  342. '#default_value' => ($override_access ? FALSE : $default_notify),
  343. '#access' => $override_access && $default_notify,
  344. '#description' => t('When enabled, the user will receive an e-mail notification after the account has been cancelled.'),
  345. );
  346. // Prepare confirmation form page title and description.
  347. if ($account->uid == $user->uid) {
  348. $question = t('Are you sure you want to cancel your account?');
  349. }
  350. else {
  351. $question = t('Are you sure you want to cancel the account %name?', array('%name' => $account->name));
  352. }
  353. $description = '';
  354. if ($can_select_method) {
  355. $description = t('Select the method to cancel the account above.');
  356. foreach (element_children($form['user_cancel_method']) as $element) {
  357. unset($form['user_cancel_method'][$element]['#description']);
  358. }
  359. }
  360. else {
  361. // The radio button #description is used as description for the confirmation
  362. // form.
  363. foreach (element_children($form['user_cancel_method']) as $element) {
  364. if ($form['user_cancel_method'][$element]['#default_value'] == $form['user_cancel_method'][$element]['#return_value']) {
  365. $description = $form['user_cancel_method'][$element]['#description'];
  366. }
  367. unset($form['user_cancel_method'][$element]['#description']);
  368. }
  369. }
  370. // Always provide entity id in the same form key as in the entity edit form.
  371. $form['uid'] = array('#type' => 'value', '#value' => $account->uid);
  372. return confirm_form($form,
  373. $question,
  374. 'user/' . $account->uid,
  375. $description . ' ' . t('This action cannot be undone.'),
  376. t('Cancel account'), t('Cancel'));
  377. }
  378. /**
  379. * Submit handler for the account cancellation confirm form.
  380. *
  381. * @see user_cancel_confirm_form()
  382. * @see user_multiple_cancel_confirm_submit()
  383. */
  384. function user_cancel_confirm_form_submit($form, &$form_state) {
  385. global $user;
  386. $account = $form_state['values']['_account'];
  387. // Cancel account immediately, if the current user has administrative
  388. // privileges, no confirmation mail shall be sent, and the user does not
  389. // attempt to cancel the own account.
  390. if (user_access('administer users') && empty($form_state['values']['user_cancel_confirm']) && $account->uid != $user->uid) {
  391. user_cancel($form_state['values'], $account->uid, $form_state['values']['user_cancel_method']);
  392. $form_state['redirect'] = 'admin/people';
  393. }
  394. else {
  395. // Store cancelling method and whether to notify the user in $account for
  396. // user_cancel_confirm().
  397. $edit = array(
  398. 'user_cancel_method' => $form_state['values']['user_cancel_method'],
  399. 'user_cancel_notify' => $form_state['values']['user_cancel_notify'],
  400. );
  401. $account = user_save($account, $edit);
  402. _user_mail_notify('cancel_confirm', $account);
  403. drupal_set_message(t('A confirmation request to cancel your account has been sent to your e-mail address.'));
  404. watchdog('user', 'Sent account cancellation request to %name %email.', array('%name' => $account->name, '%email' => '<' . $account->mail . '>'), WATCHDOG_NOTICE);
  405. $form_state['redirect'] = "user/$account->uid";
  406. }
  407. }
  408. /**
  409. * Helper function to return available account cancellation methods.
  410. *
  411. * See documentation of hook_user_cancel_methods_alter().
  412. *
  413. * @return
  414. * An array containing all account cancellation methods as form elements.
  415. *
  416. * @see hook_user_cancel_methods_alter()
  417. * @see user_admin_settings()
  418. * @see user_cancel_confirm_form()
  419. * @see user_multiple_cancel_confirm()
  420. */
  421. function user_cancel_methods() {
  422. $methods = array(
  423. 'user_cancel_block' => array(
  424. 'title' => t('Disable the account and keep its content.'),
  425. 'description' => t('Your account will be blocked and you will no longer be able to log in. All of your content will remain attributed to your user name.'),
  426. ),
  427. 'user_cancel_block_unpublish' => array(
  428. 'title' => t('Disable the account and unpublish its content.'),
  429. 'description' => t('Your account will be blocked and you will no longer be able to log in. All of your content will be hidden from everyone but administrators.'),
  430. ),
  431. 'user_cancel_reassign' => array(
  432. 'title' => t('Delete the account and make its content belong to the %anonymous-name user.', array('%anonymous-name' => variable_get('anonymous', t('Anonymous')))),
  433. 'description' => t('Your account will be removed and all account information deleted. All of your content will be assigned to the %anonymous-name user.', array('%anonymous-name' => variable_get('anonymous', t('Anonymous')))),
  434. ),
  435. 'user_cancel_delete' => array(
  436. 'title' => t('Delete the account and its content.'),
  437. 'description' => t('Your account will be removed and all account information deleted. All of your content will also be deleted.'),
  438. 'access' => user_access('administer users'),
  439. ),
  440. );
  441. // Allow modules to customize account cancellation methods.
  442. drupal_alter('user_cancel_methods', $methods);
  443. // Turn all methods into real form elements.
  444. $default_method = variable_get('user_cancel_method', 'user_cancel_block');
  445. foreach ($methods as $name => $method) {
  446. $form[$name] = array(
  447. '#type' => 'radio',
  448. '#title' => $method['title'],
  449. '#description' => (isset($method['description']) ? $method['description'] : NULL),
  450. '#return_value' => $name,
  451. '#default_value' => $default_method,
  452. '#parents' => array('user_cancel_method'),
  453. );
  454. }
  455. return $form;
  456. }
  457. /**
  458. * Menu callback; Cancel a user account via e-mail confirmation link.
  459. *
  460. * @see user_cancel_confirm_form()
  461. * @see user_cancel_url()
  462. */
  463. function user_cancel_confirm($account, $timestamp = 0, $hashed_pass = '') {
  464. // Time out in seconds until cancel URL expires; 24 hours = 86400 seconds.
  465. $timeout = 86400;
  466. $current = REQUEST_TIME;
  467. // Basic validation of arguments.
  468. if (isset($account->data['user_cancel_method']) && !empty($timestamp) && !empty($hashed_pass)) {
  469. // Validate expiration and hashed password/login.
  470. if ($timestamp <= $current && $current - $timestamp < $timeout && $account->uid && $timestamp >= $account->login && $hashed_pass == user_pass_rehash($account->pass, $timestamp, $account->login)) {
  471. $edit = array(
  472. 'user_cancel_notify' => isset($account->data['user_cancel_notify']) ? $account->data['user_cancel_notify'] : variable_get('user_mail_status_canceled_notify', FALSE),
  473. );
  474. user_cancel($edit, $account->uid, $account->data['user_cancel_method']);
  475. // Since user_cancel() is not invoked via Form API, batch processing needs
  476. // to be invoked manually and should redirect to the front page after
  477. // completion.
  478. batch_process('');
  479. }
  480. else {
  481. drupal_set_message(t('You have tried to use an account cancellation link that has expired. Please request a new one using the form below.'));
  482. drupal_goto("user/$account->uid/cancel");
  483. }
  484. }
  485. drupal_access_denied();
  486. }
  487. /**
  488. * Access callback for path /user.
  489. *
  490. * Displays user profile if user is logged in, or login form for anonymous
  491. * users.
  492. */
  493. function user_page() {
  494. global $user;
  495. if ($user->uid) {
  496. menu_set_active_item('user/' . $user->uid);
  497. return menu_execute_active_handler(NULL, FALSE);
  498. }
  499. else {
  500. return drupal_get_form('user_login');
  501. }
  502. }