Projet

Général

Profil

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

root / drupal7 / sites / all / modules / i18n / i18n_taxonomy / i18n_taxonomy.module @ 8c72e82a

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
  global $language;
381
  $options = array();
382
  foreach ($field['settings']['allowed_values'] as $tree) {
383
    if ($vocabulary = taxonomy_vocabulary_machine_name_load($tree['vocabulary'])) {
384
      if (i18n_taxonomy_vocabulary_mode($vocabulary->vid) == I18N_MODE_TRANSLATE) {
385
        $parent = i18n_taxonomy_translation_term_tid($tree['parent'], NULL, $tree['parent']);
386
        $language = i18n_language_context();
387
        $terms = i18n_taxonomy_get_tree($vocabulary->vid, $language->language, $parent);
388
      }
389
      else {
390
        $terms = taxonomy_get_tree($vocabulary->vid, $tree['parent']);
391
      }
392
      if ($terms) {
393
        foreach ($terms as $term) {
394
          $options[$term->tid] = str_repeat('-', $term->depth) . i18n_taxonomy_term_name($term);
395
        }
396
      }
397
    }
398
  }
399
  return $options;
400
}
401

    
402
/**
403
 * Implements hook_i18n_translate_path()
404
 */
405
function i18n_taxonomy_i18n_translate_path($path) {
406
  if (strpos($path, 'taxonomy/term/') === 0) {
407
    return i18n_taxonomy_translate_path($path);
408
  }
409
}
410

    
411
/**
412
 * Implements hook_i18n_context_language().
413
 */
414
function i18n_taxonomy_i18n_context_language() {
415
  if (arg(0) == 'taxonomy') {
416
    // Taxonomy term pages
417
    if (arg(1) == 'term' && is_numeric(arg(2)) && ($term = menu_get_object('taxonomy_term', 2)) && ($langcode = i18n_object_langcode($term))) {
418
      return i18n_language_object($langcode);
419
    }
420
  }
421
}
422

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

    
470
/**
471
 * Get localized term name unfiltered.
472
 */
473
function i18n_taxonomy_term_name($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}, 'name'), $term->name, array('langcode' => $langcode, 'sanitize' => FALSE)) : $term->name;
476
}
477

    
478

    
479
/**
480
 * Get localized term description unfiltered.
481
 */
482
function i18n_taxonomy_term_description($term, $langcode = NULL) {
483
  $key = i18n_object_info('taxonomy_term', 'key');
484
  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;
485
}
486

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

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

    
523
/**
524
 * Get localized vocabulary description, unfiltered.
525
 */
526
function i18n_taxonomy_vocabulary_description($vocabulary, $langcode = NULL) {
527
  return i18n_object_langcode($vocabulary) ? $vocabulary->description : i18n_string(array('taxonomy', 'vocabulary', $vocabulary->vid, 'description'), $vocabulary->description, array('langcode' => $langcode, 'sanitize' => FALSE));
528
}
529

    
530
/**
531
 * Get translated term's tid.
532
 *
533
 * @param $tid
534
 *   Node nid to search for translation.
535
 * @param $language
536
 *   Language to search for the translation, defaults to current language.
537
 * @param $default
538
 *   Value that will be returned if no translation is found.
539
 * @return
540
 *   Translated term tid if exists, or $default.
541
 */
542
function i18n_taxonomy_translation_term_tid($tid, $language = NULL, $default = NULL) {
543
  $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(
544
    ':tid' => $tid,
545
    ':language' => $language ? $language : i18n_language_content()->language
546
  ))->fetchField();
547
  return $translation ? $translation : $default;
548
}
549

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

    
575
/**
576
 * Implements hook_taxonomy_display_breadcrumb_parents_alter().
577
 */
578
function i18n_taxonomy_taxonomy_display_breadcrumb_parents_alter(&$parents) {
579
  $parents = i18n_taxonomy_localize_terms($parents);
580
}
581

    
582
/**
583
 * Implements hook_taxonomy_display_term_page_term_object_alter().
584
 */
585
function i18n_taxonomy_taxonomy_display_term_page_term_object_alter(&$term) {
586
  $term = i18n_taxonomy_localize_terms($term);
587
}
588

    
589
/**
590
 * Implements hook_taxonomy_term_insert()
591
 */
592
function i18n_taxonomy_taxonomy_term_insert($term) {
593
  i18n_taxonomy_taxonomy_term_update($term);
594
}
595

    
596
/**
597
 * Implements hook_taxonomy_term_update()
598
 */
