Projet

Général

Profil

Paste
Télécharger (21,6 ko) Statistiques
| Branche: | Révision:

root / drupal7 / modules / user / user.pages.inc @ 73a44071

1
<?php
2

    
3
/**
4
 * @file
5
 * User page callback file for the user module.
6
 */
7

    
8
/**
9
 * Menu callback; Retrieve a JSON object containing autocomplete suggestions for existing users.
10
 */
11
function user_autocomplete($string = '') {
12
  $matches = array();
13
  if ($string) {
14
    $result = db_select('users')->fields('users', array('name'))->condition('name', db_like($string) . '%', 'LIKE')->range(0, 10)->execute();
15
    foreach ($result as $user) {
16
      $matches[$user->name] = check_plain($user->name);
17
    }
18
  }
19

    
20
  drupal_json_output($matches);
21
}
22

    
23
/**
24
 * Form builder; Request a password reset.
25
 *
26
 * @ingroup forms
27
 * @see user_pass_validate()
28
 * @see user_pass_submit()
29
 */
30
function user_pass() {
31
  global $user;
32

    
33
  $form['name'] = array(
34
    '#type' => 'textfield',
35
    '#title' => t('Username or e-mail address'),
36
    '#size' => 60,
37
    '#maxlength' => max(USERNAME_MAX_LENGTH, EMAIL_MAX_LENGTH),
38
    '#required' => TRUE,
39
    '#default_value' => isset($_GET['name']) ? $_GET['name'] : '',
40
  );
41
  // Allow logged in users to request this also.
42
  if ($user->uid > 0) {
43
    $form['name']['#type'] = 'value';
44
    $form['name']['#value'] = $user->mail;
45
    $form['mail'] = array(
46
      '#prefix' => '<p>',
47
      '#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)),
48
      '#suffix' => '</p>',
49
    );
50
  }
51
  $form['actions'] = array('#type' => 'actions');
52
  $form['actions']['submit'] = array('#type' => 'submit', '#value' => t('E-mail new password'));
53

    
54
  return $form;
55
}
56

    
57
function user_pass_validate($form, &$form_state) {
58
  $name = trim($form_state['values']['name']);
59
  // Try to load by email.
60
  $users = user_load_multiple(array(), array('mail' => $name, 'status' => '1'));
61
  $account = reset($users);
62
  if (!$account) {
63
    // No success, try to load by name.
64
    $users = user_load_multiple(array(), array('name' => $name, 'status' => '1'));
65
    $account = reset($users);
66
  }
67
  if (isset($account->uid)) {
68
    form_set_value(array('#parents' => array('account')), $account, $form_state);
69
  }
70
  else {
71
    form_set_error('name', t('Sorry, %name is not recognized as a user name or an e-mail address.', array('%name' => $name)));
72
  }
73
}
74

    
75
function user_pass_submit($form, &$form_state) {
76
  global $language;
77

    
78
  $account = $form_state['values']['account'];
79
  // Mail one time login URL and instructions using current language.
80
  $mail = _user_mail_notify('password_reset', $account, $language);
81
  if (!empty($mail)) {
82
    watchdog('user', 'Password reset instructions mailed to %name at %email.', array('%name' => $account->name, '%email' => $account->mail));
83
    drupal_set_message(t('Further instructions have been sent to your e-mail address.'));
84
  }
85

    
86
  $form_state['redirect'] = 'user';
87
  return;
88
}
89

    
90
/**
91
 * Menu callback; process one time login link and redirects to the user page on success.
92
 */
93
function user_pass_reset($form, &$form_state, $uid, $timestamp, $hashed_pass, $action = NULL) {
94
  global $user;
95

    
96
  // When processing the one-time login link, we have to make sure that a user
97
  // isn't already logged in.
98
  if ($user->uid) {
99
    // The existing user is already logged in.
100
    if ($user->uid == $uid) {
101
      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"))));
102
    }
103
    // A different user is already logged in on the computer.
104
    else {
105
      $reset_link_account = user_load($uid);
106
      if (!empty($reset_link_account)) {
107
        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.',
108
          array('%other_user' => $user->name, '%resetting_user' => $reset_link_account->name, '!logout' => url('user/logout'))), 'warning');
109
      } else {
110
        // Invalid one-time link specifies an unknown user.
111
        drupal_set_message(t('The one-time login link you clicked is invalid.'), 'error');
112
      }
113
    }
114
    drupal_goto();
115
  }
