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 * Implementation of hook_help().
20 function i18ntaxonomy_help($section = 'admin/help#i18n' ) {
22 case
'admin/help#i18ntaxonomy' :
23 $output = '<p>'.
t('This module adds support for for multilingual taxonomy. You can set up multilingual options for each vocabulary:').
'</p>';
25 $output .
= '<li>'.
t('A language can be assigned globaly for a vocabulary').
'</li>';
26 $output .
= '<li>'.
t('Different terms for each language with translation relationships.').
'</li>';
27 $output .
= '<li>'.
t('Terms can be common to all languages but may be localized.').
'</li>';
29 $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>';
31 case
'admin/settings/i18n':
33 $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>';
39 * Modes for multilingual vocabularies
41 // No multilingual options
42 define('I18N_TAXONOMY_NONE', 0);
43 // Run through the localization system
44 define('I18N_TAXONOMY_LOCALIZE', 1);
45 // Predefined language for all terms
46 define('I18N_TAXONOMY_LANGUAGE', 2);
47 // Multilingual terms, translatable
48 define('I18N_TAXONOMY_TRANSLATE', 3);
51 * Returns list of vocabulary modes
53 function _i18ntaxonomy_vocabulary_options() {
55 I18N_TAXONOMY_NONE
=> t('No translation'),
56 I18N_TAXONOMY_LOCALIZE
=> t('Localize terms. Terms are common for all languages but their name and description may be localized.'),
57 I18N_TAXONOMY_TRANSLATE
=> t('Per language terms. Different terms will be allowed for each language and they can be translated.'),
58 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.'),
62 * Implementation of hook_menu().
64 function i18ntaxonomy_menu() {
65 $items['admin/content/taxonomy/%taxonomy_vocabulary/translation'] = array(
66 'title' => 'Add term',
67 'page callback' => 'i18n_taxonomy_page_vocabulary',
68 'page arguments' => array(3),
69 'type' => MENU_LOCAL_TASK
,
70 'parent' => 'admin/content/taxonomy/%taxonomy_vocabulary',
71 'file' => 'taxonomy.admin.inc',
77 * Implementation of hook_locale().
79 function i18ntaxonomy_locale($op = 'groups') {
82 return array('taxonomy' => t('Taxonomy'));
86 * Implementation of hook_alter_translation_link().
88 * Replaces links with pointers to translated versions of the content.
90 function i18ntaxonomy_translation_link_alter(&$links, $path) {
91 if (preg_match("/^(taxonomy\/term\/)([^\/]*)(.*)$/", $path, $matches)) {//or at a taxonomy-listing?
92 foreach ($links as
$langcode => $link) {
93 if ($str_tids = i18ntaxonomy_translation_tids($matches[2], $langcode)) {
94 $links[$langcode]['href'] = "taxonomy/term/$str_tids".
$matches[3];
101 * Get translated term's tid
104 * Node nid to search for translation
106 * Language to search for the translation, defaults to current language
108 * Value that will be returned if no translation is found
110 * Translated term tid if exists, or $default
112 function i18ntaxonomy_translation_term_tid($tid, $language = NULL
, $default = NULL
) {
113 $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()));
114 return $translation ?
$translation : $default;
118 * Returns an url for the translated taxonomy-page, if exists
120 function i18ntaxonomy_translation_tids($str_tids, $lang) {
121 if (preg_match('/^([0-9]+[+ ])+[0-9]+$/', $str_tids)) {
123 // The '+' character in a query string may be parsed as ' '.
124 $tids = preg_split('/[+ ]/', $str_tids);
126 else if (preg_match('/^([0-9]+,)*[0-9]+$/', $str_tids)) {
128 $tids = explode(',', $str_tids);
133 $translated_tids = array();
134 foreach ($tids as
$tid) {
135 if ($translated_tid = i18ntaxonomy_translation_term_tid($tid, $lang)) {
136 $translated_tids[] = $translated_tid;
139 return implode($separator, $translated_tids);
142 * Implementation of hook_taxonomy
144 * $edit parameter may be an array or an object !!
146 function i18ntaxonomy_taxonomy($op, $type, $edit = NULL
) {
147 $edit = (array)$edit;
148 switch ("$type/$op") {
152 $language = isset($edit['language']) ?
$edit['language'] : '';
153 db_query("UPDATE {term_data} SET language='%s' WHERE tid=%d", $language, $tid);
154 // From translation module
155 if (!$language && !empty($edit['trid'])) {
156 // Removed language, remove trid
157 db_query('UPDATE {term_data} SET trid = 0 WHERE tid = %d', $tid);
158 if(db_affected_rows()) drupal_set_message(t('Removed translation information from term'));
160 // Update strings for localizable vocabulary
161 if (i18ntaxonomy_vocabulary($edit['vid']) == I18N_TAXONOMY_LOCALIZE
) {
162 tt("taxonomy:term:$tid:name", $edit['name'], NULL
, TRUE
);
163 tt("taxonomy:term:$tid:description", $edit['description'], NULL
, TRUE
);
166 case
'vocabulary/insert':
167 case
'vocabulary/update':
169 // Update vocabulary settings
170 if (isset($edit['i18nmode'])) {
171 i18ntaxonomy_vocabulary($vid, $edit['i18nmode']);
173 $language = isset($edit['language']) ?
$edit['language'] : '';
174 db_query("UPDATE {vocabulary} SET language='%s' WHERE vid = %d", $language, $edit['vid']);
175 if ($language && $op == 'update') {
176 db_query("UPDATE {term_data} SET language='%s' WHERE vid = %d", $edit['language'], $edit['vid']);
177 drupal_set_message(t('Reset language for all terms.'));
179 // Always add vocabulary translation if !$language
181 tt("taxonomy:vocabulary:$vid:name", $edit['name'], NULL
, TRUE
);
189 * Implementation of hook_db_rewrite_sql()
191 function i18ntaxonomy_db_rewrite_sql($query, $primary_table, $primary_key){
192 // No rewrite for administration pages
193 if (arg(0) == 'admin') return;
195 switch ($primary_table) {
199 // When loading specific terms, vocabs, language conditions shouldn't apply
200 if (preg_match("/WHERE.* $primary_table\.tid\s*(=\s*\d|IN)/", $query)) return;
201 // Taxonomy for specific node
202 if (preg_match("/WHERE r\.nid = \%d/", $query)) return;
203 $result['where'] = i18n_db_rewrite_where($primary_table, 'taxonomy');
209 * Implementation of hook_form_alter
211 * This is the place to add language fields to all forms
213 function i18ntaxonomy_form_alter(&$form, $form_state, $form_id) {
215 case
'taxonomy_overview_vocabularies':
216 $vocabularies = taxonomy_get_vocabularies();
217 $languages = i18n_supported_languages();
218 foreach ($vocabularies as
$vocabulary) {
219 if($vocabulary->language
) $form[$vocabulary->vid
]['type']['#value'] = $form[$vocabulary->vid
]['type']['#value'].
' ('.
$languages[$vocabulary->language
].
')';
222 case
'taxonomy_form_vocabulary': // Taxonomy vocabulary
223 if (isset($form['vid'])) {
224 $vocabulary = taxonomy_vocabulary_load($form['vid']['#value']);
225 $mode = i18ntaxonomy_vocabulary($vocabulary->vid
);
227 $mode = I18N_TAXONOMY_NONE
;
229 $form['i18n'] = array(
230 '#type' => 'fieldset',
231 '#title' => t('Multilingual options'),
232 '#collapsible' => TRUE
,
235 $form['i18n']['i18nmode'] = array(
237 '#title' => t('Translation mode'),
238 '#options' => _i18ntaxonomy_vocabulary_options(),
239 '#default_value' => $mode,
244 case
'taxonomy_form_term': // Taxonomy term
245 $vocabulary = (object)$form['#vocabulary'];
246 $term = (object)$form['#term'];
247 // Add language field or not depending on taxonomy mode
248 switch (i18ntaxonomy_vocabulary($vocabulary->vid
)) {
249 case I18N_TAXONOMY_TRANSLATE
:
250 $form['identification']['language'] = array(
252 '#title' => t('Language'),
253 '#default_value' => isset($term) && !empty($term->language
) ?
$term->language
: '',
254 '#options' => array('' => '') + locale_language_list('name'),
255 '#description' => t('This term belongs to a multilingual vocabulary.'),
258 case I18N_TAXONOMY_LANGUAGE
:
259 $form['language'] = array('#type' => 'value', '#value' => $vocabulary->language
);
261 case I18N_TAXONOMY_NONE
:
262 case I18N_TAXONOMY_LOCALIZE
:
263 $form['language'] = array('#type' => 'value', '#value' => '');
268 if (isset($form['type']) && $form['type']['#value'] .
'_node_form' == $form_id
269 && ($node = $form['#node']) && isset($form['taxonomy']) ) {
270 // Node form. Translate vocabularies
271 i18ntaxonomy_node_form($form);
277 * Handle node form taxonomy
279 function i18ntaxonomy_node_form(&$form) {
280 $node = $form['#node'];
281 if (!isset($node->taxonomy
)) {
282 if (!empty($node->nid
)) {
283 $terms = taxonomy_node_get_terms($node->nid
);
290 $terms = $node->taxonomy
;
292 // Regenerate the whole field for translatable vocabularies
293 foreach (element_children($form['taxonomy']) as
$vid) {
294 if (is_numeric($vid) && i18ntaxonomy_vocabulary($vid) == I18N_TAXONOMY_LOCALIZE
) {
295 // Rebuild this vocabulary's form
296 $vocabulary = taxonomy_vocabulary_load($vid);
297 // Extract terms belonging to the vocabulary in question.
298 $default_terms = array();
299 foreach ($terms as
$term) {
300 if ($term->vid
== $vid) {
301 $default_terms[$term->tid
] = $term;
305 $form['taxonomy'][$vid] = i18ntaxonomy_vocabulary_form($vocabulary->vid
, array_keys($default_terms));
306 $form['taxonomy'][$vid]['#weight'] = $vocabulary->weight
;
307 $form['taxonomy'][$vid]['#required'] = $vocabulary->required
;
313 * Generate a form element for selecting terms from a vocabulary.
314 * Translates all translatable strings.
316 function i18ntaxonomy_vocabulary_form($vid, $value = 0, $help = NULL
, $name = 'taxonomy') {
317 $vocabulary = taxonomy_vocabulary_load($vid);
318 $help = $vocabulary->help ?
tt("taxonomy:vocabulary:$vid:help", $vocabulary->help
) : '';
319 if ($vocabulary->required
) {
323 $blank = '<'.
t('none') .
'>';
326 return _i18ntaxonomy_term_select(check_plain(tt("taxonomy:vocabulary:$vid:name", $vocabulary->name
)), $name, $value, $vid, $help, intval($vocabulary->multiple
), $blank);
329 // Produces translated tree
330 function _i18ntaxonomy_term_select($title, $name, $value, $vocabulary_id, $description, $multiple, $blank, $exclude = array()) {
331 $tree = taxonomy_get_tree($vocabulary_id);
335 $options[0] = $blank;
338 foreach ($tree as
$term) {
339 if (!in_array($term->tid
, $exclude)) {
340 $choice = new
stdClass();
341 $choice->option
= array($term->tid
=> str_repeat('-', $term->depth
) .
tt("taxonomy:term:$term->tid:name", $term->name
));
342 $options[] = $choice;
345 if (!$blank && !$value) {
346 // required but without a predefined value, so set first as predefined
347 $value = $tree[0]->tid
;
351 return array('#type' => 'select',
353 '#default_value' => $value,
354 '#options' => $options,
355 '#description' => $description,
356 '#multiple' => $multiple,
357 '#size' => $multiple ?
min(9, count($options)) : 0,
359 '#theme' => 'taxonomy_term_select',
363 * Returns a list for terms for vocabulary, language
365 function i18ntaxonomy_vocabulary_get_terms($vid, $lang, $status = 'all') {
368 $andsql = ' AND trid > 0';
371 $andsql = ' AND trid = 0';
376 $result = db_query("SELECT * FROM {term_data} WHERE vid=%d AND language='%s' $andsql", $vid, $lang);
378 while ($term = db_fetch_object($result)) {
379 $list[$term->tid
] = $term->name
;
385 * Multilingual Taxonomy
390 * This is the callback for taxonomy translations
393 * admin/content/taxonomy/i18n/term/xx
394 * admin/content/taxonomy/i18n/term/new/xx
395 * admin/content/taxonomy/vid/translation/op/trid
398 function i18ntaxonomy_page_vocabulary($vocabulary) {
399 $op = $_POST['op'] ?
$_POST['op'] : arg(5);
400 $edit = $_POST['edit'];
405 drupal_set_title(t('Edit term translations'));
406 $output = drupal_get_form('i18ntaxonomy_translation_term_form', $vocabulary->vid
, arg(6), $edit);
409 drupal_set_title(t('Submit'));
410 i18ntaxonomy_translation_term_save($edit);
411 $output = i18ntaxonomy_translation_overview($vocabulary->vid
);
414 //print theme('page', node_delete($edit), t('Delete'));
417 $output = i18ntaxonomy_translation_overview($vocabulary->vid
);
423 * Generate a tabular listing of translations for vocabularies.
425 function i18ntaxonomy_translation_overview($vid) {
426 $vocabulary = taxonomy_vocabulary_load($vid);
427 drupal_set_title(check_plain($vocabulary->name
));
429 $languages = i18n_supported_languages();
430 $header = array_merge($languages, array(t('Operations')));
433 // Get terms/translations for this vocab
434 $result = db_query('SELECT * FROM {term_data} t WHERE vid=%d',$vocabulary->vid
);
436 while ($term = db_fetch_object($result)) {
437 if($term->trid
&& $term->language
) {
438 $terms[$term->trid
][$term->language
] = $term;
441 // Reorder data for rows and languages
442 foreach ($terms as
$trid => $terms) {
444 foreach ($languages as
$lang => $name) {
445 if (array_key_exists($lang, $terms)) {
446 $thisrow[] = $terms[$lang]->name
;
452 $thisrow[] = l(t('edit'), "admin/content/taxonomy/$vid/translation/edit/$trid");
455 $output .
= theme('table', $header, $rows);
456 $output .
= l(t('new translation'), "admin/content/taxonomy/$vid/translation/edit/new");
461 * Produces a vocabulary translation form
463 function i18ntaxonomy_translation_term_form($vid, $trid = NULL
, $edit = array()) {
464 $languages = i18n_supported_languages();
465 if ($trid == 'new') {
466 $translations = array();
468 $form['trid'] = array('#type' => 'hidden', '#value' => $trid);
469 $translations = i18ntaxonomy_term_get_translations(array('trid' =>$trid));
471 //var_dump($translations);
472 $vocabulary = taxonomy_vocabulary_load($vid);
474 // List of terms for languages
475 foreach ($languages as
$lang => $langname) {
476 $current = isset($translations[$lang]) ?
$translations[$lang]->tid
: '';
477 $list = translation_vocabulary_get_terms($vid, $lang, 'all');
479 $form[$lang] = array('#type' => 'fieldset', '#tree' => TRUE
);
480 $form[$lang]['tid'] = array(
482 '#title' => $langname,
483 '#default_value' => $current,
486 $form[$lang]['old'] = array('#type' => 'hidden', '#value' =>$current);
488 $form['submit'] = array('#type' => 'submit', '#value' => t('Save'));
489 $form['destination'] = array('#type' => 'hidden', '#value' => 'admin/content/taxonomy/'.
arg(3).
'/translation');
494 * Form callback: Process vocabulary translation form
496 function i18ntaxonomy_translation_term_form_submit($form_id, $form_values) {
497 i18ntaxonomy_translation_save($form_values, $form_values['trid']);
498 drupal_set_message(t('Term translations have been updated'));
502 * Save taxonomy term translations
505 * Array of terms indexed by language
507 * Optional translation set id
509 function i18ntaxonomy_translation_save($terms, $trid = 0) {
510 // Delete old translations for this trid
512 db_query("UPDATE {term_data} SET trid = 0 WHERE trid= %d", $trid);
514 // Now pick up all the tids in an array
515 $translations = array();
516 foreach (i18n_supported_languages() as
$lang => $name) {
517 if (isset($terms[$lang]) && ($term = (array)$terms[$lang]) && $tid = $term['tid']) {
518 $translations[$lang] = $tid;
521 // Now set a translation set with all these terms.
522 if (count($translations)) {
523 $trid = (is_numeric($trid) && $trid) ?
$trid : db_next_id('{term_data}_trid');
524 db_query('UPDATE {term_data} SET trid = %d WHERE tid IN(%s)', $trid, implode(',',$translations));
530 * Get term translations
533 * An array of the from lang => Term
535 function i18ntaxonomy_term_get_translations($params, $getall = TRUE
) {
536 foreach($params as
$field => $value) {
537 $conds[] = "i.$field = '%s'";
540 if(!$getall){ // If not all, a parameter must be tid
541 $conds[] = "t.tid != %d";
542 $values[] = $params['tid'];
544 $conds[] = "t.trid != 0";
545 $sql = 'SELECT t.* FROM {term_data} t INNER JOIN {term_data} i ON t.trid = i.trid WHERE '.
implode(' AND ', $conds);;
546 $result = db_query($sql, $values);
548 while ($data = db_fetch_object($result)) {
549 $items[$data->language
] = $data;
556 * Like nat_get_terms() but without caching
558 function i18ntaxonomy_nat_get_terms($nid) {
561 $result = db_query("SELECT td.* FROM {nat} n INNER JOIN {term_data} td USING (tid) WHERE n.nid = %d", $nid);
562 while ($term = db_fetch_object($result)) {
563 $return[$term->tid
] = $term;
571 * Implementation of hook_nodeapi()
573 * Prepare node for translation
575 function i18ntaxonomy_nodeapi(&$node, $op) {
578 // This runs after taxonomy:nodeapi, so we just localize terms here
579 if ($op == 'view' && array_key_exists('taxonomy', $node)) {
580 $node->taxonomy
= i18ntaxonomy_localize_terms($node->taxonomy
);
583 case
'prepare translation':
584 $source = $node->translation_source
;
585 // Taxonomy translation
586 if (is_array($source->taxonomy
)) {
587 // Set translated taxonomy terms
588 $node->taxonomy
= i18ntaxonomy_translate_terms($source->taxonomy
, $node->language
);
595 * Translate an array of taxonomy terms
597 * Translates all terms with language, just passing over terms without it
599 function i18ntaxonomy_translate_terms($taxonomy, $langcode) {
600 $translation = array();
601 foreach ($taxonomy as
$index => $term) {
602 if ($term->language
&& $term->language
!= $langcode) {
603 $translated_terms = i18ntaxonomy_term_get_translations(array('tid' => $term->tid
));
604 if ($translated_terms && $newterm = $translated_terms[$langcode]) {
605 $translation[$newterm->tid
] = $newterm;
608 // Term has no language. Should be ok
609 $translation[$index] = $term;
615 * Implementation of hook_views_pre_view().
617 * Translate table header for taxonomy fields
618 * //field[i][id] = term_node_1.name, translate table header
619 * and replace handler for that field
621 function i18ntaxonomy_views_pre_view(&$view, &$items) {
623 $translate = variable_get('i18ntaxonomy_vocabularies', array());
624 foreach($view->field as
$index => $data) {
626 if($data['id'] == 'term_node.name') {
627 // That's a full taxonomy box
628 $view->field
[$index]['handler'] = 'i18ntaxonomy_views_handler_field_allterms';
629 } elseif(preg_match("/term_node_(\d+)\.name/", $data['id'], $matches)) {
631 if ($translate[$vid]) {
632 // Set new handler for this field
633 $view->field
[$index]['handler'] = 'i18ntaxonomy_views_handler_field_allterms';
641 * Field handler for taxonomy term fields
643 * Remake of views_handler_field_allterms with term name translation
645 function i18ntaxonomy_views_handler_field_allterms($fieldinfo, $fielddata, $value, $data) {
646 if ($fieldinfo['vocabulary']) {
647 $terms = taxonomy_node_get_terms_by_vocabulary($data->nid
, $fieldinfo['vocabulary']);
650 $terms = taxonomy_node_get_terms($data->nid
);
652 // Translate all these terms
653 _i18ntaxonomy_translate_terms($terms);
655 if ($fielddata['options'] == 'nolink') {
656 foreach ($terms as
$term) {
657 $links[] = check_plain($term->name
);
659 $links = !empty($links) ?
implode(' | ', $links) : '';
662 $node = new
stdClass();
663 $node->taxonomy
= $terms;
664 $links = theme('links', taxonomy_link('taxonomy terms', $node));
669 // Translate an array of term objects
670 function i18ntaxonomy_localize_terms($terms, $fields = array('name')) {
671 $translation = array();
672 $localize = i18ntaxonomy_vocabulary(NULL
, I18N_TAXONOMY_LOCALIZE
);
673 foreach ($terms as
$index => $term) {
674 if (in_array($term->vid
, $localize)) {
675 foreach ($fields as
$property ) {
676 $translation[$index]->$property = tt("taxonomy:term:$term->tid:$property", $term->name
);
679 $translation[$index] = $term;
685 // Get a list of vocabularies and terms
686 function _i18ntaxonomy_vocabulary_terms($vid = NULL
, $fullname = TRUE
) {
688 if (is_numeric($vid)) {
689 $where = "WHERE td.vid = $vid";
690 } elseif(is_array($vid)) {
691 $where = "WHERE td.vid IN(".
implode(',', $vid).
')';
693 $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");
694 while ($obj = db_fetch_object($result)) {
695 $tids[$obj->tid
] = $fullname ?
t($obj->vocabname
).
': '.
t($obj->name
) : t($obj->name
);
702 * Taxonomy vocabulary settings
704 * - If $vid and not $value, returns mode for vid
705 * - If $vid and $value, sets mode for vid
706 * - If !$vid and !$value returns all settings
707 * - If !$vid and $value returns all vids for this mode
715 function i18ntaxonomy_vocabulary($vid = NULL
, $mode = NULL
) {
716 $options = variable_get('i18ntaxonomy_vocabulary', array());
718 $options[$vid] = $mode;
719 variable_set('i18ntaxonomy_vocabulary', $options);
721 return array_key_exists($vid, $options) ?
$options[$vid] : I18N_TAXONOMY_NONE
;
723 return array_keys($options, $mode);