hook_tokens

Versions
mediamosa-21
hook_tokens($type, $tokens, array $data = array(), array $options = array())

Provide replacement values for placeholder tokens.

Parameters

$type The type of token being replaced. 'node', 'user', and 'date' are common.

$tokens An array of tokens to be replaced, keyed by the literal text of the token as it appeared in the source text.

$data (optional) An associative array of objects to be used when generating replacement values.

$options (optional) A associative array of options to control the token replacement process. Common options are:

  • 'language' A language object to be used when generating locale-sensitive tokens.
  • 'sanitize' A boolean flag indicating that tokens should be sanitized for display to a web browser.

Return value

An associative array of replacement values, keyed by the original 'raw' tokens that were found in the source text. For example: $results['[node:title]'] = 'My new node';

Related topics

Code

modules/system/system.api.php, line 3075

<?php
function hook_tokens($type, $tokens, array $data = array(), array $options = array()) {
  $url_options = array('absolute' => TRUE);
  if (isset($options['language'])) {
    $url_options['language'] = $options['language'];
    $language_code = $options['language']->language;
  }
  else {
    $language_code = NULL;
  }
  $sanitize = !empty($options['sanitize']);

  $replacements = array();

  if ($type == 'node' && !empty($data['node'])) {
    $node = $data['node'];

    foreach ($tokens as $name => $original) {
      switch ($name) {
        // Simple key values on the node.
        case 'nid':
          $replacements[$original] = $node->nid;
          break;

        case 'title':
          $replacements[$original] = $sanitize ? check_plain($node->title) : $node->title;
          break;

        case 'edit-url':
          $replacements[$original] = url('node/' . $node->nid . '/edit', $url_options);
          break;

        // Default values for the chained tokens handled below.
        case 'author':
          $name = ($node->uid == 0) ? variable_get('anonymous', t('Anonymous')) : $node->name;
          $replacements[$original] = $sanitize ? filter_xss($name) : $name;
          break;

        case 'created':
          $replacements[$original] = format_date($node->created, 'medium', '', NULL, $language_code);
          break;
      }
    }

    if ($author_tokens = token_find_with_prefix($tokens, 'author')) {
      $author = user_load($node->uid);
      $replacements += token_generate('user', $author_tokens, array('user' => $author), $options);
    }

    if ($created_tokens = token_find_with_prefix($tokens, 'created')) {
      $replacements += token_generate('date', $created_tokens, array('date' => $node->created), $options);
    }
  }

  return $replacements;
}
?>