Projet

Général

Profil

Paste
Télécharger (45,7 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / i18n / i18n_taxonomy / i18n_taxonomy.module @ 76df55b7

1
<?php
2

    
3
/**
4
 * @file
5
 * i18n taxonomy module
6
 *
7
 * Internationalization (i18n) package.
8
 *
9
 * This module groups together all existing i18n taxonomy functionality
10
 * providing several options for taxonomy translation.
11
 *
12
 * Translates taxonomy term for selected vocabularies running them through the localization system.
13
 * It also translates terms for views filters and views results.
14
 *
15
 * @author Jose A. Reyero, 2004
16
 */
17

    
18
/**
19
 * Implements hook_help().
20
 */
21
function i18n_taxonomy_help($path, $arg) {
22
  switch ($path) {
23
    case 'admin/help#i18n_taxonomy' :
24
      $output = '<p>' . t('This module adds support for multilingual taxonomy. You can set up multilingual options for each vocabulary:') . '</p>';
25
      $output .= '<ul>';
26
      $output .= '<li>' . t('A language can be assigned globaly for a vocabulary.') . '</li>';
27
      $output .= '<li>' . t('Different terms for each language with translation relationships.') . '</li>';
28
      $output .= '<li>' . t('Terms can be common to all languages, but may be localized.') . '</li>';
29
      $output .= '</ul>';
30
      $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>';
31
      $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>';
32
      return $output;
33

    
34
    case 'admin/config/regional/i18n':
35
      $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>';
36
      return $output;
37

    
38
    case 'admin/structure/taxonomy/%':
39
      $vocabulary = taxonomy_vocabulary_machine_name_load($arg[3]);
40
      switch (i18n_taxonomy_vocabulary_mode($vocabulary)) {
41
        case I18N_MODE_LOCALIZE:
42
          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>';
43

    
44
        case I18N_MODE_LANGUAGE:
45
          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>';
46

    
47
        case I18N_MODE_TRANSLATE:
48
          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>';
49
      }
50
      break;
51

    
52
  }
53
}
54

    
55
/**
56
 * Implements hook_menu().
57
 */
58
function i18n_taxonomy_menu() {
59
  $items['admin/structure/taxonomy/%taxonomy_vocabulary_machine_name/list/list'] = array(
60
    'title' => 'Terms',
61
    'type' => MENU_DEFAULT_LOCAL_TASK,
62
    'weight' => -20,
63
  );
64
  $items['admin/structure/taxonomy/%taxonomy_vocabulary_machine_name/list/sets'] = array(
65
    'title' => 'Translation sets',
66
    'page callback' => 'i18n_taxonomy_translation_sets_overview',
67
    'page arguments' => array(3),
68
    'access callback' => 'i18n_taxonomy_vocabulary_translation_tab_sets_access',
69
    'access arguments' => array(3),
70
    'type' => MENU_LOCAL_TASK,
71
    'file' => 'i18n_taxonomy.admin.inc',
72
  );
73
  $items['admin/structure/taxonomy/%taxonomy_vocabulary_machine_name/list/sets/add'] = array(
74
    'title' => 'Create new translation',
75
    'page callback' => 'drupal_get_form',
76
    'page arguments' => array('i18n_taxonomy_translation_term_form', 3),
77
    'access callback' => 'i18n_taxonomy_vocabulary_translation_tab_sets_access',
78
    'access arguments' => array(3),
79
    'type' => MENU_LOCAL_ACTION,
80
    //'parent' => 'admin/content/taxonomy/%taxonomy_vocabulary',
81
    'file' => 'i18n_taxonomy.admin.inc',
82
  );
83
  $items['admin/structure/taxonomy/%taxonomy_vocabulary_machine_name/list/sets/edit/%i18n_taxonomy_translation_set'] = array(
84
    'title' => 'Edit translation',
85
    'page callback' => 'drupal_get_form',
86
    'page arguments' => array('i18n_taxonomy_translation_term_form', 3, 7),
87
    'access callback' => 'i18n_taxonomy_vocabulary_translation_tab_sets_access',
88
    'access arguments' => array(3),
89
    'type' => MENU_CALLBACK,
90
    //'parent' => 'admin/content/taxonomy/%taxonomy_vocabulary',
91
    'file' => 'i18n_taxonomy.admin.inc',
92
  );
93
  $items['admin/structure/taxonomy/%taxonomy_vocabulary_machine_name/list/sets/delete/%i18n_taxonomy_translation_set'] = array(
94
    'title' => 'Delete translation',
95
    'page callback' => 'drupal_get_form',
96
    'page arguments' => array('i18n_translation_set_delete_confirm', 7),
97
    'access callback' => 'i18n_taxonomy_vocabulary_translation_tab_sets_access',
98
    'access arguments' => array(3),
99
    'type' => MENU_CALLBACK,
100
  );
101
  $items['i18n/taxonomy/autocomplete/vocabulary/%taxonomy_vocabulary_machine_name/%'] = array(
102
    'title' => 'Autocomplete taxonomy',
103
    'page callback' => 'i18n_taxonomy_autocomplete_language',
104
    'page arguments' => array(5, 4),
105
    'access arguments' => array('access content'),
106
    'type' => MENU_CALLBACK,
107
    'file' => 'i18n_taxonomy.pages.inc',
108
  );
109
  $items['i18n/taxonomy/autocomplete/language/%'] = array(
110
    'title' => 'Autocomplete taxonomy',
111
    'page callback' => 'i18n_taxonomy_autocomplete_language',
112
    'page arguments' => array(4, NULL),
113
    'access arguments' => array('access content'),
114
    'type' => MENU_CALLBACK,
115
    'file' => 'i18n_taxonomy.pages.inc',
116
  );
117
  return $items;
118
}
119

    
120
/**
121
 * Implements hook_admin_paths().
122
 */
123
function i18n_taxonomy_admin_paths() {
124
  $paths = array(
125
    'taxonomy/*/translate' => TRUE,
126
    'taxonomy/*/translate/*' => TRUE,
127
  );
128
  return $paths;
129
}
130

    
131
/**
132
 * Implements hook_menu_alter().
133
 *
134
 * Take over the taxonomy pages
135
 */
136
function i18n_taxonomy_menu_alter(&$items) {
137
  // If ctool's page manager is active for the path skip this modules override.
138
  // Also views module takes over this page so this won't work if views enabled.
139
  // Skip when taxonomy_display enabled, see http://drupal.org/node/1280194
140
  if (variable_get('page_manager_term_view_disabled', TRUE) && !module_exists('taxonomy_display')) {
141
    // Taxonomy term page. Localize terms.
142
    $items['taxonomy/term/%taxonomy_term']['page callback'] = 'i18n_taxonomy_term_page';
143
    $items['taxonomy/term/%taxonomy_term']['title callback'] = 'i18n_taxonomy_term_name';
144
    $items['taxonomy/term/%taxonomy_term']['file'] = 'i18n_taxonomy.pages.inc';
145
    $items['taxonomy/term/%taxonomy_term']['file path'] = drupal_get_path('module', 'i18n_taxonomy');
146
  }
147

    
148
  // Localize autocomplete
149
  $items['taxonomy/autocomplete']['page callback'] = 'i18n_taxonomy_autocomplete_field';
150
  $items['taxonomy/autocomplete']['file'] = 'i18n_taxonomy.pages.inc';
151
  $items['taxonomy/autocomplete']['file path'] = drupal_get_path('module', 'i18n_taxonomy');
152
}
153

    
154
/**
155
 * Menu access callback for vocabulary translation tab. Show tab only for full multilingual vocabularies.
156
 */
157
function i18n_taxonomy_vocabulary_translation_tab_sets_access($vocabulary) {
158
  return user_access('administer taxonomy') && i18n_taxonomy_vocabulary_mode($vocabulary->vid, I18N_MODE_TRANSLATE);
159
}
160

    
161
/**
162
 * Menu access callback for term translation tab. Show tab only for translatable terms
163
 *
164
 * @todo This should work also for localizable terms when we've got that part implemented
165
 */
166
function i18n_taxonomy_term_translation_tab_access($term) {
167
  return taxonomy_term_edit_access($term) && i18n_taxonomy_vocabulary_mode($term->vid) & I18N_MODE_MULTIPLE && user_access('translate interface');
168
}
169

    
170
/**
171
 * Implements hook_field_formatter_info().
172
 */
173
function i18n_taxonomy_field_formatter_info() {
174
  return array(
175
    'i18n_taxonomy_term_reference_link' => array(
176
      'label' => t('Link (localized)'),
177
      'field types' => array('taxonomy_term_reference'),
178
    ),
179
    'i18n_taxonomy_term_reference_plain' => array(
180
      'label' => t('Plain text (localized)'),
181
      'field types' => array('taxonomy_term_reference'),
182
    ),
183
  );
184
}
185

    
186
 /**
187
 * Implements hook_field_formatter_prepare_view().
188
 *
189
 * This preloads all taxonomy terms for multiple loaded objects at once and
190
 * unsets values for invalid terms that do not exist.
191
 */
192
function i18n_taxonomy_field_formatter_prepare_view($entity_type, $entities, $field, $instances, $langcode, &$items, $displays) {
193
  return taxonomy_field_formatter_prepare_view($entity_type, $entities, $field, $instances, $langcode, $items, $displays);
194
}
195

    
196
/**
197
 * Implements hook_field_formatter_view().
198
 */
199
function i18n_taxonomy_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
200
  $element = array();
201
  $language = i18n_language_interface();
202

    
203
  // Terms whose tid is 'autocreate' do not exist
204
  // yet and $item['taxonomy_term'] is not set. Theme such terms as
205
  // just their name.
206

    
207
  switch ($display['type']) {
208
    case 'i18n_taxonomy_term_reference_link':
209
      foreach ($items as $delta => $item) {
210
        if ($item['tid'] == 'autocreate') {
211
          $element[$delta] = array(
212
            '#markup' => check_plain($item['name']),
213
          );
214
        }
215
        else {
216
          $term = $item['taxonomy_term'];
217
          $uri = entity_uri('taxonomy_term', $term);
218
          $element[$delta] = array(
219
            '#type' => 'link',
220
            '#title' => i18n_taxonomy_term_name($term, $language->language),
221
            '#href' => $uri['path'],
222
            '#options' => $uri['options'],
223
          );
224
        }
225
      }
226
      break;
227

    
228
    case 'i18n_taxonomy_term_reference_plain':
229
      foreach ($items as $delta => $item) {
230
        $name = ($item['tid'] != 'autocreate' ? i18n_taxonomy_term_name($item['taxonomy_term'], $language->language): $item['name']);
231
        $element[$delta] = array(
232
          '#markup' => check_plain($name),
233
        );
234
      }
235
      break;
236
  }
237

    
238
  return $element;
239
}
240

    
241
/**
242
 * Implements hook_field_extra_fields().
243
 */
