Projet

Général

Profil

Paste
Télécharger (46,5 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / i18n / i18n_taxonomy / i18n_taxonomy.module @ b3ab3446

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
          if (isset($item['taxonomy_term'])) {
217
            $term = $item['taxonomy_term'];
218
          }
219
          else {
220
            $term = taxonomy_term_load($item['tid']);
221
          }
222
          $uri = entity_uri('taxonomy_term', $term);
223
          $element[$delta] = array(
224
            '#type' => 'link',
225
            '#title' => i18n_taxonomy_term_name($term, $language->language),
226
            '#href' => $uri['path'],
227
            '#options' => $uri['options'],
228
          );
229
        }
230
      }
231
      break;
232

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

    
243
  return $element;
244
}
245

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

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

    
296
/**
297
 * Implements hook_field_info_alter()
298
 */
299
function i18n_taxonomy_field_info_alter(&$info) {
300
  // Change default formatter for term reference fields
301
  $info['taxonomy_term_reference']['default_formatter'] = 'i18n_taxonomy_term_reference_link';
302

    
303
  // Translate field values.
304
  $info['taxonomy_term_reference']['options_list_callback'] = 'i18n_taxonomy_allowed_values';
305

    
306
  // Sync callback for field translations
307
  $info['taxonomy_term_reference']['i18n_sync_callback'] = 'i18n_taxonomy_field_prepare_translation';
308
}
309

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

    
324
/**
325
 * Implements hook_field_attach_prepare_translation_alter().
326
 *
327
 * Prepare and synchronize translation for term reference fields.
328
 */
