metatag.tokens.inc 11.1 KB
Newer Older
1
<?php
2

3 4 5 6 7
/**
 * @file
 * Custom tokens for Metatag.
 */

8 9 10 11 12 13 14 15 16 17 18 19 20
/**
 * Implements hook_token_info().
 */
function metatag_token_info() {
  $info = array();

  $info['types']['metatag'] = array(
    'name' => t('Meta tags'),
    'description' => t('Generated by the Metatag module, may not be used to fill in other meta tags.'),
  );

  $metatag_info = metatag_get_info();

21
  foreach ($metatag_info['tags'] as $value) {
22
    if (isset($value['group'], $metatag_info['groups'][$value['group']], $metatag_info['groups'][$value['group']]['label'])) {
23
      $label = $metatag_info['groups'][$value['group']]['label'] . ': ' . $value['label'];
24 25
    }
    else {
26
      $label = t('Basic tags: @label', array('@label' => $value['label']));
27
    }
28
    $info['tokens']['metatag'][$value['name']] = array(
29
      'name' => $label,
30
      'description' => isset($value['description']) ? $value['description'] : '',
31 32 33 34 35
    );
  }

  if (module_exists('taxonomy')) {
    $info['tokens']['term']['metatag'] = array(
36 37 38
      'name' => t('Meta tags'),
      'description' => t('Meta tags for this taxonomy term.'),
      'type' => 'metatag',
39 40 41 42 43
    );
  }

  if (module_exists('node')) {
    $info['tokens']['node']['metatag'] = array(
44 45 46
      'name' => t('Meta tags'),
      'description' => t('Meta tags for this node.'),
      'type' => 'metatag',
47 48 49
    );
  }

50 51 52 53 54 55 56 57
  if (module_exists('user')) {
    $info['tokens']['user']['metatag'] = array(
      'name' => t('Meta tags'),
      'description' => t('Meta tags for this user.'),
      'type' => 'metatag',
    );
  }

58 59 60 61 62
  // A custom pager.
  $pager = variable_get('metatag_pager_string', 'Page PAGER | ');
  $page = str_replace('PAGER', 12, $pager);
  $info['tokens']['current-page']['pager'] = array(
    'name' => t('Custom pager'),
63 64 65 66
    'description' => t('A custom pager (from the Metatag module). Currently set to "@pager" which would be output as e.g. "@page".', array(
      '@pager' => $pager,
      '@page' => $page,
    )),
67 68
  );

69 70 71 72 73 74 75 76 77 78 79 80 81 82
  // Custom summary tokens for each long text field.
  $supported_types = array('text_long', 'text_with_summary');
  if (variable_get('metatag_summary_text_field', FALSE)) {
    $supported_types[] = 'text';
  }
  $trim_length = variable_get('metatag_summary_length', 200);
  foreach (field_read_fields() as $field_name => $field) {
    if (!empty($field['module'])) {
      if (in_array($field['type'], $supported_types)) {
        $instances = field_read_instances(array('field_name' => $field_name));
        foreach ($instances as $instance) {
          if (!empty($instance['entity_type']) && !empty($instance['label'])) {
            $info['tokens'][$instance['entity_type']][$field_name . '-summary'] = array(
              'name' => t('@label (summary)', array('@label' => $instance['label'])),
83 84 85 86
              'description' => t('A summary of the @label field, trimmed to @length characters.', array(
                '@label' => $instance['label'],
                '@length' => $trim_length,
              )),
87 88 89 90 91 92 93
            );
          }
        }
      }
    }
  }

94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
  return $info;
}

/**
 * Implements hook_tokens().
 */