244
function i18n_taxonomy_field_extra_fields() {
245
  $return = array();
246
  $info = entity_get_info('taxonomy_term');
247
  foreach (array_keys($info['bundles']) as $bundle) {
248
    $vocabulary = taxonomy_vocabulary_machine_name_load($bundle);
249
    if ($vocabulary && i18n_taxonomy_vocabulary_mode($vocabulary, I18N_MODE_TRANSLATE)) {
250
      $return['taxonomy_term'][$bundle] = i18n_language_field_extra();
251
    }
252
  }
253
  return $return;
254
}
255

    
256
/**
257
 * Implements hook_field_attach_view_alter().
258
 */
259
function i18n_taxonomy_field_attach_view_alter(&$output, $context) {
260
  // Copied from rdf_field_attach_view_alter of modules/rdf/rdf.module since we have another #formatter
261
  // Append term mappings on displayed taxonomy links.
262
  foreach (element_children($output) as $field_name) {
263
    $element = &$output[$field_name];
264
    if (isset($element['#field_type']) && $element['#field_type'] == 'taxonomy_term_reference' && $element['#formatter'] == 'i18n_taxonomy_term_reference_link') {
265
      foreach ($element['#items'] as $delta => $item) {
266
        // This function is invoked during entity preview when taxonomy term
267
        // reference items might contain free-tagging terms that do not exist
268
        // yet and thus have no $item['taxonomy_term'].
269
        if (isset($item['taxonomy_term'])) {
270
          $term = $item['taxonomy_term'];
271
          if (!empty($term->rdf_mapping['rdftype'])) {
272
            $element[$delta]['#options']['attributes']['typeof'] = $term->rdf_mapping['rdftype'];
273
          }
274
          if (!empty($term->rdf_mapping['name']['predicates'])) {
275
            $element[$delta]['#options']['attributes']['property'] = $term->rdf_mapping['name']['predicates'];
276
          }
277
        }
278
      }
279
    }
280
  }
281
  // Add language field for display
282
  if ($context['entity_type'] == 'taxonomy_term' && i18n_taxonomy_vocabulary_mode($context['entity']->vid, I18N_MODE_TRANSLATE)) {
283
    $output['language'] = array(
284
      '#type' => 'item',
285
      '#title' => t('Language'),
286
      '#markup' => i18n_language_name($context['entity']->language),
287
    );
288
  }
289
}
290

    
291
/**
292
 * Implements hook_field_info_alter()
293
 */