329
function i18n_taxonomy_field_attach_prepare_translation_alter(&$entity, $context) {
330
  $entity_type = $context['entity_type'];
331
  $source_entity = $context['source_entity'];
332

    
333
  $options = array(
334
    'default' => FALSE,
335
    'deleted' => FALSE,
336
    'language' => NULL,
337
  );
338

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

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

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

    
393
/**
394
 * Implements hook_i18n_translate_path()
395
 */
396
function i18n_taxonomy_i18n_translate_path($path) {
397
  if (strpos($path, 'taxonomy/term/') === 0) {
398
    return i18n_taxonomy_translate_path($path);
399
  }
400
}
401

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

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

    
461
/**
462
 * Get localized term name unfiltered.
463
 */
464
function i18n_taxonomy_term_name($term, $langcode = NULL) {
465
  $key = i18n_object_info('taxonomy_term', 'key');
466
  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;
467
}
468

    
469

    
470
/**
471
 * Get localized term description unfiltered.
472
 */
473
function i18n_taxonomy_term_description($term, $langcode = NULL) {
474
  $key = i18n_object_info('taxonomy_term', 'key');
475
  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;
476
}
477

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

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

    
514
/**
515
 * Get localized vocabulary description, unfiltered.
516
 */
517
function i18n_taxonomy_vocabulary_description($vocabulary, $langcode = NULL) {
518
  return i18n_object_langcode($vocabulary) ? $vocabulary->description : i18n_string(array('taxonomy', 'vocabulary', $vocabulary->vid, 'description'), $vocabulary->description, array('langcode' => $langcode, 'sanitize' => FALSE));
519
}
520

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

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

    
566
/**
567
 * Implements hook_taxonomy_display_breadcrumb_parents_alter().
568
 */
569
function i18n_taxonomy_taxonomy_display_breadcrumb_parents_alter(&$parents) {
570
  $parents = i18n_taxonomy_localize_terms($parents);
571
}
572

    
573
/**
574
 * Implements hook_taxonomy_display_term_page_term_object_alter().
575
 */
576
function i18n_taxonomy_taxonomy_display_term_page_term_object_alter(&$term) {
577
  $term = i18n_taxonomy_localize_terms($term);
578
}
579

    
580
/**
581
 * Implements hook_taxonomy_term_insert()
582
 */
583
function i18n_taxonomy_taxonomy_term_insert($term) {
584
  i18n_taxonomy_taxonomy_term_update($term);
585
}
586

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

    
610
/**
611
 * Implements hook_taxonomy_term_delete()
612
 */
613
function i18n_taxonomy_taxonomy_term_delete($term) {
614
  // If a translation set exists for this term, remove this term from the set.
615
  if (isset($term->i18n_tsid) && $term->i18n_tsid) {
616
    $translation_set = i18n_translation_set_load($term->i18n_tsid);
617
    $translation_set->get_translations();
618

    
619
    $translation_set->remove_language($term->language);
620

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

    
629
/**
630
 * Implements hook_taxonomy_vocabulary_insert()
631
 */
632
function i18n_taxonomy_taxonomy_vocabulary_insert($vocabulary) {
633
  i18n_taxonomy_taxonomy_vocabulary_update($vocabulary);
634
}
635

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

    
662
/**
663
 * Implements hook_taxonomy_vocabulary_delete()
664
 */
665
function i18n_taxonomy_taxonomy_vocabulary_delete($vocabulary) {
666
  i18n_string_object_remove('taxonomy_vocabulary', $vocabulary);
667
}
668

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

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

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

    
734
/**
735
 * Implements hook_form_FORM_ID_alter()
736
 */
737
function i18n_taxonomy_form_taxonomy_form_term_alter(&$form, &$form_state) {
738
  // Check for confirmation forms
739
  if (isset($form_state['confirm_delete']) || isset($form_state['confirm_parents'])) return;
740

    
741
  $term = $form_state['term'];
742
  $vocabulary = $form['#vocabulary'];
743

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

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

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

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

    
772
        $form['language']['#default_value'] = $target_language->language;
773
        $form['language']['#disabled'] = TRUE;
774

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

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

    
816
    case I18N_MODE_LOCALIZE:
817
      $form['language'] = array(
818
        '#type' => 'value',
819
        '#value' => LANGUAGE_NONE,
820
      );
821
      break;
822

    
823
    case I18N_MODE_NONE:
824
    default:
825
      $form['language'] = array(
826
        '#type' => 'value',
827
        '#value' => LANGUAGE_NONE,
828
      );
829
      break;
830
  }
831

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

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

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

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

    
894
    case 'search_form':
895
      // Localize category selector in advanced search form.
896
      if (!empty($form['advanced']) && !empty($form['advanced']['category'])) {
897
        i18n_taxonomy_form_all_localize($form['advanced']['category']);
898
      }
899
      break;
900
  }
901
}
902

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

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

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

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

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

    
1050
/**
1051
 * Taxonomy vocabulary settings.
1052
 *
1053
 * @param $vid
1054
 *   Vocabulary object or vocabulary id.
1055
 * @param $mode
1056
 *   Vocabulary mode to compare with.
1057
 *
1058
 */
1059
function i18n_taxonomy_vocabulary_mode($vid, $mode = NULL) {
1060
  $modes = &drupal_static(__FUNCTION__);
1061
  if (is_object($vid)) {
1062
    $vid_mode = i18n_object_field($vid, 'i18n_mode', I18N_MODE_NONE);
1063
    return isset($mode) ? $mode & $vid_mode : $vid_mode;
1064
  }
1065
  else {
1066
    if (!isset($modes[$vid])) {
1067
      $modes[$vid] = i18n_object_field(taxonomy_vocabulary_load($vid), 'i18n_mode', I18N_MODE_NONE);
1068
    }
1069
    return isset($mode) ? $mode & $modes[$vid] : $modes[$vid];
1070
  }
1071
}
1072

    
1073
/**
1074
 * Get taxonomy tree for a given language
1075
 *
1076
 * @param $vid
1077
 *   Vocabulary id
1078
 * @param $lang
1079
 *   Language code
1080
 * @param $parent
1081
 *   Parent term id for the tree
1082
 */
1083
function i18n_taxonomy_get_tree($vid, $langcode, $parent = 0, $max_depth = NULL, $load_entities = FALSE) {
1084
  $children = &drupal_static(__FUNCTION__, array());
1085
  $parents = &drupal_static(__FUNCTION__ . ':parents', array());
1086
  $terms = &drupal_static(__FUNCTION__ . ':terms', array());
1087

    
1088
  // We cache trees, so it's not CPU-intensive to call get_tree() on a term
1089
  // and its children, too.
1090
  if (!isset($children[$vid][$langcode])) {
1091
    $children[$vid][$langcode] = array();
1092
    $parents[$vid][$langcode] = array();
1093
    $terms[$vid][$langcode] = array();
1094

    
1095
    $query = db_select('taxonomy_term_data', 't');
1096
    $query->join('taxonomy_term_hierarchy', 'h', 'h.tid = t.tid');
1097
    $result = $query
1098
      ->addTag('translatable')
1099
      ->addTag('taxonomy_term_access')
1100
      ->fields('t')
1101
      ->fields('h', array('parent'))
1102
      ->condition('t.vid', $vid)
1103
      ->condition('t.language', $langcode)
1104
      ->orderBy('t.weight')
1105
      ->orderBy('t.name')
1106
      ->execute();
1107

    
1108
    foreach ($result as $term) {
1109
      $children[$vid][$langcode][$term->parent][] = $term->tid;
1110
      $parents[$vid][$langcode][$term->tid][] = $term->parent;
1111
      $terms[$vid][$langcode][$term->tid] = $term;
1112
    }
1113
  }
1114

    
1115
  // Load full entities, if necessary. The entity controller statically
1116
  // caches the results.
1117
  if ($load_entities) {
1118
    $term_entities = taxonomy_term_load_multiple(array_keys($terms[$vid][$langcode]));
1119
  }
1120

    
1121
  $max_depth = (!isset($max_depth)) ? count($children[$vid][$langcode]) : $max_depth;
1122
  $tree = array();
1123

    
1124
  // Keeps track of the parents we have to process, the last entry is used
1125
  // for the next processing step.
1126
  $process_parents = array();
1127
  $process_parents[] = $parent;
1128

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

    
1155
          // We have to continue with this parent later.
1156
          $process_parents[] = $parent;
1157
          // Use the current term as parent for the next iteration.
1158
          $process_parents[] = $term->tid;
1159

    
1160
          // Reset pointers for child lists because we step in there more often
1161
          // with multi parents.
1162
          reset($children[$vid][$langcode][$term->tid]);
1163
          // Move pointer so that we get the correct term the next time.
1164
          next($children[$vid][$langcode][$parent]);
1165
          break;
1166
        }
1167
      } while ($child = next($children[$vid][$langcode][$parent]));
