6 * Internationalization (i18n) package
8 * This module groups together all existing i18n taxonomy functionality
9 * providing several options for taxonomy translation
11 * Translates taxonomy term for selected vocabularies running them through the localization system
12 * It also translates terms for views filters and views results
14 * @author Jose A. Reyero, 2004
18 * Modes for multilingual vocabularies
20 // No multilingual options
21 define('I18N_TAXONOMY_NONE', 0);
22 // Run through the localization system
23 define('I18N_TAXONOMY_LOCALIZE', 1);
24 // Predefined language for all terms
25 define('I18N_TAXONOMY_LANGUAGE', 2);
26 // Multilingual terms, translatable
27 define('I18N_TAXONOMY_TRANSLATE', 3);
30 * Implementation of hook_help().
32 function i18ntaxonomy_help($section, $arg) {
34 case
'admin/help#i18ntaxonomy' :
35 $output = '<p>'.
t('This module adds support for for multilingual taxonomy. You can set up multilingual options for each vocabulary:').
'</p>';
37 $output .
= '<li>'.
t('A language can be assigned globaly for a vocabulary').
'</li>';
38 $output .
= '<li>'.
t('Different terms for each language with translation relationships.').
'</li>';
39 $output .
= '<li>'.
t('Terms can be common to all languages but may be localized.').
'</li>';
41 $output .
= '<p>'.
t('For more information please read the <a href="@i18n">on-line help pages</a>.', array('@i18n' =>'http://drupal.org/node/31631')) .
'</p>';
43 case
'admin/settings/i18n':
45 $output .
= '<li>'.
t('To set up multilingual options for vocabularies go to !configure_taxonomy', array('!configure_taxonomy' => l(t('Taxonomy configuration page'), 'admin/content/taxonomy'))).
'</li>';
48 case
'admin/content/taxonomy/%':
49 $vocabulary = taxonomy_vocabulary_load($arg[3]);
50 switch (i18ntaxonomy_vocabulary($vocabulary->vid
)) {
51 case I18N_TAXONOMY_LOCALIZE
:
52 return '<p>'.
t('%capital_name is a localizable vocabulary. You will be able to translate term names and descriptions using the localization interface.', array('%capital_name' => drupal_ucfirst($vocabulary->name
), '%name' => $vocabulary->name
)) .
'</p>';
53 case I18N_TAXONOMY_LANGUAGE
:
54 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>';
55 case I18N_TAXONOMY_TRANSLATE
:
56 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>';
63 * Returns list of vocabulary modes
65 function _i18ntaxonomy_vocabulary_options() {
67 I18N_TAXONOMY_NONE
=> t('None. No multilingual options for this vocabulary'),
68 I18N_TAXONOMY_LOCALIZE
=> t('Localize terms. Terms are common for all languages but their name and description may be localized.'),
69 I18N_TAXONOMY_TRANSLATE
=> t('Per language terms. Different terms will be allowed for each language and they can be translated.'),
70 I18N_TAXONOMY_LANGUAGE
=> t('Set language to vocabulary. The vocabulary will have a global language and it will only show up for pages in that language.'),
74 * Implementation of hook_menu().
76 function i18ntaxonomy_menu() {
77 $items['admin/content/taxonomy/%taxonomy_vocabulary/translation'] = array(
78 'title' => 'Translation',
79 'page callback' => 'i18ntaxonomy_page_vocabulary',
80 'page arguments' => array(3, 5, 6),
81 'type' => MENU_LOCAL_TASK
,
82 'parent' => 'admin/content/taxonomy/%taxonomy_vocabulary',
83 'file' => 'i18ntaxonomy.admin.inc',
89 * Implementation of hook_locale().
91 function i18ntaxonomy_locale($op = 'groups') {
94 return array('taxonomy' => t('Taxonomy'));
98 * Implementation of hook_alter_translation_link().
100 * Replaces links with pointers to translated versions of the content.
102 function i18ntaxonomy_translation_link_alter(&$links, $path) {
103 if (preg_match("/^(taxonomy\/term\/)([^\/]*)(.*)$/", $path, $matches)) {//or at a taxonomy-listing?
104 foreach ($links as
$langcode => $link) {
105 if ($str_tids = i18ntaxonomy_translation_tids($matches[2], $langcode)) {
106 $links[$langcode]['href'] = "taxonomy/term/$str_tids".
$matches[3];
113 * Get translated term's tid
116 * Node nid to search for translation
118 * Language to search for the translation, defaults to current language
120 * Value that will be returned if no translation is found
122 * Translated term tid if exists, or $default
124 function i18ntaxonomy_translation_term_tid($tid, $language = NULL
, $default = NULL
) {
125 $translation = db_result(db_query("SELECT t.tid FROM {term_data} t INNER JOIN {term_data} a ON t.trid = a.trid AND t.tid != a.tid WHERE a.tid = %d AND t.language = '%s' AND t.trid", $tid, $language ?
$language : i18n_get_lang()));
126 return $translation ?
$translation : $default;
130 * Returns an url for the translated taxonomy-page, if exists
132 function i18ntaxonomy_translation_tids($str_tids, $lang) {
133 if (preg_match('/^([0-9]+[+ ])+[0-9]+$/', $str_tids)) {
135 // The '+' character in a query string may be parsed as ' '.
136 $tids = preg_split('/[+ ]/', $str_tids);
138 else if (preg_match('/^([0-9]+,)*[0-9]+$/', $str_tids)) {
140 $tids = explode(',', $str_tids);
145 $translated_tids = array();
146 foreach ($tids as
$tid) {
147 if ($translated_tid = i18ntaxonomy_translation_term_tid($tid, $lang)) {
148 $translated_tids[] = $translated_tid;
151 return implode($separator, $translated_tids);
154 * Implementation of hook_taxonomy
156 * $edit parameter may be an array or an object !!
158 function i18ntaxonomy_taxonomy($op, $type, $edit = NULL
) {
159 $edit = (array)$edit;
160 switch ("$type/$op") {
164 $language = isset($edit['language']) ?
$edit['language'] : '';
165 db_query("UPDATE {term_data} SET language='%s' WHERE tid=%d", $language, $tid);
166 // From translation module
167 if (!$language && !empty($edit['trid'])) {
168 // Removed language, remove trid
169 db_query('UPDATE {term_data} SET trid = 0 WHERE tid = %d', $tid);
170 if(db_affected_rows()) drupal_set_message(t('Removed translation information from term'));
172 // Update strings for localizable vocabulary
173 if (i18ntaxonomy_vocabulary($edit['vid']) == I18N_TAXONOMY_LOCALIZE
) {
174 tt("taxonomy:term:$tid:name", $edit['name'], NULL
, TRUE
);
175 tt("taxonomy:term:$tid:description", $edit['description'], NULL
, TRUE
);
178 case
'vocabulary/insert':
179 case
'vocabulary/update':
181 // Update vocabulary settings
182 if (isset($edit['i18nmode'])) {
183 i18ntaxonomy_vocabulary($vid, $edit['i18nmode']);
185 $language = isset($edit['language']) ?
$edit['language'] : '';
186 db_query("UPDATE {vocabulary} SET language='%s' WHERE vid = %d", $language, $edit['vid']);
187 if ($language && $op == 'update') {
188 db_query("UPDATE {term_data} SET language='%s' WHERE vid = %d", $edit['language'], $edit['vid']);
189 drupal_set_message(t('Reset language for all terms.'));
191 // Always add vocabulary translation if !$language
193 tt("taxonomy:vocabulary:$vid:name", $edit['name'], NULL
, TRUE
);
201 * Implementation of hook_db_rewrite_sql()
203 function i18ntaxonomy_db_rewrite_sql($query, $primary_table, $primary_key){
204 // No rewrite for administration pages
205 if (arg(0) == 'admin') return;
207 switch ($primary_table) {
211 // When loading specific terms, vocabs, language conditions shouldn't apply
212 if (preg_match("/WHERE.* $primary_table\.tid\s*(=\s*\d|IN)/", $query)) return;
213 // Taxonomy for specific node
214 if (preg_match("/WHERE r\.nid = \%d/", $query)) return;
215 $result['where'] = i18n_db_rewrite_where($primary_table, 'taxonomy');
221 * Implementation of hook_form_alter
223 * This is the place to add language fields to all forms
225 * @ TO DO The vocabulary form needs some javascript
227 function i18ntaxonomy_form_alter(&$form, $form_state, $form_id) {
229 case
'taxonomy_overview_vocabularies':
230 $vocabularies = taxonomy_get_vocabularies();
231 $languages = locale_language_list('name');
232 foreach ($vocabularies as
$vocabulary) {
233 if ($vocabulary->language
) {
234 $form[$vocabulary->vid
]['types']['#value'] .
= ' ('.
$languages[$vocabulary->language
].
')';
238 case
'taxonomy_overview_terms':
239 $mode = i18ntaxonomy_vocabulary($form['#vocabulary']['vid']);
240 if ($mode == I18N_TAXONOMY_TRANSLATE
) {
241 $languages = locale_language_list('name');
242 foreach (element_children($form) as
$key) {
243 if (isset($form[$key]['#term']) && ($lang = $form[$key]['#term']['language'])) {
244 $form[$key]['view']['#value'] .
= ' ('.
$languages[$lang].
')';
249 case
'taxonomy_form_vocabulary': // Taxonomy vocabulary
250 if ($form['vid']['#value']) {
251 $vocabulary = taxonomy_vocabulary_load($form['vid']['#value']);
252 $mode = i18ntaxonomy_vocabulary($vocabulary->vid
);
255 $mode = I18N_TAXONOMY_NONE
;
257 $form['i18n'] = array(
258 '#type' => 'fieldset',
259 '#title' => t('Multilingual options'),
260 '#collapsible' => TRUE
,
263 $form['i18n']['i18nmode'] = array(
265 '#title' => t('Translation mode'),
266 '#options' => _i18ntaxonomy_vocabulary_options(),
267 '#default_value' => $mode,
269 $form['identification']['language'] = array(
271 '#title' => t('Language'),
272 '#default_value' => $vocabulary && !empty($vocabulary->language
) ?
$vocabulary->language
: '',
273 '#options' => array('' => '') + locale_language_list('name'),
274 '#description' => t('Language for this vocbulary. If set, it will apply to all terms in this vocabulary.'),
275 '#disabled' => ($mode != I18N_TAXONOMY_LANGUAGE
),
279 case
'taxonomy_form_term': // Taxonomy term
280 $vocabulary = (object)$form['#vocabulary'];
281 $term = (object)$form['#term'];
282 // Add language field or not depending on taxonomy mode
283 switch (i18ntaxonomy_vocabulary($vocabulary->vid
)) {
284 case I18N_TAXONOMY_TRANSLATE
:
285 $form['identification']['language'] = array(
287 '#title' => t('Language'),
288 '#default_value' => isset($term) && !empty($term->language
) ?
$term->language
: '',
289 '#options' => array('' => '') + locale_language_list('name'),
290 '#description' => t('This term belongs to a multilingual vocabulary. You can set a language for it.'),
293 case I18N_TAXONOMY_LANGUAGE
:
294 $form['language'] = array('#type' => 'value', '#value' => $vocabulary->language
);
295 $form['identification']['language_info'] = array('#value' => t('All terms in this vocabulary have a fixed language: %language', array('%language' => i18n_language_property($vocabulary->language
, 'name'))));
297 case I18N_TAXONOMY_LOCALIZE
:
298 $form['language'] = array('#type' => 'value', '#value' => '');
299 $form['identification']['name']['#description'] .
= ' <strong>'.
t('This name be localizable').
'</strong>';
300 $form['identification']['description']['#description'] .
= ' <strong>'.
t('This description will be localizable').
'</strong>';
302 case I18N_TAXONOMY_NONE
:
304 $form['language'] = array('#type' => 'value', '#value' => '');
309 if (isset($form['type']) && $form['type']['#value'] .
'_node_form' == $form_id
310 && ($node = $form['#node']) && isset($form['taxonomy']) ) {
311 // Node form. Translate vocabularies
312 i18ntaxonomy_node_form($form);
318 * Handle node form taxonomy
320 function i18ntaxonomy_node_form(&$form) {
321 $node = $form['#node'];
322 if (!isset($node->taxonomy
)) {
323 if (!empty($node->nid
)) {
324 $terms = taxonomy_node_get_terms($node->nid
);
331 $terms = $node->taxonomy
;
333 // Regenerate the whole field for translatable vocabularies
334 foreach (element_children($form['taxonomy']) as
$vid) {
335 if (is_numeric($vid) && i18ntaxonomy_vocabulary($vid) == I18N_TAXONOMY_LOCALIZE
) {
336 // Rebuild this vocabulary's form
337 $vocabulary = taxonomy_vocabulary_load($vid);
338 // Extract terms belonging to the vocabulary in question.
339 $default_terms = array();
340 foreach ($terms as
$term) {
341 if ($term->vid
== $vid) {
342 $default_terms[$term->tid
] = $term;
346 $form['taxonomy'][$vid] = i18ntaxonomy_vocabulary_form($vocabulary->vid
, array_keys($default_terms));
347 $form['taxonomy'][$vid]['#weight'] = $vocabulary->weight
;
348 $form['taxonomy'][$vid]['#required'] = $vocabulary->required
;
354 * Generate a form element for selecting terms from a vocabulary.
355 * Translates all translatable strings.
357 function i18ntaxonomy_vocabulary_form($vid, $value = 0, $help = NULL
, $name = 'taxonomy') {
358 $vocabulary = taxonomy_vocabulary_load($vid);
359 $help = $vocabulary->help ?
tt("taxonomy:vocabulary:$vid:help", $vocabulary->help
) : '';
360 if ($vocabulary->required
) {
364 $blank = '<'.
t('none') .
'>';
367 return _i18ntaxonomy_term_select(check_plain(tt("taxonomy:vocabulary:$vid:name", $vocabulary->name
)), $name, $value, $vid, $help, intval($vocabulary->multiple
), $blank);
370 // Produces translated tree
371 function _i18ntaxonomy_term_select($title, $name, $value, $vocabulary_id, $description, $multiple, $blank, $exclude = array()) {
372 $tree = taxonomy_get_tree($vocabulary_id);
376 $options[0] = $blank;
379 foreach ($tree as
$term) {
380 if (!in_array($term->tid
, $exclude)) {
381 $choice = new
stdClass();
382 $choice->option
= array($term->tid
=> str_repeat('-', $term->depth
) .
tt("taxonomy:term:$term->tid:name", $term->name
));
383 $options[] = $choice;
386 if (!$blank && !$value) {
387 // required but without a predefined value, so set first as predefined
388 $value = $tree[0]->tid
;
392 return array('#type' => 'select',
394 '#default_value' => $value,
395 '#options' => $options,
396 '#description' => $description,
397 '#multiple' => $multiple,
398 '#size' => $multiple ?
min(9, count($options)) : 0,
400 '#theme' => 'taxonomy_term_select',
404 * Returns a list for terms for vocabulary, language
406 function i18ntaxonomy_vocabulary_get_terms($vid, $lang, $status = 'all') {
409 $andsql = ' AND trid > 0';
412 $andsql = ' AND trid = 0';
417 $result = db_query("SELECT * FROM {term_data} WHERE vid=%d AND language='%s' $andsql", $vid, $lang);
419 while ($term = db_fetch_object($result)) {
420 $list[$term->tid
] = $term->name
;
426 * Multilingual Taxonomy
431 * Get term translations
434 * An array of the from lang => Term
436 function i18ntaxonomy_term_get_translations($params, $getall = TRUE
) {
437 foreach($params as
$field => $value) {
438 $conds[] = "i.$field = '%s'";
441 if(!$getall){ // If not all, a parameter must be tid
442 $conds[] = "t.tid != %d";
443 $values[] = $params['tid'];
445 $conds[] = "t.trid != 0";
446 $sql = 'SELECT t.* FROM {term_data} t INNER JOIN {term_data} i ON t.trid = i.trid WHERE '.
implode(' AND ', $conds);;
447 $result = db_query($sql, $values);
449 while ($data = db_fetch_object($result)) {
450 $items[$data->language
] = $data;
457 * Like nat_get_terms() but without caching
459 function i18ntaxonomy_nat_get_terms($nid) {
462 $result = db_query("SELECT td.* FROM {nat} n INNER JOIN {term_data} td USING (tid) WHERE n.nid = %d", $nid);
463 while ($term = db_fetch_object($result)) {
464 $return[$term->tid
] = $term;
472 * Implementation of hook_nodeapi()
474 * Prepare node for translation
476 function i18ntaxonomy_nodeapi(&$node, $op) {
479 // This runs after taxonomy:nodeapi, so we just localize terms here
480 if ($op == 'view' && array_key_exists('taxonomy', $node)) {
481 $node->taxonomy
= i18ntaxonomy_localize_terms($node->taxonomy
);
484 case
'prepare translation':
485 $source = $node->translation_source
;
486 // Taxonomy translation
487 if (is_array($source->taxonomy
)) {
488 // Set translated taxonomy terms
489 $node->taxonomy
= i18ntaxonomy_translate_terms($source->taxonomy
, $node->language
);
496 * Translate an array of taxonomy terms
498 * Translates all terms with language, just passing over terms without it
500 function i18ntaxonomy_translate_terms($taxonomy, $langcode) {
501 $translation = array();
502 foreach ($taxonomy as
$index => $term) {
503 if ($term->language
&& $term->language
!= $langcode) {
504 $translated_terms = i18ntaxonomy_term_get_translations(array('tid' => $term->tid
));
505 if ($translated_terms && $newterm = $translated_terms[$langcode]) {
506 $translation[$newterm->tid
] = $newterm;
509 // Term has no language. Should be ok
510 $translation[$index] = $term;
516 * Implementation of hook_views_pre_view().
518 * Translate table header for taxonomy fields
519 * //field[i][id] = term_node_1.name, translate table header
520 * and replace handler for that field
522 function i18ntaxonomy_views_pre_view(&$view, &$items) {
524 $translate = variable_get('i18ntaxonomy_vocabularies', array());
525 foreach($view->field as
$index => $data) {
527 if($data['id'] == 'term_node.name') {
528 // That's a full taxonomy box
529 $view->field
[$index]['handler'] = 'i18ntaxonomy_views_handler_field_allterms';
530 } elseif(preg_match("/term_node_(\d+)\.name/", $data['id'], $matches)) {
532 if ($translate[$vid]) {
533 // Set new handler for this field
534 $view->field
[$index]['handler'] = 'i18ntaxonomy_views_handler_field_allterms';
542 * Field handler for taxonomy term fields
544 * Remake of views_handler_field_allterms with term name translation
546 function i18ntaxonomy_views_handler_field_allterms($fieldinfo, $fielddata, $value, $data) {
547 if ($fieldinfo['vocabulary']) {
548 $terms = taxonomy_node_get_terms_by_vocabulary($data->nid
, $fieldinfo['vocabulary']);
551 $terms = taxonomy_node_get_terms($data->nid
);
553 // Translate all these terms
554 _i18ntaxonomy_translate_terms($terms);
556 if ($fielddata['options'] == 'nolink') {
557 foreach ($terms as
$term) {
558 $links[] = check_plain($term->name
);
560 $links = !empty($links) ?
implode(' | ', $links) : '';
563 $node = new
stdClass();
564 $node->taxonomy
= $terms;
565 $links = theme('links', taxonomy_link('taxonomy terms', $node));
571 * Localize taxonomy terms for localizable vocabularies
574 * Array of term objects
576 * Object properties to localize
578 * Array of terms with the right ones localized
580 function i18ntaxonomy_localize_terms($terms, $fields = array('name')) {
581 $localize = i18ntaxonomy_vocabulary(NULL
, I18N_TAXONOMY_LOCALIZE
);
582 foreach ($terms as
$index => $term) {
583 if (in_array($term->vid
, $localize)) {
584 foreach ($fields as
$property) {
585 $terms[$index]->$property = tt("taxonomy:term:$term->tid:$property", $term->name
);
592 // Get a list of vocabularies and terms
593 function _i18ntaxonomy_vocabulary_terms($vid = NULL
, $fullname = TRUE
) {
595 if (is_numeric($vid)) {
596 $where = "WHERE td.vid = $vid";
597 } elseif(is_array($vid)) {
598 $where = "WHERE td.vid IN(".
implode(',', $vid).
')';
600 $result = db_query("SELECT DISTINCT(td.tid), td.name, td.weight, v.name as vocabname, v.weight FROM {term_data} td LEFT JOIN {vocabulary} v ON v.vid = td.vid $where ORDER BY v.weight, v.name, td.weight, td.name");
601 while ($obj = db_fetch_object($result)) {
602 $tids[$obj->tid
] = $fullname ?
t($obj->vocabname
).
': '.
t($obj->name
) : t($obj->name
);
609 * Taxonomy vocabulary settings
611 * - If $vid and not $value, returns mode for vid
612 * - If $vid and $value, sets mode for vid
613 * - If !$vid and !$value returns all settings
614 * - If !$vid and $value returns all vids for this mode
622 function i18ntaxonomy_vocabulary($vid = NULL
, $mode = NULL
) {
623 $options = variable_get('i18ntaxonomy_vocabulary', array());
625 $options[$vid] = $mode;
626 variable_set('i18ntaxonomy_vocabulary', $options);
628 return array_key_exists($vid, $options) ?
$options[$vid] : I18N_TAXONOMY_NONE
;
630 return array_keys($options, $mode);