294
function i18n_taxonomy_field_info_alter(&$info) {
295
  // Change default formatter for term reference fields
296
  $info['taxonomy_term_reference']['default_formatter'] = 'i18n_taxonomy_term_reference_link';
297

    
298
  // Translate field values.
299
  $info['taxonomy_term_reference']['options_list_callback'] = 'i18n_taxonomy_allowed_values';
300

    
301
  // Sync callback for field translations
302
  $info['taxonomy_term_reference']['i18n_sync_callback'] = 'i18n_taxonomy_field_prepare_translation';
303
}
304

    
305
/**
306
 * Implements hook_field_storage_details_alter().
307
 *
308
 * We don't alter the storage details but the stored details of the field itself...
309
 *
310
 * @param array $field
311
 *   The field record just read from the database.
312
 */
313
function i18n_taxonomy_field_storage_details_alter(&$details, &$field) {
314
  if ($field['type'] === 'taxonomy_term_reference') {
315
    $field['settings']['options_list_callback'] = 'i18n_taxonomy_allowed_values';
316
  }
317
}
318

    
319
/**
320
 * Implements hook_field_attach_prepare_translation_alter().
321
 *
322
 * Prepare and synchronize translation for term reference fields.
323
 */
324
function i18n_taxonomy_field_attach_prepare_translation_alter(&$entity, $context) {
325
  $entity_type = $context['entity_type'];
326
  $source_entity = $context['source_entity'];
327

    
328
  $options = array(
329
    'default' => FALSE,
330
    'deleted' => FALSE,
331
    'language' => NULL,
332
  );
333

    
334
  // Determine the list of instances to iterate on.
335
  list(, , $bundle) = entity_extract_ids($entity_type, $source_entity);
336
  $instances = _field_invoke_get_instances($entity_type, $bundle, $options);
337
  if (!empty($instances)) {
338
    foreach ($instances as $field_info) {
339
      $field = field_info_field($field_info['field_name']);
340
      if ($field['type'] == 'taxonomy_term_reference' && isset($entity->{$field_info['field_name']})) {
341
        // iterate over languages.
342
        foreach ($entity->{$field_info['field_name']} as $language => &$items) {
343
          i18n_taxonomy_field_prepare_translation($entity_type, $entity, $field, $field_info, $entity->language, $items, $source_entity, $source_entity->language);
344
        }
345
      }
346
    }
347
  }
348
}
349

    
350
/**
351
 * Prepare and synchronize translation for term reference fields
352
 */
353
function i18n_taxonomy_field_prepare_translation($entity_type, $entity, $field, $instance, $langcode, &$items, $source_entity, $source_langcode) {
354
  foreach ($items as $index => $item) {
355
    $term = isset($item['taxonomy_term']) ? $item['taxonomy_term'] : taxonomy_term_load($item['tid']);
356
    if ($translation = i18n_taxonomy_term_get_translation($term, $langcode)) {
357
      $items[$index] = array(
358
        'taxonomy_term' => $translation,
359
        'tid' => $translation->tid
360
      );
361
    }
362
    $field['settings']['options_list_callback'] = 'i18n_taxonomy_allowed_values';
363
  }
364
}
365

    
366
/**
367
 * Returns the set of valid terms for a taxonomy field.
368
 *
369
 * @param $field
370
 *   The field definition.
371
 * @return
372
 *   The array of valid terms for this field, keyed by term id.
373
 */
374
function i18n_taxonomy_allowed_values($field) {
375
  $options = array();
376
  foreach ($field['settings']['allowed_values'] as $tree) {
377
    if ($vocabulary = taxonomy_vocabulary_machine_name_load($tree['vocabulary'])) {
378
      if ($terms = taxonomy_get_tree($vocabulary->vid, $tree['parent'])) {
379
        foreach ($terms as $term) {
380
          $options[$term->tid] = str_repeat('-', $term->depth) . i18n_taxonomy_term_name($term);
381
        }
382
      }
383
    }
384
  }
385
  return $options;
386
}
387

    
388
/**
389
 * Implements hook_i18n_translate_path()
390
 */
391
function i18n_taxonomy_i18n_translate_path($path) {
392
  if (strpos($path, 'taxonomy/term/') === 0) {
393
    return i18n_taxonomy_translate_path($path);
394
  }
395
}
396

    
397
/**
398
 * Implements hook_i18n_context_language().
399
 */
400
function i18n_taxonomy_i18n_context_language() {
401
  if (arg(0) == 'taxonomy') {
402
    // Taxonomy term pages
403
    if (arg(1) == 'term' && is_numeric(arg(2)) && ($term = menu_get_object('taxonomy_term', 2)) && ($langcode = i18n_object_langcode($term))) {
404
      return i18n_language_object($langcode);
405
    }
406
  }
407
}
408

    
409
/**
410
 * Find translations for taxonomy paths.
411
 *
412
 * @param $path
413
 *   Path to translate.
414
 * @param $path_prefix
415
 *   Path prefix, including trailing slash, defaults to 'taxonomy/term/'.
416
 *   It will be different for taxonomy term pages and for forum pages.
417
 *
418
 * @return
419
 *   Array of links (each an array with href, title), indexed by language code.
420
 */
421
function i18n_taxonomy_translate_path($path, $path_prefix = 'taxonomy/term/') {
422
  $prefix_match = strtr($path_prefix, array('/' => '\/'));
423
  if (preg_match("/^($prefix_match)([^\/]*)(.*)$/", $path, $matches)) {
424
    $links = array();
425
    $term = FALSE;
426
    // If single term, treat it differently
427
    if (is_numeric($matches[2]) && !$matches[3]) {
428
      $term = taxonomy_term_load($matches[2]);
429
      if (!empty($term->i18n_tsid)) {
430
        $set = i18n_translation_set_load($term->i18n_tsid);
431
      }
432
    }
433
    foreach (language_list() as $langcode => $language) {
434
      if ($term) {
435
        if (!empty($set) && ($translation = $set->get_item($langcode))) {
436
          $links[$langcode] = array(
437
            'href' => $path_prefix . $translation->tid,
438
            'title' => $translation->name,
439
          );
440
        }
441
        else {
442
          $links[$langcode] = array(
443
            'href' => $path,
444
            'title' => i18n_taxonomy_term_name($term, $langcode),
445
          );
446
        }
447
      }
448
      elseif ($str_tids = i18n_taxonomy_translation_tids($matches[2], $langcode)) {
449
        $links[$langcode]['href'] = $path_prefix . $str_tids . $matches[3];
450
      }
451
    }
452
    return $links;
453
  }
454
}
455

    
456
/**
457
 * Get localized term name unfiltered.
458
 */
