user.pages.inc 21 KB

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