599
function i18n_taxonomy_taxonomy_term_update($term) {
600
  if (i18n_taxonomy_vocabulary_mode($term->vid, I18N_MODE_LOCALIZE)) {
601
    i18n_string_object_update('taxonomy_term', $term);
602
  }
603
  // Multilingual terms, translatable. Link / unlink from translation set.
604
  if (i18n_taxonomy_vocabulary_mode($term->vid, I18N_MODE_TRANSLATE) && !empty($term->translation_set)) {
605
    if (i18n_object_langcode($term)) {
606
      $term->translation_set
607
        ->add_item($term)
608
        ->save();
609
    }
610
    elseif (!empty($term->original)) {
611
      // Term set to language neutral, remove it from translation set and update set (delete if empty)
612
      $term->translation_set
613
        ->remove_item($term->original)
614
        ->update_delete();
615
    }
616
  }
617
}
618

    
619
/**
620
 * Implements hook_taxonomy_term_delete()
621
 */
622
function i18n_taxonomy_taxonomy_term_delete($term) {
623
  // If a translation set exists for this term, remove this term from the set.
624
  if (isset($term->i18n_tsid) && $term->i18n_tsid) {
625
    $translation_set = i18n_translation_set_load($term->i18n_tsid);
626
    $translation_set->get_translations();
627

    
628
    $translation_set->remove_language($term->language);
629

    
630
    // If there are no terms left in this translation set, delete the set.
631
    // Otherwise update the set.
632
    $translation_set->update_delete();
633
  }
634
  // Just in case there's any left over string we run it for all terms.
635
  i18n_string_object_remove('taxonomy_term', $term);
636
}
637

    
638
/**
639
 * Implements hook_taxonomy_vocabulary_insert()
640
 */
641
function i18n_taxonomy_taxonomy_vocabulary_insert($vocabulary) {
642
  i18n_taxonomy_taxonomy_vocabulary_update($vocabulary);
643
}
644

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

    
671
/**
672
 * Implements hook_taxonomy_vocabulary_delete()
673
 */
674
function i18n_taxonomy_taxonomy_vocabulary_delete($vocabulary) {
675
  i18n_string_object_remove('taxonomy_vocabulary', $vocabulary);
676
}
677

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

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

    
734
/**
735
 * Form submit callback to redirect when using the save and translate button.
736
 */
737
function i18n_taxonomy_form_vocabulary_submit($form, &$form_state) {
738
  if ($form_state['triggering_element']['#name'] == 'save_translate') {
739
    $form_state['redirect'] = 'admin/structure/taxonomy/' . $form_state['values']['machine_name'] . '/translate';
740
  }
741
}
742

    
743
/**
744
 * Implements hook_form_FORM_ID_alter()
745
 */
