user.api.php 15.7 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 21 22 23 24 25 26 27 28 29
/**
 * 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.
 *
 * @param \Drupal\user\Plugin\Core\Entity\User $user
 *   The user object.
 */
function hook_user_create(\Drupal\user\Plugin\Core\Entity\User $user) {
  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 55
 * This hook is invoked from user_delete_multiple() before
 * field_attach_delete() is called and before the user is actually removed from
 * the database.
56
 *
57 58 59
 * Modules should additionally implement hook_user_cancel() to process stored
 * user data for other account cancellation methods.
 *
60
 * @param $account
61
 *   The account that is about to be deleted.
62
 *
63
 * @see hook_user_delete()
64 65
 * @see user_delete_multiple()
 */
66
function hook_user_predelete($account) {
67 68 69 70 71
  db_delete('mytable')
    ->condition('uid', $account->uid)
    ->execute();
}

72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
/**
 * Respond to user deletion.
 *
 * This hook is invoked from user_delete_multiple() after field_attach_delete()
 * has been called and after the user has been removed from the database.
 *
 * 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) {
  drupal_set_message(t('User: @name has been deleted.', array('@name' => $account->name)));
}

91 92 93
/**
 * Act on user account cancellations.
 *
94 95 96 97 98 99 100
 * 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
101 102
 * method. To react to that method, implement hook_user_predelete() or
 * hook_user_delete() instead.
103
 *
104 105
 * Expensive operations should be added to the global account cancellation batch
 * by using batch_set().
106
 *
107
 * @param $edit
108
 *   The array of form values submitted by the user.
109
 * @param $account
110 111 112 113 114 115 116
 *   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()
 */
117
function hook_user_cancel($edit, $account, $method) {
118 119 120 121
  switch ($method) {
    case 'user_cancel_block_unpublish':
      // Unpublish nodes (current revisions).
      module_load_include('inc', 'node', 'node.admin');
122 123 124 125 126
      $nodes = db_select('node', 'n')
        ->fields('n', array('nid'))
        ->condition('uid', $account->uid)
        ->execute()
        ->fetchCol();
127 128 129 130 131 132
      node_mass_update($nodes, array('status' => 0));
      break;

    case 'user_cancel_reassign':
      // Anonymize nodes (current revisions).
      module_load_include('inc', 'node', 'node.admin');
133 134 135 136 137
      $nodes = db_select('node', 'n')
        ->fields('n', array('nid'))
        ->condition('uid', $account->uid)
        ->execute()
        ->fetchCol();
138 139
      node_mass_update($nodes, array('uid' => 0));
      // Anonymize old revisions.
140 141 142 143
      db_update('node_revision')
        ->fields(array('uid' => 0))
        ->condition('uid', $account->uid)
        ->execute();
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
      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
161 162
 *   a method. If 'access' is defined, the method cannot be configured as
 *   default method.
163
 *
164
 * @param $methods
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
 *   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) {
  // Limit access to disable account and unpublish content method.
  $methods['user_cancel_block_unpublish']['access'] = user_access('administer site configuration');

  // 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.
    'access' => user_access('access zero-out account cancellation method'),
  );
}

186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
/**
 * 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.
  if (isset($account->uid)) {
    $name = t('User !uid', array('!uid' => $account->uid));
  }
}

208 209 210 211
/**
 * Add mass user operations.
 *
 * This hook enables modules to inject custom operations into the mass operations
212
 * dropdown found at admin/people, by associating a callback function with
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
 * the operation, which is called when the form is submitted. The callback function
 * receives one initial argument, which is an array of the checked users.
 *
 * @return
 *   An array of operations. Each operation is an associative array that may
 *   contain the following key-value pairs:
 *   - "label": Required. The label for the operation, displayed in the dropdown menu.
 *   - "callback": Required. The function to call for the operation.
 *   - "callback arguments": Optional. An array of additional arguments to pass to
 *     the callback function.
 *
 */
function hook_user_operations() {
  $operations = array(
    'unblock' => array(
      'label' => t('Unblock the selected users'),
      'callback' => 'user_user_operations_unblock',
    ),
    'block' => array(
      'label' => t('Block the selected users'),
      'callback' => 'user_user_operations_block',
    ),
235 236
    'cancel' => array(
      'label' => t('Cancel the selected user accounts'),
237 238 239 240 241
    ),
  );
  return $operations;
}

242
/**
243
 * Act on a user account being inserted or updated.
244
 *
245 246
 * This hook is invoked before the user account is saved to the database.
 *
247
 * @param $account
248
 *   The user account object.
249 250 251 252
 *
 * @see hook_user_insert()
 * @see hook_user_update()
 */
253
function hook_user_presave($account) {
254
  // Ensure that our value is an array.
255
  if (isset($account->mymodule_foo)) {
256
    $account->mymodule_foo = (array) $account->mymodule_foo;
257 258 259 260
  }
}

/**
261
 * Respond to creation of a new user account.
262
 *
263 264
 * 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
265 266 267 268 269 270
 * transaction is not finalized until the insert operation is entirely completed
 * and \Drupal\user\DataStorageController::save() goes out of scope. You should
 * 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
 * are also not committed immediately. Check \Drupal\user\DataStorageController::save()
 * and db_transaction() for more info.
271
 *
272
 * @param $account
273
 *   The user account object.
274 275 276
 *
 * @see hook_user_presave()
 * @see hook_user_update()
277
 */
278 279
function hook_user_insert($account) {
  db_insert('user_changes')
280 281
    ->fields(array(
      'uid' => $account->uid,
282
      'created' => time(),
283 284 285 286
    ))
    ->execute();
}

287
/**
288
 * Respond to updates to a user account.
289
 *
290 291
 * 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
292 293 294 295 296 297
 * transaction is not finalized until the update operation is entirely completed
 * and \Drupal\user\DataStorageController::save() goes out of scope. You should 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 are
 * also not committed immediately. Check \Drupal\user\DataStorageController::save()
 * and db_transaction() for more info.
298
 *
299
 * @param $account
300
 *   The user account object.
301 302 303 304
 *
 * @see hook_user_presave()
 * @see hook_user_insert()
 */
305
function hook_user_update($account) {
306 307 308 309 310 311 312 313
  db_insert('user_changes')
    ->fields(array(
      'uid' => $account->uid,
      'changed' => time(),
    ))
    ->execute();
}

314 315 316 317 318 319
/**
 * The user just logged in.
 *
 * @param $account
 *   The user object on which the operation was just performed.
 */
320
function hook_user_login($account) {
321
  $config = config('system.timezone');
322
  // If the user has a NULL time zone, notify them to set a time zone.
323
  if (!$account->timezone && $config->get('user.configurable') && $config->get('user.warn')) {
324
    drupal_set_message(t('Configure your <a href="@user-edit">account time zone setting</a>.', array('@user-edit' => url("user/$account->uid/edit", array('query' => drupal_get_destination(), 'fragment' => 'edit-timezone')))));
325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348
  }
}

/**
 * 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(
      'uid' => $account->uid,
      '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
 * $account->content array.
 *
349
 * @param \Drupal\user\Plugin\Core\Entity\User $account
350
 *   The user object on which the operation is being performed.
351 352 353
 * @param \Drupal\entity\Plugin\Core\Entity\EntityDisplay $display
 *   The entity_display object holding the display options configured for the
 *   user components.
354 355
 * @param $view_mode
 *   View mode, e.g. 'full'.
356 357
 * @param $langcode
 *   The language code used for rendering.
358 359 360
 *
 * @see hook_user_view_alter()
 * @see hook_entity_view()
361
 */
362 363 364 365 366 367 368 369 370
function hook_user_view(\Drupal\user\Plugin\Core\Entity\User $account, \Drupal\entity\Plugin\Core\Entity\EntityDisplay $display, $view_mode, $langcode) {
  // 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
  // user entity type in hook_field_extra_fields().
  if ($display->getComponent('mymodule_addition')) {
    $account->content['mymodule_addition'] = array(
      '#markup' => mymodule_addition($account),
      '#theme' => 'mymodule_my_additional_field',
    );
371
  }
372
}
373

374 375 376 377 378 379 380 381 382
/**
 * 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.
383
 * Alternatively, it could also implement hook_preprocess_HOOK() for
384
 * user.tpl.php. See drupal_render() and theme() documentation
385
 * respectively for details.
386 387 388
 *
 * @param $build
 *   A renderable array representing the user.
389
 * @param \Drupal\user\Plugin\Core\Entity\User $account
390
 *   The user account being rendered.
391 392 393
 * @param \Drupal\entity\Plugin\Core\Entity\EntityDisplay $display
 *   The entity_display object holding the display options configured for the
 *   user components.
394
 *
395
 * @see user_view()
396
 * @see hook_entity_view_alter()
397
 */
398
function hook_user_view_alter(&$build, \Drupal\user\Plugin\Core\Entity\User $account, \Drupal\entity\Plugin\Core\Entity\EntityDisplay $display) {
399 400 401 402 403 404 405 406 407 408
  // 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';
}

409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427
/**
 * Inform other modules that a user role is about to be saved.
 *
 * 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();
  }
}

428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
/**
 * Inform other modules that a user role has been added.
 *
 * 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(
443
      'rid' => $role->rid,
444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462
      'role_description' => $role->description,
    ))
    ->execute();
}

/**
 * Inform other modules that a user role has been updated.
 *
 * 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')
463
    ->key(array('rid' => $role->rid))
464 465 466 467 468 469 470 471 472 473
    ->fields(array(
      'role_description' => $role->description
    ))
    ->execute();
}

/**
 * Inform other modules that a user role has been deleted.
 *
 * This hook allows you act when a user role has been deleted.
474
 * If your module stores references to roles, it's recommended that you
475 476 477 478 479 480 481 482 483
 * 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')
484
    ->condition('rid', $role->rid)
485 486 487
    ->execute();
}

488 489 490
/**
 * @} End of "addtogroup hooks".
 */