user.api.php 14.5 KB
Newer Older
1 2
<?php

3
use Drupal\Core\Entity\EntityInterface;
4

5 6 7 8 9 10 11 12 13 14
/**
 * @file
 * Hooks provided by the User module.
 */

/**
 * @addtogroup hooks
 * @{
 */

15 16 17 18 19 20
/**
 * Act on a newly created user.
 *
 * This hook runs after a new user object has just been instantiated. It can be
 * used to set initial values, e.g. to provide defaults.
 *
21
 * @param \Drupal\user\UserInterface $user
22 23
 *   The user object.
 */
24
function hook_user_create(\Drupal\user\Entity\User $user) {
25 26 27 28 29
  if (!isset($user->foo)) {
    $user->foo = 'some_initial_value';
  }
}

30 31 32 33 34 35 36 37 38 39 40 41 42 43
/**
 * Act on user objects when loaded from the database.
 *
 * Due to the static cache in user_load_multiple() you should not use this
 * hook to modify the user properties returned by the {users} table itself
 * since this may result in unreliable results when loading from cache.
 *
 * @param $users
 *   An array of user objects, indexed by uid.
 *
 * @see user_load_multiple()
 * @see profile_user_load()
 */
function hook_user_load($users) {
44
  $result = db_query('SELECT uid, foo FROM {my_table} WHERE uid IN (:uids)', array(':uids' => array_keys($users)));
45
  foreach ($result as $record) {
46
    $users[$record->uid]->foo = $record->foo;
47 48
  }
}
49

50
/**
51
 * Act before user deletion.
52
 *
53 54
 * This hook is invoked from user_delete_multiple() before field values are
 * deleted and before the user is actually removed from the database.
55
 *
56 57 58
 * Modules should additionally implement hook_user_cancel() to process stored
 * user data for other account cancellation methods.
 *
59
 * @param $account
60
 *   The account that is about to be deleted.
61
 *
62
 * @see hook_user_delete()
63 64
 * @see user_delete_multiple()
 */
65
function hook_user_predelete($account) {
66
  db_delete('mytable')
67
    ->condition('uid', $account->id())
68 69 70
    ->execute();
}

71 72 73
/**
 * Respond to user deletion.
 *
74 75
 * This hook is invoked from user_delete_multiple() after field values are
 * deleted and after the user has been removed from the database.
76 77 78 79 80 81 82 83 84 85 86
 *
 * Modules should additionally implement hook_user_cancel() to process stored
 * user data for other account cancellation methods.
 *
 * @param $account
 *   The account that has been deleted.
 *
 * @see hook_user_predelete()
 * @see user_delete_multiple()
 */
function hook_user_delete($account) {
87
  drupal_set_message(t('User: @name has been deleted.', array('@name' => $account->getUsername())));
88 89
}

90 91 92
/**
 * Act on user account cancellations.
 *
93 94 95 96 97 98 99
 * This hook is invoked from user_cancel() before a user account is canceled.
 * Depending on the account cancellation method, the module should either do
 * nothing, unpublish content, or anonymize content. See user_cancel_methods()
 * for the list of default account cancellation methods provided by User module.
 * Modules may add further methods via hook_user_cancel_methods_alter().
 *
 * This hook is NOT invoked for the 'user_cancel_delete' account cancellation
100 101
 * method. To react to that method, implement hook_user_predelete() or
 * hook_user_delete() instead.
102
 *
103 104
 * Expensive operations should be added to the global account cancellation batch
 * by using batch_set().
105
 *
106
 * @param $edit
107
 *   The array of form values submitted by the user.
108
 * @param $account
109 110 111 112 113 114 115
 *   The user object on which the operation is being performed.
 * @param $method
 *   The account cancellation method.
 *
 * @see user_cancel_methods()
 * @see hook_user_cancel_methods_alter()
 */