746
function i18n_taxonomy_form_taxonomy_form_term_alter(&$form, &$form_state) {
747
  // Check for confirmation forms
748
  if (isset($form_state['confirm_delete']) || isset($form_state['confirm_parents'])) return;
749

    
750
  $term = $form_state['term'];
751
  $vocabulary = $form['#vocabulary'];
752

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

    
756
  // Add language field or not depending on taxonomy mode.
757
  switch (i18n_taxonomy_vocabulary_mode($vocabulary->vid)) {
758
    case I18N_MODE_TRANSLATE:
759
      $form['language'] = array(
760
        '#description' => t('This term belongs to a multilingual vocabulary. You can set a language for it.'),
761
      ) + i18n_element_language_select($term);
762

    
763
      // If the term to be added will be a translation of a source term,
764
      // set the default value of the option list to the target language and
765
      // create a form element for storing the translation set of the source term.
766
      if (empty($term->tid) && isset($_GET['translation']) && isset($_GET['target']) && ($source_term = taxonomy_term_load($_GET['translation'])) && ($target_language = i18n_language_object($_GET['target']))) {
767
        // Set context language to target language.
768
        i18n_language_context($target_language);
769

    
770
        // Add the translation set to the form so we know the new term
771
        // needs to be added to that set.
772
        if (!empty($source_term->i18n_tsid)) {
773
          $translation_set = i18n_taxonomy_translation_set_load($source_term->i18n_tsid);
774
        }
775
        else {
776
          // No translation set yet, build a new one with the source term.
777
          $translation_set = i18n_translation_set_create('taxonomy_term', $vocabulary->machine_name)
778
          ->add_item($source_term);
779
        }
780

    
781
        $form['language']['#default_value'] = $target_language->language;
782
        $form['language']['#disabled'] = TRUE;
783

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

    
815
    case I18N_MODE_LANGUAGE:
816
      // Set context language to vocabulary language and add value to the form.
817
      i18n_language_context(i18n_language_object($vocabulary->language));
818
      $form['language'] = array(
819
        '#type' => 'value',
820
        '#value' => $vocabulary->language
821
      );
822
      $form['identification']['language_info'] = array('#value' => t('All terms in this vocabulary have a fixed language: %language', array('%language' => i18n_language_name($vocabulary->language))));
823
      break;
824

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

    
832
    case I18N_MODE_NONE:
833
    default:
834
      $form['language'] = array(
835
        '#type' => 'value',
836
        '#value' => LANGUAGE_NONE,
837
      );
838
      break;
839
  }
840

    
841
  if (user_access('translate interface') && i18n_taxonomy_vocabulary_mode($vocabulary->vid) & I18N_MODE_MULTIPLE) {
842
    $form['actions']['translate'] = array(
843
      '#type' => 'submit',
844
      '#name'   => 'save_translate',
845
      '#value' => t('Save and translate'),
846
      '#weight' => 5,
847
      '#states' => array(
848
        'invisible' => array(
849
          // Hide the button if term is language neutral.
850
          'select[name=language]' => array('value' => LANGUAGE_NONE),
851
        ),
852
      ),
853
    );
854
    // Make sure the delete buttons shows up last.
855
    if (isset($form['actions']['delete'])) {
856
      $form['actions']['delete']['#weight'] = 10;
857
    }
858
    $form['#submit'][] = 'i18n_taxonomy_form_term_submit';
859
  }
860
}
861

    
862
/**
863
 * Form submit callback to redirect when using the save and translate button.
864
 */
865
function i18n_taxonomy_form_term_submit($form, &$form_state) {
866
  if ($form_state['triggering_element']['#name'] == 'save_translate') {
867
    // When using the edit link on the list terms, a destination param is
868
    // added that needs to be unset to make the redirection work.
869
    unset($_GET['destination']);
870
    $form_state['redirect'] = 'taxonomy/term/' . $form_state['values']['tid'] . '/translate';
871
  }
872
}
873

    
874
/**
875
 * Implements hook_form_alter().
876
 *
877
 * This is the place to add language fields to all forms.
878
 *
879
 * @ TO DO The vocabulary form needs some javascript.
880
 */
881
function i18n_taxonomy_form_alter(&$form, $form_state, $form_id) {
882
  switch ($form_id) {
883
    case 'taxonomy_overview_vocabularies':
884
      $vocabularies = taxonomy_get_vocabularies();
885
      foreach ($vocabularies as $vocabulary) {
886
        if (i18n_object_langcode($vocabulary)) {
887
          $form[$vocabulary->vid]['name']['#markup'] .= ' (' . i18n_language_name($vocabulary->language) . ')';
888
        }
889
      }
890
      break;
891

    
892
    case 'taxonomy_overview_terms':
893
      // We check for vocabulary object first, because when confirming alphabetical ordering it uses the same form
894
      if (!empty($form['#vocabulary']) && i18n_taxonomy_vocabulary_mode($form['#vocabulary']->vid) & I18N_MODE_TRANSLATE) {
895
        foreach (element_children($form) as $key) {
896
          if (isset($form[$key]['#term']) && ($lang = i18n_object_langcode($form[$key]['#term']))) {
897
            $form[$key]['view']['#suffix'] = ' (' . i18n_language_name($lang) . ')';
898
          }
899
        }
900
      }
901
      break;
902

    
903
    case 'search_form':
904
      // Localize category selector in advanced search form.
905
      if (!empty($form['advanced']) && !empty($form['advanced']['category'])) {
906
        i18n_taxonomy_form_all_localize($form['advanced']['category']);
907
      }
908
      break;
909
  }
910
}
911

    
912
/**
913
 * Validate multilingual options for vocabulary form
914
 */
915
function i18n_taxonomy_form_vocabulary_validate($form, &$form_state) {
916
  if ($form_state['values']['i18n_mode'] & I18N_MODE_LANGUAGE) {
917
    if ($form_state['values']['language'] == LANGUAGE_NONE) {
918
      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.'));
919
    }
920
  }
921
  else {
922
    $form_state['values']['language'] = LANGUAGE_NONE;
923
  }
924
}
925

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

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

    
1010
        if ($translations && !empty($translations[$langcode])) {
1011
          $newterm = $translations[$langcode];
1012
          $translation[$newterm->tid] = $fullterms ? $newterm : $newterm->tid;
1013
        }
1014
      }
