You are here

function profile_tokens in Token 7

Implements hook_tokens() on behalf of profile.module.

File

./token.tokens.inc, line 1203
Token callbacks for the token module.

Code

function profile_tokens($type, $tokens, array $data = array(), array $options = array()) {
  $replacements = array();
  $sanitize = !empty($options['sanitize']);
  $language_code = isset($options['language']) ? $options['language']->language : NULL;
  if ($type == 'user' && !empty($data['user'])) {
    $account = $data['user'];

    // Load profile fields if this is the global user account.
    // @see http://drupal.org/node/361471
    // @see http://drupal.org/node/967330
    if ($account->uid == $GLOBALS['user']->uid && isset($account->timestamp)) {
      $profile_users = array(
        $account->uid => $account,
      );
      profile_user_load($profile_users);
      $account = $profile_users[$account->uid];
    }
    $profile_fields = _token_profile_fields();
    foreach ($tokens as $name => $original) {
      if (isset($profile_fields[$name]) && !empty($account->{$profile_fields[$name]->name})) {
        $value = $account->{$profile_fields[$name]->name};
        switch ($profile_fields[$name]->type) {
          case 'textarea':
            $replacements[$original] = $sanitize ? check_markup($value, filter_default_format($account), '', TRUE) : $value;
            break;
          case 'date':
            $timestamp = gmmktime(0, 0, 0, $value['month'], $value['day'], $value['year']);
            $replacements[$original] = format_date($timestamp, 'medium', '', NULL, $language_code);
            break;
          case 'url':
            $replacements[$original] = $sanitize ? check_url($value) : $value;
            break;
          case 'checkbox':

            // Checkbox field if checked should return the text.
            $replacements[$original] = $sanitize ? check_plain($profile_fields[$name]->title) : $profile_fields[$name]->title;
            break;
          case 'list':
            $value = preg_split("/[,\n\r]/", $value);
            $value = array_map('trim', $value);
            $value = implode(', ', $value);

          // Intentionally fall through to the default condition.
          default:
            $replacements[$original] = $sanitize ? check_plain($value) : $value;
            break;
        }
      }
    }

    // Chained token relationships.
    foreach ($profile_fields as $field) {
      if ($field->type == 'date' && isset($account->{$field->name}) && ($field_tokens = token_find_with_prefix($tokens, $field->token_name))) {
        $date = $account->{$field->name};
        $replacements += token_generate('date', $field_tokens, array(
          'date' => gmmktime(0, 0, 0, $date['month'], $date['day'], $date['year']),
        ), $options);
      }
    }
  }
  return $replacements;
}