realname.module 13 KB
Newer Older
1
<?php
2

3 4 5 6
/**
 * @file
 * Provides token-based name displays for users.
 *
7
 * @todo Add a 'view realname' permission enabled by default
8 9 10 11 12 13 14
 * @todo Allow users to login with their real name
 * @todo Disable the username field
 */

/**
 * @defgroup realname Real name API
 */
15

NancyDru's avatar
NancyDru committed
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
/**
 * Implements hook_help().
 */
function realname_help($path, $arg) {
  switch ($path) {
    // Main module help for the Realname module.
    case 'admin/config/people/realname':
    case 'admin/help#realname':
      return '<p>' 
        . t('A Real Name is what the site developer decides that users\' names 
        should look like. It is constructed from various tokens that are available 
        within the site.')
        . '</p>';
  }
}

32
/**
33
 * Implements hook_permission().
34
 */
35
function realname_permission() {
36 37 38 39 40
  return array(
    'administer realname' => array(
      'title' => t('Administer Real Name'),
      'description' => t('Allows users to administer realname settings.'),
    ),
41 42
  );
}
43

44
/**
45
 * Implements hook_menu().
46
 */
47 48 49
function realname_menu() {
  $items['admin/config/people/realname'] = array(
    'title' => 'Real name',
50
    'description' => 'Use tokens to configure how user names are displayed.',
51 52 53 54 55
    'page callback' => 'drupal_get_form',
    'page arguments' => array('realname_settings_form'),
    'access arguments' => array('administer realname'),
    'file' => 'realname.admin.inc',
  );
56

57 58
  $items['realname/autocomplete'] = array(
    'page callback' => 'realname_autocomplete',
59
    'page arguments' => array('', '', 2),
60 61 62
    'access arguments' => array('access user profiles'),
    'type' => MENU_CALLBACK,
  );
63 64 65 66 67 68 69
  $items['realname/autocomplete/%/%/%'] = array(
    'page callback' => 'realname_autocomplete',
    'page arguments' => array(2, 3, 4),
    'access callback' => 'realname_autocomplete_access_callback',
    'access arguments' => array(2, 3, 4),
    'type' => MENU_CALLBACK,
  );
70

71
  return $items;
72 73
}

74
/**
75
 * Implements hook_menu_alter() to replace user autocomplete with realname autocomplete.
76 77 78 79
 */
function realname_menu_alter(&$items) {
  // Implement realname autocomplete.
  $items['user/autocomplete']['page callback'] = 'realname_autocomplete';
80
  $items['user/autocomplete']['page arguments'] = array('', '', 2);
81 82
}

83
/**
84
 * Implements hook_username_alter().
85
 */
86
function realname_username_alter(&$name, $account) {
87
  static $in_username_alter = FALSE;
88

89 90 91 92 93 94
  if (empty($account->uid)) {
    // Don't alter anonymous users or objects that do not have any user ID.
    return;
  }

  // Real name was loaded/generated via hook_user_load(), so re-use it.
95
  if (isset($account->realname)) {
96
    if (drupal_strlen($account->realname)) {
97
      // Only if the real name is a non-empty string is $name actually altered.
98 99
      $name = $account->realname;
    }
100
    return;
101
  }
102 103 104 105

  // Real name was not yet available for the account so we need to generate it.
  // Because tokens may call format_username() we need to prevent recursion.
  if (!$in_username_alter) {
106
    $in_username_alter = TRUE;
107 108

    // If $account->realname was undefined, then the user account object was
109 110 111
    // not properly loaded. We must enforce calling user_load().
    if ($realname_account = user_load($account->uid)) {
      realname_username_alter($name, $realname_account);
112
    }
113

114
    $in_username_alter = FALSE;
115
  }
116 117 118
}

/**
119
 * Implements hook_user_load().
120
 */
121
function realname_user_load($accounts) {
122 123 124
  $realnames = realname_load_multiple($accounts);
  foreach ($realnames as $uid => $realname) {
    $accounts[$uid]->realname = $realname;
125 126 127 128
  }
}

/**
129
 * Implements hook_user_update().
130
 */
131
function realname_user_update(&$edit, $account, $category) {
132 133
  // Since user data may have changed, update the realname.
  realname_update($account);
134 135
}

136 137 138 139 140 141 142 143 144 145
/**
 * Implements hook_profile2_update().
 */
function realname_profile2_update($profile) {
  $account = user_load($profile->uid);
  if (is_object($account)) {
    realname_update($account);
  }
}

146 147 148
/**
 * Implements hook_user_delete().
 */
149
function realname_user_delete($account) {
150 151
  realname_delete($account->uid);
}
152

153 154 155 156 157 158 159 160 161 162 163 164 165 166
/**
 * Implements hook_user_operations().
 */
function realname_user_operations() {
  $operations['realname_update'] = array(
    'label' => t('Update real name'),
    'callback' => 'realname_user_operations_realname_update',
  );
  return $operations;
}

/**
 * Callback function for admin mass generating user real names.
 *
167
 * @param array $uids
168 169
 *   An array of user IDs.
 */
170
function realname_user_operations_realname_update($uids) {
171 172
  $accounts = user_load_multiple($uids);
  foreach ($accounts as $account) {
173
    realname_update($account);
174 175 176
  }
}

177 178 179 180 181 182 183 184 185 186 187 188 189
/**
 * Implements hook_action_info().
 */
function realname_action_info() {
  $info['realname_action_realname_update'] = array(
    'type' => 'user',
    'label' => t('Update real name'),
    'configurable' => FALSE,
  );

  return $info;
}

190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209
/**
 * Implements hook_rules_action_info().
 */
function realname_rules_action_info() {
  $items['user_realname_update'] = array(
    'label' => t('Update real name'),
    'base' => 'realname_action_realname_update',
    'parameter' => array(
      'account' => array(
        'type' => 'user',
        'label' => t('User'),
        'save' => FALSE,
      ),
    ),
    'group' => t('User'),
    'access callback' => 'rules_user_integration_access',
  );
  return $items;
}

210 211 212 213
/**
 * Action callback to update a user's realname.
 */
function realname_action_realname_update($account, $context = array()) {
214
  realname_update($account);
215 216
}

217 218 219 220 221 222 223
/**
 * Implements hook_views_api().
 */
function realname_views_api() {
  return array('api' => 3);
}

224 225 226 227 228
/**
 * @addtogroup realname
 * @{
 */

229
/**
230
 * Loads a real name.
231
 *
232
 * @param object $uid
233
 *   A user account object.
234
 * @return string
235
 *   The user's generated real name.
236
 */
237
function realname_load($account) {
238 239 240
  $realnames = realname_load_multiple(array($account->uid => $account));
  return reset($realnames);
}
241

242 243 244
/**
 * Loads multiple real names.
 *
245
 * @param array $accounts
246
 *   An array of user account objects keyed by user ID.
247
 * @return array
248 249
 *   An array of real names keyed by user ID.
 */
250
function realname_load_multiple($accounts) {
251 252 253 254 255 256 257 258 259
  $realnames = &drupal_static(__FUNCTION__, array());

  if ($new_accounts = array_diff_key($accounts, $realnames)) {
    // Attempt to fetch realnames from the database first.
    $realnames += db_query("SELECT uid, realname FROM {realname} WHERE uid IN (:uids)", array(':uids' => array_keys($new_accounts)))->fetchAllKeyed();

    // For each account that was not present in the database, generate its
    // real name.
    foreach ($new_accounts as $uid => $account) {
260
      if (!isset($realnames[$uid])) {
261
        $realnames[$uid] = realname_update($account);
262
      }
263
    }
264 265
  }

266
  return array_intersect_key($realnames, $accounts);
267 268
}

269 270 271
/**
 * Update the realname for a user account.
 *
272
 * @param object $account
273 274 275 276 277 278 279 280 281 282 283 284
 *   A user account object.
 *
 * @see hook_realname_pattern_alter()
 * @see hook_realname_alter()
 * @see hook_realname_update()
 */
function realname_update($account) {
  // Get the default pattern and allow other modules to alter it.
  $pattern = variable_get('realname_pattern', '[user:name-raw]');
  drupal_alter('realname_pattern', $pattern, $account);

  // Perform token replacement on the real name pattern.
285
  $realname = token_replace($pattern, array('user' => $account), array('clear' => TRUE, 'sanitize' => FALSE));
286 287 288 289 290 291

  // Remove any HTML tags.
  $realname = strip_tags(decode_entities($realname));

  // Remove double spaces (if a token had no value).
  $realname = preg_replace('/ {2,}/', ' ', $realname);
292 293

  // The name must be trimmed to 255 characters before inserting into the database.
294
  $realname = truncate_utf8(trim($realname), 255);
295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314

  // Allow other modules to alter the generated realname.
  drupal_alter('realname', $realname, $account);

  // Save to the database and the static cache.
  db_merge('realname')
    ->key(array('uid' => $account->uid))
    ->fields(array(
      'realname' => $realname,
      'created' => REQUEST_TIME,
    ))
    ->execute();

  // Allow modules to react to the realname being updated.
  module_invoke_all('realname_update', $realname, $account);

  $account->realname = $realname;
  return $realname;
}

315
/**
316
 * Delete a real name.
317
 *
318
 * @param int $uid
319
 *   A user ID.
320
 */
321 322
function realname_delete($uid) {
  return realname_delete_multiple(array($uid));
323 324 325
}

/**
326 327
 * Delete multiple real names.
 *
328
 * @param array $uids
329
 *   An array of user IDs.
330
 */
331
function realname_delete_multiple($uids) {
332 333
  db_delete('realname')->condition('uid', $uids, 'IN')->execute();
  drupal_static_reset('realname_load_multiple');
334
  entity_get_controller('user')->resetCache($uids);
335 336 337
}

/**
338
 * Delete all real names.
339
 */
340
function realname_delete_all() {
341
  db_truncate('realname')->execute();
342
  drupal_static_reset('realname_load_multiple');
343
  entity_get_controller('user')->resetCache();
344
}
345 346 347 348

/**
 * @} End of "addtogroup realname".
 */
349 350 351 352 353

/**
 * Menu callback; Retrieve a JSON object containing autocomplete suggestions
 * for existing users based on their generated real names.
 */
354 355
function realname_autocomplete($field_name, $entity_type, $bundle_name, $string = '') {
  $instance = field_info_instance($entity_type, $field_name, $bundle_name);
356 357
  $matches = array();

358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379
  // User entityreference autocomplete fields.
  if ($instance['widget']['type'] == 'entityreference_autocomplete' && !empty($string)) {
    $query = db_select('users', 'u');
    $query->leftJoin('realname', 'rn', 'u.uid = rn.uid');
    $query->fields('u', array('uid', 'name'));
    if ($instance['widget']['settings']['match_operator'] == 'CONTAINS') {
      $query->condition(db_or()
        ->condition('rn.realname', '%' . db_like($string) . '%', 'LIKE')
        ->condition('u.name', '%' . db_like($string) . '%', 'LIKE')
      );
    }
    else {
      $query->condition(db_or()
        ->condition('rn.realname', db_like($string) . '%', 'LIKE')
        ->condition('u.name', db_like($string) . '%', 'LIKE')
      );
    }
    $query->range(0, 10);
    $uids = $query->execute()->fetchCol();
    $accounts = user_load_multiple($uids);

    foreach ($accounts as $account) {
380
      $matches[t('!account (@uid)', array('!account' => format_username($account), '@uid' => $account->uid))] = t('!realname (@username)', array('!realname' => format_username($account), '@username' => $account->name));
381 382 383 384
    }
  }
  // User autocomplete fields.
  elseif (!empty($string)) {
385 386
    $query = db_select('users', 'u');
    $query->leftJoin('realname', 'rn', 'u.uid = rn.uid');
387 388 389 390 391
    $query->fields('u', array('uid', 'name'));
    $query->condition(db_or()
      ->condition('rn.realname', db_like($string) . '%', 'LIKE')
      ->condition('u.name', db_like($string) . '%', 'LIKE')
    );
392 393 394 395 396
    $query->range(0, 10);
    $uids = $query->execute()->fetchCol();
    $accounts = user_load_multiple($uids);

    foreach ($accounts as $account) {
397
      $matches[$account->name] = t('!realname (@username)', array('!realname' => format_username($account), '@username' => $account->name));
398 399 400 401 402
    }
  }

  drupal_json_output($matches);
}
403

hass's avatar
hass committed
404 405 406
/**
 * Menu Access callback for the autocomplete widget.
 *
407
 * @param string $field_name
hass's avatar
hass committed
408
 *   The name of the entity-reference field.
409
 * @param string $entity_type
hass's avatar
hass committed
410
 *   The entity type.
411
 * @param string $bundle_name
hass's avatar
hass committed
412
 *   The bundle name.
413 414
 *
 * @return boolean
hass's avatar
hass committed
415 416 417 418 419 420 421 422 423 424 425 426
 *   True if user can access this menu item.
 */
function realname_autocomplete_access_callback($field_name, $entity_type, $bundle_name) {
  $field = field_info_field($field_name);
  $instance = field_info_instance($entity_type, $field_name, $bundle_name);

  if (!$field || !$instance || $field['type'] != 'entityreference' || !field_access('edit', $field, $entity_type)) {
    return FALSE;
  }
  return TRUE;
}

427 428 429 430 431 432 433 434 435 436 437 438 439 440
/**
 * Implements hook_widget_form_alter().
 *
 * Overrides entityreference autocomplete fields that point to an entity
 * of type 'user'.
 */
function realname_field_widget_form_alter(&$element, &$form_state, $context) {
  if ($context['field']['type'] == 'entityreference') {
    if ($context['field']['settings']['target_type'] == 'user') {
      $element['target_id']['#autocomplete_path'] = 'realname/autocomplete/' . $context['field']['field_name'] . '/' . $context['instance']['entity_type'] . '/' . $context['instance']['bundle'];
    }
  }
}

441 442 443 444 445 446 447 448 449 450 451 452 453 454 455
/**
 * Implements hook_form_FORM_ID_alter().
 */
function realname_form_user_admin_settings_alter(&$form, &$form_state, $form_id) {
  $form['email_admin_created']['user_mail_register_admin_created_body']['#element_validate'][] = 'realname_username_raw_token_validate';
  $form['email_no_approval_required']['user_mail_register_no_approval_required_body']['#element_validate'][] = 'realname_username_raw_token_validate';
  $form['email_activated']['settings']['user_mail_status_activated_body']['#element_validate'][] = 'realname_username_raw_token_validate';
}

/**
 * E-mail settings form validation callback.
 */
function realname_username_raw_token_validate(&$element, &$form_state) {
  $value = isset($element['#value']) ? $element['#value'] : $element['#default_value'];

456
  if (strpos($value, '[user:name-raw]') === FALSE) {
457
    drupal_set_message(t('The %element-title does not contain the <code>[user:name-raw]</code> token, which is necessary when using username for login.', array('%element-title' => $element['#title'])), 'warning');
458 459 460 461
  }

  return $element;
}