Projet

Général

Profil

Paste
Télécharger (9,59 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / feeds / mappers / taxonomy.inc @ a192dc0b

1
<?php
2

    
3
/**
4
 * @file
5
 * On behalf implementation of Feeds mapping API for taxonomy.module.
6
 */
7

    
8
/**
9
 * Search by term name.
10
 */
11
define('FEEDS_TAXONOMY_SEARCH_TERM_NAME', 0);
12

    
13
/**
14
 * Search by term id.
15
 */
16
define('FEEDS_TAXONOMY_SEARCH_TERM_ID', 1);
17

    
18
/**
19
 * Search by GUID.
20
 */
21
define('FEEDS_TAXONOMY_SEARCH_TERM_GUID', 2);
22

    
23
/**
24
 * Implements hook_feeds_parser_sources_alter().
25
 */
26
function taxonomy_feeds_parser_sources_alter(array &$sources, $content_type) {
27
  if (!empty($content_type)) {
28
    foreach (taxonomy_get_vocabularies($content_type) as $vocabulary) {
29
      $sources['parent:taxonomy:' . $vocabulary->machine_name] = array(
30
        'name' => t('Feed node: Taxonomy: @vocabulary', array('@vocabulary' => $vocabulary->name)),
31
        'description' => t('Taxonomy terms from feed node in given vocabulary.'),
32
        'callback' => 'taxonomy_feeds_get_source',
33
      );
34
    }
35
  }
36
}
37

    
38
/**
39
 * Callback, returns taxonomy from feed node.
40
 */
41
function taxonomy_feeds_get_source(FeedsSource $source, FeedsParserResult $result, $key) {
42
  if ($node = node_load($source->feed_nid)) {
43
    $terms = taxonomy_feeds_node_get_terms($node);
44
    $vocabularies = taxonomy_vocabulary_load_multiple(array(), array('machine_name' => str_replace('parent:taxonomy:', '', $key)));
45
    $vocabulary = array_shift($vocabularies);
46
    $result = array();
47
    foreach ($terms as $tid => $term) {
48
      if ($term->vid == $vocabulary->vid) {
49
        $result[] = new FeedsTermElement($term);
50
      }
51
    }
52

    
53
    return $result;
54
  }
55
}
56

    
57
/**
58
 * Implements hook_feeds_processor_targets().
59
 */
60
function taxonomy_feeds_processor_targets($entity_type, $bundle_name) {
61
  $targets = array();
62

    
63
  foreach (field_info_instances($entity_type, $bundle_name) as $name => $instance) {
64
    $info = field_info_field($name);
65
    if ($info['type'] == 'taxonomy_term_reference') {
66
      $targets[$name] = array(
67
        'name' => check_plain($instance['label']),
68
        'callback' => 'taxonomy_feeds_set_target',
69
        'description' => t('The @label field of the entity.', array('@label' => $instance['label'])),
70
        'summary_callbacks' => array('taxonomy_feeds_summary_callback'),
71
        'form_callbacks' => array('taxonomy_feeds_form_callback'),
72
      );
73
    }
74
  }
75
  if ($entity_type == 'taxonomy_term') {
76
    $targets['tid']['name'] = t('Term id');
77
    $targets['tid']['description'] = t('The tid of the taxonomy term. NOTE: use this feature with care, node ids are usually assigned by Drupal.');
78
    unset($targets['vocabulary']);
79
  }
80

    
81
  return $targets;
82
}
83

    
84
/**
85
 * Callback for mapping taxonomy terms.
86
 */
87
function taxonomy_feeds_set_target(FeedsSource $source, $entity, $target, array $terms, array $mapping) {
88
  $language = $mapping['language'];
89

    
90
  // Add in default values.
91
  $mapping += array(
92
    'term_search' => FEEDS_TAXONOMY_SEARCH_TERM_NAME,
93
    'autocreate' => FALSE,
94
  );
95

    
96
  $info = field_info_field($target);
97

    
98
  $cache = &drupal_static(__FUNCTION__);
99
  if (!isset($cache['allowed_values'][$target])) {
100
    $cache['allowed_values'][$target] = taxonomy_allowed_values($info);
101
  }
102

    
103
  if (!isset($cache['allowed_vocabularies'][$target])) {
104
    foreach ($info['settings']['allowed_values'] as $tree) {
105
      if ($vocabulary = taxonomy_vocabulary_machine_name_load($tree['vocabulary'])) {
106
        $cache['allowed_vocabularies'][$target][$vocabulary->vid] = $vocabulary->machine_name;
107
      }
108
    }
109
  }
110

    
111
  // Some kind of configuration issue. Perhaps the vocabulary was deleted.
112
  // Nothing we can do about it.
113
  if (empty($cache['allowed_vocabularies'][$target])) {
114
    return;
115
  }
116

    
117
  $query = new EntityFieldQuery();
118
  $query->entityCondition('entity_type', 'taxonomy_term')
119
    ->entityCondition('bundle', $cache['allowed_vocabularies'][$target])
120
    ->range(0, 1);
121

    
122

    
123
  $field = isset($entity->$target) ? $entity->$target : array($language => array());
124

    
125
  if (!isset($field[$language])) {
126
    $field[$language] = array();
127
  }
128

    
129
  // Allow for multiple mappings to the same target.
130
  $delta = count($field[$language]);
131

    
132
  // Iterate over all values.
133
  foreach ($terms as $term) {
134

    
135
    if ($info['cardinality'] == $delta) {
136
      break;
137
    }
138

    
139
    $tid = FALSE;
140

    
141
    // FeedsTermElement already is a term.
142
    if ($term instanceof FeedsTermElement) {
143
      $tid = $term->tid;
144
    }
145
    else {
146
      switch ($mapping['term_search']) {
147

    
148
        // Lookup by name.
149
        case FEEDS_TAXONOMY_SEARCH_TERM_NAME:
150
          $term = trim($term);
151
          $name_query = clone $query;
152
          if (strlen($term) && $tids = $name_query->propertyCondition('name', $term)->execute()) {
153

    
154
            // Find the first allowed term.
155
            foreach ($tids['taxonomy_term'] as $possible_term) {
156
              if (isset($cache['allowed_values'][$target][$possible_term->tid])) {
157
                $tid = $possible_term->tid;
158
                break;
159
              }
160
            }
161
          }
162
          elseif ($mapping['autocreate'] && strlen($term)) {
163
            $term = (object) array(
164
              'name' => drupal_substr($term, 0, 255),
165
              'vid' => key($cache['allowed_vocabularies'][$target]),
166
              'vocabulary_machine_name' => reset($cache['allowed_vocabularies'][$target]),
167
            );
168
            // Set language if the taxonomy is multilingual.
169
            if ($language !== LANGUAGE_NONE) {
170
              $info = entity_get_info('taxonomy_term');
171
              if (!empty($info['entity keys']['language'])) {
172
                $term->{$info['entity keys']['language']} = $language;
173
              }
174
            }
175
            taxonomy_term_save($term);
176
            $tid = $term->tid;
177
            // Add to the list of allowed values.
178
            $cache['allowed_values'][$target][$tid] = $term->name;
179
          }
180
          break;
181

    
182
        // Lookup by tid.
183
        case FEEDS_TAXONOMY_SEARCH_TERM_ID:
184
          if (is_numeric($term)) {
185
            $tid = (int) $term;
186
          }
187
          break;
188

    
189
        // Lookup by GUID.
190
        case FEEDS_TAXONOMY_SEARCH_TERM_GUID:
191
          $tid = taxonomy_feeds_term_lookup_term_by_guid($term);
192
          break;
193
      }
194
    }
195

    
196
    if ($tid && isset($cache['allowed_values'][$target][$tid])) {
197
      $field[$language][] = array('tid' => $tid);
198
      $delta++;
199
    }
200
  }
201

    
202
  $entity->$target = $field;
203
}
204

    
205
/**
206
 * Finds all terms associated with the given node, within one vocabulary.
207
 */
208
function taxonomy_feeds_node_get_terms($node, $key = 'tid') {
209
  $terms = &drupal_static(__FUNCTION__);
210

    
211
  if (!isset($terms[$node->nid][$key])) {
212
    // Get tids from all taxonomy_term_reference fields.
213
    $tids = array();
214
    $fields = field_info_fields();
215
    foreach ($fields as $field_name => $field) {
216
      if ($field['type'] == 'taxonomy_term_reference' && field_info_instance('node', $field_name, $node->type)) {
217
        if (($items = field_get_items('node', $node, $field_name)) && is_array($items)) {
218
          $tids = array_merge($tids, array_map('_taxonomy_feeds_extract_tid', $items));
219
        }
220
      }
221
    }
222

    
223
    // Load terms and cache them in static var.
224
    $curr_terms = taxonomy_term_load_multiple($tids);
225
    $terms[$node->nid][$key] = array();
226
    foreach ($curr_terms as $term) {
227
      $terms[$node->nid][$key][$term->$key] = $term;
228
    }
229
  }
230
  return $terms[$node->nid][$key];
231
}
232

    
233
/**
234
 * Extracts tid from array item returned by field_get_items().
235
 *
236
 * @param array $item
237
 *   Tid information in the form of a single element array
238
 *   (key == 'tid', value == tid we're looking for)
239
 *
240
 * @return int
241
 *   Term id extracted from $item.
242
 *
243
 * @see taxonomy_feeds_node_get_terms()
244
 * @see field_get_items()
245
 */
246
function _taxonomy_feeds_extract_tid($item) {
247
  return $item['tid'];
248
}
249

    
250
/**
251
 * Looks up a term by GUID, assumes SQL storage backend.
252
 *
253
 * @param string $guid
254
 *   The Feeds GUID to compare against.
255
 *
256
 * @return int|FALSE
257
 *   The term id, or FALSE if one was not found.
258
 */
259
function taxonomy_feeds_term_lookup_term_by_guid($guid) {
260
  return db_select('feeds_item')
261
    ->fields('feeds_item', array('entity_id'))
262
    ->condition('entity_type', 'taxonomy_term')
263
    ->condition('guid', $guid)
264
    ->execute()
265
    ->fetchField();
266
}
267

    
268
/**
269
 * Mapping configuration summary for taxonomy.module.
270
 */
271
function taxonomy_feeds_summary_callback(array $mapping, $target, array $form, array $form_state) {
272
  $options = _taxonomy_feeds_form_callback_options();
273
  if (empty($mapping['term_search'])) {
274
    return t('Search taxonomy terms by: <strong>@search</strong>', array('@search' => $options[FEEDS_TAXONOMY_SEARCH_TERM_NAME]));
275
  }
276
  return t('Search taxonomy terms by: <strong>@search</strong>', array('@search' => $options[$mapping['term_search']]));
277
}
278

    
279
/**
280
 * Settings form callback.
281
 */
282
function taxonomy_feeds_form_callback(array $mapping, $target, array $form, array $form_state) {
283
  return array(
284
    'term_search' => array(
285
      '#type' => 'select',
286
      '#title' => t('Search taxonomy terms by'),
287
      '#options' => _taxonomy_feeds_form_callback_options(),
288
      '#default_value' => !empty($mapping['term_search']) ? $mapping['term_search'] : FEEDS_TAXONOMY_SEARCH_TERM_NAME,
289
    ),
290
    'autocreate' => array(
291
      '#type' => 'checkbox',
292
      '#title' => t('Auto create'),
293
      '#description' => t("Create the term if it doesn't exist."),
294
      '#default_value' => !empty($mapping['autocreate']) ? $mapping['autocreate'] : 0,
295
      '#states' => array(
296
        'visible' => array(
297
          ':input[name$="[settings][term_search]"]' => array('value' => FEEDS_TAXONOMY_SEARCH_TERM_NAME),
298
        ),
299
      ),
300
    ),
301
  );
302
}
303

    
304
/**
305
 * Returns the list of available term search methods.
306
 *
307
 * @return array
308
 *   An array of taxonomy search option titles.
309
 */
310
function _taxonomy_feeds_form_callback_options() {
311
  return array(
312
    FEEDS_TAXONOMY_SEARCH_TERM_NAME => 'Term name',
313
    FEEDS_TAXONOMY_SEARCH_TERM_ID => 'Term ID',
314
    FEEDS_TAXONOMY_SEARCH_TERM_GUID => 'GUID',
315
  );
316
}