116
  else {
117
    // Time out, in seconds, until login URL expires. Defaults to 24 hours =
118
    // 86400 seconds.
119
    $timeout = variable_get('user_password_reset_timeout', 86400);
120
    $current = REQUEST_TIME;
121
    // Some redundant checks for extra security ?
122
    $users = user_load_multiple(array($uid), array('status' => '1'));
123
    if ($timestamp <= $current && $account = reset($users)) {
124
      // No time out for first time login.
125
      if ($account->login && $current - $timestamp > $timeout) {
126
        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.'), 'error');
127
        drupal_goto('user/password');
128
      }
129
      elseif ($account->uid && $timestamp >= $account->login && $timestamp <= $current && $hashed_pass == user_pass_rehash($account->pass, $timestamp, $account->login, $account->uid)) {
130
        // First stage is a confirmation form, then login
131
        if ($action == 'login') {
132
          // Set the new user.
133
          $user = $account;
134
          // user_login_finalize() also updates the login timestamp of the
135
          // user, which invalidates further use of the one-time login link.
136
          user_login_finalize();
137
          watchdog('user', 'User %name used one-time login link at time %timestamp.', array('%name' => $account->name, '%timestamp' => $timestamp));
138
          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.'));
139
          // Let the user's password be changed without the current password check.
140
          $token = drupal_random_key();
141
          $_SESSION['pass_reset_' . $user->uid] = $token;
142
          drupal_goto('user/' . $user->uid . '/edit', array('query' => array('pass-reset-token' => $token)));
143
        }
144
        else {
145
          $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))));
146
          $form['help'] = array('#markup' => '<p>' . t('This login can be used only once.') . '</p>');
147
          $form['actions'] = array('#type' => 'actions');
148
          $form['actions']['submit'] = array('#type' => 'submit', '#value' => t('Log in'));
149
          $form['#action'] = url("user/reset/$uid/$timestamp/$hashed_pass/login");
150
          return $form;
151
        }
152
      }
153
      else {
154
        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.'), 'error');
155
        drupal_goto('user/password');
156
      }
157
    }
158
    else {
159
      // Deny access, no more clues.
160
      // Everything will be in the watchdog's URL for the administrator to check.
161
      drupal_access_denied();
162
      drupal_exit();
163
    }
164
  }
165
}
166

    
167
/**
168
 * Menu callback; logs the current user out, and redirects to the home page.
169
 */
170
function user_logout() {
171
  global $user;
172

    
173
  watchdog('user', 'Session closed for %name.', array('%name' => $user->name));
174

    
175
  module_invoke_all('user_logout', $user);
176

    
177
  // Destroy the current session, and reset $user to the anonymous user.
178
  session_destroy();
179

    
180
  drupal_goto();
181
}
182

    
183
/**
184
 * Process variables for user-profile.tpl.php.
185
 *
186
 * @param array $variables
187
 *   An associative array containing:
188
 *   - elements: An associative array containing the user information and any
189
 *     fields attached to the user. Properties used:
190
 *     - #account: The user account of the profile being viewed.
191
 *
192
 * @see user-profile.tpl.php
193
 */
194
function template_preprocess_user_profile(&$variables) {
195
  $account = $variables['elements']['#account'];
196

    
197
  // Helpful $user_profile variable for templates.
198
  foreach (element_children($variables['elements']) as $key) {
199
    $variables['user_profile'][$key] = $variables['elements'][$key];
200
  }
201

    
202
  // Preprocess fields.
203
  field_attach_preprocess('user', $account, $variables['elements'], $variables);
204
}
205

    
206
/**
207
 * Process variables for user-profile-item.tpl.php.
208
 *
209
 * The $variables array contains the following arguments:
210
 * - $element
211
 *
212
 * @see user-profile-item.tpl.php
213
 */
214
function template_preprocess_user_profile_item(&$variables) {
215
  $variables['title'] = $variables['element']['#title'];
216
  $variables['value'] = $variables['element']['#markup'];
217
  $variables['attributes'] = '';
218
  if (isset($variables['element']['#attributes'])) {
219
    $variables['attributes'] = drupal_attributes($variables['element']['#attributes']);
220
  }
221
}
222

    
223
/**
224
 * Process variables for user-profile-category.tpl.php.
225
 *
226
 * The $variables array contains the following arguments:
227
 * - $element
228
 *
229
 * @see user-profile-category.tpl.php
230
 */