116
function hook_user_cancel($edit, $account, $method) {
117 118 119 120
  switch ($method) {
    case 'user_cancel_block_unpublish':
      // Unpublish nodes (current revisions).
      module_load_include('inc', 'node', 'node.admin');
121 122 123
      $nodes = \Drupal::entityQuery('node')
        ->condition('uid', $user->id())
        ->execute();
124
      node_mass_update($nodes, array('status' => 0), NULL, TRUE);
125 126 127 128 129
      break;

    case 'user_cancel_reassign':
      // Anonymize nodes (current revisions).
      module_load_include('inc', 'node', 'node.admin');
130 131 132
      $nodes = \Drupal::entityQuery('node')
        ->condition('uid', $user->id())
        ->execute();
133
      node_mass_update($nodes, array('uid' => 0), NULL, TRUE);
134
      // Anonymize old revisions.
135
      db_update('node_field_revision')
136
        ->fields(array('uid' => 0))
137
        ->condition('uid', $account->id())
138
        ->execute();
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
      break;
  }
}

/**
 * Modify account cancellation methods.
 *
 * By implementing this hook, modules are able to add, customize, or remove
 * account cancellation methods. All defined methods are turned into radio
 * button form elements by user_cancel_methods() after this hook is invoked.
 * The following properties can be defined for each method:
 * - title: The radio button's title.
 * - description: (optional) A description to display on the confirmation form
 *   if the user is not allowed to select the account cancellation method. The
 *   description is NOT used for the radio button, but instead should provide
 *   additional explanation to the user seeking to cancel their account.
 * - access: (optional) A boolean value indicating whether the user can access
156 157
 *   a method. If 'access' is defined, the method cannot be configured as
 *   default method.
158
 *
159
 * @param $methods
160 161 162 163 164 165
 *   An array containing user account cancellation methods, keyed by method id.
 *
 * @see user_cancel_methods()
 * @see user_cancel_confirm_form()
 */
function hook_user_cancel_methods_alter(&$methods) {
166
  $account = \Drupal::currentUser();
167
  // Limit access to disable account and unpublish content method.
168
  $methods['user_cancel_block_unpublish']['access'] = $account->hasPermission('administer site configuration');
169 170 171 172 173 174 175 176 177

  // Remove the content re-assigning method.
  unset($methods['user_cancel_reassign']);

  // Add a custom zero-out method.
  $methods['mymodule_zero_out'] = array(
    'title' => t('Delete the account and remove all content.'),
    'description' => t('All your content will be replaced by empty strings.'),
    // access should be used for administrative methods only.
178
    'access' => $account->hasPermission('access zero-out account cancellation method'),
179 180 181
  );
}

182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198
/**
 * Alter the username that is displayed for a user.
 *
 * Called by user_format_name() to allow modules to alter the username that's
 * displayed. Can be used to ensure user privacy in situations where
 * $account->name is too revealing.
 *
 * @param $name
 *   The string that user_format_name() will return.
 *
 * @param $account
 *   The account object passed to user_format_name().
 *
 * @see user_format_name()
 */
function hook_user_format_name_alter(&$name, $account) {
  // Display the user's uid instead of name.
199 200
  if ($account->id()) {
    $name = t('User !uid', array('!uid' => $account->id()));
201 202 203
  }
}

204
/**
205
 * Act on a user account being inserted or updated.
206
 *
207 208
 * This hook is invoked before the user account is saved to the database.
 *
209
 * @param $account
210
 *   The user account object.
211 212 213 214
 *
 * @see hook_user_insert()
 * @see hook_user_update()
 */
215
function hook_user_presave($account) {
216
  // Ensure that our value is an array.
217
  if (isset($account->mymodule_foo)) {
218
    $account->mymodule_foo = (array) $account->mymodule_foo;
219 220 221 222
  }
}