function metatag_tokens($type, $tokens, array $data = array(), array $options = array()) {
  $replacements = array();

  $sanitize = !empty($options['sanitize']);

  // Metatag tokens.
  if ($type == 'metatag' && !empty($data['metatag'])) {
    $metatag = $data['metatag'];
    foreach ($tokens as $name => $original) {
109
      if (isset($metatag[$name])) {
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
        $replacements[$original] = $sanitize ? filter_xss($metatag[$name]) : $metatag[$name];
      }
    }
  }

  // Token tokens.
  if ($type == 'term' && !empty($data['term'])) {
    $term = $data['term'];

    if ($metatag_tokens = token_find_with_prefix($tokens, 'metatag')) {
      $result = metatag_token_generate_array($term, 'taxonomy_term', $term->vocabulary_machine_name);
      $replacements += token_generate('metatag', $metatag_tokens, array('metatag' => $result), $options);
    }
  }

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

    if ($metatag_tokens = token_find_with_prefix($tokens, 'metatag')) {
      $result = metatag_token_generate_array($node, 'node', $node->type);
      $replacements += token_generate('metatag', $metatag_tokens, array('metatag' => $result), $options);
    }
  }

135 136 137 138 139 140 141 142 143 144
  // User tokens.
  if ($type == 'user' && !empty($data['user'])) {
    $account = $data['user'];

    if ($metatag_tokens = token_find_with_prefix($tokens, 'metatag')) {
      $result = metatag_token_generate_array($account, 'user', 'user');
      $replacements += token_generate('metatag', $metatag_tokens, array('metatag' => $result), $options);
    }
  }

145 146 147 148 149
  // Custom pager.
  if ($type == 'current-page') {
    foreach ($tokens as $name => $original) {
      switch ($name) {
        case 'pager':
150 151 152
          $pager = metatag_get_current_pager();
          if (!empty($pager)) {
            $replacements[$original] = $pager;
153 154 155 156 157 158
          }
          break;
      }
    }
  }

159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
  // Summary tokens. It is safe to rely upon an "entity" token type here because
  // it is added by the Token module.
  if ($type == 'entity' && isset($options['entity'], $options['entity_type'])) {
    $trim_length = variable_get('metatag_summary_length', 200);
    foreach ($tokens as $name => $original) {
      if (substr($name, -8) == '-summary') {
        // The field name is the token name minus "-summary".
        $field_name = substr($name, 0, -8);

        // Work out the requested language, if appropriate.
        if (isset($options['language'])) {
          $language_code = $options['language']->language;
        }
        else {
          $language_code = NULL;
        }
        $entity = $options['entity'];
        $entity_type = $options['entity_type'];
        list($entity_id, $revision_id, $bundle) = entity_extract_ids($entity_type, $entity);
        $items = field_get_items($entity_type, $entity, $field_name, $language_code);
        if (!empty($items)) {
          $instance = field_info_instance($entity_type, $field_name, $bundle);
          $field_langcode = field_language($entity_type, $entity, $field_name, $language_code);

          // If the summary was filled in it is not empty, use it.
          if (!empty($items[0]['summary'])) {
            $output = $sanitize ? _text_sanitize($instance, $field_langcode, $items[0], 'summary') : $items[0]['summary'];
          }
          // Attempt to provide a suitable version of the 'body' field.
          else {
            $output = $sanitize ? _text_sanitize($instance, $field_langcode, $items[0], 'value') : $items[0]['value'];
          }
          if (!empty($output)) {
            // Trim the summary.
            $output = text_summary($output, $instance['settings']['text_processing'] ? $items[0]['format'] : NULL, $trim_length);
            if (!empty($output)) {
              $replacements[$original] = $output;
            }
          }
        }
      }
    }
  }

203 204 205 206 207 208 209 210 211 212
  return $replacements;
}

/**
 * Generate an array of meta tags for a given entity.
 */
