i18n_taxonomy.module 46 KB

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