459
function i18n_taxonomy_term_name($term, $langcode = NULL) {
460
  $key = i18n_object_info('taxonomy_term', 'key');
461
  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;
462
}
463

    
464

    
465
/**
466
 * Get localized term description unfiltered.
467
 */
468
function i18n_taxonomy_term_description($term, $langcode = NULL) {
469
  $key = i18n_object_info('taxonomy_term', 'key');
470
  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;
471
}
472

    
473
/**
474
 * Find term translation from translation set.
475
 *
476
 * @param $term
477
 *   Term object to find translation.
478
 * @param $langcode
479
 *   Language code to find translation for.
480
 * @result object Taxonomy Term
481
 *   Translation if exists.
482
 */
483
function i18n_taxonomy_term_get_translation($term, $langcode) {
484
  if (i18n_object_langcode($term)) {
485
    if ($term->language == $langcode) {
486
      // Translation is the term itself.
487
      return $term;
488
    }
489
    elseif (!empty($term->i18n_tsid)) {
490
      return i18n_translation_set_load($term->i18n_tsid)->get_item($langcode);
491
    }
492
    else {
493
      return NULL;
494
    }
495
  }
496
  else {
497
    // Term has no language, translation should be the same
498
    return $term;
499
  }
500
}
501

    
502
/**
503
 * Get localized vocabulary name, unfiltered.
504
 */
505
function i18n_taxonomy_vocabulary_name($vocabulary, $langcode = NULL) {
506
  return i18n_object_langcode($vocabulary) ? $vocabulary->name : i18n_string(array('taxonomy', 'vocabulary', $vocabulary->vid, 'name'), $vocabulary->name, array('langcode' => $langcode, 'sanitize' => FALSE));
507
}
508

    
509
/**
510
 * Get localized vocabulary description, unfiltered.
511
 */
512
function i18n_taxonomy_vocabulary_description($vocabulary, $langcode = NULL) {
513
  return i18n_object_langcode($vocabulary) ? $vocabulary->description : i18n_string(array('taxonomy', 'vocabulary', $vocabulary->vid, 'description'), $vocabulary->description, array('langcode' => $langcode, 'sanitize' => FALSE));
514
}
515

    
516
/**
517
 * Get translated term's tid.
518
 *
519
 * @param $tid
520
 *   Node nid to search for translation.
521
 * @param $language
522
 *   Language to search for the translation, defaults to current language.
523
 * @param $default
524
 *   Value that will be returned if no translation is found.
525
 * @return
526
 *   Translated term tid if exists, or $default.
527
 */
528
function i18n_taxonomy_translation_term_tid($tid, $language = NULL, $default = NULL) {
529
  $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(
530
    ':tid' => $tid,
531
    ':language' => $language ? $language : i18n_language_content()->language
532
  ))->fetchField();
533
  return $translation ? $translation : $default;
534
}
535

    
536
/**
537
 *  Returns an url for the translated taxonomy-page, if exists.
538
 */
539
function i18n_taxonomy_translation_tids($str_tids, $lang) {
540
  if (preg_match('/^([0-9]+[+ ])+[0-9]+$/', $str_tids)) {
541
    $separator = '+';
542
    // The '+' character in a query string may be parsed as ' '.
543
    $tids = preg_split('/[+ ]/', $str_tids);
544
  }
545
  elseif (preg_match('/^([0-9]+,)*[0-9]+$/', $str_tids)) {
546
    $separator = ',';
547
    $tids = explode(',', $str_tids);
548
  }
549
  else {
550
    return;
551
  }
552
  $translated_tids = array();
553
  foreach ($tids as $tid) {
554
    if ($translated_tid = i18n_taxonomy_translation_term_tid($tid, $lang)) {
555
      $translated_tids[] = $translated_tid;
556
    }
557
  }
558
  return implode($separator, $translated_tids);
559
}
560

    
561
/**
562
 * Implements hook_taxonomy_display_breadcrumb_parents_alter().
563
 */
564
function i18n_taxonomy_taxonomy_display_breadcrumb_parents_alter(&$parents) {
565
  $parents = i18n_taxonomy_localize_terms($parents);
566
}
567

    
568
/**
569
 * Implements hook_taxonomy_display_term_page_term_object_alter().
570
 */
571
function i18n_taxonomy_taxonomy_display_term_page_term_object_alter(&$term) {
572
  $term = i18n_taxonomy_localize_terms($term);
573
}
574

    
575
/**
576
 * Implements hook_taxonomy_term_insert()
577
 */
578
function i18n_taxonomy_taxonomy_term_insert($term) {
579
  i18n_taxonomy_taxonomy_term_update($term);
580
}
581

    
582
/**
583
 * Implements hook_taxonomy_term_update()
584
 */
585
function i18n_taxonomy_taxonomy_term_update($term) {
586
  if (i18n_taxonomy_vocabulary_mode($term->vid, I18N_MODE_LOCALIZE)) {
587
    i18n_string_object_update('taxonomy_term', $term);
588
  }
589
  // Multilingual terms, translatable. Link / unlink from translation set.
590
  if (i18n_taxonomy_vocabulary_mode($term->vid, I18N_MODE_TRANSLATE) && !empty($term->translation_set)) {
591
    if (i18n_object_langcode($term)) {
592
      $term->translation_set
593
        ->add_item($term)
594
        ->save();
595
    }
596
    elseif (!empty($term->original)) {
597
      // Term set to language neutral, remove it from translation set and update set (delete if empty)
598
      $term->translation_set
599
        ->remove_item($term->original)
600
        ->update_delete();
601
    }
602
  }
603
}
604

    
605
/**
606
 * Implements hook_taxonomy_term_delete()
607
 */
608
function i18n_taxonomy_taxonomy_term_delete($term) {
609
  // If a translation set exists for this term, remove this term from the set.
610
  if (isset($term->i18n_tsid) && $term->i18n_tsid) {
611
    $translation_set = i18n_translation_set_load($term->i18n_tsid);
612
    $translation_set->get_translations();
613

    
614
    $translation_set->remove_language($term->language);
615

    
616
    // If there are no terms left in this translation set, delete the set.
617
    // Otherwise update the set.
618
    $translation_set->update_delete();
619
  }
620
  // Just in case there's any left over string we run it for all terms.
621
  i18n_string_object_remove('taxonomy_term', $term);
622
}
623

    
624
/**
625
 * Implements hook_taxonomy_vocabulary_insert()
626
 */
627
function i18n_taxonomy_taxonomy_vocabulary_insert($vocabulary) {
628
  i18n_taxonomy_taxonomy_vocabulary_update($vocabulary);
629
}
630

    
631
/**
632
 * Implements hook_taxonomy_vocabulary_update()
633
 */