function metatag_token_generate_array($entity, $entity_type, $bundle) {
  if (metatag_entity_supports_metatags($entity_type, $bundle)) {
    $token_type = token_get_entity_mapping('entity', $entity_type);

213
    $instance = metatag_get_entity_metatags_instance($entity, $entity_type, $bundle);
214 215 216 217
    $options = array();
    $options['token data'][$token_type] = $entity;
    $options['entity'] = $entity;

218 219 220 221 222 223 224
    $metatags = array();
    if (!empty($entity->metatags)) {
      $language = metatag_entity_get_language($entity_type, $entity);
      if (!empty($entity->metatags[$language])) {
        $metatags = $entity->metatags[$language];
      }
    }
225
    $metatags += metatag_config_load_with_defaults($instance);
226 227
    // Process it for entity metatag replacement to avoid infinite recursion.
    $metatags = _metatag_token_process_metatag($metatags, $token_type);
228 229 230 231 232 233 234 235 236 237 238 239

    $result = array();
    foreach ($metatags as $metatag => $data) {
      if ($metatag_instance = metatag_get_instance($metatag, $data)) {
        $result[$metatag] = $metatag_instance->getValue($options);
      }
    }
    return $result;
  }

  return NULL;
}
240 241

/**
242 243 244 245
 * Loop through metatags to avoid recursion on entity tokens.
 *
 * It will replace entity metatag token to its actual entity metatag field
 * value.
246 247 248 249 250 251 252 253 254
 *
 * @param array $metatags
 *   An array of entity metatag tokens.
 * @param string $token_type
 *   The entity token type, such as 'node' or 'term'.
 *
 * @return array
 *   Return metatags array with entity metatag tokens replaced.
 */
255
function _metatag_token_process_metatag(array $metatags, $token_type) {
256
  foreach ($metatags as $metatag => $data) {
257 258 259 260 261
    // Skip values that are not strings.
    if (!is_string($data['value'])) {
      continue;
    }

262 263 264
    // Explode all metatag token in field.
    $data_tokens = token_scan($data['value']);
    if (isset($data_tokens[$token_type])) {
265
      foreach ($data_tokens[$token_type] as $key => $value) {
266 267 268 269
        $metatag_parts = explode(':', $key);
        // Check entity metatag token. Like [<entity_token_type>:metatag:<xyz>].
        if ($metatag_parts[0] == 'metatag') {
          $entity_field = implode(':', array_slice($metatag_parts, 1));
270 271 272 273 274 275 276 277 278 279
          // If a value is not set here it will trigger an infinite loop.
          $metatags[$metatag]['value'] = '';

          // If the meta tag was defined then try parsing it.
          if (!empty($metatags[$entity_field]['value'])) {
            // Entity metatag field may contain other entity metatag token
            // that need to be replaced too.
            $replaced_value = metatag_token_entitymetatagtoken_replace($metatags, $metatags[$entity_field]['value'], $token_type);
            $metatags[$metatag]['value'] = str_replace($value, $replaced_value, $metatags[$metatag]['value']);
          }
280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304
        }
      }
    }
  }

  return $metatags;
}

/**
 * Replace entity metatag token with actual entity metatag field value.
 *
 * @param array $metatags
 *   An array entity metatag tokens.
 * @param string $token
 *   A token to be replaced.
 * @param string $token_type
 *   The entity token type, such as 'node' or 'term'.
 * @param array $search_tokens
 *   An array of tokens to search for.
 * @param array $replace_tokens
 *   An array of tokens to be replaced.
 *
 * @return string
 *   The replaced value of $token.
 */
305
function metatag_token_entitymetatagtoken_replace(array $metatags, $token, $token_type, array $search_tokens = array(), array $replace_tokens = array()) {
306 307 308 309
  $data_tokens = token_scan($token);
  // Check field has tokens.
  if (isset($data_tokens[$token_type])) {
    // Go through each token in field and find entity metatag tokens.
310
    foreach ($data_tokens[$token_type] as $key => $value) {
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325
      $metatag_parts = explode(':', $key);
      if ($metatag_parts[0] == 'metatag' && !in_array($value, $search_tokens)) {
        // Entity metatag field value.
        $entity_field = implode(':', array_slice($metatag_parts, 1));
        $replaced_value = metatag_token_entitymetatagtoken_replace($metatags, $metatags[$entity_field]['value'], $token_type, $replace_tokens, $search_tokens);
        $replace_tokens[] = $replaced_value;
        $search_tokens[] = $value;
      }
    }
    return str_replace($search_tokens, $replace_tokens, $token);
  }
  else {
    return $token;
  }
}