231
function template_preprocess_user_profile_category(&$variables) {
232
  $variables['title'] = check_plain($variables['element']['#title']);
233
  $variables['profile_items'] = $variables['element']['#children'];
234
  $variables['attributes'] = '';
235
  if (isset($variables['element']['#attributes'])) {
236
    $variables['attributes'] = drupal_attributes($variables['element']['#attributes']);
237
  }
238
}
239

    
240
/**
241
 * Form builder; edit a user account or one of their profile categories.
242
 *
243
 * @ingroup forms
244
 * @see user_account_form()
245
 * @see user_account_form_validate()
246
 * @see user_profile_form_validate()
247
 * @see user_profile_form_submit()
248
 * @see user_cancel_confirm_form_submit()
249
 */
250
function user_profile_form($form, &$form_state, $account, $category = 'account') {
251
  global $user;
252

    
253
  // During initial form build, add the entity to the form state for use during
254
  // form building and processing. During a rebuild, use what is in the form
255
  // state.
256
  if (!isset($form_state['user'])) {
257
    $form_state['user'] = $account;
258
  }
259
  else {
260
    $account = $form_state['user'];
261
  }
262

    
263
  // @todo Legacy support. Modules are encouraged to access the entity using
264
  //   $form_state. Remove in Drupal 8.
265
  $form['#user'] = $account;
266
  $form['#user_category'] = $category;
267

    
268
  if ($category == 'account') {
269
    user_account_form($form, $form_state);
270
    // Attach field widgets.
271
    $langcode = entity_language('user', $account);
272
    field_attach_form('user', $account, $form, $form_state, $langcode);
273
  }
274

    
275
  $form['actions'] = array('#type' => 'actions');
276
  $form['actions']['submit'] = array(
277
    '#type' => 'submit',
278
    '#value' => t('Save'),
279
  );
280
  if ($category == 'account') {
281
    $form['actions']['cancel'] = array(
282
      '#type' => 'submit',
283
      '#value' => t('Cancel account'),
284
      '#submit' => array('user_edit_cancel_submit'),
285
      '#access' => $account->uid > 1 && (($account->uid == $user->uid && user_access('cancel account')) || user_access('administer users')),
286
    );
287
  }
288

    
289
  $form['#validate'][] = 'user_profile_form_validate';
290
  // Add the final user profile form submit handler.
291
  $form['#submit'][] = 'user_profile_form_submit';
292

    
293
  return $form;
294
}
295

    
296
/**
297
 * Validation function for the user account and profile editing form.
298
 */
299
function user_profile_form_validate($form, &$form_state) {
300
  entity_form_field_validate('user', $form, $form_state);
301
}
302

    
303
/**
304
 * Submit function for the user account and profile editing form.
305
 */
306
function user_profile_form_submit($form, &$form_state) {
307
  $account = $form_state['user'];
308
  $category = $form['#user_category'];
309
  // Remove unneeded values.
310
  form_state_values_clean($form_state);
311

    
312
  // Before updating the account entity, keep an unchanged copy for use with
313
  // user_save() later. This is necessary for modules implementing the user
314
  // hooks to be able to react on changes by comparing the values of $account
315
  // and $edit.
316
  $account_unchanged = clone $account;
317

    
318
  entity_form_submit_build_entity('user', $account, $form, $form_state);
319

    
320
  // Populate $edit with the properties of $account, which have been edited on
321
  // this form by taking over all values, which appear in the form values too.
322
  $edit = array_intersect_key((array) $account, $form_state['values']);
323

    
324
  user_save($account_unchanged, $edit, $category);
325
  $form_state['values']['uid'] = $account->uid;
326

    
327
  if ($category == 'account' && !empty($edit['pass'])) {
328
    // Remove the password reset tag since a new password was saved.
329
    unset($_SESSION['pass_reset_'. $account->uid]);
330
  }
331
  // Clear the page cache because pages can contain usernames and/or profile information:
332
  cache_clear_all();
333

    
334
  drupal_set_message(t('The changes have been saved.'));
335
}
336

    
337
/**
338
 * Submit function for the 'Cancel account' button on the user edit form.
339
 */
340
function user_edit_cancel_submit($form, &$form_state) {
341
  $destination = array();
342
  if (isset($_GET['destination'])) {
343
    $destination = drupal_get_destination();
344
    unset($_GET['destination']);
345
  }
346
  // Note: We redirect from user/uid/edit to user/uid/cancel to make the tabs disappear.
347
  $form_state['redirect'] = array("user/" . $form['#user']->uid . "/cancel", array('query' => $destination));
348
}
349

    
350
/**
351
 * Form builder; confirm form for cancelling user account.
352
 *
353
 * @ingroup forms
354
 * @see user_edit_cancel_submit()
355
 */
