Project

General

Profile

Paste
Download (12.8 KB) Statistics
| Branch: | Revision:

root / drupal7 / sites / all / modules / entity / entity_token.tokens.inc @ 7d7b5830

1
<?php
2

    
3
/**
4
 * @file
5
 * Provides tokens for entity properties which have no token yet.
6
 */
7

    
8
/**
9
 * Defines the types of properties to be added as token.
10
 *
11
 * @return
12
 *   An array mapping token types to the usual (entity) type names.
13
 */
14
function entity_token_types() {
15
  $return = entity_token_types_chained();
16
  return $return + drupal_map_assoc(array('text', 'integer', 'decimal', 'duration', 'boolean', 'uri'));
17
}
18

    
19
/**
20
 * Defines a list of token types that need to be chained.
21
 *
22
 * @return
23
 *   If a (token) type is given, whether the given type needs to be chained.
24
 *   Else a full list of token types to be chained as returned by
25
 *   entity_token_token_types().
26
 */
27
function entity_token_types_chained($type = NULL) {
28
  // This functions gets called rather often when replacing tokens, thus
29
  // we statically cache $types using the advanced drupal static pattern.
30
  static $drupal_static_fast;
31
  if (!isset($drupal_static_fast)) {
32
    $drupal_static_fast['types'] = &drupal_static(__FUNCTION__, array());
33
  }
34
  $types = &$drupal_static_fast['types'];
35

    
36
  if (!$types) {
37
    // Add entities.
38
    foreach (entity_get_info() as $entity_type => $info) {
39
      if ($token_type = isset($info['token type']) ? $info['token type'] : $entity_type) {
40
        $types[$token_type] = $entity_type;
41
      }
42
    }
43
    // Add 'date' and 'site' tokens.
44
    $types['date'] = 'date';
45
    $types['site'] = 'site';
46
    // Add a 'struct' type.
47
    $types['struct'] = 'struct';
48
  }
49

    
50
  if (isset($type)) {
51
    return isset($types[$type]) || entity_property_list_extract_type($type);
52
  }
53
  return $types;
54
}
55

    
56
/**
57
 * Gets the right token type for a given property info array.
58
 */
59
function _entity_token_map_to_token_type($property_info) {
60
  $lookup = &drupal_static(__FUNCTION__);
61

    
62
  if (!$lookup) {
63
    // Initialize a lookup array mapping property types to token types.
64
    $lookup = array_flip(entity_token_types());
65
  }
66

    
67
  $type = isset($property_info['type']) ? $property_info['type'] : 'text';
68
  // Just use the type 'struct' for all structures.
69
  if (!empty($property_info['property info'])) {
70
    $type = 'struct';
71
  }
72

    
73
  if ($item_type = entity_property_list_extract_type($type)) {
74
    return isset($lookup[$item_type]) ? "list<$lookup[$item_type]>" : FALSE;
75
  }
76
  return isset($lookup[$type]) ? $lookup[$type] : FALSE;
77
}
78

    
79
/**
80
 * Implements hook_token_info_alter().
81
 */
