Projet

Général

Profil

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

root / htmltest / sites / all / modules / i18n / i18n_taxonomy / i18n_taxonomy.module @ 4543c6c7

1
<?php
2

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

    
18
/**
19
 * Implements hook_help().
20
 */
21
function i18n_taxonomy_help($path, $arg) {
22
  switch ($path) {
23
    case 'admin/help#i18n_taxonomy' :
24
      $output = '<p>' . t('This module adds support for multilingual taxonomy. You can set up multilingual options for each vocabulary:') . '</p>';
25
      $output .= '<ul>';
26
      $output .= '<li>' . t('A language can be assigned globaly for a vocabulary.') . '</li>';
27
      $output .= '<li>' . t('Different terms for each language with translation relationships.') . '</li>';
28
      $output .= '<li>' . t('Terms can be common to all languages, but may be localized.') . '</li>';
29
      $output .= '</ul>';
30
      $output .= '<p>' . t('To search and translate strings, use the <a href="@translate-interface">translation interface</a> pages.', array('@translate-interface' => url('admin/config/regional/translate'))) . '</p>';
31
      $output .= '<p>' . t('For more information, see the online handbook entry for <a href="@i18n">Internationalization module</a>.', array('@i18n' => 'http://drupal.org/node/133977')) . '</p>';
32
      return $output;
33

    
34
    case 'admin/config/regional/i18n':
35
      $output = '<p>' . t('To set up multilingual options for vocabularies go to <a href="@configure_taxonomy">Taxonomy configuration page</a>.', array('@configure_taxonomy' => url('admin/structure/taxonomy'))) . '</p>';
36
      return $output;
37

    
38
    case 'admin/structure/taxonomy/%':
39
      $vocabulary = taxonomy_vocabulary_machine_name_load($arg[3]);
40
      switch (i18n_taxonomy_vocabulary_mode($vocabulary)) {
41
        case I18N_MODE_LOCALIZE:
42
          return '<p>' . t('%capital_name is a localizable vocabulary. You will be able to translate term names and descriptions using the <a href="@translate-interface">translate interface</a> pages.', array('%capital_name' => drupal_ucfirst($vocabulary->name), '%name' => $vocabulary->name, '@translate-interface' => url('admin/config/regional/translate'))) . '</p>';
43

    
44
        case I18N_MODE_LANGUAGE:
45
          return '<p>' . t('%capital_name is a vocabulary with a fixed language. All the terms in this vocabulary will have %language language.', array('%capital_name' => drupal_ucfirst($vocabulary->name), '%name' => $vocabulary->name, '%language' => i18n_language_property($vocabulary->language, 'name'))) . '</p>';
46

    
47
        case I18N_MODE_TRANSLATE:
48
          return '<p>' . t('%capital_name is a full multilingual vocabulary. You will be able to set a language for each term and create translation relationships.', array('%capital_name' => drupal_ucfirst($vocabulary->name))) . '</p>';
49
      }
50
      break;
51

    
52
  }
53
}
54

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

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

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

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

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

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

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

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

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

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

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

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

    
238
  return $element;
239
}
240

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
475

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

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

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

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

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

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

    
572
/**
573
 * Implements hook_taxonomy_display_breadcrumb_parents_alter().
574
 */
575
function i18n_taxonomy_taxonomy_display_breadcrumb_parents_alter(&$parents) {
576
  $parents = i18n_taxonomy_localize_terms($parents);
577
}
578

    
579
/**
580
 * Implements hook_taxonomy_display_term_page_term_object_alter().
581
 */
582
function i18n_taxonomy_taxonomy_display_term_page_term_object_alter(&$term) {
583
  $term = i18n_taxonomy_localize_terms($term);
584
}
585

    
586
/**
587
 * Implements hook_taxonomy_term_insert()
588
 */
589
function i18n_taxonomy_taxonomy_term_insert($term) {
590
  i18n_taxonomy_taxonomy_term_update($term);
591
}
592

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

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

    
625
    $translation_set->remove_language($term->language);
626

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

    
635
/**
636
 * Implements hook_taxonomy_vocabulary_insert()
637
 */
638
function i18n_taxonomy_taxonomy_vocabulary_insert($vocabulary) {
639
  i18n_taxonomy_taxonomy_vocabulary_update($vocabulary);
640
}
641

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

    
668
/**
669
 * Implements hook_taxonomy_vocabulary_delete()
670
 */
671
function i18n_taxonomy_taxonomy_vocabulary_delete($vocabulary) {
672
  i18n_string_object_remove('taxonomy_vocabulary', $vocabulary);
673
}
674

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

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

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

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

    
747
  $term = $form_state['term'];
748
  $vocabulary = $form['#vocabulary'];
749

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

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

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

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

    
778
        $form['language']['#default_value'] = $target_language->language;
779
        $form['language']['#disabled'] = TRUE;
780

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1179
  return $tree;
1180
}
1181

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

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

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

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

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

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

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

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