content_taxonomy_et.module 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. <?php
  2. /**
  3. * @file
  4. * Entity Translation integration for taxonomy terms.
  5. */
  6. /**
  7. * Implements hook_content_taxonomy_tree_callback_alter().
  8. */
  9. function content_taxonomy_et_content_taxonomy_tree_callback_alter(&$tree_callback, $field, $vocabulary) {
  10. // Checks whether the Entity Translation mode with the title field is enabled,
  11. // if so, replace the tree callback with our custom language specific
  12. // implementation.
  13. if (title_field_replacement_enabled('taxonomy_term', $vocabulary->machine_name, 'name')) {
  14. $tree_callback = 'content_taxonomy_et_get_tree';
  15. }
  16. }
  17. /**
  18. * Implements hook_menu_alter().
  19. */
  20. function content_taxonomy_et_menu_alter(&$items) {
  21. // Localize autocompletes.
  22. $items['taxonomy/autocomplete']['page callback'] = 'content_taxonomy_et_autocomplete';
  23. if (isset($items['autocomplete_deluxe/taxonomy'])) {
  24. $items['autocomplete_deluxe/taxonomy']['page callback'] = 'content_taxonomy_et_autocomplete_deluxe';
  25. }
  26. }
  27. /**
  28. * Implements hook_field_widget_form_alter().
  29. */
  30. function content_taxonomy_et_field_widget_form_alter(&$element, &$form_state, $context) {
  31. // Change validation callback for autocompletes in order to fix the
  32. // retrieving of terms in the right language.
  33. if (in_array($context['instance']['widget']['type'], array('taxonomy_autocomplete', 'autocomplete_deluxe_taxonomy'))) {
  34. foreach ($element['#element_validate'] as $key => $validate_callback) {
  35. if ($validate_callback == 'taxonomy_autocomplete_validate') {
  36. $element['#element_validate'][$key] = 'content_taxonomy_et_autocomplete_validate';
  37. break;
  38. }
  39. }
  40. }
  41. }
  42. /**
  43. * Replacement for taxonomy_get_tree().
  44. *
  45. * Exchanges the term name property with the title field value in the current
  46. * language.
  47. */
  48. function content_taxonomy_et_get_tree($vid, $parent = 0, $max_depth = NULL, $load_entities = FALSE) {
  49. global $language;
  50. $children = &drupal_static(__FUNCTION__, array());
  51. $parents = &drupal_static(__FUNCTION__ . ':parents', array());
  52. $terms = &drupal_static(__FUNCTION__ . ':terms', array());
  53. // We cache trees, so it's not CPU-intensive to call taxonomy_get_tree() on a
  54. // term and its children, too.
  55. if (!isset($children[$vid])) {
  56. $children[$vid] = array();
  57. $parents[$vid] = array();
  58. $terms[$vid] = array();
  59. $query = db_select('taxonomy_term_data', 't');
  60. $query->join('taxonomy_term_hierarchy', 'h', 'h.tid = t.tid');
  61. $query->leftJoin('field_data_name_field', 'fd', 'fd.entity_id = t.tid AND fd.entity_type = :type AND fd.language = :language',
  62. array(':type' => 'taxonomy_term', ':language' => $language->language));
  63. $result = $query
  64. ->addTag('translatable')
  65. ->addTag('term_access')
  66. ->fields('t')
  67. ->fields('h', array('parent'))
  68. ->fields('fd', array('name_field_value'))
  69. ->condition('t.vid', $vid)
  70. ->orderBy('t.weight')
  71. ->orderBy('t.name')
  72. ->execute();
  73. foreach ($result as $term) {
  74. $children[$vid][$term->parent][] = $term->tid;
  75. $parents[$vid][$term->tid][] = $term->parent;
  76. $terms[$vid][$term->tid] = $term;
  77. }
  78. }
  79. // Load full entities, if necessary. The entity controller statically
  80. // caches the results.
  81. if ($load_entities) {
  82. $term_entities = taxonomy_term_load_multiple(array_keys($terms[$vid]));
  83. }
  84. $max_depth = (!isset($max_depth)) ? count($children[$vid]) : $max_depth;
  85. $tree = array();
  86. // Keeps track of the parents we have to process, the last entry is used
  87. // for the next processing step.
  88. $process_parents = array();
  89. $process_parents[] = $parent;
  90. // Loops over the parent terms and adds its children to the tree array.
  91. // Uses a loop instead of a recursion, because it's more efficient.
  92. while (count($process_parents)) {
  93. $parent = array_pop($process_parents);
  94. // The number of parents determines the current depth.
  95. $depth = count($process_parents);
  96. if ($max_depth > $depth && !empty($children[$vid][$parent])) {
  97. $has_children = FALSE;
  98. $child = current($children[$vid][$parent]);
  99. do {
  100. if (empty($child)) {
  101. break;
  102. }
  103. $term = $load_entities ? $term_entities[$child] : $terms[$vid][$child];
  104. if (isset($parents[$vid][$term->tid])) {
  105. // Clone the term so that the depth attribute remains correct
  106. // in the event of multiple parents.
  107. $term = clone $term;
  108. }
  109. // Use translation if it exists in the name property.
  110. if (!empty($term->name_field_value)) {
  111. $term->name = $term->name_field_value;
  112. }
  113. $term->depth = $depth;
  114. unset($term->parent);
  115. $term->parents = $parents[$vid][$term->tid];
  116. $tree[] = $term;
  117. if (!empty($children[$vid][$term->tid])) {
  118. $has_children = TRUE;
  119. // We have to continue with this parent later.
  120. $process_parents[] = $parent;
  121. // Use the current term as parent for the next iteration.
  122. $process_parents[] = $term->tid;
  123. // Reset pointers for child lists because we step in there more often
  124. // with multi parents.
  125. reset($children[$vid][$term->tid]);
  126. // Move pointer so that we get the correct term the next time.
  127. next($children[$vid][$parent]);
  128. break;
  129. }
  130. } while ($child = next($children[$vid][$parent]));
  131. if (!$has_children) {
  132. // We processed all terms in this hierarchy-level, reset pointer
  133. // so that this function works the next time it gets called.
  134. reset($children[$vid][$parent]);
  135. }
  136. }
  137. }
  138. return $tree;
  139. }
  140. /**
  141. * Replacement for form validate handler taxonomy_autocomplete_validate().
  142. *
  143. * Uses content_taxonomy_et_get_first_possible_term() to retrieve the right term
  144. * in the right language, instead of term_load_multiple().
  145. */
  146. function content_taxonomy_et_autocomplete_validate($element, &$form_state) {
  147. // Autocomplete widgets do not send their tids in the form, so we must detect
  148. // them here and process them independently.
  149. $value = array();
  150. if ($tags = $element['#value']) {
  151. // Collect candidate vocabularies.
  152. $field = field_widget_field($element, $form_state);
  153. $vocabularies = array();
  154. foreach ($field['settings']['allowed_values'] as $tree) {
  155. if ($vocabulary = taxonomy_vocabulary_machine_name_load($tree['vocabulary'])) {
  156. $vocabularies[$vocabulary->vid] = $vocabulary;
  157. }
  158. }
  159. // Translate term names into actual terms.
  160. $typed_terms = drupal_explode_tags($tags);
  161. foreach ($typed_terms as $typed_term) {
  162. // See if the term exists in the chosen vocabulary and return the tid;
  163. // otherwise, create a new 'autocreate' term for insert/update.
  164. $term = content_taxonomy_et_get_first_possible_term(trim($typed_term), array_keys($vocabularies));
  165. if (!$term) {
  166. $vocabulary = reset($vocabularies);
  167. $term = array(
  168. 'tid' => 'autocreate',
  169. 'vid' => $vocabulary->vid,
  170. 'name' => $typed_term,
  171. 'vocabulary_machine_name' => $vocabulary->machine_name,
  172. );
  173. }
  174. $value[] = (array)$term;
  175. }
  176. }
  177. form_set_value($element, $value, $form_state);
  178. }
  179. /**
  180. * Replacement for taxonomy_autocomplete().
  181. *
  182. * Adds an additional left join to the translatable title field.
  183. */
  184. function content_taxonomy_et_autocomplete($field_name = '', $tags_typed = '') {
  185. global $language;
  186. // If the request has a '/' in the search text, then the menu system will have
  187. // split it into multiple arguments, recover the intended $tags_typed.
  188. $args = func_get_args();
  189. // Shift off the $field_name argument.
  190. array_shift($args);
  191. $tags_typed = implode('/', $args);
  192. // Make sure the field exists and is a taxonomy field.
  193. if (!($field = field_info_field($field_name)) || $field['type'] !== 'taxonomy_term_reference') {
  194. // Error string. The JavaScript handler will realize this is not JSON and
  195. // will display it as debugging information.
  196. print t('Taxonomy field @field_name not found.', array('@field_name' => $field_name));
  197. exit;
  198. }
  199. // The user enters a comma-separated list of tags. We only autocomplete the last tag.
  200. $tags_typed = drupal_explode_tags($tags_typed);
  201. $tag_last = drupal_strtolower(array_pop($tags_typed));
  202. $term_matches = array();
  203. if ($tag_last != '') {
  204. // Part of the criteria for the query come from the field's own settings.
  205. $vids = array();
  206. $vocabularies = taxonomy_vocabulary_get_names();
  207. foreach ($field['settings']['allowed_values'] as $tree) {
  208. $vids[] = $vocabularies[$tree['vocabulary']]->vid;
  209. }
  210. $query = db_select('taxonomy_term_data', 't');
  211. $query->addTag('translatable');
  212. $query->addTag('term_access');
  213. $query->leftJoin('field_data_name_field', 'fd', 'fd.entity_id = t.tid AND fd.entity_type = :type AND fd.language = :language',
  214. array(':type' => 'taxonomy_term', ':language' => $language->language));
  215. // Do not select already entered terms.
  216. if (!empty($tags_typed)) {
  217. $query->condition('t.name', $tags_typed, 'NOT IN');
  218. }
  219. // Select rows that match by term name.
  220. $tags_return = $query
  221. ->fields('t', array('tid', 'name'))
  222. ->fields('fd', array('name_field_value'))
  223. ->condition('t.vid', $vids)
  224. ->condition(db_or()->condition('t.name', '%' . db_like($tag_last) . '%', 'LIKE')->condition('fd.name_field_value', '%' . db_like($tag_last) . '%', 'LIKE'))
  225. ->range(0, 10)
  226. ->execute();
  227. $prefix = count($tags_typed) ? drupal_implode_tags($tags_typed) . ', ' : '';
  228. foreach ($tags_return as $record) {
  229. $name = !empty($record->name_field_value) ? $record->name_field_value : $record->name;
  230. $n = $name;
  231. // Term names containing commas or quotes must be wrapped in quotes.
  232. if (strpos($name, ',') !== FALSE || strpos($name, '"') !== FALSE) {
  233. $n = '"' . str_replace('"', '""', $name) . '"';
  234. }
  235. $term_matches[$prefix . $n] = check_plain($name);
  236. }
  237. }
  238. drupal_json_output($term_matches);
  239. }
  240. /**
  241. * Replacement for taxonomy_autocomplete_deluxe().
  242. *
  243. * Adds an additional left join to the translatable title field.
  244. *
  245. * @todo
  246. * Merge with content_taxonomy_et_autocomplete().
  247. */
  248. function content_taxonomy_et_autocomplete_deluxe($field_name, $tags_typed = '', $limit = 10) {
  249. global $language;
  250. $field = field_info_field($field_name);
  251. $use_synonyms = !empty($_GET['synonyms']);
  252. // The user enters a comma-separated list of tags. We only autocomplete the last tag.
  253. $tags_typed = drupal_explode_tags($tags_typed);
  254. $tag_last = drupal_strtolower(array_pop($tags_typed));
  255. $matches = array();
  256. // Part of the criteria for the query come from the field's own settings.
  257. $vids = array();
  258. $vocabularies = taxonomy_vocabulary_get_names();
  259. foreach ($field['settings']['allowed_values'] as $tree) {
  260. // If the content taxonomy setting content_taxonomy_ignore_in_suggestions
  261. // is set, then the vocabulary is ignored.
  262. if (empty($tree['content_taxonomy_ignore_in_suggestions'])) {
  263. $vids[] = $vocabularies[$tree['vocabulary']]->vid;
  264. }
  265. }
  266. $query = db_select('taxonomy_term_data', 't');
  267. $query->addTag('translatable');
  268. $query->addTag('term_access');
  269. $query->leftJoin('field_data_name_field', 'fd', 'fd.entity_id = t.tid AND fd.entity_type = :type AND fd.language = :language',
  270. array(':type' => 'taxonomy_term', ':language' => $language->language));
  271. if (module_exists('synonyms') && !empty($use_synonyms)) {
  272. $query->leftJoin('field_data_synonyms_synonym', 'fdss', 'fdss.entity_id = t.tid');
  273. }
  274. if ($tag_last != '') {
  275. // Do not select already entered terms.
  276. if (!empty($tags_typed)) {
  277. $query->condition('t.name', $tags_typed, 'NOT IN');
  278. }
  279. // Select rows that match by term name.
  280. $query
  281. ->fields('t', array('tid', 'name'))
  282. ->fields('fd', array('name_field_value'))
  283. ->condition('t.vid', $vids);
  284. if (module_exists('synonyms') && !empty($use_synonyms)) {
  285. $or = db_or();
  286. $or->condition('fdss.synonyms_synonym_value', '%' . db_like($tag_last) . '%', 'LIKE');
  287. $or->condition('t.name', '%' . db_like($tag_last) . '%', 'LIKE');
  288. $or->condition('fd.name_field_value', '%' . db_like($tag_last) . '%', 'LIKE');
  289. $query->condition($or);
  290. }
  291. else {
  292. $query->condition(db_or()->condition('t.name', '%' . db_like($tag_last) . '%', 'LIKE')->condition('fd.name_field_value', '%' . db_like($tag_last) . '%', 'LIKE'));
  293. }
  294. if (isset($limit) && $limit > 0) {
  295. $query->range(0, $limit);
  296. }
  297. $tags_return = $query->execute();
  298. }
  299. else {
  300. $query
  301. ->fields('t', array('tid', 'name'))
  302. ->fields('fd', array('name_field_value'))
  303. ->condition('t.vid', $vids);
  304. if (isset($limit) && $limit > 0) {
  305. $query->range(0, $limit);
  306. }
  307. $tags_return = $query->execute();
  308. }
  309. $prefix = count($tags_typed) ? drupal_implode_tags($tags_typed) . ', ' : '';
  310. $term_matches = array();
  311. foreach ($tags_return as $record) {
  312. $name = !empty($record->name_field_value) ? $record->name_field_value : $record->name;
  313. $n = $name;
  314. // Term names containing commas or quotes must be wrapped in quotes.
  315. if (strpos($name, ',') !== FALSE || strpos($name, '"') !== FALSE) {
  316. $n = '"' . str_replace('"', '""', $name) . '"';
  317. }
  318. $term_matches[$prefix . $n] = check_plain($name);
  319. }
  320. drupal_json_output($term_matches);
  321. }
  322. /**
  323. * Helper function that retrieves the first possible term object for a given
  324. * term name and and array of vocabulary ids.
  325. *
  326. * Used in content_taxonomy_et_autocomplete_validate().
  327. */
  328. function content_taxonomy_et_get_first_possible_term($term_name, $vids) {
  329. global $language;
  330. // EFQ does not work here, as we do not have OR condition possibilities.
  331. $query = db_select('taxonomy_term_data', 't');
  332. $query->addTag('translatable');
  333. $query->addTag('term_access');
  334. $query->leftJoin('field_data_name_field', 'fd', 'fd.entity_id = t.tid AND fd.entity_type = :type AND fd.language = :language',
  335. array(':type' => 'taxonomy_term', ':language' => $language->language));
  336. $query->fields('t', array('tid'))
  337. ->condition('t.vid', $vids, 'IN')
  338. ->condition(db_or()->condition('t.name', $term_name)->condition('fd.name_field_value', $term_name))
  339. ->orderBy('t.tid', 'ASC')
  340. ->execute();
  341. $first_tid = $query->execute()->fetchColumn();
  342. if (!empty($first_tid)) {
  343. $term = taxonomy_term_load($first_tid);
  344. return $term;
  345. }
  346. return FALSE;
  347. }