82
function entity_token_token_info_alter(&$info) {
83
  $entity_info = entity_get_info();
84
  $token_types = entity_token_types_chained();
85

    
86
  // Loop over all chain-able token types, as those may contain further tokens,
87
  // e.g. entity types or 'site'.
88
  foreach ($token_types as $token_type => $type) {
89
    // Just add all properties regardless whether it's in a bundle, but only if
90
    // there is no token of the property yet.
91
    foreach (entity_get_all_property_info($type) as $name => $property) {
92
      $name = str_replace('_', '-', $name);
93
      $property += array('type' => 'text', 'description' => $property['label']);
94
      $property_token_type = _entity_token_map_to_token_type($property);
95

    
96
      if (!isset($info['tokens'][$token_type][$name]) && $property_token_type) {
97

    
98
        $info['tokens'][$token_type][$name] = array(
99
          'name' => $property['label'],
100
          'description' => $property['description'],
101
          'type' => $property_token_type,
102
          // Mark the token so we know we have to provide the value afterwards.
103
          'entity-token' => TRUE,
104
        );
105
      }
106
      if ($property_token_type == 'struct' && !empty($property['property info'])) {
107
        $info['tokens'][$token_type][$name]['dynamic'] = TRUE;
108
        $help = array();
109
        foreach ($property['property info'] as $key => $property_info) {
110
          $help[] = $key . ' (' . $property_info['label'] . ')';
111
        }
112
        $info['tokens'][$token_type][$name]['description'] .= ' ' . t('The following properties may be appended to the token: @keys',
113
          array('@keys' => implode(', ', $help))
114
        );
115
      }
116
    }
117
  }
118

    
119
  // Make sure all chain-able token types we support are registered.
120
  foreach ($token_types as $token_type => $type) {
121

    
122
    if (!empty($info['tokens'][$token_type]) && !isset($info['types'][$token_type])) {
123
      if (isset($entity_info[$type])) {
124
        $info['types'][$token_type] = array(
125
          'name' => $entity_info[$type]['label'],
126
          'description' => t('Tokens related to the "@name" entities.', array('@name' => $entity_info[$type]['label'])),
127
          'needs-data' => $token_type,
128
        );
129
      }
130
      else {
131
        $info['types'][$token_type] = array(
132
          'name' => drupal_strtoupper($token_type),
133
          'description' => t('@name tokens.', array('@name' => drupal_strtoupper($token_type))),
134
          'needs-data' => $token_type,
135
        );
136
      }
137
    }
138
    if (!empty($info['tokens'][$token_type]) && !isset($info['types']["list<$token_type>"]) && $token_type != 'site') {
139
      if (isset($entity_info[$type])) {
140
        $info['types']["list<$token_type>"] = array(
141
          'name' => t('List of @entities', array('@entities' => isset($entity_info[$type]['plural label']) ? $entity_info[$type]['plural label'] : $entity_info[$type]['label'] . 's')),
142
          'description' => t('Tokens related to the "@name" entities.', array('@name' => $entity_info[$type]['label'])),
143
          'needs-data' => "list<$token_type>",
144
        );
145
      }
146
      else {
147
        $info['types']["list<$token_type>"] = array(
148
          'name' => t('List of @type values', array('@type' => $token_type)),
149
          'description' => t('Tokens for lists of @type values.', array('@type' => $token_type)),
150
          'needs-data' => "list<$token_type>",
151
        );
152
      }
153
      // Also add some basic token replacements for lists...
154
      for ($i = 0; $i < 4; $i++) {
155
        $info['tokens']["list<$token_type>"][$i] = array(
156
          'name' => t('@type with delta @delta', array('@delta' => $i, '@type' => $info['types'][$token_type]['name'])),
157
          'description' => t('The list item with delta @delta. Delta values start from 0 and are incremented by one per list item.', array('@delta' => $i)),
158
          'type' => $token_type,
159
        );
160
      }
161
    }
162
  }
163
}
164

    
165
/**
166
 * Implements hook_tokens().
167
 */
168
function entity_token_tokens($type, $tokens, array $data = array(), array $options = array()) {
169
  $token_types = entity_token_types_chained();
170
  $replacements = array();
171

    
172
  if (isset($token_types[$type]) && (!empty($data[$type]) || $type == 'site')) {
173
    $data += array($type => FALSE);
174

    
175
    // Make use of token module's token cache if available.
176
    $info = module_exists('token') ? token_get_info() : token_info();
177
    foreach ($tokens as $name => $original) {
178
      // Provide the token for all properties marked to stem from us.
179
      if (!empty($info['tokens'][$type][$name]['entity-token']) || $type == 'struct') {
180
        $wrapper = !isset($wrapper) ? _entity_token_wrap_data($type, $token_types[$type], $data[$type], $options) : $wrapper;
181
        $property_name = str_replace('-', '_', $name);
182
        try {
183
          if (isset($wrapper->$property_name)) {
184
            $replacement = _entity_token_get_token($wrapper->$property_name, $options);
185
            if (isset($replacement)) {
186
              $replacements[$original] = $replacement;
187
            }
188
          }
189
        }
190
        catch (EntityMetadataWrapperException $e) {
191
          // If tokens for not existing values are requested, just do nothing.
192
        }
193
      }
194
    }
195

    
196
    // Properly chain everything of a type marked as needs chaining.
197
    $info['tokens'] += array($type => array());
198
    foreach ($info['tokens'][$type] as $name => $token_info) {
199
      if (!empty($token_info['entity-token']) && isset($token_info['type']) && entity_token_types_chained($token_info['type'])) {
200

    
201
        if ($chained_tokens = token_find_with_prefix($tokens, $name)) {
202
          $wrapper = !isset($wrapper) ? _entity_token_wrap_data($type, $token_types[$type], $data[$type], $options) : $wrapper;
203
          $property_name = str_replace('-', '_', $name);
204

    
205
          try {
206
            // Pass on 'struct' properties wrapped, else un-wrap the data.
207
            $value = ($token_info['type'] == 'struct') ? $wrapper->$property_name : $wrapper->$property_name->value();
208
            $replacements += token_generate($token_info['type'], $chained_tokens, array($token_info['type'] => $value), $options);
209
          }
210
          catch (EntityMetadataWrapperException $e) {
211
            // If tokens for not existing values are requested, just do nothing.
212
          }
213
        }
214
      }
215
    }
216
  }
217
  // Add support for evaluating tokens for "list<type"> types.
218
  elseif ($item_token_type = entity_property_list_extract_type($type)) {
219
    foreach ($tokens as $name => $original) {
220
      // Care about getting entries of a list.
221
      if (is_numeric($name)) {
222
        $wrapper = !isset($wrapper) ? _entity_token_wrap_data($type, "list<$token_types[$item_token_type]>", $data[$type], $options) : $wrapper;
223
        try {
224
          $replacement = _entity_token_get_token($wrapper->get($name), $options);
225
          if (isset($replacement)) {
226
            $replacements[$original] = $replacement;
227
          }
228
        }
229
        catch (EntityMetadataWrapperException $e) {
230
          // If tokens for not existing values are requested, just do nothing.
231
        }
232
      }
233
      // Care about generating chained tokens for list-items.
234
      else {
235
        $parts = explode(':', $name, 2);
236
        $delta = $parts[0];
237

    
238
        if (is_numeric($delta) && $chained_tokens = token_find_with_prefix($tokens, $delta)) {
239
          $wrapper = !isset($wrapper) ? _entity_token_wrap_data($type, "list<$token_types[$item_token_type]>", $data[$type], $options) : $wrapper;
240
          try {
241
            $replacements += token_generate($item_token_type, $chained_tokens, array($item_token_type => $wrapper->get($delta)->value()), $options);
242
          }
243
          catch (EntityMetadataWrapperException $e) {
244
            // If tokens for not existing values are requested, just do nothing.
245
          }
246
        }
247
      }
248
    }
249
  }
250

    
251
  // Add support for chaining struct data. As struct data has no registered
252
  // tokens, we have to chain based upon wrapper property info.
253
  if ($type == 'struct') {
254
    $wrapper = $data[$type];
255
    foreach ($wrapper as $name => $property) {
256
      $token_type = _entity_token_map_to_token_type($property->info());
257

    
258
      if (entity_token_types_chained($token_type) && $chained_tokens = token_find_with_prefix($tokens, $name)) {
259
        try {
260
          // Pass on 'struct' properties wrapped, else un-wrap the data.
261
          $value = ($token_type == 'struct') ? $property : $property->value();
262
          $replacements += token_generate($token_type, $chained_tokens, array($token_type => $value), $options);
263
        }
264
        catch (EntityMetadataWrapperException $e) {
265
          // If tokens for not existing values are requested, just do nothing.
266
        }
267
      }
268
    }
269
  }
270

    
271
  return $replacements;
272
}
273

    
274
/**
275
 * Wraps the given data by correctly obeying the options.
276
 */