634
function i18n_taxonomy_taxonomy_vocabulary_update($vocabulary) {
635
  // Update language for related terms
636
  switch (i18n_taxonomy_vocabulary_mode($vocabulary)) {
637
    case I18N_MODE_LANGUAGE:
638
      $update['language'] = $vocabulary->language;
639
      break;
640
    case I18N_MODE_NONE:
641
      $update['language'] = LANGUAGE_NONE;
642
      break;
643
  }
644
  if (isset($update)) {
645
    db_update('taxonomy_term_data')
646
      ->fields($update)
647
      ->condition('vid', $vocabulary->vid)
648
      ->execute();
649
    drupal_set_message(t('Reset language for all terms.'));
650
  }
651
  // Update strings, always add translation if no language
652
  if (!i18n_object_langcode($vocabulary)) {
653
    i18n_string_object_update('taxonomy_vocabulary', $vocabulary);
654
  }
655
}
656

    
657
/**
658
 * Implements hook_taxonomy_vocabulary_delete()
659
 */
660
function i18n_taxonomy_taxonomy_vocabulary_delete($vocabulary) {
661
  i18n_string_object_remove('taxonomy_vocabulary', $vocabulary);
662
}
663

    
664
/**
665
 * Implements hook_taxonomy_term_presave()
666
 */
667
function i18n_taxonomy_taxonomy_term_presave($term) {
668
  switch (i18n_taxonomy_vocabulary_mode($term->vid)) {
669
    case I18N_MODE_LANGUAGE: // Predefined language for all terms
670
      $term->language = taxonomy_vocabulary_load($term->vid)->language;
671
      break;
672
    case I18N_MODE_TRANSLATE: // Multilingual terms, translatable
673
      if (!isset($term->language)) {
674
         // The term may come from a node tags field, just if this is not a taxonomy form.
675
         // Or from any other object we are editing. So we use 'context' language here.
676
        $term->language = i18n_language_context()->language;
677
      }
678
      // Only for the case the term has no language, it may need to be removed from translation set
679
      if (empty($term->language)) {
680
        $term->i18n_tsid = 0;
681
      }
682
      break;
683
  }
684
}
685

    
686
/**
687
 * Implements hook_form_FORM_ID_alter()
688
 */
689
function i18n_taxonomy_form_taxonomy_form_vocabulary_alter(&$form, &$form_state) {
690
  if (!isset($form_state['confirm_delete'])) {
691
    $vocabulary = $form_state['vocabulary'];
692
    $i18n_mode = i18n_taxonomy_vocabulary_mode($vocabulary);
693
    $langcode = i18n_object_langcode($vocabulary, LANGUAGE_NONE);
694
    // Define the replacement names to add some logic to the translation mode options.
695
    $form += i18n_translation_mode_element('taxonomy_vocabulary', $i18n_mode, $langcode);
696
    if (user_access('translate interface')) {
697
      $form['actions']['translate'] = array(
698
        '#type' => 'submit',
699
        '#name'   => 'save_translate',
700
        '#value' => t('Save and translate'),
701
        '#weight' => 5,
702
        '#states' => array(
703
          'invisible' => array(
704
            // Hide the button if language mode is selected value needs to be a
705
            // string so that the javascript-side matching works.
706
            'input[name=i18n_mode]' => array('value' => (string)I18N_MODE_LANGUAGE),
707
          )
708
        )
709
      );
710
      // Make sure the delete buttons shows up last.
711
      if (isset($form['actions']['delete'])) {
712
        $form['actions']['delete']['#weight'] = 10;
713
      }
714
    }
715
    $form['#validate'][] = 'i18n_taxonomy_form_vocabulary_validate';
716
    $form['#submit'][] = 'i18n_taxonomy_form_vocabulary_submit';
717
  }
718
}
719

    
720
/**
721
 * Form submit callback to redirect when using the save and translate button.
722
 */
723
function i18n_taxonomy_form_vocabulary_submit($form, &$form_state) {
724
  if ($form_state['triggering_element']['#name'] == 'save_translate') {
725
    $form_state['redirect'] = 'admin/structure/taxonomy/' . $form_state['values']['machine_name'] . '/translate';
726
  }
727
}
728

    
729
/**
730
 * Implements hook_form_FORM_ID_alter()
731
 */
