Project

General

Profile

Paste
Download (48.1 KB) Statistics
| Branch: | Revision:

root / drupal7 / sites / all / modules / i18n / i18n_taxonomy / i18n_taxonomy.module @ 01f36513

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
      // Set $form_state['storage'] default as empty array because we will add
760
      // the translation and target from $_GET. So we still have it when the
761
      // page partially reloads with ajax.
762
      if(!isset($form_state['storage'])) {
763
        $form_state['storage'] = array();
764
      }
765
      // get translation from $_GET or $form_state['storage']
766
      $translation = null;
767
      if(isset($_GET['translation'])) {
768
        $translation = $_GET['translation'];
769
        $form_state['storage']['translation'] = $translation;
770
      } else if(isset($form_state['storage']) && isset($form_state['storage']['translation'])){
771
        $translation = $form_state['storage']['translation'];
772
      }
773
      // get target from $_GET or $form_state['storage']
774
      $target = null;
775
      if(isset($_GET['target'])) {
776
        $target = $_GET['target'];
777
        $form_state['storage']['target'] = $target;
778
      } else if(isset($form_state['storage']) && isset($form_state['storage']['target'])){
779
        $target = $form_state['storage']['target'];
780
      }
781
      $form['language'] = array(
782
        '#description' => t('This term belongs to a multilingual vocabulary. You can set a language for it.'),
783
      ) + i18n_element_language_select($term);
784

    
785
      // If the term to be added will be a translation of a source term,
786
      // set the default value of the option list to the target language and
787
      // create a form element for storing the translation set of the source term.
788
      if (empty($term->tid) && isset($translation) && isset($target) && ($source_term = taxonomy_term_load($translation)) && ($target_language = i18n_language_object($target))) {
789
        // Set context language to target language.
790
        i18n_language_context($target_language);
791

    
792
        // Add the translation set to the form so we know the new term
793
        // needs to be added to that set.
794
        if (!empty($source_term->i18n_tsid)) {
795
          $translation_set = i18n_taxonomy_translation_set_load($source_term->i18n_tsid);
796
        }
797
        else {
798
          // No translation set yet, build a new one with the source term.
799
          $translation_set = i18n_translation_set_create('taxonomy_term', $vocabulary->machine_name)
800
          ->add_item($source_term);
801
        }
802

    
803
        $form['language']['#default_value'] = $target_language->language;
804
        $form['language']['#disabled'] = TRUE;
805

    
806
        drupal_set_title(t('%language translation of term %title', array('%language' => locale_language_name($_GET['target']), '%title' => $source_term->name)), PASS_THROUGH);
807
      }
808
      elseif (!empty($term->tid) && i18n_object_langcode($term)) {
809
        // Set context language to term language.
810
        i18n_language_context(i18n_language_object($term->language));
811
        // If the current term is part of a translation set,
812
        // remove all other languages of the option list.
813
        if (!empty($term->i18n_tsid)) {
814
          $translation_set = i18n_taxonomy_translation_set_load($term->i18n_tsid);
815
          $translations = $translation_set->get_translations();
816
          // If the number of translations equals 1, there's only a source translation.
817
          if (count($translations) > 1) {
818
            //unset($form['language']['#options'][LANGUAGE_NONE]);
819
            foreach ($translations as $langcode => $translation) {
820
              if ($translation->tid !== $term->tid) {
821
                unset($form['language']['#options'][$langcode]);
822
              }
823
            }
824
            $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')));
825
          }
826
        }
827
      }
828
      // If we've got a translation set, add it to the form.
829
      if (!empty($translation_set)) {
830
        $form['translation_set'] = array(
831
          '#type' => 'value',
832
          '#value' => $translation_set,
833
        );
834
      }
835
      break;
836

    
837
    case I18N_MODE_LANGUAGE:
838
      // Set context language to vocabulary language and add value to the form.
839
      i18n_language_context(i18n_language_object($vocabulary->language));
840
      $form['language'] = array(
841
        '#type' => 'value',
842
        '#value' => $vocabulary->language
843
      );