277
function _entity_token_wrap_data($token_type, $type, $data, $options) {
278
  if ($type == 'site') {
279
    $wrapper = entity_metadata_site_wrapper();
280
  }
281
  elseif ($type == 'struct') {
282
    // 'struct' data items are passed on wrapped.
283
    $wrapper = $data;
284
  }
285
  else {
286
    $wrapper = entity_metadata_wrapper($type, $data);
287
  }
288
  if (isset($options['language']) && $wrapper instanceof EntityStructureWrapper) {
289
    $wrapper->language($options['language']->language);
290
  }
291
  return $wrapper;
292
}
293

    
294
/**
295
 * Gets the token replacement by correctly obeying the options.
296
 */
297
function _entity_token_get_token($wrapper, $options) {
298

    
299
  if (!$wrapper || $wrapper->value() === NULL) {
300
    // Do not provide a replacement if there is no value.
301
    return NULL;
302
  }
303

    
304
  if (empty($options['sanitize'])) {
305
    // When we don't need sanitized tokens decode already sanitizied texts.
306
    $options['decode'] = TRUE;
307
  }
308
  $langcode = isset($options['language']) ? $options['language']->language : NULL;
309

    
310
  // If there is a label for a property, e.g. defined by an options list or an
311
  // entity label, make use of it.
312
  if ($label = $wrapper->label()) {
313
    return empty($options['sanitize']) ? $label : check_plain($label);
314
  }
315

    
316
  switch ($wrapper->type()) {
317
    case 'integer':
318
      return $wrapper->value();
319
    case 'decimal':
320
      return number_format($wrapper->value(), 2);
321
    case 'date':
322
      return format_date($wrapper->value(), 'medium', '', NULL, $langcode);
323
    case 'duration':
324
      return format_interval($wrapper->value(), 2, $langcode);
325
    case 'boolean':
326
      return $wrapper->value() ? t('true') : t('false');
327
    case 'uri':
328
    case 'text':
329
      return $wrapper->value($options);
330
  }
331

    
332
  // Care for outputing list values.
333
  if ($wrapper instanceof EntityListWrapper) {
334
    $output = array();
335
    foreach ($wrapper as $item) {
336
      $output[] = _entity_token_get_token($item, $options);
337
    }
338
    return implode(', ', $output);
339
  }
340
  // Else we do not have a good string to output, e.g. for struct values. Just
341
  // output the string representation of the wrapper.
342
  return (string) $wrapper;
343
}