You are here

token_example.tokens.inc in Examples for Developers 6

Same filename and directory in other branches
  1. 7 token_example/token_example.tokens.inc

File

token_example/token_example.tokens.inc
View source
<?php

/**
 * Implementation of hook_token_list().
 */
function _token_example_token_list($type = 'all') {
  $tokens = array();
  if ($type == 'global' || $type == 'all') {
    $tokens['global']['random-sha1'] = t("A randomly generated SHA1 hash.");
    $tokens['global']['site-date-timestamp'] = t('The current timestamp in seconds past January 1, 1970.');
    $tokens['global']['random-num-1'] = t('A randomly generated single-digit number.');
    $tokens['global']['random-num-3'] = t('A randomly generated three-digit number.');
    $tokens['global']['random-num-10'] = t('A randomly generated ten-digit number.');
    $tokens['global']['random-alpha-1'] = t('Randomly generated single-digit letter.');
    $tokens['global']['random-alpha-3'] = t('Randomly generated three-digit letters.');
    $tokens['global']['random-alpha-10'] = t('Randomly generated ten-digit letters.');
  }
  if ($type == 'node' || $type == 'all') {
    $tokens['node']['node-format'] = t('Input format used for the node body.');
    $tokens['node'] += token_get_date_token_info(t('Node revision timestamp'), 'node-revision-');

    // Node tokens here.
  }
  return $tokens;
}

/**
 * Implementation of hook_token_values().
 */
function _token_example_token_values($type, $object = NULL) {
  $values = array();
  if ($type == 'global') {
    $values['random-sha1'] = sha1(rand());

    // Create random numbers.
    $values['random-num-1'] = mt_rand(0, 9);
    $values['random-num-3'] = mt_rand(100, 999);
    $values['random-num-10'] = mt_rand(10000, 99999) . mt_rand(10000, 99999);

    // Create random letters.
    $letters = range('a', 'z');
    $values['random-alpha-1'] = $letters[array_rand($letters, 1)];
    shuffle($letters);
    $values['random-alpha-3'] = implode('', array_slice($letters, 0, 3));
    shuffle($letters);
    $values['random-alpha-10'] = implode('', array_slice($letters, 0, 10));

    // Create a UNIX timestamp token.
    $time = time();
    $tz = variable_get('date_default_timezone', 0);
    $values['site-date-timestamp'] = format_date($time, 'custom', 'Y', $tz);
  }
  elseif ($type == 'node' && !empty($object)) {
    $format = $object->format || variable_get('filter_default_format', 1);
    $format = filter_format_load($object->format);
    if (!empty($format->name)) {
      $values['node-format'] = check_plain($format->name);
    }
    if (isset($object->revision_timestamp)) {
      $values += token_get_date_token_values($object->revision_timestamp, 'node-revision-');
    }

    // Node tokens go here.
  }
  return $values;
}

Functions

Namesort descending Description
_token_example_token_list Implementation of hook_token_list().
_token_example_token_values Implementation of hook_token_values().