356
function user_cancel_confirm_form($form, &$form_state, $account) {
357
  global $user;
358

    
359
  $form['_account'] = array('#type' => 'value', '#value' => $account);
360

    
361
  // Display account cancellation method selection, if allowed.
362
  $admin_access = user_access('administer users');
363
  $can_select_method = $admin_access || user_access('select account cancellation method');
364
  $form['user_cancel_method'] = array(
365
    '#type' => 'item',
366
    '#title' => ($account->uid == $user->uid ? t('When cancelling your account') : t('When cancelling the account')),
367
    '#access' => $can_select_method,
368
  );
369
  $form['user_cancel_method'] += user_cancel_methods();
370

    
371
  // Allow user administrators to skip the account cancellation confirmation
372
  // mail (by default), as long as they do not attempt to cancel their own
373
  // account.
374
  $override_access = $admin_access && ($account->uid != $user->uid);
375
  $form['user_cancel_confirm'] = array(
376
    '#type' => 'checkbox',
377
    '#title' => t('Require e-mail confirmation to cancel account.'),
378
    '#default_value' => ($override_access ? FALSE : TRUE),
379
    '#access' => $override_access,
380
    '#description' => t('When enabled, the user must confirm the account cancellation via e-mail.'),
381
  );
382
  // Also allow to send account canceled notification mail, if enabled.
383
  $default_notify = variable_get('user_mail_status_canceled_notify', FALSE);
384
  $form['user_cancel_notify'] = array(
385
    '#type' => 'checkbox',
386
    '#title' => t('Notify user when account is canceled.'),
387
    '#default_value' => ($override_access ? FALSE : $default_notify),
388
    '#access' => $override_access && $default_notify,
389
    '#description' => t('When enabled, the user will receive an e-mail notification after the account has been cancelled.'),
390
  );
391

    
392
  // Prepare confirmation form page title and description.
393
  if ($account->uid == $user->uid) {
394
    $question = t('Are you sure you want to cancel your account?');
395
  }
396
  else {
397
    $question = t('Are you sure you want to cancel the account %name?', array('%name' => $account->name));
398
  }
399
  $description = '';
400
  if ($can_select_method) {
401
    $description = t('Select the method to cancel the account above.');
402
    foreach (element_children($form['user_cancel_method']) as $element) {
403
      unset($form['user_cancel_method'][$element]['#description']);
404
    }
405
  }
406
  else {
407
    // The radio button #description is used as description for the confirmation
408
    // form.
409
    foreach (element_children($form['user_cancel_method']) as $element) {
410
      if ($form['user_cancel_method'][$element]['#default_value'] == $form['user_cancel_method'][$element]['#return_value']) {
411
        $description = $form['user_cancel_method'][$element]['#description'];
412
      }
413
      unset($form['user_cancel_method'][$element]['#description']);
414
    }
415
  }
416

    
417
  // Always provide entity id in the same form key as in the entity edit form.
418
  $form['uid'] = array('#type' => 'value', '#value' => $account->uid);
419
  return confirm_form($form,
420
    $question,
421
    'user/' . $account->uid,
422
    $description . ' ' . t('This action cannot be undone.'),
423
    t('Cancel account'), t('Cancel'));
424
}
425

    
426
/**
427
 * Submit handler for the account cancellation confirm form.
428
 *
429
 * @see user_cancel_confirm_form()
430
 * @see user_multiple_cancel_confirm_submit()
431
 */
432
function user_cancel_confirm_form_submit($form, &$form_state) {
433
  global $user;
434
  $account = $form_state['values']['_account'];
435

    
436
  // Cancel account immediately, if the current user has administrative
437
  // privileges, no confirmation mail shall be sent, and the user does not
438
  // attempt to cancel the own account.
439
  if (user_access('administer users') && empty($form_state['values']['user_cancel_confirm']) && $account->uid != $user->uid) {
440
    user_cancel($form_state['values'], $account->uid, $form_state['values']['user_cancel_method']);
441

    
442
    $form_state['redirect'] = 'admin/people';
443
  }
444
  else {
445
    // Store cancelling method and whether to notify the user in $account for
446
    // user_cancel_confirm().
447
    $edit = array(
448
      'user_cancel_method' => $form_state['values']['user_cancel_method'],
449
      'user_cancel_notify' => $form_state['values']['user_cancel_notify'],
450
    );
451
    $account = user_save($account, $edit);
452
    _user_mail_notify('cancel_confirm', $account);
453
    drupal_set_message(t('A confirmation request to cancel your account has been sent to your e-mail address.'));
454
    watchdog('user', 'Sent account cancellation request to %name %email.', array('%name' => $account->name, '%email' => '<' . $account->mail . '>'), WATCHDOG_NOTICE);
455

    
456
    $form_state['redirect'] = "user/$account->uid";
457
  }
458
}
459

    
460
/**
461
 * Helper function to return available account cancellation methods.
462
 *
463
 * See documentation of hook_user_cancel_methods_alter().
464
 *
465
 * @return
466
 *   An array containing all account cancellation methods as form elements.
467
 *
468
 * @see hook_user_cancel_methods_alter()
469
 * @see user_admin_settings()
470
 * @see user_cancel_confirm_form()
471
 * @see user_multiple_cancel_confirm()
472
 */