732
function i18n_taxonomy_form_taxonomy_form_term_alter(&$form, &$form_state) {
733
  // Check for confirmation forms
734
  if (isset($form_state['confirm_delete']) || isset($form_state['confirm_parents'])) return;
735

    
736
  $term = $form_state['term'];
737
  $vocabulary = $form['#vocabulary'];
738

    
739
  // Mark form so we can know later when saving the term it came from a taxonomy form
740
  $form['i18n_taxonomy_form'] = array('#type' => 'value', '#value' => 1);
741

    
742
  // Add language field or not depending on taxonomy mode.
743
  switch (i18n_taxonomy_vocabulary_mode($vocabulary->vid)) {
744
    case I18N_MODE_TRANSLATE:
745
      $form['language'] = array(
746
        '#description' => t('This term belongs to a multilingual vocabulary. You can set a language for it.'),
747
      ) + i18n_element_language_select($term);
748

    
749
      // If the term to be added will be a translation of a source term,
750
      // set the default value of the option list to the target language and
751
      // create a form element for storing the translation set of the source term.
752
      if (empty($term->tid) && isset($_GET['translation']) && isset($_GET['target']) && ($source_term = taxonomy_term_load($_GET['translation'])) && ($target_language = i18n_language_object($_GET['target']))) {
753
        // Set context language to target language.
754
        i18n_language_context($target_language);
755

    
756
        // Add the translation set to the form so we know the new term
757
        // needs to be added to that set.
758
        if (!empty($source_term->i18n_tsid)) {
759
          $translation_set = i18n_taxonomy_translation_set_load($source_term->i18n_tsid);
760
        }
761
        else {
762
          // No translation set yet, build a new one with the source term.
763
          $translation_set = i18n_translation_set_create('taxonomy_term', $vocabulary->machine_name)
764
          ->add_item($source_term);
765
        }
766

    
767
        $form['language']['#default_value'] = $target_language->language;
768
        $form['language']['#disabled'] = TRUE;
769

    
770
        drupal_set_title(t('%language translation of term %title', array('%language' => locale_language_name($_GET['target']), '%title' => $source_term->name)), PASS_THROUGH);
771
      }
772
      elseif (!empty($term->tid) && i18n_object_langcode($term)) {
773
        // Set context language to term language.
774
        i18n_language_context(i18n_language_object($term->language));
775
        // If the current term is part of a translation set,
776
        // remove all other languages of the option list.
777
        if (!empty($term->i18n_tsid)) {
778
          $translation_set = i18n_taxonomy_translation_set_load($term->i18n_tsid);
779
          $translations = $translation_set->get_translations();
780
          // If the number of translations equals 1, there's only a source translation.
781
          if (count($translations) > 1) {
782
            //unset($form['language']['#options'][LANGUAGE_NONE]);
783
            foreach ($translations as $langcode => $translation) {
784
              if ($translation->tid !== $term->tid) {
785
                unset($form['language']['#options'][$langcode]);
786
              }
787
            }
788
            $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')));
789
          }
790
        }
791
      }
792
      // If we've got a translation set, add it to the form.
793
      if (!empty($translation_set)) {
794
        $form['translation_set'] = array(
795
          '#type' => 'value',
796
          '#value' => $translation_set,
797
        );
798
      }
799
      break;
800

    
801
    case I18N_MODE_LANGUAGE:
802
      // Set context language to vocabulary language and add value to the form.
803
      i18n_language_context(i18n_language_object($vocabulary->language));
804
      $form['language'] = array(
805
        '#type' => 'value',
806
        '#value' => $vocabulary->language
807
      );
808
      $form['identification']['language_info'] = array('#value' => t('All terms in this vocabulary have a fixed language: %language', array('%language' => i18n_language_name($vocabulary->language))));
809
      break;
810

    
811
    case I18N_MODE_LOCALIZE:
812
      $form['language'] = array(
813
        '#type' => 'value',
814
        '#value' => LANGUAGE_NONE,
815
      );
816
      break;
817

    
818
    case I18N_MODE_NONE:
819
    default:
820
      $form['language'] = array(
821
        '#type' => 'value',
822
        '#value' => LANGUAGE_NONE,
823
      );
824
      break;
825
  }
826

    
827
  if (user_access('translate interface') && i18n_taxonomy_vocabulary_mode($vocabulary->vid) & I18N_MODE_MULTIPLE) {
828
    $form['actions']['translate'] = array(
829
      '#type' => 'submit',
830
      '#name'   => 'save_translate',
831
      '#value' => t('Save and translate'),
832
      '#weight' => 5,
833
      '#states' => array(
834
        'invisible' => array(
835
          // Hide the button if term is language neutral.
836
          'select[name=language]' => array('value' => LANGUAGE_NONE),
837
        ),
838
      ),
839
    );
840
    // Make sure the delete buttons shows up last.
841
    if (isset($form['actions']['delete'])) {
842
      $form['actions']['delete']['#weight'] = 10;
843
    }
844
    $form['#submit'][] = 'i18n_taxonomy_form_term_submit';
845
  }
846
}
847

    
848
/**
849
 * Form submit callback to redirect when using the save and translate button.
850
 */
851
function i18n_taxonomy_form_term_submit($form, &$form_state) {
852
  if ($form_state['triggering_element']['#name'] == 'save_translate') {
853
    // When using the edit link on the list terms, a destination param is
854
    // added that needs to be unset to make the redirection work.
855
    unset($_GET['destination']);
856
    $form_state['redirect'] = 'taxonomy/term/' . $form_state['values']['tid'] . '/translate';
857
  }
858
}
859

    
860
/**
861
 * Implements hook_form_alter().
862
 *
863
 * This is the place to add language fields to all forms.
864
 *
865
 * @ TO DO The vocabulary form needs some javascript.
866
 */
867
function i18n_taxonomy_form_alter(&$form, $form_state, $form_id) {
868
  switch ($form_id) {
869
    case 'taxonomy_overview_vocabularies':
870
      $vocabularies = taxonomy_get_vocabularies();
871
      foreach ($vocabularies as $vocabulary) {
872
        if (i18n_object_langcode($vocabulary)) {
873
          $form[$vocabulary->vid]['name']['#markup'] .= ' (' . i18n_language_name($vocabulary->language) . ')';
874
        }
875
      }
876
      break;
877

    
878
    case 'taxonomy_overview_terms':
879
      // We check for vocabulary object first, because when confirming alphabetical ordering it uses the same form
880
      if (!empty($form['#vocabulary']) && i18n_taxonomy_vocabulary_mode($form['#vocabulary']->vid) & I18N_MODE_TRANSLATE) {
881
        foreach (element_children($form) as $key) {
882
          if (isset($form[$key]['#term']) && ($lang = i18n_object_langcode($form[$key]['#term']))) {
883
            $form[$key]['view']['#suffix'] = ' (' . i18n_language_name($lang) . ')';
884
          }
885
        }
886
      }
887
      break;
888

    
889
    case 'search_form':
890
      // Localize category selector in advanced search form.
891
      if (!empty($form['advanced']) && !empty($form['advanced']['category'])) {
892
        i18n_taxonomy_form_all_localize($form['advanced']['category']);
893
      }
894
      break;
895
  }
896
}
897

    
898
/**
899
 * Validate multilingual options for vocabulary form
900
 */
901
function i18n_taxonomy_form_vocabulary_validate($form, &$form_state) {
902
  if ($form_state['values']['i18n_mode'] & I18N_MODE_LANGUAGE) {
903
    if ($form_state['values']['language'] == LANGUAGE_NONE) {
904
      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.'));
905
    }
906
  }
907
  else {
908
    $form_state['values']['language'] = LANGUAGE_NONE;
909
  }
910
}
911

    
912
/**
913
 * Localize a taxonomy_form_all() kind of control
914
 *
915
 * The options array is indexed by vocabulary name and then by term id, with tree structure
916
 * We just need to localize vocabulary name and localizable terms. Multilingual vocabularies
917
 * should have been taken care of by query rewriting.
918
 **/
919
function i18n_taxonomy_form_all_localize(&$item) {
920
  $options = &$item['#options'];
921
  foreach (taxonomy_get_vocabularies() as $vid => $vocabulary) {
922
    if (!empty($options[$vocabulary->name])) {
923
      // Localize vocabulary name if translated
924
      $vname = i18n_taxonomy_vocabulary_name($vocabulary);
925
      if ($vname != $vocabulary->name) {
926
        $options[$vname] = $options[$vocabulary->name];
927
        unset($options[$vocabulary->name]);
928
      }
929
      if (i18n_taxonomy_vocabulary_mode($vid) & I18N_MODE_LOCALIZE) {
930
        $tree = taxonomy_get_tree($vid);
931
        if ($tree && (count($tree) > 0)) {
932
          foreach ($tree as $term) {
933
            if (isset($options[$vname][$term->tid])) {
934
              $options[$vname][$term->tid] = str_repeat('-', $term->depth) . i18n_taxonomy_term_name($term);
935
            }
936
          }
937
        }
938
      }
939
    }
940
  }
941
}
942

    
943
/**
944
 * Translate an array of taxonomy terms.
945
 *
946
 * Translates all terms with language, just passing over terms without it.
947
 * Filter out terms with a different language
948
 *
949
 * @param $taxonomy
950
 *   Array of term objects or tids or multiple arrays or terms indexed by vid
951
 * @param $langcode
952
 *   Language code of target language
953
 * @param $fullterms
954
 *   Whether to return full $term objects, returns tids otherwise
955
 * @return
956
 *   Array with translated terms: tid -> $term
957
 *   Array with vid and term array
958
 */