844
      $form['identification']['language_info'] = array('#value' => t('All terms in this vocabulary have a fixed language: %language', array('%language' => i18n_language_name($vocabulary->language))));
845
      break;
846

    
847
    case I18N_MODE_LOCALIZE:
848
      $form['language'] = array(
849
        '#type' => 'value',
850
        '#value' => LANGUAGE_NONE,
851
      );
852
      break;
853

    
854
    case I18N_MODE_NONE:
855
    default:
856
      $form['language'] = array(
857
        '#type' => 'value',
858
        '#value' => LANGUAGE_NONE,
859
      );
860
      break;
861
  }
862

    
863
  if (user_access('translate interface') && i18n_taxonomy_vocabulary_mode($vocabulary->vid) & I18N_MODE_MULTIPLE) {
864
    $form['actions']['translate'] = array(
865
      '#type' => 'submit',
866
      '#name'   => 'save_translate',
867
      '#value' => t('Save and translate'),
868
      '#weight' => 5,
869
      '#states' => array(
870
        'invisible' => array(
871
          // Hide the button if term is language neutral.
872
          'select[name=language]' => array('value' => LANGUAGE_NONE),
873
        ),
874
      ),
875
    );
876
    // Make sure the delete buttons shows up last.
877
    if (isset($form['actions']['delete'])) {
878
      $form['actions']['delete']['#weight'] = 10;
879
    }
880
    $form['#submit'][] = 'i18n_taxonomy_form_term_submit';
881
  }
882
}
883

    
884
/**
885
 * Form submit callback to redirect when using the save and translate button.
886
 */
887
function i18n_taxonomy_form_term_submit($form, &$form_state) {
888
  if ($form_state['triggering_element']['#name'] == 'save_translate') {
889
    // When using the edit link on the list terms, a destination param is
890
    // added that needs to be unset to make the redirection work.
891
    unset($_GET['destination']);
892
    $form_state['redirect'] = 'taxonomy/term/' . $form_state['values']['tid'] . '/translate';
893
  }
894
}
895

    
896
/**
897
 * Implements hook_form_alter().
898
 *
899
 * This is the place to add language fields to all forms.
900
 *
901
 * @ TO DO The vocabulary form needs some javascript.
902
 */
903
function i18n_taxonomy_form_alter(&$form, $form_state, $form_id) {
904
  switch ($form_id) {
905
    case 'taxonomy_overview_vocabularies':
906
      $vocabularies = taxonomy_get_vocabularies();
907
      foreach ($vocabularies as $vocabulary) {
908
        if (i18n_object_langcode($vocabulary)) {
909
          $form[$vocabulary->vid]['name']['#markup'] .= ' (' . i18n_language_name($vocabulary->language) . ')';
910
        }
911
      }
912
      break;
913

    
914
    case 'taxonomy_overview_terms':
915
      // We check for vocabulary object first, because when confirming alphabetical ordering it uses the same form
916
      if (!empty($form['#vocabulary']) && i18n_taxonomy_vocabulary_mode($form['#vocabulary']->vid) & I18N_MODE_TRANSLATE) {
917
        foreach (element_children($form) as $key) {
918
          if (isset($form[$key]['#term']) && ($lang = i18n_object_langcode($form[$key]['#term']))) {
919
            $form[$key]['view']['#suffix'] = ' (' . i18n_language_name($lang) . ')';
920
          }
921
        }
922
      }
923
      break;
924

    
925
    case 'search_form':
926
      // Localize category selector in advanced search form.
927
      if (!empty($form['advanced']) && !empty($form['advanced']['category'])) {
928
        i18n_taxonomy_form_all_localize($form['advanced']['category']);
929
      }
930
      break;
931
  }
932
}
933

    
934
/**
935
 * Validate multilingual options for vocabulary form
936
 */