1015
      else {
1016
        // Term has no language. Should be ok.
1017
        $translation[$index] = $fullterms ? $term : $term->tid;
1018
      }
1019
    }
1020
  }
1021
  return $translation;
1022
}
1023

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

    
1059
/**
1060
 * Taxonomy vocabulary settings.
1061
 *
1062
 * @param $vid
1063
 *   Vocabulary object or vocabulary id.
1064
 * @param $mode
1065
 *   Vocabulary mode to compare with.
1066
 *
1067
 */
1068
function i18n_taxonomy_vocabulary_mode($vid, $mode = NULL) {
1069
  $modes = &drupal_static(__FUNCTION__);
1070
  if (is_object($vid)) {
1071
    $vid_mode = i18n_object_field($vid, 'i18n_mode', I18N_MODE_NONE);
1072
    return isset($mode) ? $mode & $vid_mode : $vid_mode;
1073
  }
1074
  else {
1075
    if (!isset($modes[$vid])) {
1076
      $modes[$vid] = i18n_object_field(taxonomy_vocabulary_load($vid), 'i18n_mode', I18N_MODE_NONE);
1077
    }
1078
    return isset($mode) ? $mode & $modes[$vid] : $modes[$vid];
1079
  }
1080
}
1081

    
1082
/**
1083
 * Get taxonomy tree for a given language
1084
 *
1085
 * @param $vid
1086
 *   Vocabulary id
1087
 * @param $lang
1088
 *   Language code
1089
 * @param $parent
1090
 *   Parent term id for the tree
1091
 */
1092
function i18n_taxonomy_get_tree($vid, $langcode, $parent = 0, $max_depth = NULL, $load_entities = FALSE) {
1093
  $children = &drupal_static(__FUNCTION__, array());
1094
  $parents = &drupal_static(__FUNCTION__ . ':parents', array());
1095
  $terms = &drupal_static(__FUNCTION__ . ':terms', array());
1096

    
1097
  // We cache trees, so it's not CPU-intensive to call get_tree() on a term
1098
  // and its children, too.
1099
  if (!isset($children[$vid][$langcode])) {
1100
    $children[$vid][$langcode] = array();
1101
    $parents[$vid][$langcode] = array();
1102
    $terms[$vid][$langcode] = array();
1103

    
1104
    $query = db_select('taxonomy_term_data', 't');
1105
    $query->join('taxonomy_term_hierarchy', 'h', 'h.tid = t.tid');
1106
    $result = $query
1107
      ->addTag('translatable')
1108
      ->addTag('taxonomy_term_access')
1109
      ->fields('t')
1110
      ->fields('h', array('parent'))
1111
      ->condition('t.vid', $vid)
1112
      ->condition('t.language', $langcode)
1113
      ->orderBy('t.weight')
1114
      ->orderBy('t.name')
1115
      ->execute();
1116

    
1117
    foreach ($result as $term) {
1118
      $children[$vid][$langcode][$term->parent][] = $term->tid;
1119
      $parents[$vid][$langcode][$term->tid][] = $term->parent;
1120
      $terms[$vid][$langcode][$term->tid] = $term;
1121
    }
1122
  }
1123

    
1124
  // Load full entities, if necessary. The entity controller statically
1125
  // caches the results.
1126
  if ($load_entities) {
1127
    $term_entities = taxonomy_term_load_multiple(array_keys($terms[$vid][$langcode]));
1128
  }
1129

    
1130
  $max_depth = (!isset($max_depth)) ? count($children[$vid][$langcode]) : $max_depth;
1131
  $tree = array();
1132

    
1133
  // Keeps track of the parents we have to process, the last entry is used
1134
  // for the next processing step.
1135
  $process_parents = array();
1136
  $process_parents[] = $parent;
1137

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

    
1164
          // We have to continue with this parent later.
1165
          $process_parents[] = $parent;
1166
          // Use the current term as parent for the next iteration.
1167
          $process_parents[] = $term->tid;
1168

    
1169
          // Reset pointers for child lists because we step in there more often
1170
          // with multi parents.
1171
          reset($children[$vid][$langcode][$term->tid]);
1172
          // Move pointer so that we get the correct term the next time.
1173
          next($children[$vid][$langcode][$parent]);
1174
          break;
1175
        }
1176
      } while ($child = next($children[$vid][$langcode][$parent]));
1177

    
1178
      if (!$has_children) {
1179
        // We processed all terms in this hierarchy-level, reset pointer
1180
        // so that this function works the next time it gets called.
1181
        reset($children[$vid][$langcode][$parent]);
1182
      }
1183
    }
