i18n_taxonomy.module 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272
  1. <?php
  2. /**
  3. * @file
  4. * i18n taxonomy module
  5. *
  6. * Internationalization (i18n) package.
  7. *
  8. * This module groups together all existing i18n taxonomy functionality
  9. * providing several options for taxonomy translation.
  10. *
  11. * Translates taxonomy term for selected vocabularies running them through the localization system.
  12. * It also translates terms for views filters and views results.
  13. *
  14. * @author Jose A. Reyero, 2004
  15. */
  16. /**
  17. * Implements hook_help().
  18. */
  19. function i18n_taxonomy_help($path, $arg) {
  20. switch ($path) {
  21. case 'admin/help#i18n_taxonomy' :
  22. $output = '<p>' . t('This module adds support for multilingual taxonomy. You can set up multilingual options for each vocabulary:') . '</p>';
  23. $output .= '<ul>';
  24. $output .= '<li>' . t('A language can be assigned globaly for a vocabulary.') . '</li>';
  25. $output .= '<li>' . t('Different terms for each language with translation relationships.') . '</li>';
  26. $output .= '<li>' . t('Terms can be common to all languages, but may be localized.') . '</li>';
  27. $output .= '</ul>';
  28. $output .= '<p>' . t('To search and translate strings, use the <a href="@translate-interface">translation interface</a> pages.', array('@translate-interface' => url('admin/config/regional/translate'))) . '</p>';
  29. $output .= '<p>' . t('For more information, see the online handbook entry for <a href="@i18n">Internationalization module</a>.', array('@i18n' => 'http://drupal.org/node/133977')) . '</p>';
  30. return $output;
  31. case 'admin/config/regional/i18n':
  32. $output = '<p>' . t('To set up multilingual options for vocabularies go to <a href="@configure_taxonomy">Taxonomy configuration page</a>.', array('@configure_taxonomy' => url('admin/structure/taxonomy'))) . '</p>';
  33. return $output;
  34. case 'admin/structure/taxonomy/%':
  35. $vocabulary = taxonomy_vocabulary_machine_name_load($arg[3]);
  36. switch (i18n_taxonomy_vocabulary_mode($vocabulary)) {
  37. case I18N_MODE_LOCALIZE:
  38. return '<p>' . t('%capital_name is a localizable vocabulary. You will be able to translate term names and descriptions using the <a href="@translate-interface">translate interface</a> pages.', array('%capital_name' => drupal_ucfirst($vocabulary->name), '%name' => $vocabulary->name, '@translate-interface' => url('admin/config/regional/translate'))) . '</p>';
  39. case I18N_MODE_LANGUAGE:
  40. return '<p>' . t('%capital_name is a vocabulary with a fixed language. All the terms in this vocabulary will have %language language.', array('%capital_name' => drupal_ucfirst($vocabulary->name), '%name' => $vocabulary->name, '%language' => i18n_language_property($vocabulary->language, 'name'))) . '</p>';
  41. case I18N_MODE_TRANSLATE:
  42. return '<p>' . t('%capital_name is a full multilingual vocabulary. You will be able to set a language for each term and create translation relationships.', array('%capital_name' => drupal_ucfirst($vocabulary->name))) . '</p>';
  43. }
  44. break;
  45. }
  46. }
  47. /**
  48. * Implements hook_menu().
  49. */
  50. function i18n_taxonomy_menu() {
  51. $items['admin/structure/taxonomy/%taxonomy_vocabulary_machine_name/list/list'] = array(
  52. 'title' => 'Terms',
  53. 'type' => MENU_DEFAULT_LOCAL_TASK,
  54. 'weight' => -20,
  55. );
  56. $items['admin/structure/taxonomy/%taxonomy_vocabulary_machine_name/list/sets'] = array(
  57. 'title' => 'Translation sets',
  58. 'page callback' => 'i18n_taxonomy_translation_sets_overview',
  59. 'page arguments' => array(3),
  60. 'access callback' => 'i18n_taxonomy_vocabulary_translation_tab_sets_access',
  61. 'access arguments' => array(3),
  62. 'type' => MENU_LOCAL_TASK,
  63. 'file' => 'i18n_taxonomy.admin.inc',
  64. );
  65. $items['admin/structure/taxonomy/%taxonomy_vocabulary_machine_name/list/sets/add'] = array(
  66. 'title' => 'Create new translation',
  67. 'page callback' => 'drupal_get_form',
  68. 'page arguments' => array('i18n_taxonomy_translation_term_form', 3),
  69. 'access callback' => 'i18n_taxonomy_vocabulary_translation_tab_sets_access',
  70. 'access arguments' => array(3),
  71. 'type' => MENU_LOCAL_ACTION,
  72. //'parent' => 'admin/content/taxonomy/%taxonomy_vocabulary',
  73. 'file' => 'i18n_taxonomy.admin.inc',
  74. );
  75. $items['admin/structure/taxonomy/%taxonomy_vocabulary_machine_name/list/sets/edit/%i18n_taxonomy_translation_set'] = array(
  76. 'title' => 'Edit translation',
  77. 'page callback' => 'drupal_get_form',
  78. 'page arguments' => array('i18n_taxonomy_translation_term_form', 3, 7),
  79. 'access callback' => 'i18n_taxonomy_vocabulary_translation_tab_sets_access',
  80. 'access arguments' => array(3),
  81. 'type' => MENU_CALLBACK,
  82. //'parent' => 'admin/content/taxonomy/%taxonomy_vocabulary',
  83. 'file' => 'i18n_taxonomy.admin.inc',
  84. );
  85. $items['admin/structure/taxonomy/%taxonomy_vocabulary_machine_name/list/sets/delete/%i18n_taxonomy_translation_set'] = array(
  86. 'title' => 'Delete translation',
  87. 'page callback' => 'drupal_get_form',
  88. 'page arguments' => array('i18n_translation_set_delete_confirm', 7),
  89. 'access callback' => 'i18n_taxonomy_vocabulary_translation_tab_sets_access',
  90. 'access arguments' => array(3),
  91. 'type' => MENU_CALLBACK,
  92. );
  93. $items['i18n/taxonomy/autocomplete/vocabulary/%taxonomy_vocabulary_machine_name/%'] = array(
  94. 'title' => 'Autocomplete taxonomy',
  95. 'page callback' => 'i18n_taxonomy_autocomplete_language',
  96. 'page arguments' => array(5, 4),
  97. 'access arguments' => array('access content'),
  98. 'type' => MENU_CALLBACK,
  99. 'file' => 'i18n_taxonomy.pages.inc',
  100. );
  101. $items['i18n/taxonomy/autocomplete/language/%'] = array(
  102. 'title' => 'Autocomplete taxonomy',
  103. 'page callback' => 'i18n_taxonomy_autocomplete_language',
  104. 'page arguments' => array(4, NULL),
  105. 'access arguments' => array('access content'),
  106. 'type' => MENU_CALLBACK,
  107. 'file' => 'i18n_taxonomy.pages.inc',
  108. );
  109. return $items;
  110. }
  111. /**
  112. * Implements hook_admin_paths().
  113. */
  114. function i18n_taxonomy_admin_paths() {
  115. $paths = array(
  116. 'taxonomy/*/translate' => TRUE,
  117. 'taxonomy/*/translate/*' => TRUE,
  118. );
  119. return $paths;
  120. }
  121. /**
  122. * Implements hook_menu_alter().
  123. *
  124. * Take over the taxonomy pages
  125. */
  126. function i18n_taxonomy_menu_alter(&$items) {
  127. // If ctool's page manager is active for the path skip this modules override.
  128. // Also views module takes over this page so this won't work if views enabled.
  129. // Skip when taxonomy_display enabled, see http://drupal.org/node/1280194
  130. if (variable_get('page_manager_term_view_disabled', TRUE) && !module_exists('taxonomy_display')) {
  131. // Taxonomy term page. Localize terms.
  132. $items['taxonomy/term/%taxonomy_term']['page callback'] = 'i18n_taxonomy_term_page';
  133. $items['taxonomy/term/%taxonomy_term']['title callback'] = 'i18n_taxonomy_term_name';
  134. $items['taxonomy/term/%taxonomy_term']['file'] = 'i18n_taxonomy.pages.inc';
  135. $items['taxonomy/term/%taxonomy_term']['file path'] = drupal_get_path('module', 'i18n_taxonomy');
  136. }
  137. // Localize autocomplete
  138. $items['taxonomy/autocomplete']['page callback'] = 'i18n_taxonomy_autocomplete_field';
  139. $items['taxonomy/autocomplete']['file'] = 'i18n_taxonomy.pages.inc';
  140. $items['taxonomy/autocomplete']['file path'] = drupal_get_path('module', 'i18n_taxonomy');
  141. }
  142. /**
  143. * Menu access callback for vocabulary translation tab. Show tab only for full multilingual vocabularies.
  144. */
  145. function i18n_taxonomy_vocabulary_translation_tab_sets_access($vocabulary) {
  146. return user_access('administer taxonomy') && i18n_taxonomy_vocabulary_mode($vocabulary->vid, I18N_MODE_TRANSLATE);
  147. }
  148. /**
  149. * Menu access callback for term translation tab. Show tab only for translatable terms
  150. *
  151. * @todo This should work also for localizable terms when we've got that part implemented
  152. */
  153. function i18n_taxonomy_term_translation_tab_access($term) {
  154. return taxonomy_term_edit_access($term) && i18n_taxonomy_vocabulary_mode($term->vid) & I18N_MODE_MULTIPLE && user_access('translate interface');
  155. }
  156. /**
  157. * Implements hook_field_formatter_info().
  158. */
  159. function i18n_taxonomy_field_formatter_info() {
  160. return array(
  161. 'i18n_taxonomy_term_reference_link' => array(
  162. 'label' => t('Link (localized)'),
  163. 'field types' => array('taxonomy_term_reference'),
  164. ),
  165. 'i18n_taxonomy_term_reference_plain' => array(
  166. 'label' => t('Plain text (localized)'),
  167. 'field types' => array('taxonomy_term_reference'),
  168. ),
  169. );
  170. }
  171. /**
  172. * Implements hook_field_formatter_prepare_view().
  173. *
  174. * This preloads all taxonomy terms for multiple loaded objects at once and
  175. * unsets values for invalid terms that do not exist.
  176. */
  177. function i18n_taxonomy_field_formatter_prepare_view($entity_type, $entities, $field, $instances, $langcode, &$items, $displays) {
  178. return taxonomy_field_formatter_prepare_view($entity_type, $entities, $field, $instances, $langcode, $items, $displays);
  179. }
  180. /**
  181. * Implements hook_field_formatter_view().
  182. */
  183. function i18n_taxonomy_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  184. $element = array();
  185. $language = i18n_language_interface();
  186. // Terms whose tid is 'autocreate' do not exist
  187. // yet and $item['taxonomy_term'] is not set. Theme such terms as
  188. // just their name.
  189. switch ($display['type']) {
  190. case 'i18n_taxonomy_term_reference_link':
  191. foreach ($items as $delta => $item) {
  192. if ($item['tid'] == 'autocreate') {
  193. $element[$delta] = array(
  194. '#markup' => check_plain($item['name']),
  195. );
  196. }
  197. else {
  198. if (isset($item['taxonomy_term'])) {
  199. $term = $item['taxonomy_term'];
  200. }
  201. else {
  202. $term = taxonomy_term_load($item['tid']);
  203. }
  204. $uri = entity_uri('taxonomy_term', $term);
  205. $element[$delta] = array(
  206. '#type' => 'link',
  207. '#title' => i18n_taxonomy_term_name($term, $language->language),
  208. '#href' => $uri['path'],
  209. '#options' => $uri['options'],
  210. );
  211. }
  212. }
  213. break;
  214. case 'i18n_taxonomy_term_reference_plain':
  215. foreach ($items as $delta => $item) {
  216. $name = ($item['tid'] != 'autocreate' ? i18n_taxonomy_term_name($item['taxonomy_term'], $language->language): $item['name']);
  217. $element[$delta] = array(
  218. '#markup' => check_plain($name),
  219. );
  220. }
  221. break;
  222. }
  223. return $element;
  224. }
  225. /**
  226. * Implements hook_field_extra_fields().
  227. */
  228. function i18n_taxonomy_field_extra_fields() {
  229. $return = array();
  230. $info = entity_get_info('taxonomy_term');
  231. foreach (array_keys($info['bundles']) as $bundle) {
  232. $vocabulary = taxonomy_vocabulary_machine_name_load($bundle);
  233. if ($vocabulary && i18n_taxonomy_vocabulary_mode($vocabulary, I18N_MODE_TRANSLATE)) {
  234. $return['taxonomy_term'][$bundle] = i18n_language_field_extra();
  235. }
  236. }
  237. return $return;
  238. }
  239. /**
  240. * Implements hook_field_attach_view_alter().
  241. */
  242. function i18n_taxonomy_field_attach_view_alter(&$output, $context) {
  243. // Copied from rdf_field_attach_view_alter of modules/rdf/rdf.module since we have another #formatter
  244. // Append term mappings on displayed taxonomy links.
  245. foreach (element_children($output) as $field_name) {
  246. $element = &$output[$field_name];
  247. if (isset($element['#field_type']) && $element['#field_type'] == 'taxonomy_term_reference' && $element['#formatter'] == 'i18n_taxonomy_term_reference_link') {
  248. foreach ($element['#items'] as $delta => $item) {
  249. // This function is invoked during entity preview when taxonomy term
  250. // reference items might contain free-tagging terms that do not exist
  251. // yet and thus have no $item['taxonomy_term'].
  252. if (isset($item['taxonomy_term'])) {
  253. $term = $item['taxonomy_term'];
  254. if (!empty($term->rdf_mapping['rdftype'])) {
  255. $element[$delta]['#options']['attributes']['typeof'] = $term->rdf_mapping['rdftype'];
  256. }
  257. if (!empty($term->rdf_mapping['name']['predicates'])) {
  258. $element[$delta]['#options']['attributes']['property'] = $term->rdf_mapping['name']['predicates'];
  259. }
  260. }
  261. }
  262. }
  263. }
  264. // Add language field for display
  265. if ($context['entity_type'] == 'taxonomy_term' && i18n_taxonomy_vocabulary_mode($context['entity']->vid, I18N_MODE_TRANSLATE)) {
  266. $output['language'] = array(
  267. '#type' => 'item',
  268. '#title' => t('Language'),
  269. '#markup' => i18n_language_name($context['entity']->language),
  270. );
  271. }
  272. }
  273. /**
  274. * Implements hook_field_info_alter()
  275. */
  276. function i18n_taxonomy_field_info_alter(&$info) {
  277. // Change default formatter for term reference fields
  278. $info['taxonomy_term_reference']['default_formatter'] = 'i18n_taxonomy_term_reference_link';
  279. // Translate field values.
  280. $info['taxonomy_term_reference']['options_list_callback'] = 'i18n_taxonomy_allowed_values';
  281. // Sync callback for field translations
  282. $info['taxonomy_term_reference']['i18n_sync_callback'] = 'i18n_taxonomy_field_prepare_translation';
  283. }
  284. /**
  285. * Implements hook_field_storage_details_alter().
  286. *
  287. * We don't alter the storage details but the stored details of the field itself...
  288. *
  289. * @param array $field
  290. * The field record just read from the database.
  291. */
  292. function i18n_taxonomy_field_storage_details_alter(&$details, &$field) {
  293. if ($field['type'] === 'taxonomy_term_reference') {
  294. $field['settings']['options_list_callback'] = 'i18n_taxonomy_allowed_values';
  295. }
  296. }
  297. /**
  298. * Implements hook_field_attach_prepare_translation_alter().
  299. *
  300. * Prepare and synchronize translation for term reference fields.
  301. */
  302. function i18n_taxonomy_field_attach_prepare_translation_alter(&$entity, $context) {
  303. $entity_type = $context['entity_type'];
  304. $source_entity = $context['source_entity'];
  305. $options = array(
  306. 'default' => FALSE,
  307. 'deleted' => FALSE,
  308. 'language' => NULL,
  309. );
  310. // Determine the list of instances to iterate on.
  311. list(, , $bundle) = entity_extract_ids($entity_type, $source_entity);
  312. $instances = _field_invoke_get_instances($entity_type, $bundle, $options);
  313. if (!empty($instances)) {
  314. foreach ($instances as $field_info) {
  315. $field = field_info_field($field_info['field_name']);
  316. if ($field['type'] == 'taxonomy_term_reference' && isset($entity->{$field_info['field_name']})) {
  317. // iterate over languages.
  318. foreach ($entity->{$field_info['field_name']} as $language => &$items) {
  319. i18n_taxonomy_field_prepare_translation($entity_type, $entity, $field, $field_info, $entity->language, $items, $source_entity, $source_entity->language);
  320. }
  321. }
  322. }
  323. }
  324. }
  325. /**
  326. * Prepare and synchronize translation for term reference fields
  327. */
  328. function i18n_taxonomy_field_prepare_translation($entity_type, $entity, $field, $instance, $langcode, &$items, $source_entity, $source_langcode) {
  329. foreach ($items as $index => $item) {
  330. $term = isset($item['taxonomy_term']) ? $item['taxonomy_term'] : taxonomy_term_load($item['tid']);
  331. if ($translation = i18n_taxonomy_term_get_translation($term, $langcode)) {
  332. $items[$index] = array(
  333. 'taxonomy_term' => $translation,
  334. 'tid' => $translation->tid
  335. );
  336. }
  337. $field['settings']['options_list_callback'] = 'i18n_taxonomy_allowed_values';
  338. }
  339. }
  340. /**
  341. * Returns the set of valid terms for a taxonomy field.
  342. *
  343. * @param $field
  344. * The field definition.
  345. * @return
  346. * The array of valid terms for this field, keyed by term id.
  347. */
  348. function i18n_taxonomy_allowed_values($field) {
  349. $options = array();
  350. foreach ($field['settings']['allowed_values'] as $tree) {
  351. if ($vocabulary = taxonomy_vocabulary_machine_name_load($tree['vocabulary'])) {
  352. if ($terms = taxonomy_get_tree($vocabulary->vid, $tree['parent'])) {
  353. foreach ($terms as $term) {
  354. $options[$term->tid] = str_repeat('-', $term->depth) . i18n_taxonomy_term_name($term);
  355. }
  356. }
  357. }
  358. }
  359. return $options;
  360. }
  361. /**
  362. * Implements hook_i18n_translate_path()
  363. */
  364. function i18n_taxonomy_i18n_translate_path($path) {
  365. if (strpos($path, 'taxonomy/term/') === 0) {
  366. return i18n_taxonomy_translate_path($path);
  367. }
  368. }
  369. /**
  370. * Implements hook_i18n_context_language().
  371. */
  372. function i18n_taxonomy_i18n_context_language() {
  373. if (arg(0) == 'taxonomy') {
  374. // Taxonomy term pages
  375. if (arg(1) == 'term' && is_numeric(arg(2)) && ($term = menu_get_object('taxonomy_term', 2)) && ($langcode = i18n_object_langcode($term))) {
  376. return i18n_language_object($langcode);
  377. }
  378. }
  379. }
  380. /**
  381. * Find translations for taxonomy paths.
  382. *
  383. * @param $path
  384. * Path to translate.
  385. * @param $path_prefix
  386. * Path prefix, including trailing slash, defaults to 'taxonomy/term/'.
  387. * It will be different for taxonomy term pages and for forum pages.
  388. *
  389. * @return
  390. * Array of links (each an array with href, title), indexed by language code.
  391. */
  392. function i18n_taxonomy_translate_path($path, $path_prefix = 'taxonomy/term/') {
  393. $prefix_match = strtr($path_prefix, array('/' => '\/'));
  394. if (preg_match("/^($prefix_match)([^\/]*)(.*)$/", $path, $matches)) {
  395. $links = array();
  396. $term = FALSE;
  397. // If single term, treat it differently
  398. if (is_numeric($matches[2]) && !$matches[3]) {
  399. $term = taxonomy_term_load($matches[2]);
  400. if (!empty($term->i18n_tsid)) {
  401. $set = i18n_translation_set_load($term->i18n_tsid);
  402. }
  403. }
  404. foreach (language_list() as $langcode => $language) {
  405. if ($term) {
  406. if (!empty($set) && ($translation = $set->get_item($langcode))) {
  407. $links[$langcode] = array(
  408. 'href' => $path_prefix . $translation->tid,
  409. 'title' => $translation->name,
  410. );
  411. }
  412. else {
  413. $links[$langcode] = array(
  414. 'href' => $path,
  415. 'title' => i18n_taxonomy_term_name($term, $langcode),
  416. );
  417. }
  418. }
  419. elseif ($str_tids = i18n_taxonomy_translation_tids($matches[2], $langcode)) {
  420. $links[$langcode]['href'] = $path_prefix . $str_tids . $matches[3];
  421. }
  422. }
  423. return $links;
  424. }
  425. }
  426. /**
  427. * Get localized term name unfiltered.
  428. */
  429. function i18n_taxonomy_term_name($term, $langcode = NULL) {
  430. $key = i18n_object_info('taxonomy_term', 'key');
  431. return i18n_taxonomy_vocabulary_mode($term->vid, I18N_MODE_LOCALIZE) ? i18n_string(array('taxonomy', 'term', $term->{$key}, 'name'), $term->name, array('langcode' => $langcode, 'sanitize' => FALSE)) : $term->name;
  432. }
  433. /**
  434. * Get localized term description unfiltered.
  435. */
  436. function i18n_taxonomy_term_description($term, $langcode = NULL) {
  437. $key = i18n_object_info('taxonomy_term', 'key');
  438. return i18n_taxonomy_vocabulary_mode($term->vid, I18N_MODE_LOCALIZE) ? i18n_string(array('taxonomy', 'term', $term->{$key}, 'description'), $term->description, array('langcode' => $langcode, 'sanitize' => FALSE)) : $term->description;
  439. }
  440. /**
  441. * Find term translation from translation set.
  442. *
  443. * @param $term
  444. * Term object to find translation.
  445. * @param $langcode
  446. * Language code to find translation for.
  447. * @result object Taxonomy Term
  448. * Translation if exists.
  449. */
  450. function i18n_taxonomy_term_get_translation($term, $langcode) {
  451. if (i18n_object_langcode($term)) {
  452. if ($term->language == $langcode) {
  453. // Translation is the term itself.
  454. return $term;
  455. }
  456. elseif (!empty($term->i18n_tsid)) {
  457. return i18n_translation_set_load($term->i18n_tsid)->get_item($langcode);
  458. }
  459. else {
  460. return NULL;
  461. }
  462. }
  463. else {
  464. // Term has no language, translation should be the same
  465. return $term;
  466. }
  467. }
  468. /**
  469. * Get localized vocabulary name, unfiltered.
  470. */
  471. function i18n_taxonomy_vocabulary_name($vocabulary, $langcode = NULL) {
  472. return i18n_object_langcode($vocabulary) ? $vocabulary->name : i18n_string(array('taxonomy', 'vocabulary', $vocabulary->vid, 'name'), $vocabulary->name, array('langcode' => $langcode, 'sanitize' => FALSE));
  473. }
  474. /**
  475. * Get localized vocabulary description, unfiltered.
  476. */
  477. function i18n_taxonomy_vocabulary_description($vocabulary, $langcode = NULL) {
  478. return i18n_object_langcode($vocabulary) ? $vocabulary->description : i18n_string(array('taxonomy', 'vocabulary', $vocabulary->vid, 'description'), $vocabulary->description, array('langcode' => $langcode, 'sanitize' => FALSE));
  479. }
  480. /**
  481. * Get translated term's tid.
  482. *
  483. * @param $tid
  484. * Node nid to search for translation.
  485. * @param $language
  486. * Language to search for the translation, defaults to current language.
  487. * @param $default
  488. * Value that will be returned if no translation is found.
  489. * @return
  490. * Translated term tid if exists, or $default.
  491. */
  492. function i18n_taxonomy_translation_term_tid($tid, $language = NULL, $default = NULL) {
  493. $translation = db_query('SELECT t.tid FROM {taxonomy_term_data} t INNER JOIN {taxonomy_term_data} a ON t.i18n_tsid = a.i18n_tsid AND t.tid <> a.tid WHERE a.tid = :tid AND t.language = :language AND t.i18n_tsid > 0', array(
  494. ':tid' => $tid,
  495. ':language' => $language ? $language : i18n_language_content()->language
  496. ))->fetchField();
  497. return $translation ? $translation : $default;
  498. }
  499. /**
  500. * Returns an url for the translated taxonomy-page, if exists.
  501. */
  502. function i18n_taxonomy_translation_tids($str_tids, $lang) {
  503. if (preg_match('/^([0-9]+[+ ])+[0-9]+$/', $str_tids)) {
  504. $separator = '+';
  505. // The '+' character in a query string may be parsed as ' '.
  506. $tids = preg_split('/[+ ]/', $str_tids);
  507. }
  508. elseif (preg_match('/^([0-9]+,)*[0-9]+$/', $str_tids)) {
  509. $separator = ',';
  510. $tids = explode(',', $str_tids);
  511. }
  512. else {
  513. return;
  514. }
  515. $translated_tids = array();
  516. foreach ($tids as $tid) {
  517. if ($translated_tid = i18n_taxonomy_translation_term_tid($tid, $lang)) {
  518. $translated_tids[] = $translated_tid;
  519. }
  520. }
  521. return implode($separator, $translated_tids);
  522. }
  523. /**
  524. * Implements hook_taxonomy_display_breadcrumb_parents_alter().
  525. */
  526. function i18n_taxonomy_taxonomy_display_breadcrumb_parents_alter(&$parents) {
  527. $parents = i18n_taxonomy_localize_terms($parents);
  528. }
  529. /**
  530. * Implements hook_taxonomy_display_term_page_term_object_alter().
  531. */
  532. function i18n_taxonomy_taxonomy_display_term_page_term_object_alter(&$term) {
  533. $term = i18n_taxonomy_localize_terms($term);
  534. }
  535. /**
  536. * Implements hook_taxonomy_term_insert()
  537. */
  538. function i18n_taxonomy_taxonomy_term_insert($term) {
  539. i18n_taxonomy_taxonomy_term_update($term);
  540. }
  541. /**
  542. * Implements hook_taxonomy_term_update()
  543. */
  544. function i18n_taxonomy_taxonomy_term_update($term) {
  545. if (i18n_taxonomy_vocabulary_mode($term->vid, I18N_MODE_LOCALIZE)) {
  546. i18n_string_object_update('taxonomy_term', $term);
  547. }
  548. // Multilingual terms, translatable. Link / unlink from translation set.
  549. if (i18n_taxonomy_vocabulary_mode($term->vid, I18N_MODE_TRANSLATE) && !empty($term->translation_set)) {
  550. if (i18n_object_langcode($term)) {
  551. $term->translation_set
  552. ->add_item($term)
  553. ->save();
  554. }
  555. elseif (!empty($term->original)) {
  556. // Term set to language neutral, remove it from translation set and update set (delete if empty)
  557. $term->translation_set
  558. ->remove_item($term->original)
  559. ->update_delete();
  560. }
  561. }
  562. }
  563. /**
  564. * Implements hook_taxonomy_term_delete()
  565. */
  566. function i18n_taxonomy_taxonomy_term_delete($term) {
  567. // If a translation set exists for this term, remove this term from the set.
  568. if (isset($term->i18n_tsid) && $term->i18n_tsid) {
  569. $translation_set = i18n_translation_set_load($term->i18n_tsid);
  570. $translation_set->get_translations();
  571. $translation_set->remove_language($term->language);
  572. // If there are no terms left in this translation set, delete the set.
  573. // Otherwise update the set.
  574. $translation_set->update_delete();
  575. }
  576. // Just in case there's any left over string we run it for all terms.
  577. i18n_string_object_remove('taxonomy_term', $term);
  578. }
  579. /**
  580. * Implements hook_taxonomy_vocabulary_insert()
  581. */
  582. function i18n_taxonomy_taxonomy_vocabulary_insert($vocabulary) {
  583. i18n_taxonomy_taxonomy_vocabulary_update($vocabulary);
  584. }
  585. /**
  586. * Implements hook_taxonomy_vocabulary_update()
  587. */
  588. function i18n_taxonomy_taxonomy_vocabulary_update($vocabulary) {
  589. // Update language for related terms
  590. switch (i18n_taxonomy_vocabulary_mode($vocabulary)) {
  591. case I18N_MODE_LANGUAGE:
  592. $update['language'] = $vocabulary->language;
  593. break;
  594. case I18N_MODE_NONE:
  595. $update['language'] = LANGUAGE_NONE;
  596. break;
  597. }
  598. if (isset($update)) {
  599. db_update('taxonomy_term_data')
  600. ->fields($update)
  601. ->condition('vid', $vocabulary->vid)
  602. ->execute();
  603. drupal_set_message(t('Reset language for all terms.'));
  604. }
  605. // Update strings, always add translation if no language
  606. if (!i18n_object_langcode($vocabulary)) {
  607. i18n_string_object_update('taxonomy_vocabulary', $vocabulary);
  608. }
  609. }
  610. /**
  611. * Implements hook_taxonomy_vocabulary_delete()
  612. */
  613. function i18n_taxonomy_taxonomy_vocabulary_delete($vocabulary) {
  614. i18n_string_object_remove('taxonomy_vocabulary', $vocabulary);
  615. }
  616. /**
  617. * Implements hook_taxonomy_term_presave()
  618. */
  619. function i18n_taxonomy_taxonomy_term_presave($term) {
  620. switch (i18n_taxonomy_vocabulary_mode($term->vid)) {
  621. case I18N_MODE_LANGUAGE: // Predefined language for all terms
  622. $term->language = taxonomy_vocabulary_load($term->vid)->language;
  623. break;
  624. case I18N_MODE_TRANSLATE: // Multilingual terms, translatable
  625. if (!isset($term->language)) {
  626. // The term may come from a node tags field, just if this is not a taxonomy form.
  627. // Or from any other object we are editing. So we use 'context' language here.
  628. $term->language = i18n_language_context()->language;
  629. }
  630. // Only for the case the term has no language, it may need to be removed from translation set
  631. if (empty($term->language)) {
  632. $term->i18n_tsid = 0;
  633. }
  634. break;
  635. }
  636. }
  637. /**
  638. * Implements hook_form_FORM_ID_alter()
  639. */
  640. function i18n_taxonomy_form_taxonomy_form_vocabulary_alter(&$form, &$form_state) {
  641. if (!isset($form_state['confirm_delete'])) {
  642. $vocabulary = $form_state['vocabulary'];
  643. $i18n_mode = i18n_taxonomy_vocabulary_mode($vocabulary);
  644. $langcode = i18n_object_langcode($vocabulary, LANGUAGE_NONE);
  645. // Define the replacement names to add some logic to the translation mode options.
  646. $form += i18n_translation_mode_element('taxonomy_vocabulary', $i18n_mode, $langcode);
  647. if (user_access('translate interface')) {
  648. $form['actions']['translate'] = array(
  649. '#type' => 'submit',
  650. '#name' => 'save_translate',
  651. '#value' => t('Save and translate'),
  652. '#weight' => 5,
  653. '#states' => array(
  654. 'invisible' => array(
  655. // Hide the button if language mode is selected value needs to be a
  656. // string so that the javascript-side matching works.
  657. 'input[name=i18n_mode]' => array('value' => (string)I18N_MODE_LANGUAGE),
  658. )
  659. )
  660. );
  661. // Make sure the delete buttons shows up last.
  662. if (isset($form['actions']['delete'])) {
  663. $form['actions']['delete']['#weight'] = 10;
  664. }
  665. }
  666. $form['#validate'][] = 'i18n_taxonomy_form_vocabulary_validate';
  667. $form['#submit'][] = 'i18n_taxonomy_form_vocabulary_submit';
  668. }
  669. }
  670. /**
  671. * Form submit callback to redirect when using the save and translate button.
  672. */
  673. function i18n_taxonomy_form_vocabulary_submit($form, &$form_state) {
  674. if ($form_state['triggering_element']['#name'] == 'save_translate') {
  675. $form_state['redirect'] = 'admin/structure/taxonomy/' . $form_state['values']['machine_name'] . '/translate';
  676. }
  677. }
  678. /**
  679. * Implements hook_form_FORM_ID_alter()
  680. */
  681. function i18n_taxonomy_form_taxonomy_form_term_alter(&$form, &$form_state) {
  682. // Check for confirmation forms
  683. if (isset($form_state['confirm_delete']) || isset($form_state['confirm_parents'])) return;
  684. $term = $form_state['term'];
  685. $vocabulary = $form['#vocabulary'];
  686. // Mark form so we can know later when saving the term it came from a taxonomy form
  687. $form['i18n_taxonomy_form'] = array('#type' => 'value', '#value' => 1);
  688. // Add language field or not depending on taxonomy mode.
  689. switch (i18n_taxonomy_vocabulary_mode($vocabulary->vid)) {
  690. case I18N_MODE_TRANSLATE:
  691. $form['language'] = array(
  692. '#description' => t('This term belongs to a multilingual vocabulary. You can set a language for it.'),
  693. ) + i18n_element_language_select($term);
  694. // If the term to be added will be a translation of a source term,
  695. // set the default value of the option list to the target language and
  696. // create a form element for storing the translation set of the source term.
  697. if (empty($term->tid) && isset($_GET['translation']) && isset($_GET['target']) && ($source_term = taxonomy_term_load($_GET['translation'])) && ($target_language = i18n_language_object($_GET['target']))) {
  698. // Set context language to target language.
  699. i18n_language_context($target_language);
  700. // Add the translation set to the form so we know the new term
  701. // needs to be added to that set.
  702. if (!empty($source_term->i18n_tsid)) {
  703. $translation_set = i18n_taxonomy_translation_set_load($source_term->i18n_tsid);
  704. }
  705. else {
  706. // No translation set yet, build a new one with the source term.
  707. $translation_set = i18n_translation_set_create('taxonomy_term', $vocabulary->machine_name)
  708. ->add_item($source_term);
  709. }
  710. $form['language']['#default_value'] = $target_language->language;
  711. $form['language']['#disabled'] = TRUE;
  712. drupal_set_title(t('%language translation of term %title', array('%language' => locale_language_name($_GET['target']), '%title' => $source_term->name)), PASS_THROUGH);
  713. }
  714. elseif (!empty($term->tid) && i18n_object_langcode($term)) {
  715. // Set context language to term language.
  716. i18n_language_context(i18n_language_object($term->language));
  717. // If the current term is part of a translation set,
  718. // remove all other languages of the option list.
  719. if (!empty($term->i18n_tsid)) {
  720. $translation_set = i18n_taxonomy_translation_set_load($term->i18n_tsid);
  721. $translations = $translation_set->get_translations();
  722. // If the number of translations equals 1, there's only a source translation.
  723. if (count($translations) > 1) {
  724. //unset($form['language']['#options'][LANGUAGE_NONE]);
  725. foreach ($translations as $langcode => $translation) {
  726. if ($translation->tid !== $term->tid) {
  727. unset($form['language']['#options'][$langcode]);
  728. }
  729. }
  730. $form['language']['#description'] = t('This term already belongs to a <a href="@term-translation">translation set</a>. Changing language to <i>Language neutral</i> will remove it from the set.', array('@term-translation' => url('taxonomy/term/' . $term->tid . '/translate')));
  731. }
  732. }
  733. }
  734. // If we've got a translation set, add it to the form.
  735. if (!empty($translation_set)) {
  736. $form['translation_set'] = array(
  737. '#type' => 'value',
  738. '#value' => $translation_set,
  739. );
  740. }
  741. break;
  742. case I18N_MODE_LANGUAGE:
  743. // Set context language to vocabulary language and add value to the form.
  744. i18n_language_context(i18n_language_object($vocabulary->language));
  745. $form['language'] = array(
  746. '#type' => 'value',
  747. '#value' => $vocabulary->language
  748. );
  749. $form['identification']['language_info'] = array('#value' => t('All terms in this vocabulary have a fixed language: %language', array('%language' => i18n_language_name($vocabulary->language))));
  750. break;
  751. case I18N_MODE_LOCALIZE:
  752. $form['language'] = array(
  753. '#type' => 'value',
  754. '#value' => LANGUAGE_NONE,
  755. );
  756. break;
  757. case I18N_MODE_NONE:
  758. default:
  759. $form['language'] = array(
  760. '#type' => 'value',
  761. '#value' => LANGUAGE_NONE,
  762. );
  763. break;
  764. }
  765. if (user_access('translate interface') && i18n_taxonomy_vocabulary_mode($vocabulary->vid) & I18N_MODE_MULTIPLE) {
  766. $form['actions']['translate'] = array(
  767. '#type' => 'submit',
  768. '#name' => 'save_translate',
  769. '#value' => t('Save and translate'),
  770. '#weight' => 5,
  771. '#states' => array(
  772. 'invisible' => array(
  773. // Hide the button if term is language neutral.
  774. 'select[name=language]' => array('value' => LANGUAGE_NONE),
  775. ),
  776. ),
  777. );
  778. // Make sure the delete buttons shows up last.
  779. if (isset($form['actions']['delete'])) {
  780. $form['actions']['delete']['#weight'] = 10;
  781. }
  782. $form['#submit'][] = 'i18n_taxonomy_form_term_submit';
  783. }
  784. }
  785. /**
  786. * Form submit callback to redirect when using the save and translate button.
  787. */
  788. function i18n_taxonomy_form_term_submit($form, &$form_state) {
  789. if ($form_state['triggering_element']['#name'] == 'save_translate') {
  790. // When using the edit link on the list terms, a destination param is
  791. // added that needs to be unset to make the redirection work.
  792. unset($_GET['destination']);
  793. $form_state['redirect'] = 'taxonomy/term/' . $form_state['values']['tid'] . '/translate';
  794. }
  795. }
  796. /**
  797. * Implements hook_form_alter().
  798. *
  799. * This is the place to add language fields to all forms.
  800. *
  801. * @ TO DO The vocabulary form needs some javascript.
  802. */
  803. function i18n_taxonomy_form_alter(&$form, $form_state, $form_id) {
  804. switch ($form_id) {
  805. case 'taxonomy_overview_vocabularies':
  806. $vocabularies = taxonomy_get_vocabularies();
  807. foreach ($vocabularies as $vocabulary) {
  808. if (i18n_object_langcode($vocabulary)) {
  809. $form[$vocabulary->vid]['name']['#markup'] .= ' (' . i18n_language_name($vocabulary->language) . ')';
  810. }
  811. }
  812. break;
  813. case 'taxonomy_overview_terms':
  814. // We check for vocabulary object first, because when confirming alphabetical ordering it uses the same form
  815. if (!empty($form['#vocabulary']) && i18n_taxonomy_vocabulary_mode($form['#vocabulary']->vid) & I18N_MODE_TRANSLATE) {
  816. foreach (element_children($form) as $key) {
  817. if (isset($form[$key]['#term']) && ($lang = i18n_object_langcode($form[$key]['#term']))) {
  818. $form[$key]['view']['#suffix'] = ' (' . i18n_language_name($lang) . ')';
  819. }
  820. }
  821. }
  822. break;
  823. case 'search_form':
  824. // Localize category selector in advanced search form.
  825. if (!empty($form['advanced']) && !empty($form['advanced']['category'])) {
  826. i18n_taxonomy_form_all_localize($form['advanced']['category']);
  827. }
  828. break;
  829. }
  830. }
  831. /**
  832. * Validate multilingual options for vocabulary form
  833. */
  834. function i18n_taxonomy_form_vocabulary_validate($form, &$form_state) {
  835. if ($form_state['values']['i18n_mode'] & I18N_MODE_LANGUAGE) {
  836. if ($form_state['values']['language'] == LANGUAGE_NONE) {
  837. form_set_error('language', t('If selecting "Set language to vocabulary" you need to set a language to this vocabulary. Either change the translation mode or select a language.'));
  838. }
  839. }
  840. else {
  841. $form_state['values']['language'] = LANGUAGE_NONE;
  842. }
  843. }
  844. /**
  845. * Localize a taxonomy_form_all() kind of control
  846. *
  847. * The options array is indexed by vocabulary name and then by term id, with tree structure
  848. * We just need to localize vocabulary name and localizable terms. Multilingual vocabularies
  849. * should have been taken care of by query rewriting.
  850. **/
  851. function i18n_taxonomy_form_all_localize(&$item) {
  852. $options = &$item['#options'];
  853. foreach (taxonomy_get_vocabularies() as $vid => $vocabulary) {
  854. if (!empty($options[$vocabulary->name])) {
  855. // Localize vocabulary name if translated
  856. $vname = i18n_taxonomy_vocabulary_name($vocabulary);
  857. if ($vname != $vocabulary->name) {
  858. $options[$vname] = $options[$vocabulary->name];
  859. unset($options[$vocabulary->name]);
  860. }
  861. if (i18n_taxonomy_vocabulary_mode($vid) & I18N_MODE_LOCALIZE) {
  862. $tree = taxonomy_get_tree($vid);
  863. if ($tree && (count($tree) > 0)) {
  864. foreach ($tree as $term) {
  865. if (isset($options[$vname][$term->tid])) {
  866. $options[$vname][$term->tid] = str_repeat('-', $term->depth) . i18n_taxonomy_term_name($term);
  867. }
  868. }
  869. }
  870. }
  871. }
  872. }
  873. }
  874. /**
  875. * Translate an array of taxonomy terms.
  876. *
  877. * Translates all terms with language, just passing over terms without it.
  878. * Filter out terms with a different language
  879. *
  880. * @param $taxonomy
  881. * Array of term objects or tids or multiple arrays or terms indexed by vid
  882. * @param $langcode
  883. * Language code of target language
  884. * @param $fullterms
  885. * Whether to return full $term objects, returns tids otherwise
  886. * @return
  887. * Array with translated terms: tid -> $term
  888. * Array with vid and term array
  889. */
  890. function i18n_taxonomy_translate_terms($taxonomy, $langcode, $fullterms = TRUE) {
  891. $translation = array();
  892. if (is_array($taxonomy) && $taxonomy) {
  893. foreach ($taxonomy as $index => $tdata) {
  894. if (is_array($tdata)) {
  895. // Case 1: Index is vid, $tdata is an array of terms
  896. $mode = i18n_taxonomy_vocabulary_mode($index);
  897. // We translate just some vocabularies: translatable, fixed language
  898. // Fixed language ones may have terms translated, though the UI doesn't support it
  899. if ($mode & I18N_MODE_LANGUAGE || $mode & I18N_MODE_TRANSLATE) {
  900. $translation[$index] = i18n_taxonomy_translate_terms($tdata, $langcode, $fullterms);
  901. }
  902. elseif ($fullterms) {
  903. $translation[$index] = array_map('_i18n_taxonomy_filter_terms', $tdata);
  904. }
  905. else {
  906. $translation[$index] = array_map('_i18n_taxonomy_filter_tids', $tdata);
  907. }
  908. continue;
  909. }
  910. elseif (is_object($tdata)) {
  911. // Case 2: This is a term object
  912. $term = $tdata;
  913. }
  914. elseif (is_numeric($tdata) && ($tid = (int)$tdata)) {
  915. // Case 3: This is a term tid, load the full term
  916. $term = taxonomy_term_load($tid);
  917. }
  918. // Translate the term if we got it
  919. if (empty($term)) {
  920. // Couldn't identify term, pass through whatever it is
  921. $translation[$index] = $tdata;
  922. }
  923. elseif ($term->language && $term->language != $langcode) {
  924. $translation_set = i18n_translation_set_load($term->i18n_tsid);
  925. $translations = $translation_set->get_translations();
  926. if ($translations && !empty($translations[$langcode])) {
  927. $newterm = $translations[$langcode];
  928. $translation[$newterm->tid] = $fullterms ? $newterm : $newterm->tid;
  929. }
  930. }
  931. else {
  932. // Term has no language. Should be ok.
  933. $translation[$index] = $fullterms ? $term : $term->tid;
  934. }
  935. }
  936. }
  937. return $translation;
  938. }
  939. /**
  940. * Localize taxonomy terms for localizable vocabularies.
  941. *
  942. * @param $terms
  943. * Array of term objects or term object.
  944. * @return
  945. * Array of terms with the right ones localized.
  946. */
  947. function i18n_taxonomy_localize_terms($terms) {
  948. // If not localizable language just return. Performance optimizations.
  949. if (!i18n_string_translate_langcode()) {
  950. return $terms;
  951. }
  952. // $terms is not a valid array or term.
  953. if (empty($terms)) {
  954. return $terms;
  955. }
  956. $object_info = i18n_object_info('taxonomy_term');
  957. $list = is_array($terms) ? $terms : array($terms);
  958. foreach ($list as $index => $term) {
  959. if (i18n_taxonomy_vocabulary_mode($term->vid, I18N_MODE_LOCALIZE)) {
  960. $localize[$index] = $term->tid;
  961. }
  962. }
  963. // If multiple terms, preload all translations, then run object translation.
  964. if (!empty($localize)) {
  965. i18n_string_translation_search(array('taxonomy', 'term', $localize, '*'));
  966. foreach ($localize as $index => $tid) {
  967. $list[$index] = i18n_string_object_translate('taxonomy_term', $list[$index]);
  968. }
  969. }
  970. // Return array or simple object, depending on incoming format.
  971. return is_array($terms) ? $list : reset($list);
  972. }
  973. /**
  974. * Taxonomy vocabulary settings.
  975. *
  976. * @param $vid
  977. * Vocabulary object or vocabulary id.
  978. * @param $mode
  979. * Vocabulary mode to compare with.
  980. *
  981. */
  982. function i18n_taxonomy_vocabulary_mode($vid, $mode = NULL) {
  983. $modes = &drupal_static(__FUNCTION__);
  984. if (is_object($vid)) {
  985. $vid_mode = i18n_object_field($vid, 'i18n_mode', I18N_MODE_NONE);
  986. return isset($mode) ? $mode & $vid_mode : $vid_mode;
  987. }
  988. else {
  989. if (!isset($modes[$vid])) {
  990. $modes[$vid] = i18n_object_field(taxonomy_vocabulary_load($vid), 'i18n_mode', I18N_MODE_NONE);
  991. }
  992. return isset($mode) ? $mode & $modes[$vid] : $modes[$vid];
  993. }
  994. }
  995. /**
  996. * Get taxonomy tree for a given language
  997. *
  998. * @param $vid
  999. * Vocabulary id
  1000. * @param $lang
  1001. * Language code
  1002. * @param $parent
  1003. * Parent term id for the tree
  1004. */
  1005. function i18n_taxonomy_get_tree($vid, $langcode, $parent = 0, $max_depth = NULL, $load_entities = FALSE) {
  1006. $children = &drupal_static(__FUNCTION__, array());
  1007. $parents = &drupal_static(__FUNCTION__ . ':parents', array());
  1008. $terms = &drupal_static(__FUNCTION__ . ':terms', array());
  1009. // We cache trees, so it's not CPU-intensive to call get_tree() on a term
  1010. // and its children, too.
  1011. if (!isset($children[$vid][$langcode])) {
  1012. $children[$vid][$langcode] = array();
  1013. $parents[$vid][$langcode] = array();
  1014. $terms[$vid][$langcode] = array();
  1015. $query = db_select('taxonomy_term_data', 't');
  1016. $query->join('taxonomy_term_hierarchy', 'h', 'h.tid = t.tid');
  1017. $result = $query
  1018. ->addTag('translatable')
  1019. ->addTag('term_access')
  1020. ->fields('t')
  1021. ->fields('h', array('parent'))
  1022. ->condition('t.vid', $vid)
  1023. ->condition('t.language', $langcode)
  1024. ->orderBy('t.weight')
  1025. ->orderBy('t.name')
  1026. ->execute();
  1027. foreach ($result as $term) {
  1028. $children[$vid][$langcode][$term->parent][] = $term->tid;
  1029. $parents[$vid][$langcode][$term->tid][] = $term->parent;
  1030. $terms[$vid][$langcode][$term->tid] = $term;
  1031. }
  1032. }
  1033. // Load full entities, if necessary. The entity controller statically
  1034. // caches the results.
  1035. if ($load_entities) {
  1036. $term_entities = taxonomy_term_load_multiple(array_keys($terms[$vid][$langcode]));
  1037. }
  1038. $max_depth = (!isset($max_depth)) ? count($children[$vid][$langcode]) : $max_depth;
  1039. $tree = array();
  1040. // Keeps track of the parents we have to process, the last entry is used
  1041. // for the next processing step.
  1042. $process_parents = array();
  1043. $process_parents[] = $parent;
  1044. // Loops over the parent terms and adds its children to the tree array.
  1045. // Uses a loop instead of a recursion, because it's more efficient.
  1046. while (count($process_parents)) {
  1047. $parent = array_pop($process_parents);
  1048. // The number of parents determines the current depth.
  1049. $depth = count($process_parents);
  1050. if ($max_depth > $depth && !empty($children[$vid][$langcode][$parent])) {
  1051. $has_children = FALSE;
  1052. $child = current($children[$vid][$langcode][$parent]);
  1053. do {
  1054. if (empty($child)) {
  1055. break;
  1056. }
  1057. $term = $load_entities ? $term_entities[$child] : $terms[$vid][$langcode][$child];
  1058. if (count($parents[$vid][$langcode][$term->tid]) > 1) {
  1059. // We have a term with multi parents here. Clone the term,
  1060. // so that the depth attribute remains correct.
  1061. $term = clone $term;
  1062. }
  1063. $term->depth = $depth;
  1064. unset($term->parent);
  1065. $term->parents = $parents[$vid][$langcode][$term->tid];
  1066. $tree[] = $term;
  1067. if (!empty($children[$vid][$langcode][$term->tid])) {
  1068. $has_children = TRUE;
  1069. // We have to continue with this parent later.
  1070. $process_parents[] = $parent;
  1071. // Use the current term as parent for the next iteration.
  1072. $process_parents[] = $term->tid;
  1073. // Reset pointers for child lists because we step in there more often
  1074. // with multi parents.
  1075. reset($children[$vid][$langcode][$term->tid]);
  1076. // Move pointer so that we get the correct term the next time.
  1077. next($children[$vid][$langcode][$parent]);
  1078. break;
  1079. }
  1080. } while ($child = next($children[$vid][$langcode][$parent]));
  1081. if (!$has_children) {
  1082. // We processed all terms in this hierarchy-level, reset pointer
  1083. // so that this function works the next time it gets called.
  1084. reset($children[$vid][$langcode][$parent]);
  1085. }
  1086. }
  1087. }
  1088. return $tree;
  1089. }
  1090. /**
  1091. * Recursive array filtering, convert all terms to 'tid'.
  1092. */
  1093. function _i18n_taxonomy_filter_tids($tid) {
  1094. if (is_array($tid)) {
  1095. return array_map('_i18n_taxonomy_filter_tids', $tid);
  1096. }
  1097. else {
  1098. return is_object($tid) ? $tid->tid : (int)$tid;
  1099. }
  1100. }
  1101. /**
  1102. * Recursive array filtering, convert all terms to 'term object'
  1103. */
  1104. function _i18n_taxonomy_filter_terms($term) {
  1105. if (is_array($term)) {
  1106. return array_map('_i18n_taxonomy_filter_terms', $term);
  1107. }
  1108. else {
  1109. return is_object($term) ? $term : taxonomy_term_load($term);
  1110. }
  1111. }
  1112. /**
  1113. * Load translation set. Menu loading callback.
  1114. */
  1115. function i18n_taxonomy_translation_set_load($tsid) {
  1116. return i18n_translation_set_load($tsid, 'taxonomy_term');
  1117. }
  1118. /**
  1119. * Implements hook_field_uuid_load().
  1120. */
  1121. function i18n_taxonomy_field_uuid_load($entity_type, $entity, $field, $instance, $langcode, &$items) {
  1122. taxonomy_field_uuid_load($entity_type, $entity, $field, $instance, $langcode, $items);
  1123. }
  1124. /**
  1125. * Implements hook_field_uuid_presave().
  1126. */
  1127. function i18n_taxonomy_field_uuid_presave($entity_type, $entity, $field, $instance, $langcode, &$items) {
  1128. taxonomy_field_uuid_presave($entity_type, $entity, $field, $instance, $langcode, $items);
  1129. }
  1130. /**
  1131. * Implements hook_entity_info_alter().
  1132. */
  1133. function i18n_taxonomy_entity_info_alter(&$entity_info) {
  1134. if (isset($entity_info['taxonomy_term'])) {
  1135. // Core doesn't provide a label callback for taxonomy terms. By setting one
  1136. // we can use it to return the correct localized term name.
  1137. $entity_info['taxonomy_term']['label callback'] = 'i18n_taxonomy_taxonomy_term_label';
  1138. // Also let core know terms have languages, now.
  1139. $entity_info['taxonomy_term']['entity keys']['language'] = 'language';
  1140. }
  1141. }
  1142. /**
  1143. * Providing a hook_entity_info() 'label callback' to ensure modules that use
  1144. * entity_label() get the correct localized taxonomy term.
  1145. */
  1146. function i18n_taxonomy_taxonomy_term_label($term, $entity_type) {
  1147. return i18n_taxonomy_term_name($term, i18n_language_interface()->language);
  1148. }
  1149. /**
  1150. * Implements hook_views_api().
  1151. */
  1152. function i18n_taxonomy_views_api() {
  1153. return array(
  1154. 'api' => 3,
  1155. );
  1156. }
  1157. /**
  1158. * Implements hook_module_enabled().
  1159. *
  1160. * Updates options_list_callback for taxonomy term fields.
  1161. *
  1162. * @param $modules
  1163. */
  1164. function i18n_taxonomy_modules_enabled($modules) {
  1165. $modules = drupal_map_assoc($modules);
  1166. if (isset($modules['i18n_taxonomy'])) {
  1167. foreach (field_info_fields() as $fieldname => $field) {
  1168. if ($field['type'] == 'taxonomy_term_reference') {
  1169. $field['settings']['options_list_callback'] = 'i18n_taxonomy_allowed_values';
  1170. field_update_field($field);
  1171. }
  1172. }
  1173. }
  1174. }