473
function user_cancel_methods() {
474
  $methods = array(
475
    'user_cancel_block' => array(
476
      'title' => t('Disable the account and keep its content.'),
477
      '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.'),
478
    ),
479
    'user_cancel_block_unpublish' => array(
480
      'title' => t('Disable the account and unpublish its content.'),
481
      '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.'),
482
    ),
483
    'user_cancel_reassign' => array(
484
      'title' => t('Delete the account and make its content belong to the %anonymous-name user.', array('%anonymous-name' => variable_get('anonymous', t('Anonymous')))),
485
      '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')))),
486
    ),
487
    'user_cancel_delete' => array(
488
      'title' => t('Delete the account and its content.'),
489
      'description' => t('Your account will be removed and all account information deleted. All of your content will also be deleted.'),
490
      'access' => user_access('administer users'),
491
    ),
492
  );
493
  // Allow modules to customize account cancellation methods.
494
  drupal_alter('user_cancel_methods', $methods);
495

    
496
  // Turn all methods into real form elements.
497
  $default_method = variable_get('user_cancel_method', 'user_cancel_block');
498
  foreach ($methods as $name => $method) {
499
    $form[$name] = array(
500
      '#type' => 'radio',
501
      '#title' => $method['title'],
502
      '#description' => (isset($method['description']) ? $method['description'] : NULL),
503
      '#return_value' => $name,
504
      '#default_value' => $default_method,
505
      '#parents' => array('user_cancel_method'),
506
    );
507
  }
508
  return $form;
509
}
510

    
511
/**
512
 * Menu callback; Cancel a user account via e-mail confirmation link.
513
 *
514
 * @see user_cancel_confirm_form()
515
 * @see user_cancel_url()
516
 */
517
function user_cancel_confirm($account, $timestamp = 0, $hashed_pass = '') {
518
  // Time out in seconds until cancel URL expires; 24 hours = 86400 seconds.
519
  $timeout = 86400;
520
  $current = REQUEST_TIME;
521

    
522
  // Basic validation of arguments.
523
  if (isset($account->data['user_cancel_method']) && !empty($timestamp) && !empty($hashed_pass)) {
524
    // Validate expiration and hashed password/login.
525
    if ($timestamp <= $current && $current - $timestamp < $timeout && $account->uid && $timestamp >= $account->login && $hashed_pass == user_pass_rehash($account->pass, $timestamp, $account->login, $account->uid)) {
526
      $edit = array(
527
        'user_cancel_notify' => isset($account->data['user_cancel_notify']) ? $account->data['user_cancel_notify'] : variable_get('user_mail_status_canceled_notify', FALSE),
528
      );
529
      user_cancel($edit, $account->uid, $account->data['user_cancel_method']);
530
      // Since user_cancel() is not invoked via Form API, batch processing needs
531
      // to be invoked manually and should redirect to the front page after
532
      // completion.
533
      batch_process('');
534
    }
535
    else {
536
      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.'), 'error');
537
      drupal_goto("user/$account->uid/cancel");
538
    }
539
  }
540
  return MENU_ACCESS_DENIED;
541
}
542

    
543
/**
544
 * Page callback: Displays the user page.
545
 *
546
 * Displays user profile if user is logged in, or login form for anonymous
547
 * users.
548
 *
549
 * @return
550
 *   A render array for either a user profile or a login form.
551
 *
552
 * @see user_view_page()
553
 * @see user_login()
554
 */
555
function user_page() {
556
  global $user;
557
  if ($user->uid) {
558
    menu_set_active_item('user/' . $user->uid);
559
    return menu_execute_active_handler(NULL, FALSE);
560
  }
561
  else {
562
    return drupal_get_form('user_login');
563
  }
564
}