1184
  }
1185

    
1186
  return $tree;
1187
}
1188

    
1189
/**
1190
 * Recursive array filtering, convert all terms to 'tid'.
1191
 */
1192
function _i18n_taxonomy_filter_tids($tid) {
1193
  if (is_array($tid)) {
1194
    return array_map('_i18n_taxonomy_filter_tids', $tid);
1195
  }
1196
  else {
1197
    return is_object($tid) ? $tid->tid : (int)$tid;
1198
  }
1199
}
1200

    
1201
/**
1202
 * Recursive array filtering, convert all terms to 'term object'
1203
 */
1204
function _i18n_taxonomy_filter_terms($term) {
1205
  if (is_array($term)) {
1206
    return array_map('_i18n_taxonomy_filter_terms', $term);
1207
  }
1208
  else {
1209
    return is_object($term) ? $term : taxonomy_term_load($term);
1210
  }
1211
}
1212

    
1213
/**
1214
 * Load translation set. Menu loading callback.
1215
 */
1216
function i18n_taxonomy_translation_set_load($tsid) {
1217
  return i18n_translation_set_load($tsid, 'taxonomy_term');
1218
}
1219

    
1220
/**
1221
 * Implements hook_field_uuid_load().
1222
 */
1223
function i18n_taxonomy_field_uuid_load($entity_type, $entity, $field, $instance, $langcode, &$items) {
1224
  taxonomy_field_uuid_load($entity_type, $entity, $field, $instance, $langcode, $items);
1225
}
1226

    
1227
/**
1228
 * Implements hook_field_uuid_presave().
1229
 */
1230
function i18n_taxonomy_field_uuid_presave($entity_type, $entity, $field, $instance, $langcode, &$items) {
1231
  taxonomy_field_uuid_presave($entity_type, $entity, $field, $instance, $langcode, $items);
1232
}
1233
/**
1234
 * Implements hook_entity_info_alter().
1235
 */
1236
function i18n_taxonomy_entity_info_alter(&$entity_info) {
1237
  if (isset($entity_info['taxonomy_term'])) {
1238
    // Core doesn't provide a label callback for taxonomy terms. By setting one
1239
    // we can use it to return the correct localized term name.
1240
    $entity_info['taxonomy_term']['label callback'] = 'i18n_taxonomy_taxonomy_term_label';
1241

    
1242
    // Also let core know terms have languages, now.
1243
    $entity_info['taxonomy_term']['entity keys']['language'] = 'language';
1244
  }
1245
}
1246

    
1247
/**
1248
 * Providing a hook_entity_info() 'label callback' to ensure modules that use
1249
 * entity_label() get the correct localized taxonomy term.
1250
 */
1251
function i18n_taxonomy_taxonomy_term_label($term, $entity_type) {
1252
  return i18n_taxonomy_term_name($term, i18n_language_interface()->language);
1253
}
1254

    
1255
/**
1256
 * Implements hook_views_api().
1257
 */
1258
function i18n_taxonomy_views_api() {
1259
  return array(
1260
    'api' => 3,
1261
  );
1262
}
1263

    
1264
/**
1265
 * Implements hook_module_enabled().
1266
 *
1267
 * Updates options_list_callback for taxonomy term fields.
1268
 *
1269
 * @param $modules
1270
 */
1271
function i18n_taxonomy_modules_enabled($modules) {
1272
  $modules = drupal_map_assoc($modules);
1273
  if (isset($modules['i18n_taxonomy'])) {
1274
    foreach (field_info_fields() as $fieldname => $field) {
1275
      if ($field['type'] == 'taxonomy_term_reference') {
1276
        $field['settings']['options_list_callback'] = 'i18n_taxonomy_allowed_values';
1277
        field_update_field($field);
1278
      }
1279
    }
1280
  }
1281
}
1282

    
1283
/**
1284
 * Implements hook_views_pre_render().
1285
 */
1286
function i18n_taxonomy_views_pre_render(&$view) {
1287
  if(!module_exists('rules_scheduler')) {
1288
    global $language;
1289

    
1290
    foreach ($view->result as $delta => $term){
1291
      if (isset($term->tid)) {
1292
        i18n_string_translate_langcode($language->language);
1293
        $localized_term = i18n_taxonomy_localize_terms(taxonomy_term_load($term->tid));
1294
        $term->tid = $localized_term->tid;
1295
        $term->taxonomy_term_data_name = $localized_term->name;
1296
        $term->taxonomy_term_data_description = $localized_term->description;
1297
      }
1298
    }
1299
  }
1300
}