937
function i18n_taxonomy_form_vocabulary_validate($form, &$form_state) {
938
  if ($form_state['values']['i18n_mode'] & I18N_MODE_LANGUAGE) {
939
    if ($form_state['values']['language'] == LANGUAGE_NONE) {
940
      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.'));
941
    }
942
  }
943
  else {
944
    $form_state['values']['language'] = LANGUAGE_NONE;
945
  }
946
}
947

    
948
/**
949
 * Localize a taxonomy_form_all() kind of control
950
 *
951
 * The options array is indexed by vocabulary name and then by term id, with tree structure
952
 * We just need to localize vocabulary name and localizable terms. Multilingual vocabularies
953
 * should have been taken care of by query rewriting.
954
 **/
955
function i18n_taxonomy_form_all_localize(&$item) {
956
  $options = &$item['#options'];
957
  foreach (taxonomy_get_vocabularies() as $vid => $vocabulary) {
958
    if (!empty($options[$vocabulary->name])) {
959
      // Localize vocabulary name if translated
960
      $vname = i18n_taxonomy_vocabulary_name($vocabulary);
961
      if ($vname != $vocabulary->name) {
962
        $options[$vname] = $options[$vocabulary->name];
963
        unset($options[$vocabulary->name]);
964
      }
965
      if (i18n_taxonomy_vocabulary_mode($vid) & I18N_MODE_LOCALIZE) {
966
        $tree = taxonomy_get_tree($vid);
967
        if ($tree && (count($tree) > 0)) {
968
          foreach ($tree as $term) {
969
            if (isset($options[$vname][$term->tid])) {
970
              $options[$vname][$term->tid] = str_repeat('-', $term->depth) . i18n_taxonomy_term_name($term);
971
            }
972
          }
973
        }
974
      }
975
    }
976
  }
977
}
978

    
979
/**
980
 * Translate an array of taxonomy terms.
981
 *
982
 * Translates all terms with language, just passing over terms without it.
983
 * Filter out terms with a different language
984
 *
985
 * @param $taxonomy
986
 *   Array of term objects or tids or multiple arrays or terms indexed by vid
987
 * @param $langcode
988
 *   Language code of target language
989
 * @param $fullterms
990
 *   Whether to return full $term objects, returns tids otherwise
991
 * @return
992
 *   Array with translated terms: tid -> $term
993
 *   Array with vid and term array
994
 */
995
function i18n_taxonomy_translate_terms($taxonomy, $langcode, $fullterms = TRUE) {
996
  $translation = array();
997
  if (is_array($taxonomy) && $taxonomy) {
998
    foreach ($taxonomy as $index => $tdata) {
999
      if (is_array($tdata)) {
1000
        // Case 1: Index is vid, $tdata is an array of terms
1001
        $mode = i18n_taxonomy_vocabulary_mode($index);
1002
        // We translate just some vocabularies: translatable, fixed language
1003
        // Fixed language ones may have terms translated, though the UI doesn't support it
1004
        if ($mode & I18N_MODE_LANGUAGE || $mode & I18N_MODE_TRANSLATE) {
1005
          $translation[$index] = i18n_taxonomy_translate_terms($tdata, $langcode, $fullterms);
1006
        }
1007
        elseif ($fullterms) {
1008
          $translation[$index] = array_map('_i18n_taxonomy_filter_terms', $tdata);
1009
        }
1010
        else {
1011
          $translation[$index] = array_map('_i18n_taxonomy_filter_tids', $tdata);
1012
        }
1013
        continue;
1014
      }
1015
      elseif (is_object($tdata)) {
1016
        // Case 2: This is a term object
1017
        $term = $tdata;
1018
      }
1019
      elseif (is_numeric($tdata) && ($tid = (int)$tdata)) {
1020
        // Case 3: This is a term tid, load the full term
1021
        $term = taxonomy_term_load($tid);
1022
      }
1023
      // Translate the term if we got it
1024
      if (empty($term)) {
1025
        // Couldn't identify term, pass through whatever it is
1026
        $translation[$index] = $tdata;
1027
      }
1028
      elseif ($term->language && $term->language != $langcode) {
1029
        $translation_set = i18n_translation_set_load($term->i18n_tsid);
1030
        $translations = $translation_set->get_translations();
1031

    
1032
        if ($translations && !empty($translations[$langcode])) {
1033
          $newterm = $translations[$langcode];
1034
          $translation[$newterm->tid] = $fullterms ? $newterm : $newterm->tid;
1035
        }
1036
      }
1037
      else {
1038
        // Term has no language. Should be ok.
1039
        $translation[$index] = $fullterms ? $term : $term->tid;
1040
      }
1041
    }
1042
  }
1043
  return $translation;
1044
}
1045

    
1046
/**
1047
 * Localize taxonomy terms for localizable vocabularies.
1048
 *
1049
 * @param $terms
1050
 *   Array of term objects or term object.
1051
 * @return
1052
 *   Array of terms with the right ones localized.
1053
 */