1168

    
1169
      if (!$has_children) {
1170
        // We processed all terms in this hierarchy-level, reset pointer
1171
        // so that this function works the next time it gets called.
1172
        reset($children[$vid][$langcode][$parent]);
1173
      }
1174
    }
1175
  }
1176

    
1177
  return $tree;
1178
}
1179

    
1180
/**
1181
 * Recursive array filtering, convert all terms to 'tid'.
1182
 */
1183
function _i18n_taxonomy_filter_tids($tid) {
1184
  if (is_array($tid)) {
1185
    return array_map('_i18n_taxonomy_filter_tids', $tid);
1186
  }
1187
  else {
1188
    return is_object($tid) ? $tid->tid : (int)$tid;
1189
  }
1190
}
1191

    
1192
/**
1193
 * Recursive array filtering, convert all terms to 'term object'
1194
 */
1195
function _i18n_taxonomy_filter_terms($term) {
1196
  if (is_array($term)) {
1197
    return array_map('_i18n_taxonomy_filter_terms', $term);
1198
  }
1199
  else {
1200
    return is_object($term) ? $term : taxonomy_term_load($term);
1201
  }
1202
}
1203

    
1204
/**
1205
 * Load translation set. Menu loading callback.
1206
 */
1207
function i18n_taxonomy_translation_set_load($tsid) {
1208
  return i18n_translation_set_load($tsid, 'taxonomy_term');
1209
}
1210

    
1211
/**
1212
 * Implements hook_field_uuid_load().
1213
 */
1214
function i18n_taxonomy_field_uuid_load($entity_type, $entity, $field, $instance, $langcode, &$items) {
1215
  taxonomy_field_uuid_load($entity_type, $entity, $field, $instance, $langcode, $items);
1216
}
1217

    
1218
/**
1219
 * Implements hook_field_uuid_presave().
1220
 */
1221
function i18n_taxonomy_field_uuid_presave($entity_type, $entity, $field, $instance, $langcode, &$items) {
1222
  taxonomy_field_uuid_presave($entity_type, $entity, $field, $instance, $langcode, $items);
1223
}
1224
/**
1225
 * Implements hook_entity_info_alter().
1226
 */
1227
function i18n_taxonomy_entity_info_alter(&$entity_info) {
1228
  if (isset($entity_info['taxonomy_term'])) {
1229
    // Core doesn't provide a label callback for taxonomy terms. By setting one
1230
    // we can use it to return the correct localized term name.
1231
    $entity_info['taxonomy_term']['label callback'] = 'i18n_taxonomy_taxonomy_term_label';
1232

    
1233
    // Also let core know terms have languages, now.
1234
    $entity_info['taxonomy_term']['entity keys']['language'] = 'language';
1235
  }
1236
}
1237

    
1238
/**
1239
 * Providing a hook_entity_info() 'label callback' to ensure modules that use
1240
 * entity_label() get the correct localized taxonomy term.
1241
 */
1242
function i18n_taxonomy_taxonomy_term_label($term, $entity_type) {
1243
  return i18n_taxonomy_term_name($term, i18n_language_interface()->language);
1244
}
1245

    
1246
/**
1247
 * Implements hook_views_api().
1248
 */
1249
function i18n_taxonomy_views_api() {
1250
  return array(
1251
    'api' => 3,
1252
  );
1253
}
1254

    
1255
/**
1256
 * Implements hook_module_enabled().
1257
 *
1258
 * Updates options_list_callback for taxonomy term fields.
1259
 *
1260
 * @param $modules
1261
 */
1262
function i18n_taxonomy_modules_enabled($modules) {
1263
  $modules = drupal_map_assoc($modules);
1264
  if (isset($modules['i18n_taxonomy'])) {
1265
    foreach (field_info_fields() as $fieldname => $field) {
1266
      if ($field['type'] == 'taxonomy_term_reference') {
1267
        $field['settings']['options_list_callback'] = 'i18n_taxonomy_allowed_values';
1268
        field_update_field($field);
1269
      }
1270
    }
1271
  }
1272
}
1273

    
1274
/**
1275
 * Implements hook_views_pre_render().
1276
 */
1277
function i18n_taxonomy_views_pre_render(&$view) {
1278
  if(!module_exists('rules_scheduler')) {
1279
    global $language;
1280

    
1281
    foreach ($view->result as $delta => $term){
1282
      if (isset($term->tid)) {
1283
        i18n_string_translate_langcode($language->language);
1284
        $localized_term = i18n_taxonomy_localize_terms(taxonomy_term_load($term->tid));
1285
        $term->tid = $localized_term->tid;
1286
        $term->taxonomy_term_data_name = $localized_term->name;
1287
        $term->taxonomy_term_data_description = $localized_term->description;
1288
      }
1289
    }
1290
  }
1291
}