/**
223
 * Respond to creation of a new user account.
224
 *
225 226
 * Note that when this hook is invoked, the changes have not yet been written to
 * the database, because a database transaction is still in progress. The
227
 * transaction is not finalized until the insert operation is entirely completed
228
 * and \Drupal\user\DataStorage::save() goes out of scope. You should
229 230
 * not rely on data in the database at this time as it is not updated yet. You
 * should also note that any write/update database queries executed from this hook
231
 * are also not committed immediately. Check \Drupal\user\DataStorage::save()
232
 * and db_transaction() for more info.
233
 *
234
 * @param $account
235
 *   The user account object.
236 237 238
 *
 * @see hook_user_presave()
 * @see hook_user_update()
239
 */
240 241
function hook_user_insert($account) {
  db_insert('user_changes')
242
    ->fields(array(
243
      'uid' => $account->id(),
244
      'created' => time(),
245 246 247 248
    ))
    ->execute();
}

249
/**
250
 * Respond to updates to a user account.
251
 *
252 253
 * Note that when this hook is invoked, the changes have not yet been written to
 * the database, because a database transaction is still in progress. The
254
 * transaction is not finalized until the update operation is entirely completed
255
 * and \Drupal\user\DataStorage::save() goes out of scope. You should not
256 257
 * rely on data in the database at this time as it is not updated yet. You should
 * also note that any write/update database queries executed from this hook are
258
 * also not committed immediately. Check \Drupal\user\DataStorage::save()
259
 * and db_transaction() for more info.
260
 *
261
 * @param $account
262
 *   The user account object.
263 264 265 266
 *
 * @see hook_user_presave()
 * @see hook_user_insert()
 */
267
function hook_user_update($account) {
268 269
  db_insert('user_changes')
    ->fields(array(
270
      'uid' => $account->id(),
271 272 273 274 275
      'changed' => time(),
    ))
    ->execute();
}

276 277 278 279 280 281
/**
 * The user just logged in.
 *
 * @param $account
 *   The user object on which the operation was just performed.
 */
282
function hook_user_login($account) {
283
  $config = \Drupal::config('system.date');
284
  // If the user has a NULL time zone, notify them to set a time zone.
285
  if (!$account->getTimezone() && $config->get('timezone.user.configurable') && $config->get('timezone.user.warn')) {
286
    drupal_set_message(t('Configure your <a href="@user-edit">account time zone setting</a>.', array('@user-edit' => url("user/" . $account->id() . "/edit", array('query' => drupal_get_destination(), 'fragment' => 'edit-timezone')))));
287 288 289 290 291 292 293 294 295 296 297 298
  }
}

/**
 * The user just logged out.
 *
 * @param $account
 *   The user object on which the operation was just performed.
 */
function hook_user_logout($account) {
  db_insert('logouts')
    ->fields(array(
299
      'uid' => $account->id(),
300 301 302 303 304 305 306 307 308
      'time' => time(),
    ))
    ->execute();
}

/**
 * The user's account information is being displayed.
 *
 * The module should format its custom additions for display and add them to the
309
 * $build array.
310
 *
311 312
 * @param array &$build
 *   A renderable array representing the user content.
313
 * @param \Drupal\user\UserInterface $account
314
 *   The user object on which the operation is being performed.
315
 * @param \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display
316 317
 *   The entity view display holding the display options configured for the user
 *   components.
318 319
 * @param $view_mode
 *   View mode, e.g. 'full'.
320 321
 * @param $langcode
 *   The language code used for rendering.
322 323 324
 *
 * @see hook_user_view_alter()
 * @see hook_entity_view()
325
 */
326
function hook_user_view(array &$build, \Drupal\user\UserInterface $account, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display, $view_mode, $langcode) {
327 328
  // Only do the extra work if the component is configured to be displayed.
  // This assumes a 'mymodule_addition' extra field has been defined for the
329
  // user entity type in hook_entity_extra_field_info().
330
  if ($display->getComponent('mymodule_addition')) {
331
    $build['mymodule_addition'] = array(
332 333 334
      '#markup' => mymodule_addition($account),
      '#theme' => 'mymodule_my_additional_field',
    );
335
  }
336
}
337

