i18n_taxonomy.module 46 KB

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