Projet

Général

Profil

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

root / drupal7 / modules / user / user.pages.inc @ f7a2490e

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'))));
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.'));
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.'));
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)) {
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.'));
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
 * The $variables array contains the following arguments:
187
 * - $account
188
 *
189
 * @see user-profile.tpl.php
190
 */
191
function template_preprocess_user_profile(&$variables) {
192
  $account = $variables['elements']['#account'];
193

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

    
199
  // Preprocess fields.
200
  field_attach_preprocess('user', $account, $variables['elements'], $variables);
201
}
202

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

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

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

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

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

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

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

    
286
  $form['#validate'][] = 'user_profile_form_validate';
287
  // Add the final user profile form submit handler.
288
  $form['#submit'][] = 'user_profile_form_submit';
289

    
290
  return $form;
291
}
292

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

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

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

    
315
  entity_form_submit_build_entity('user', $account, $form, $form_state);
316

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

    
321
  user_save($account_unchanged, $edit, $category);
322
  $form_state['values']['uid'] = $account->uid;
323

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

    
331
  drupal_set_message(t('The changes have been saved.'));
332
}
333

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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