959
function i18n_taxonomy_translate_terms($taxonomy, $langcode, $fullterms = TRUE) {
960
  $translation = array();
961
  if (is_array($taxonomy) && $taxonomy) {
962
    foreach ($taxonomy as $index => $tdata) {
963
      if (is_array($tdata)) {
964
        // Case 1: Index is vid, $tdata is an array of terms
965
        $mode = i18n_taxonomy_vocabulary_mode($index);
966
        // We translate just some vocabularies: translatable, fixed language
967
        // Fixed language ones may have terms translated, though the UI doesn't support it
968
        if ($mode & I18N_MODE_LANGUAGE || $mode & I18N_MODE_TRANSLATE) {
969
          $translation[$index] = i18n_taxonomy_translate_terms($tdata, $langcode, $fullterms);
970
        }
971
        elseif ($fullterms) {
972
          $translation[$index] = array_map('_i18n_taxonomy_filter_terms', $tdata);
973
        }
974
        else {
975
          $translation[$index] = array_map('_i18n_taxonomy_filter_tids', $tdata);
976
        }
977
        continue;
978
      }
979
      elseif (is_object($tdata)) {
980
        // Case 2: This is a term object
981
        $term = $tdata;
982
      }
983
      elseif (is_numeric($tdata) && ($tid = (int)$tdata)) {
984
        // Case 3: This is a term tid, load the full term
985
        $term = taxonomy_term_load($tid);
986
      }
987
      // Translate the term if we got it
988
      if (empty($term)) {
989
        // Couldn't identify term, pass through whatever it is
990
        $translation[$index] = $tdata;
991
      }
992
      elseif ($term->language && $term->language != $langcode) {
993
        $translation_set = i18n_translation_set_load($term->i18n_tsid);
994
        $translations = $translation_set->get_translations();
995

    
996
        if ($translations && !empty($translations[$langcode])) {
997
          $newterm = $translations[$langcode];
998
          $translation[$newterm->tid] = $fullterms ? $newterm : $newterm->tid;
999
        }
1000
      }
1001
      else {
1002
        // Term has no language. Should be ok.
1003
        $translation[$index] = $fullterms ? $term : $term->tid;
1004
      }
1005
    }
1006
  }
1007
  return $translation;
1008
}
1009

    
1010
/**
1011
 * Localize taxonomy terms for localizable vocabularies.
1012
 *
1013
 * @param $terms
1014
 *   Array of term objects or term object.
1015
 * @return
1016
 *   Array of terms with the right ones localized.
1017
 */
1018
function i18n_taxonomy_localize_terms($terms) {
1019
  // If not localizable language just return. Performance optimizations.
1020
  if (!i18n_string_translate_langcode()) {
1021
    return $terms;
1022
  }
1023
  $object_info = i18n_object_info('taxonomy_term');
1024
  $list = is_array($terms) ? $terms : array($terms);
1025
  foreach ($list as $index => $term) {
1026
    if (i18n_taxonomy_vocabulary_mode($term->vid, I18N_MODE_LOCALIZE)) {
1027
      $localize[$index] = $term->tid;
1028
    }
1029
  }
1030
  // If multiple terms, preload all translations, then run object translation.
1031
  if (!empty($localize)) {
1032
    i18n_string_translation_search(array('taxonomy', 'term', $localize, '*'));
1033
    foreach ($localize as $index => $tid) {
1034
      $list[$index] = i18n_string_object_translate('taxonomy_term', $list[$index]);
1035
    }
1036
  }
1037
  // Return array or simple object, depending on incoming format.
1038
  return is_array($terms) ? $list : reset($list);
1039
}
1040

    
1041
/**
1042
 * Taxonomy vocabulary settings.
1043
 *
1044
 * @param $vid
1045
 *   Vocabulary object or vocabulary id.
1046
 * @param $mode
1047
 *   Vocabulary mode to compare with.
1048
 *
1049
 */
1050
function i18n_taxonomy_vocabulary_mode($vid, $mode = NULL) {
1051
  $modes = &drupal_static(__FUNCTION__);
1052
  if (is_object($vid)) {
1053
    $vid_mode = i18n_object_field($vid, 'i18n_mode', I18N_MODE_NONE);
1054
    return isset($mode) ? $mode & $vid_mode : $vid_mode;
1055
  }
1056
  else {
1057
    if (!isset($modes[$vid])) {
1058
      $modes[$vid] = i18n_object_field(taxonomy_vocabulary_load($vid), 'i18n_mode', I18N_MODE_NONE);
1059
    }
1060
    return isset($mode) ? $mode & $modes[$vid] : $modes[$vid];
1061
  }
1062
}
1063

    
1064
/**
1065
 * Get taxonomy tree for a given language
1066
 *
1067
 * @param $vid
1068
 *   Vocabulary id
1069
 * @param $lang
1070
 *   Language code
1071
 * @param $parent
1072
 *   Parent term id for the tree
1073
 */