1054
function i18n_taxonomy_localize_terms($terms) {
1055
  // If not localizable language just return. Performance optimizations.
1056
  if (!i18n_string_translate_langcode()) {
1057
    return $terms;
1058
  }
1059
  // $terms is not a valid array or term.
1060
  if (empty($terms)) {
1061
    return $terms;
1062
  }
1063
  $object_info = i18n_object_info('taxonomy_term');
1064
  $list = is_array($terms) ? $terms : array($terms);
1065
  foreach ($list as $index => $term) {
1066
    if (i18n_taxonomy_vocabulary_mode($term->vid, I18N_MODE_LOCALIZE)) {
1067
      $localize[$index] = $term->tid;
1068
    }
1069
  }
1070
  // If multiple terms, preload all translations, then run object translation.
1071
  if (!empty($localize)) {
1072
    i18n_string_translation_search(array('taxonomy', 'term', $localize, '*'));
1073
    foreach ($localize as $index => $tid) {
1074
      $list[$index] = i18n_string_object_translate('taxonomy_term', $list[$index]);
1075
    }
1076
  }
1077
  // Return array or simple object, depending on incoming format.
1078
  return is_array($terms) ? $list : reset($list);
1079
}
1080

    
1081
/**
1082
 * Taxonomy vocabulary settings.
1083
 *
1084
 * @param $vid
1085
 *   Vocabulary object or vocabulary id.
1086
 * @param $mode
1087
 *   Vocabulary mode to compare with.
1088
 *
1089
 */
1090
function i18n_taxonomy_vocabulary_mode($vid, $mode = NULL) {
1091
  $modes = &drupal_static(__FUNCTION__);
1092
  if (is_object($vid)) {
1093
    $vid_mode = i18n_object_field($vid, 'i18n_mode', I18N_MODE_NONE);
1094
    return isset($mode) ? $mode & $vid_mode : $vid_mode;
1095
  }
1096
  else {
1097
    if (!isset($modes[$vid])) {
1098
      $modes[$vid] = i18n_object_field(taxonomy_vocabulary_load($vid), 'i18n_mode', I18N_MODE_NONE);
1099
    }
1100
    return isset($mode) ? $mode & $modes[$vid] : $modes[$vid];
1101
  }
1102
}
1103

    
1104
/**
1105
 * Get taxonomy tree for a given language
1106
 *
1107
 * @param $vid
1108
 *   Vocabulary id
1109
 * @param $lang
1110
 *   Language code
1111
 * @param $parent
1112
 *   Parent term id for the tree
1113
 */