338 339 340 341 342 343 344 345 346
/**
 * The user was built; the module may modify the structured content.
 *
 * This hook is called after the content has been assembled in a structured array
 * and may be used for doing processing which requires that the complete user
 * content structure has been built.
 *
 * If the module wishes to act on the rendered HTML of the user rather than the
 * structured content array, it may use this hook to add a #post_render callback.
347
 * Alternatively, it could also implement hook_preprocess_HOOK() for
348
 * user.html.twig. See drupal_render() and _theme() documentation
349
 * respectively for details.
350
 *
351
 * @param array &$build
352
 *   A renderable array representing the user.
353
 * @param \Drupal\user\UserInterface $account
354
 *   The user account being rendered.
355
 * @param \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display
356 357
 *   The entity view display holding the display options configured for the user
 *   components.
358
 *
359
 * @see user_view()
360
 * @see hook_entity_view_alter()
361
 */
362
function hook_user_view_alter(array &$build, \Drupal\user\UserInterface $account, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display) {
363 364 365 366 367 368 369 370 371 372
  // Check for the existence of a field added by another module.
  if (isset($build['an_additional_field'])) {
    // Change its weight.
    $build['an_additional_field']['#weight'] = -10;
  }

  // Add a #post_render callback to act on the rendered HTML of the user.
  $build['#post_render'][] = 'my_module_user_post_render';
}

373
/**
374
 * Act on a user role being inserted or updated.
375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391
 *
 * Modules implementing this hook can act on the user role object before
 * it has been saved to the database.
 *
 * @param $role
 *   A user role object.
 *
 * @see hook_user_role_insert()
 * @see hook_user_role_update()
 */
function hook_user_role_presave($role) {
  // Set a UUID for the user role if it doesn't already exist
  if (empty($role->uuid)) {
    $role->uuid = uuid_uuid();
  }
}

392
/**
393
 * Respond to creation of a new user role.
394 395 396 397 398 399 400 401 402 403 404 405 406
 *
 * Modules implementing this hook can act on the user role object when saved to
 * the database. It's recommended that you implement this hook if your module
 * adds additional data to user roles object. The module should save its custom
 * additions to the database.
 *
 * @param $role
 *   A user role object.
 */
function hook_user_role_insert($role) {
  // Save extra fields provided by the module to user roles.
  db_insert('my_module_table')
    ->fields(array(
407
      'rid' => $role->id(),
408 409 410 411 412 413
      'role_description' => $role->description,
    ))
    ->execute();
}

/**
414
 * Respond to updates to a user role.
415 416 417 418 419 420 421 422 423 424 425 426
 *
 * Modules implementing this hook can act on the user role object when updated.
 * It's recommended that you implement this hook if your module adds additional
 * data to user roles object. The module should save its custom additions to
 * the database.
 *
 * @param $role
 *   A user role object.
 */
function hook_user_role_update($role) {
  // Save extra fields provided by the module to user roles.
  db_merge('my_module_table')
427
    ->key('rid', $role->id())
428 429 430 431 432 433 434
    ->fields(array(
      'role_description' => $role->description
    ))
    ->execute();
}

/**
435
 * Respond to user role deletion.
436 437
 *
 * This hook allows you act when a user role has been deleted.
438
 * If your module stores references to roles, it's recommended that you
439 440 441 442 443 444 445 446 447
 * implement this hook and delete existing instances of the deleted role
 * in your module database tables.
 *
 * @param $role
 *   The $role object being deleted.
 */
function hook_user_role_delete($role) {
  // Delete existing instances of the deleted role.
  db_delete('my_module_table')
448
    ->condition('rid', $role->id())
449 450 451
    ->execute();
}

452 453 454
/**
 * @} End of "addtogroup hooks".
 */