user.pages.inc 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565
  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_random_key();
  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. drupal_exit();
  151. }
  152. }
  153. }
  154. /**
  155. * Menu callback; logs the current user out, and redirects to the home page.
  156. */
  157. function user_logout() {
  158. global $user;
  159. watchdog('user', 'Session closed for %name.', array('%name' => $user->name));
  160. module_invoke_all('user_logout', $user);
  161. // Destroy the current session, and reset $user to the anonymous user.
  162. session_destroy();
  163. drupal_goto();
  164. }
  165. /**
  166. * Process variables for user-profile.tpl.php.
  167. *
  168. * @param array $variables
  169. * An associative array containing:
  170. * - elements: An associative array containing the user information and any
  171. * fields attached to the user. Properties used:
  172. * - #account: The user account of the profile being viewed.
  173. *
  174. * @see user-profile.tpl.php
  175. */
  176. function template_preprocess_user_profile(&$variables) {
  177. $account = $variables['elements']['#account'];
  178. // Helpful $user_profile variable for templates.
  179. foreach (element_children($variables['elements']) as $key) {
  180. $variables['user_profile'][$key] = $variables['elements'][$key];
  181. }
  182. // Preprocess fields.
  183. field_attach_preprocess('user', $account, $variables['elements'], $variables);
  184. }
  185. /**
  186. * Process variables for user-profile-item.tpl.php.
  187. *
  188. * The $variables array contains the following arguments:
  189. * - $element
  190. *
  191. * @see user-profile-item.tpl.php
  192. */
  193. function template_preprocess_user_profile_item(&$variables) {
  194. $variables['title'] = $variables['element']['#title'];
  195. $variables['value'] = $variables['element']['#markup'];
  196. $variables['attributes'] = '';
  197. if (isset($variables['element']['#attributes'])) {
  198. $variables['attributes'] = drupal_attributes($variables['element']['#attributes']);
  199. }
  200. }
  201. /**
  202. * Process variables for user-profile-category.tpl.php.
  203. *
  204. * The $variables array contains the following arguments:
  205. * - $element
  206. *
  207. * @see user-profile-category.tpl.php
  208. */
  209. function template_preprocess_user_profile_category(&$variables) {
  210. $variables['title'] = check_plain($variables['element']['#title']);
  211. $variables['profile_items'] = $variables['element']['#children'];
  212. $variables['attributes'] = '';
  213. if (isset($variables['element']['#attributes'])) {
  214. $variables['attributes'] = drupal_attributes($variables['element']['#attributes']);
  215. }
  216. }
  217. /**
  218. * Form builder; edit a user account or one of their profile categories.
  219. *
  220. * @ingroup forms
  221. * @see user_account_form()
  222. * @see user_account_form_validate()
  223. * @see user_profile_form_validate()
  224. * @see user_profile_form_submit()
  225. * @see user_cancel_confirm_form_submit()
  226. */
  227. function user_profile_form($form, &$form_state, $account, $category = 'account') {
  228. global $user;
  229. // During initial form build, add the entity to the form state for use during
  230. // form building and processing. During a rebuild, use what is in the form
  231. // state.
  232. if (!isset($form_state['user'])) {
  233. $form_state['user'] = $account;
  234. }
  235. else {
  236. $account = $form_state['user'];
  237. }
  238. // @todo Legacy support. Modules are encouraged to access the entity using
  239. // $form_state. Remove in Drupal 8.
  240. $form['#user'] = $account;
  241. $form['#user_category'] = $category;
  242. if ($category == 'account') {
  243. user_account_form($form, $form_state);
  244. // Attach field widgets.
  245. $langcode = entity_language('user', $account);
  246. field_attach_form('user', $account, $form, $form_state, $langcode);
  247. }
  248. $form['actions'] = array('#type' => 'actions');
  249. $form['actions']['submit'] = array(
  250. '#type' => 'submit',
  251. '#value' => t('Save'),
  252. );
  253. if ($category == 'account') {
  254. $form['actions']['cancel'] = array(
  255. '#type' => 'submit',
  256. '#value' => t('Cancel account'),
  257. '#submit' => array('user_edit_cancel_submit'),
  258. '#access' => $account->uid > 1 && (($account->uid == $user->uid && user_access('cancel account')) || user_access('administer users')),
  259. );
  260. }
  261. $form['#validate'][] = 'user_profile_form_validate';
  262. // Add the final user profile form submit handler.
  263. $form['#submit'][] = 'user_profile_form_submit';
  264. return $form;
  265. }
  266. /**
  267. * Validation function for the user account and profile editing form.
  268. */
  269. function user_profile_form_validate($form, &$form_state) {
  270. entity_form_field_validate('user', $form, $form_state);
  271. }
  272. /**
  273. * Submit function for the user account and profile editing form.
  274. */
  275. function user_profile_form_submit($form, &$form_state) {
  276. $account = $form_state['user'];
  277. $category = $form['#user_category'];
  278. // Remove unneeded values.
  279. form_state_values_clean($form_state);
  280. // Before updating the account entity, keep an unchanged copy for use with
  281. // user_save() later. This is necessary for modules implementing the user
  282. // hooks to be able to react on changes by comparing the values of $account
  283. // and $edit.
  284. $account_unchanged = clone $account;
  285. entity_form_submit_build_entity('user', $account, $form, $form_state);
  286. // Populate $edit with the properties of $account, which have been edited on
  287. // this form by taking over all values, which appear in the form values too.
  288. $edit = array_intersect_key((array) $account, $form_state['values']);
  289. user_save($account_unchanged, $edit, $category);
  290. $form_state['values']['uid'] = $account->uid;
  291. if ($category == 'account' && !empty($edit['pass'])) {
  292. // Remove the password reset tag since a new password was saved.
  293. unset($_SESSION['pass_reset_'. $account->uid]);
  294. }
  295. // Clear the page cache because pages can contain usernames and/or profile information:
  296. cache_clear_all();
  297. drupal_set_message(t('The changes have been saved.'));
  298. }
  299. /**
  300. * Submit function for the 'Cancel account' button on the user edit form.
  301. */
  302. function user_edit_cancel_submit($form, &$form_state) {
  303. $destination = array();
  304. if (isset($_GET['destination'])) {
  305. $destination = drupal_get_destination();
  306. unset($_GET['destination']);
  307. }
  308. // Note: We redirect from user/uid/edit to user/uid/cancel to make the tabs disappear.
  309. $form_state['redirect'] = array("user/" . $form['#user']->uid . "/cancel", array('query' => $destination));
  310. }
  311. /**
  312. * Form builder; confirm form for cancelling user account.
  313. *
  314. * @ingroup forms
  315. * @see user_edit_cancel_submit()
  316. */
  317. function user_cancel_confirm_form($form, &$form_state, $account) {
  318. global $user;
  319. $form['_account'] = array('#type' => 'value', '#value' => $account);
  320. // Display account cancellation method selection, if allowed.
  321. $default_method = variable_get('user_cancel_method', 'user_cancel_block');
  322. $admin_access = user_access('administer users');
  323. $can_select_method = $admin_access || user_access('select account cancellation method');
  324. $form['user_cancel_method'] = array(
  325. '#type' => 'item',
  326. '#title' => ($account->uid == $user->uid ? t('When cancelling your account') : t('When cancelling the account')),
  327. '#access' => $can_select_method,
  328. );
  329. $form['user_cancel_method'] += user_cancel_methods();
  330. // Allow user administrators to skip the account cancellation confirmation
  331. // mail (by default), as long as they do not attempt to cancel their own
  332. // account.
  333. $override_access = $admin_access && ($account->uid != $user->uid);
  334. $form['user_cancel_confirm'] = array(
  335. '#type' => 'checkbox',
  336. '#title' => t('Require e-mail confirmation to cancel account.'),
  337. '#default_value' => ($override_access ? FALSE : TRUE),
  338. '#access' => $override_access,
  339. '#description' => t('When enabled, the user must confirm the account cancellation via e-mail.'),
  340. );
  341. // Also allow to send account canceled notification mail, if enabled.
  342. $default_notify = variable_get('user_mail_status_canceled_notify', FALSE);
  343. $form['user_cancel_notify'] = array(
  344. '#type' => 'checkbox',
  345. '#title' => t('Notify user when account is canceled.'),
  346. '#default_value' => ($override_access ? FALSE : $default_notify),
  347. '#access' => $override_access && $default_notify,
  348. '#description' => t('When enabled, the user will receive an e-mail notification after the account has been cancelled.'),
  349. );
  350. // Prepare confirmation form page title and description.
  351. if ($account->uid == $user->uid) {
  352. $question = t('Are you sure you want to cancel your account?');
  353. }
  354. else {
  355. $question = t('Are you sure you want to cancel the account %name?', array('%name' => $account->name));
  356. }
  357. $description = '';
  358. if ($can_select_method) {
  359. $description = t('Select the method to cancel the account above.');
  360. foreach (element_children($form['user_cancel_method']) as $element) {
  361. unset($form['user_cancel_method'][$element]['#description']);
  362. }
  363. }
  364. else {
  365. // The radio button #description is used as description for the confirmation
  366. // form.
  367. foreach (element_children($form['user_cancel_method']) as $element) {
  368. if ($form['user_cancel_method'][$element]['#default_value'] == $form['user_cancel_method'][$element]['#return_value']) {
  369. $description = $form['user_cancel_method'][$element]['#description'];
  370. }
  371. unset($form['user_cancel_method'][$element]['#description']);
  372. }
  373. }
  374. // Always provide entity id in the same form key as in the entity edit form.
  375. $form['uid'] = array('#type' => 'value', '#value' => $account->uid);
  376. return confirm_form($form,
  377. $question,
  378. 'user/' . $account->uid,
  379. $description . ' ' . t('This action cannot be undone.'),
  380. t('Cancel account'), t('Cancel'));
  381. }
  382. /**
  383. * Submit handler for the account cancellation confirm form.
  384. *
  385. * @see user_cancel_confirm_form()
  386. * @see user_multiple_cancel_confirm_submit()
  387. */
  388. function user_cancel_confirm_form_submit($form, &$form_state) {
  389. global $user;
  390. $account = $form_state['values']['_account'];
  391. // Cancel account immediately, if the current user has administrative
  392. // privileges, no confirmation mail shall be sent, and the user does not
  393. // attempt to cancel the own account.
  394. if (user_access('administer users') && empty($form_state['values']['user_cancel_confirm']) && $account->uid != $user->uid) {
  395. user_cancel($form_state['values'], $account->uid, $form_state['values']['user_cancel_method']);
  396. $form_state['redirect'] = 'admin/people';
  397. }
  398. else {
  399. // Store cancelling method and whether to notify the user in $account for
  400. // user_cancel_confirm().
  401. $edit = array(
  402. 'user_cancel_method' => $form_state['values']['user_cancel_method'],
  403. 'user_cancel_notify' => $form_state['values']['user_cancel_notify'],
  404. );
  405. $account = user_save($account, $edit);
  406. _user_mail_notify('cancel_confirm', $account);
  407. drupal_set_message(t('A confirmation request to cancel your account has been sent to your e-mail address.'));
  408. watchdog('user', 'Sent account cancellation request to %name %email.', array('%name' => $account->name, '%email' => '<' . $account->mail . '>'), WATCHDOG_NOTICE);
  409. $form_state['redirect'] = "user/$account->uid";
  410. }
  411. }
  412. /**
  413. * Helper function to return available account cancellation methods.
  414. *
  415. * See documentation of hook_user_cancel_methods_alter().
  416. *
  417. * @return
  418. * An array containing all account cancellation methods as form elements.
  419. *
  420. * @see hook_user_cancel_methods_alter()
  421. * @see user_admin_settings()
  422. * @see user_cancel_confirm_form()
  423. * @see user_multiple_cancel_confirm()
  424. */
  425. function user_cancel_methods() {
  426. $methods = array(
  427. 'user_cancel_block' => array(
  428. 'title' => t('Disable the account and keep 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 remain attributed to your user name.'),
  430. ),
  431. 'user_cancel_block_unpublish' => array(
  432. 'title' => t('Disable the account and unpublish its content.'),
  433. '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.'),
  434. ),
  435. 'user_cancel_reassign' => array(
  436. 'title' => t('Delete the account and make its content belong to the %anonymous-name user.', array('%anonymous-name' => variable_get('anonymous', t('Anonymous')))),
  437. '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')))),
  438. ),
  439. 'user_cancel_delete' => array(
  440. 'title' => t('Delete the account and its content.'),
  441. 'description' => t('Your account will be removed and all account information deleted. All of your content will also be deleted.'),
  442. 'access' => user_access('administer users'),
  443. ),
  444. );
  445. // Allow modules to customize account cancellation methods.
  446. drupal_alter('user_cancel_methods', $methods);
  447. // Turn all methods into real form elements.
  448. $default_method = variable_get('user_cancel_method', 'user_cancel_block');
  449. foreach ($methods as $name => $method) {
  450. $form[$name] = array(
  451. '#type' => 'radio',
  452. '#title' => $method['title'],
  453. '#description' => (isset($method['description']) ? $method['description'] : NULL),
  454. '#return_value' => $name,
  455. '#default_value' => $default_method,
  456. '#parents' => array('user_cancel_method'),
  457. );
  458. }
  459. return $form;
  460. }
  461. /**
  462. * Menu callback; Cancel a user account via e-mail confirmation link.
  463. *
  464. * @see user_cancel_confirm_form()
  465. * @see user_cancel_url()
  466. */
  467. function user_cancel_confirm($account, $timestamp = 0, $hashed_pass = '') {
  468. // Time out in seconds until cancel URL expires; 24 hours = 86400 seconds.
  469. $timeout = 86400;
  470. $current = REQUEST_TIME;
  471. // Basic validation of arguments.
  472. if (isset($account->data['user_cancel_method']) && !empty($timestamp) && !empty($hashed_pass)) {
  473. // Validate expiration and hashed password/login.
  474. if ($timestamp <= $current && $current - $timestamp < $timeout && $account->uid && $timestamp >= $account->login && $hashed_pass == user_pass_rehash($account->pass, $timestamp, $account->login)) {
  475. $edit = array(
  476. 'user_cancel_notify' => isset($account->data['user_cancel_notify']) ? $account->data['user_cancel_notify'] : variable_get('user_mail_status_canceled_notify', FALSE),
  477. );
  478. user_cancel($edit, $account->uid, $account->data['user_cancel_method']);
  479. // Since user_cancel() is not invoked via Form API, batch processing needs
  480. // to be invoked manually and should redirect to the front page after
  481. // completion.
  482. batch_process('');
  483. }
  484. else {
  485. 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.'));
  486. drupal_goto("user/$account->uid/cancel");
  487. }
  488. }
  489. return MENU_ACCESS_DENIED;
  490. }
  491. /**
  492. * Page callback: Displays the user page.
  493. *
  494. * Displays user profile if user is logged in, or login form for anonymous
  495. * users.
  496. *
  497. * @return
  498. * A render array for either a user profile or a login form.
  499. *
  500. * @see user_view_page()
  501. * @see user_login()
  502. */
  503. function user_page() {
  504. global $user;
  505. if ($user->uid) {
  506. menu_set_active_item('user/' . $user->uid);
  507. return menu_execute_active_handler(NULL, FALSE);
  508. }
  509. else {
  510. return drupal_get_form('user_login');
  511. }
  512. }