taxonomy.inc 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. <?php
  2. /**
  3. * @file
  4. * On behalf implementation of Feeds mapping API for taxonomy.module.
  5. */
  6. /**
  7. * Search by term name.
  8. */
  9. define('FEEDS_TAXONOMY_SEARCH_TERM_NAME', 0);
  10. /**
  11. * Search by term id.
  12. */
  13. define('FEEDS_TAXONOMY_SEARCH_TERM_ID', 1);
  14. /**
  15. * Search by GUID.
  16. */
  17. define('FEEDS_TAXONOMY_SEARCH_TERM_GUID', 2);
  18. /**
  19. * Implements hook_feeds_parser_sources_alter().
  20. */
  21. function taxonomy_feeds_parser_sources_alter(array &$sources, $content_type) {
  22. if (!empty($content_type)) {
  23. foreach (taxonomy_get_vocabularies($content_type) as $vocabulary) {
  24. $sources['parent:taxonomy:' . $vocabulary->machine_name] = array(
  25. 'name' => t('Feed node: Taxonomy: @vocabulary', array('@vocabulary' => $vocabulary->name)),
  26. 'description' => t('Taxonomy terms from feed node in given vocabulary.'),
  27. 'callback' => 'taxonomy_feeds_get_source',
  28. );
  29. }
  30. }
  31. }
  32. /**
  33. * Callback, returns taxonomy from feed node.
  34. */
  35. function taxonomy_feeds_get_source(FeedsSource $source, FeedsParserResult $result, $key) {
  36. if ($node = node_load($source->feed_nid)) {
  37. $terms = taxonomy_feeds_node_get_terms($node);
  38. $vocabularies = taxonomy_vocabulary_load_multiple(array(), array('machine_name' => str_replace('parent:taxonomy:', '', $key)));
  39. $vocabulary = array_shift($vocabularies);
  40. $result = array();
  41. foreach ($terms as $tid => $term) {
  42. if ($term->vid == $vocabulary->vid) {
  43. $result[] = new FeedsTermElement($term);
  44. }
  45. }
  46. return $result;
  47. }
  48. }
  49. /**
  50. * Implements hook_feeds_processor_targets().
  51. */
  52. function taxonomy_feeds_processor_targets($entity_type, $bundle_name) {
  53. $targets = array();
  54. foreach (field_info_instances($entity_type, $bundle_name) as $name => $instance) {
  55. $info = field_info_field($name);
  56. if ($info['type'] == 'taxonomy_term_reference') {
  57. $targets[$name] = array(
  58. 'name' => check_plain($instance['label']),
  59. 'callback' => 'taxonomy_feeds_set_target',
  60. 'description' => t('The @label field of the entity.', array('@label' => $instance['label'])),
  61. 'summary_callbacks' => array('taxonomy_feeds_summary_callback'),
  62. 'form_callbacks' => array('taxonomy_feeds_form_callback'),
  63. );
  64. }
  65. }
  66. if ($entity_type == 'taxonomy_term') {
  67. $targets['tid']['name'] = t('Term id');
  68. $targets['tid']['description'] = t('The tid of the taxonomy term. NOTE: use this feature with care, node ids are usually assigned by Drupal.');
  69. unset($targets['vocabulary']);
  70. }
  71. return $targets;
  72. }
  73. /**
  74. * Callback for mapping taxonomy terms.
  75. */
  76. function taxonomy_feeds_set_target(FeedsSource $source, $entity, $target, array $terms, array $mapping) {
  77. $language = $mapping['language'];
  78. // Add in default values.
  79. $mapping += array(
  80. 'term_search' => FEEDS_TAXONOMY_SEARCH_TERM_NAME,
  81. 'autocreate' => FALSE,
  82. );
  83. $info = field_info_field($target);
  84. $cache = &drupal_static(__FUNCTION__);
  85. if (!isset($cache['allowed_values'][$target])) {
  86. $cache['allowed_values'][$target] = taxonomy_allowed_values($info);
  87. }
  88. if (!isset($cache['allowed_vocabularies'][$target])) {
  89. foreach ($info['settings']['allowed_values'] as $tree) {
  90. if ($vocabulary = taxonomy_vocabulary_machine_name_load($tree['vocabulary'])) {
  91. $cache['allowed_vocabularies'][$target][$vocabulary->vid] = $vocabulary->machine_name;
  92. }
  93. }
  94. }
  95. // Some kind of configuration issue. Perhaps the vocabulary was deleted.
  96. // Nothing we can do about it.
  97. if (empty($cache['allowed_vocabularies'][$target])) {
  98. return;
  99. }
  100. $query = new EntityFieldQuery();
  101. $query->entityCondition('entity_type', 'taxonomy_term')
  102. ->entityCondition('bundle', $cache['allowed_vocabularies'][$target])
  103. ->range(0, 1);
  104. $field = isset($entity->$target) ? $entity->$target : array($language => array());
  105. if (!isset($field[$language])) {
  106. $field[$language] = array();
  107. }
  108. // Allow for multiple mappings to the same target.
  109. $delta = count($field[$language]);
  110. // Iterate over all values.
  111. foreach ($terms as $term) {
  112. if ($info['cardinality'] == $delta) {
  113. break;
  114. }
  115. $tid = FALSE;
  116. // FeedsTermElement already is a term.
  117. if ($term instanceof FeedsTermElement) {
  118. $tid = $term->tid;
  119. }
  120. else {
  121. switch ($mapping['term_search']) {
  122. // Lookup by name.
  123. case FEEDS_TAXONOMY_SEARCH_TERM_NAME:
  124. $term = trim($term);
  125. $name_query = clone $query;
  126. if (strlen($term) && $tids = $name_query->propertyCondition('name', $term)->execute()) {
  127. // Find the first allowed term.
  128. foreach ($tids['taxonomy_term'] as $possible_term) {
  129. if (isset($cache['allowed_values'][$target][$possible_term->tid])) {
  130. $tid = $possible_term->tid;
  131. break;
  132. }
  133. }
  134. }
  135. elseif ($mapping['autocreate'] && strlen($term)) {
  136. $term = (object) array(
  137. 'name' => drupal_substr($term, 0, 255),
  138. 'vid' => key($cache['allowed_vocabularies'][$target]),
  139. 'vocabulary_machine_name' => reset($cache['allowed_vocabularies'][$target]),
  140. );
  141. // Set language if the taxonomy is multilingual.
  142. if ($language !== LANGUAGE_NONE) {
  143. $info = entity_get_info('taxonomy_term');
  144. if (!empty($info['entity keys']['language'])) {
  145. $term->{$info['entity keys']['language']} = $language;
  146. }
  147. }
  148. taxonomy_term_save($term);
  149. $tid = $term->tid;
  150. // Add to the list of allowed values.
  151. $cache['allowed_values'][$target][$tid] = $term->name;
  152. }
  153. break;
  154. // Lookup by tid.
  155. case FEEDS_TAXONOMY_SEARCH_TERM_ID:
  156. if (is_numeric($term)) {
  157. $tid = (int) $term;
  158. }
  159. break;
  160. // Lookup by GUID.
  161. case FEEDS_TAXONOMY_SEARCH_TERM_GUID:
  162. $tid = taxonomy_feeds_term_lookup_term_by_guid($term);
  163. break;
  164. }
  165. }
  166. if ($tid && isset($cache['allowed_values'][$target][$tid])) {
  167. $field[$language][] = array('tid' => $tid);
  168. $delta++;
  169. }
  170. }
  171. $entity->$target = $field;
  172. }
  173. /**
  174. * Finds all terms associated with the given node, within one vocabulary.
  175. */
  176. function taxonomy_feeds_node_get_terms($node, $key = 'tid') {
  177. $terms = &drupal_static(__FUNCTION__);
  178. if (!isset($terms[$node->nid][$key])) {
  179. // Get tids from all taxonomy_term_reference fields.
  180. $tids = array();
  181. $fields = field_info_fields();
  182. foreach ($fields as $field_name => $field) {
  183. if ($field['type'] == 'taxonomy_term_reference' && field_info_instance('node', $field_name, $node->type)) {
  184. if (($items = field_get_items('node', $node, $field_name)) && is_array($items)) {
  185. $tids = array_merge($tids, array_map('_taxonomy_feeds_extract_tid', $items));
  186. }
  187. }
  188. }
  189. // Load terms and cache them in static var.
  190. $curr_terms = taxonomy_term_load_multiple($tids);
  191. $terms[$node->nid][$key] = array();
  192. foreach ($curr_terms as $term) {
  193. $terms[$node->nid][$key][$term->$key] = $term;
  194. }
  195. }
  196. return $terms[$node->nid][$key];
  197. }
  198. /**
  199. * Extracts tid from array item returned by field_get_items().
  200. *
  201. * @param array $item
  202. * Tid information in the form of a single element array
  203. * (key == 'tid', value == tid we're looking for)
  204. *
  205. * @return int
  206. * Term id extracted from $item.
  207. *
  208. * @see taxonomy_feeds_node_get_terms()
  209. * @see field_get_items()
  210. */
  211. function _taxonomy_feeds_extract_tid($item) {
  212. return $item['tid'];
  213. }
  214. /**
  215. * Looks up a term by GUID, assumes SQL storage backend.
  216. *
  217. * @param string $guid
  218. * The Feeds GUID to compare against.
  219. *
  220. * @return int|FALSE
  221. * The term id, or FALSE if one was not found.
  222. */
  223. function taxonomy_feeds_term_lookup_term_by_guid($guid) {
  224. return db_select('feeds_item')
  225. ->fields('feeds_item', array('entity_id'))
  226. ->condition('entity_type', 'taxonomy_term')
  227. ->condition('guid', $guid)
  228. ->execute()
  229. ->fetchField();
  230. }
  231. /**
  232. * Mapping configuration summary for taxonomy.module.
  233. */
  234. function taxonomy_feeds_summary_callback(array $mapping, $target, array $form, array $form_state) {
  235. $options = _taxonomy_feeds_form_callback_options();
  236. if (empty($mapping['term_search'])) {
  237. return t('Search taxonomy terms by: <strong>@search</strong>', array('@search' => $options[FEEDS_TAXONOMY_SEARCH_TERM_NAME]));
  238. }
  239. return t('Search taxonomy terms by: <strong>@search</strong>', array('@search' => $options[$mapping['term_search']]));
  240. }
  241. /**
  242. * Settings form callback.
  243. */
  244. function taxonomy_feeds_form_callback(array $mapping, $target, array $form, array $form_state) {
  245. return array(
  246. 'term_search' => array(
  247. '#type' => 'select',
  248. '#title' => t('Search taxonomy terms by'),
  249. '#options' => _taxonomy_feeds_form_callback_options(),
  250. '#default_value' => !empty($mapping['term_search']) ? $mapping['term_search'] : FEEDS_TAXONOMY_SEARCH_TERM_NAME,
  251. ),
  252. 'autocreate' => array(
  253. '#type' => 'checkbox',
  254. '#title' => t('Auto create'),
  255. '#description' => t("Create the term if it doesn't exist."),
  256. '#default_value' => !empty($mapping['autocreate']) ? $mapping['autocreate'] : 0,
  257. '#states' => array(
  258. 'visible' => array(
  259. ':input[name$="[settings][term_search]"]' => array('value' => FEEDS_TAXONOMY_SEARCH_TERM_NAME),
  260. ),
  261. ),
  262. ),
  263. );
  264. }
  265. /**
  266. * Returns the list of available term search methods.
  267. *
  268. * @return array
  269. * An array of taxonomy search option titles.
  270. */
  271. function _taxonomy_feeds_form_callback_options() {
  272. return array(
  273. FEEDS_TAXONOMY_SEARCH_TERM_NAME => 'Term name',
  274. FEEDS_TAXONOMY_SEARCH_TERM_ID => 'Term ID',
  275. FEEDS_TAXONOMY_SEARCH_TERM_GUID => 'GUID',
  276. );
  277. }