1114
function i18n_taxonomy_get_tree($vid, $langcode, $parent = 0, $max_depth = NULL, $load_entities = FALSE) {
1115
  $children = &drupal_static(__FUNCTION__, array());
1116
  $parents = &drupal_static(__FUNCTION__ . ':parents', array());
1117
  $terms = &drupal_static(__FUNCTION__ . ':terms', array());
1118

    
1119
  // We cache trees, so it's not CPU-intensive to call get_tree() on a term
1120
  // and its children, too.
1121
  if (!isset($children[$vid][$langcode])) {
1122
    $children[$vid][$langcode] = array();
1123
    $parents[$vid][$langcode] = array();
1124
    $terms[$vid][$langcode] = array();
1125

    
1126
    $query = db_select('taxonomy_term_data', 't');
1127
    $query->join('taxonomy_term_hierarchy', 'h', 'h.tid = t.tid');
1128
    $result = $query
1129
      ->addTag('translatable')
1130
      ->addTag('taxonomy_term_access')
1131
      ->fields('t')
1132
      ->fields('h', array('parent'))
1133
      ->condition('t.vid', $vid)
1134
      ->condition('t.language', $langcode)
1135
      ->orderBy('t.weight')
1136
      ->orderBy('t.name')
1137
      ->execute();
1138

    
1139
    foreach ($result as $term) {
1140
      $children[$vid][$langcode][$term->parent][] = $term->tid;
1141
      $parents[$vid][$langcode][$term->tid][] = $term->parent;
1142
      $terms[$vid][$langcode][$term->tid] = $term;
1143
    }
1144
  }
1145

    
1146
  // Load full entities, if necessary. The entity controller statically
1147
  // caches the results.
1148
  if ($load_entities) {
1149
    $term_entities = taxonomy_term_load_multiple(array_keys($terms[$vid][$langcode]));
1150
  }
1151

    
1152
  $max_depth = (!isset($max_depth)) ? count($children[$vid][$langcode]) : $max_depth;
1153
  $tree = array();
1154

    
1155
  // Keeps track of the parents we have to process, the last entry is used
1156
  // for the next processing step.
1157
  $process_parents = array();
1158
  $process_parents[] = $parent;
1159

    
1160
  // Loops over the parent terms and adds its children to the tree array.
1161
  // Uses a loop instead of a recursion, because it's more efficient.
1162
  while (count($process_parents)) {
1163
    $parent = array_pop($process_parents);
1164
    // The number of parents determines the current depth.
1165
    $depth = count($process_parents);
1166
    if ($max_depth > $depth && !empty($children[$vid][$langcode][$parent])) {
1167
      $has_children = FALSE;
1168
      $child = current($children[$vid][$langcode][$parent]);
1169
      do {
1170
        if (empty($child)) {
1171
          break;
1172
        }
1173
        $term = $load_entities ? $term_entities[$child] : $terms[$vid][$langcode][$child];
1174
        if (count($parents[$vid][$langcode][$term->tid]) > 1) {
1175
          // We have a term with multi parents here. Clone the term,
1176
          // so that the depth attribute remains correct.
1177
          $term = clone $term;
1178
        }
1179
        $term->depth = $depth;
1180
        unset($term->parent);
1181
        $term->parents = $parents[$vid][$langcode][$term->tid];
1182
        $tree[] = $term;
1183
        if (!empty($children[$vid][$langcode][$term->tid])) {
1184
          $has_children = TRUE;
1185

    
1186
          // We have to continue with this parent later.
1187
          $process_parents[] = $parent;
1188
          // Use the current term as parent for the next iteration.
1189
          $process_parents[] = $term->tid;
1190

    
1191
          // Reset pointers for child lists because we step in there more often
1192
          // with multi parents.
1193
          reset($children[$vid][$langcode][$term->tid]);
1194
          // Move pointer so that we get the correct term the next time.
1195
          next($children[$vid][$langcode][$parent]);
1196
          break;
1197
        }
1198
      } while ($child = next($children[$vid][$langcode][$parent]));
1199

    
1200
      if (!$has_children) {
1201
        // We processed all terms in this hierarchy-level, reset pointer
1202
        // so that this function works the next time it gets called.
1203
        reset($children[$vid][$langcode][$parent]);
1204
      }
1205
    }
1206
  }
1207

    
1208
  return $tree;
1209
}
1210

    
1211
/**
1212
 * Recursive array filtering, convert all terms to 'tid'.
1213
 */
1214
function _i18n_taxonomy_filter_tids($tid) {
1215
  if (is_array($tid)) {
1216
    return array_map('_i18n_taxonomy_filter_tids', $tid);
1217
  }
1218
  else {
1219
    return is_object($tid) ? $tid->tid : (int)$tid;
1220
  }
1221
}
1222

    
1223
/**
1224
 * Recursive array filtering, convert all terms to 'term object'
1225
 */
1226
function _i18n_taxonomy_filter_terms($term) {
1227
  if (is_array($term)) {
1228
    return array_map('_i18n_taxonomy_filter_terms', $term);
1229
  }
1230
  else {
1231
    return is_object($term) ? $term : taxonomy_term_load($term);
1232
  }
1233
}
1234

    
1235
/**
1236
 * Load translation set. Menu loading callback.
1237
 */