1074
function i18n_taxonomy_get_tree($vid, $langcode, $parent = 0, $max_depth = NULL, $load_entities = FALSE) {
1075
  $children = &drupal_static(__FUNCTION__, array());
1076
  $parents = &drupal_static(__FUNCTION__ . ':parents', array());
1077
  $terms = &drupal_static(__FUNCTION__ . ':terms', array());
1078

    
1079
  // We cache trees, so it's not CPU-intensive to call get_tree() on a term
1080
  // and its children, too.
1081
  if (!isset($children[$vid][$langcode])) {
1082
    $children[$vid][$langcode] = array();
1083
    $parents[$vid][$langcode] = array();
1084
    $terms[$vid][$langcode] = array();
1085

    
1086
    $query = db_select('taxonomy_term_data', 't');
1087
    $query->join('taxonomy_term_hierarchy', 'h', 'h.tid = t.tid');
1088
    $result = $query
1089
      ->addTag('translatable')
1090
      ->addTag('term_access')
1091
      ->fields('t')
1092
      ->fields('h', array('parent'))
1093
      ->condition('t.vid', $vid)
1094
      ->condition('t.language', $langcode)
1095
      ->orderBy('t.weight')
1096
      ->orderBy('t.name')
1097
      ->execute();
1098

    
1099
    foreach ($result as $term) {
1100
      $children[$vid][$langcode][$term->parent][] = $term->tid;
1101
      $parents[$vid][$langcode][$term->tid][] = $term->parent;
1102
      $terms[$vid][$langcode][$term->tid] = $term;
1103
    }
1104
  }
1105

    
1106
  // Load full entities, if necessary. The entity controller statically
1107
  // caches the results.
1108
  if ($load_entities) {
1109
    $term_entities = taxonomy_term_load_multiple(array_keys($terms[$vid][$langcode]));
1110
  }
1111

    
1112
  $max_depth = (!isset($max_depth)) ? count($children[$vid][$langcode]) : $max_depth;
1113
  $tree = array();
1114

    
1115
  // Keeps track of the parents we have to process, the last entry is used
1116
  // for the next processing step.
1117
  $process_parents = array();
1118
  $process_parents[] = $parent;
1119

    
1120
  // Loops over the parent terms and adds its children to the tree array.
1121
  // Uses a loop instead of a recursion, because it's more efficient.
1122
  while (count($process_parents)) {
1123
    $parent = array_pop($process_parents);
1124
    // The number of parents determines the current depth.
1125
    $depth = count($process_parents);
1126
    if ($max_depth > $depth && !empty($children[$vid][$langcode][$parent])) {
1127
      $has_children = FALSE;
1128
      $child = current($children[$vid][$langcode][$parent]);
1129
      do {
1130
        if (empty($child)) {
1131
          break;
1132
        }
1133
        $term = $load_entities ? $term_entities[$child] : $terms[$vid][$langcode][$child];
1134
        if (count($parents[$vid][$langcode][$term->tid]) > 1) {
1135
          // We have a term with multi parents here. Clone the term,
1136
          // so that the depth attribute remains correct.
1137
          $term = clone $term;
1138
        }
1139
        $term->depth = $depth;
1140
        unset($term->parent);
1141
        $term->parents = $parents[$vid][$langcode][$term->tid];
1142
        $tree[] = $term;
1143
        if (!empty($children[$vid][$langcode][$term->tid])) {
1144
          $has_children = TRUE;
1145

    
1146
          // We have to continue with this parent later.
1147
          $process_parents[] = $parent;
1148
          // Use the current term as parent for the next iteration.
1149
          $process_parents[] = $term->tid;
1150

    
1151
          // Reset pointers for child lists because we step in there more often
1152
          // with multi parents.
1153
          reset($children[$vid][$langcode][$term->tid]);
1154
          // Move pointer so that we get the correct term the next time.
1155
          next($children[$vid][$langcode][$parent]);
1156
          break;
1157
        }
1158
      } while ($child = next($children[$vid][$langcode][$parent]));
1159

    
1160
      if (!$has_children) {
1161
        // We processed all terms in this hierarchy-level, reset pointer
1162
        // so that this function works the next time it gets called.
1163
        reset($children[$vid][$langcode][$parent]);
1164
      }
1165
    }
1166
  }
1167

    
1168
  return $tree;
1169
}
1170

    
1171
/**
1172
 * Recursive array filtering, convert all terms to 'tid'.
1173
 */
1174
function _i18n_taxonomy_filter_tids($tid) {
1175
  if (is_array($tid)) {
1176
    return array_map('_i18n_taxonomy_filter_tids', $tid);
1177
  }
1178
  else {
1179
    return is_object($tid) ? $tid->tid : (int)$tid;
1180
  }
1181
}
1182

    
1183
/**
1184
 * Recursive array filtering, convert all terms to 'term object'
1185
 */
1186
function _i18n_taxonomy_filter_terms($term) {
1187
  if (is_array($term)) {
1188
    return array_map('_i18n_taxonomy_filter_terms', $term);
1189
  }
1190
  else {
1191
    return is_object($term) ? $term : taxonomy_term_load($term);
1192
  }
1193
}
1194

    
1195
/**
1196
 * Load translation set. Menu loading callback.
1197
 */
1198
function i18n_taxonomy_translation_set_load($tsid) {
1199
  return i18n_translation_set_load($tsid, 'taxonomy_term');
1200
}
1201

    
1202
/**
1203
 * Implements hook_field_uuid_load().
1204
 */
1205
function i18n_taxonomy_field_uuid_load($entity_type, $entity, $field, $instance, $langcode, &$items) {
1206
  taxonomy_field_uuid_load($entity_type, $entity, $field, $instance, $langcode, $items);
1207
}
1208

    
1209
/**
1210
 * Implements hook_field_uuid_presave().
1211
 */
1212
function i18n_taxonomy_field_uuid_presave($entity_type, $entity, $field, $instance, $langcode, &$items) {
1213
  taxonomy_field_uuid_presave($entity_type, $entity, $field, $instance, $langcode, $items);
1214
}
1215
/**
1216
 * Implements hook_entity_info_alter().
1217
 */
1218
function i18n_taxonomy_entity_info_alter(&$entity_info) {
1219
  if (isset($entity_info['taxonomy_term'])) {
1220
    // Core doesn't provide a label callback for taxonomy terms. By setting one
1221
    // we can use it to return the correct localized term name.
1222
    $entity_info['taxonomy_term']['label callback'] = 'i18n_taxonomy_taxonomy_term_label';
1223

    
1224
    // Also let core know terms have languages, now.
1225
    $entity_info['taxonomy_term']['entity keys']['language'] = 'language';
1226
  }
1227
}
1228

    
1229
/**
1230
 * Providing a hook_entity_info() 'label callback' to ensure modules that use
1231
 * entity_label() get the correct localized taxonomy term.
1232
 */
1233
function i18n_taxonomy_taxonomy_term_label($term, $entity_type) {
1234
  return i18n_taxonomy_term_name($term, i18n_language_interface()->language);
1235
}
1236

    
1237
/**
1238
 * Implements hook_views_api().
1239
 */
1240
function i18n_taxonomy_views_api() {
1241
  return array(
1242
    'api' => 3,
1243
  );
1244
}
1245

    
1246
/**
1247
 * Implements hook_module_enabled().
1248
 *
1249
 * Updates options_list_callback for taxonomy term fields.
1250
 *
1251
 * @param $modules
1252
 */
1253
function i18n_taxonomy_modules_enabled($modules) {
1254
  $modules = drupal_map_assoc($modules);
1255
  if (isset($modules['i18n_taxonomy'])) {
1256
    foreach (field_info_fields() as $fieldname => $field) {
1257
      if ($field['type'] == 'taxonomy_term_reference') {
1258
        $field['settings']['options_list_callback'] = 'i18n_taxonomy_allowed_values';
1259
        field_update_field($field);
1260
      }
1261
    }
1262
  }
1263
}