1238
function i18n_taxonomy_translation_set_load($tsid) {
1239
  return i18n_translation_set_load($tsid, 'taxonomy_term');
1240
}
1241

    
1242
/**
1243
 * Implements hook_field_uuid_load().
1244
 */
1245
function i18n_taxonomy_field_uuid_load($entity_type, $entity, $field, $instance, $langcode, &$items) {
1246
  taxonomy_field_uuid_load($entity_type, $entity, $field, $instance, $langcode, $items);
1247
}
1248

    
1249
/**
1250
 * Implements hook_field_uuid_presave().
1251
 */
1252
function i18n_taxonomy_field_uuid_presave($entity_type, $entity, $field, $instance, $langcode, &$items) {
1253
  taxonomy_field_uuid_presave($entity_type, $entity, $field, $instance, $langcode, $items);
1254
}
1255
/**
1256
 * Implements hook_entity_info_alter().
1257
 */
1258
function i18n_taxonomy_entity_info_alter(&$entity_info) {
1259
  if (isset($entity_info['taxonomy_vocabulary'])) {
1260
    // Add altered vocabulary schema fields.
1261
    $entity_info['taxonomy_vocabulary']['schema_fields_sql']['base table'][] = 'i18n_mode';
1262
    $entity_info['taxonomy_vocabulary']['schema_fields_sql']['base table'][] = 'language';
1263
  }
1264
  if (isset($entity_info['taxonomy_term'])) {
1265
    // Core doesn't provide a label callback for taxonomy terms. By setting one
1266
    // we can use it to return the correct localized term name.
1267
    $entity_info['taxonomy_term']['label callback'] = 'i18n_taxonomy_taxonomy_term_label';
1268

    
1269
    // Also let core know terms have languages, now.
1270
    $entity_info['taxonomy_term']['entity keys']['language'] = 'language';
1271
  }
1272
}
1273

    
1274
/**
1275
 * Providing a hook_entity_info() 'label callback' to ensure modules that use
1276
 * entity_label() get the correct localized taxonomy term.
1277
 */
1278
function i18n_taxonomy_taxonomy_term_label($term, $entity_type) {
1279
  return i18n_taxonomy_term_name($term, i18n_language_interface()->language);
1280
}
1281

    
1282
/**
1283
 * Implements hook_views_api().
1284
 */
1285
function i18n_taxonomy_views_api() {
1286
  return array(
1287
    'api' => 3,
1288
  );
1289
}
1290

    
1291
/**
1292
 * Implements hook_module_enabled().
1293
 *
1294
 * Updates options_list_callback for taxonomy term fields.
1295
 *
1296
 * @param $modules
1297
 */
1298
function i18n_taxonomy_modules_enabled($modules) {
1299
  $modules = drupal_map_assoc($modules);
1300
  if (isset($modules['i18n_taxonomy'])) {
1301
    foreach (field_info_fields() as $fieldname => $field) {
1302
      if ($field['type'] == 'taxonomy_term_reference') {
1303
        $field['settings']['options_list_callback'] = 'i18n_taxonomy_allowed_values';
1304
        field_update_field($field);
1305
      }
1306
    }
1307
  }
1308
}
1309

    
1310
/**
1311
 * Implements hook_views_pre_render().
1312
 */
1313
function i18n_taxonomy_views_pre_render(&$view) {
1314
  if($view->base_table !== 'rules_scheduler') {
1315
    global $language;
1316

    
1317
    foreach ($view->result as $delta => $term){
1318
      if (isset($term->tid)) {
1319
        i18n_string_translate_langcode($language->language);
1320
        $localized_term = i18n_taxonomy_localize_terms(taxonomy_term_load($term->tid));
1321
        $term->tid = $localized_term->tid;
1322
        $term->taxonomy_term_data_name = $localized_term->name;
1323
        $term->taxonomy_term_data_description = $localized_term->description;
1324
      }
1325
    }
1326
  }
1327
}