translation.module

Manages content translations.

Translations are managed in sets of posts, which represent the same information in different languages. Only content types for which the administrator has explicitly enabled translations could have translations associated. Translations are managed in sets with exactly one source post per set. The source post is used to translate to different languages, so if the source post is significantly updated, the editor can decide to mark all translations outdated.

The node table stores the values used by this module:

  • tnid: Integer for the translation set ID, which equals the node ID of the source post.
  • translate: Integer flag, either indicating that the translation is up to date (0) or needs to be updated (1).

File

drupal/core/modules/translation/translation.module
View source
<?php

/**
 * @file
 * Manages content translations.
 *
 * Translations are managed in sets of posts, which represent the same
 * information in different languages. Only content types for which the
 * administrator has explicitly enabled translations could have translations
 * associated. Translations are managed in sets with exactly one source post
 * per set. The source post is used to translate to different languages, so if
 * the source post is significantly updated, the editor can decide to mark all
 * translations outdated.
 *
 * The node table stores the values used by this module:
 * - tnid: Integer for the translation set ID, which equals the node ID of the
 *   source post.
 * - translate: Integer flag, either indicating that the translation is up to
 *   date (0) or needs to be updated (1).
 */
use Drupal\node\Plugin\Core\Entity\Node;

/**
 * Implements hook_help().
 */
function translation_help($path, $arg) {
  switch ($path) {
    case 'admin/help#translation':
      $output = '';
      $output .= '<h3>' . t('About') . '</h3>';
      $output .= '<p>' . t('The Content Translation module allows content to be translated into different languages. Working with the <a href="@locale">Locale module</a> (which manages enabled languages and provides translation for the site interface), the Content Translation module is key to creating and maintaining translated site content. For more information, see the online handbook entry for <a href="@translation">Content Translation module</a>.', array(
        '@locale' => url('admin/help/locale'),
        '@translation' => 'http://drupal.org/documentation/modules/translation/',
      )) . '</p>';
      $output .= '<h3>' . t('Uses') . '</h3>';
      $output .= '<dl>';
      $output .= '<dt>' . t('Configuring content types for translation') . '</dt>';
      $output .= '<dd>' . t('To configure a particular content type for translation, visit the <a href="@content-types">Content types</a> page, and click the <em>edit</em> link for the content type. In the <em>Publishing options</em> section, select <em>Enabled, with translation</em> under <em>Multilingual support</em>.', array(
        '@content-types' => url('admin/structure/types'),
      )) . '</dd>';
      $output .= '<dt>' . t('Assigning a language to content') . '</dt>';
      $output .= '<dd>' . t('Use the <em>Language</em> drop down to select the appropriate language when creating or editing content.') . '</dd>';
      $output .= '<dt>' . t('Translating content') . '</dt>';
      $output .= '<dd>' . t('Users with the <em>translate all content</em> or <em>translate own content</em> permission can translate content, if the content type has been configured to allow translations. To translate content, select the <em>Translations</em> tab when viewing the content, select the language for which you wish to provide content, and then enter the content.') . '</dd>';
      $output .= '<dt>' . t('Maintaining translations') . '</dt>';
      $output .= '<dd>' . t('If editing content in one language requires that translated versions also be updated to reflect the change, use the <em>Flag translations as outdated</em> check box to mark the translations as outdated and in need of revision. Individual translations may also be marked for revision by selecting the <em>This translation needs to be updated</em> check box on the translation editing form.') . '</dd>';
      $output .= '</dl>';
      return $output;
    case 'node/%/translate':
      $output = '<p>' . t('Translations of a piece of content are managed with translation sets. Each translation set has one source post and any number of translations in any of the <a href="!languages">enabled languages</a>. All translations are tracked to be up to date or outdated based on whether the source post was modified significantly.', array(
        '!languages' => url('admin/config/regional/language'),
      )) . '</p>';
      return $output;
  }
}

/**
 * Implements hook_menu().
 */
function translation_menu() {
  $items = array();
  $items['node/%node/translate'] = array(
    'title' => 'Translations',
    'page callback' => 'translation_node_overview',
    'page arguments' => array(
      1,
    ),
    'access callback' => '_translation_tab_access',
    'access arguments' => array(
      1,
    ),
    'type' => MENU_LOCAL_TASK,
    'context' => MENU_CONTEXT_PAGE | MENU_CONTEXT_INLINE,
    'weight' => 2,
    'file' => 'translation.pages.inc',
  );
  return $items;
}

/**
 * Access callback: Checks that the user has permission to 'translate
 * all content' or to 'translate own content' and has created the node
 * being translated.
 *
 * Only displays the translation tab for nodes that are not language-neutral
 * of types that have translation enabled.
 *
 * @param $node
 *   A node entity.
 *
 * @return
 *   TRUE if the translation tab should be displayed, FALSE otherwise.
 *
 * @see translation_menu()
 */
function _translation_tab_access($node) {
  if ($node->langcode != LANGUAGE_NOT_SPECIFIED && translation_supported_type($node->type) && node_access('view', $node)) {
    return translation_user_can_translate_node($node);
  }
  return FALSE;
}

/**
 * Implements hook_admin_paths().
 */
function translation_admin_paths() {
  if (variable_get('node_admin_theme')) {
    $paths = array(
      'node/*/translate' => TRUE,
    );
    return $paths;
  }
}

/**
 * Implements hook_permission().
 */
function translation_permission() {
  return array(
    'translate all content' => array(
      'title' => t('Translate all content'),
    ),
    'translate own content' => array(
      'title' => t('Translate own content'),
    ),
  );
}

/**
 * Implements hook_node_access().
 */
function translation_node_access($node, $op, $account, $langcode) {
  $request_has_translation_arg = isset($_GET['translation']) && isset($_GET['target']) && is_numeric($_GET['translation']);
  if ($op == 'create' && $request_has_translation_arg) {
    $source_node = node_load($_GET['translation']);
    if (empty($source_node) || !translation_user_can_translate_node($source_node, $account)) {
      return NODE_ACCESS_DENY;
    }
  }
  return NODE_ACCESS_IGNORE;
}

/**
 * Check if the user has permissions to translate a node.
 *
 * @param $node
 *   Node being checked.
 * @param $account
 *   User object to check translation permissions.
 *
 * @return
 *   TRUE if the user can translate a node, FALSE otherwise.
 */
function translation_user_can_translate_node($node, $account = NULL) {

  // If no user object is supplied, the access check is for the current user.
  if (empty($account)) {
    $account = $GLOBALS['user'];
  }
  return node_access('view', $node, $account) && (user_access('translate all content', $account) || $node->uid == $account->uid && user_access('translate own content', $account));
}

/**
 * Implements hook_form_FORM_ID_alter() for node_type_form().
 */
function translation_form_node_type_form_alter(&$form, &$form_state) {

  // Hide form element if default language is a constant.
  // TODO: When form #states allows OR values change this to use form #states.
  $form['#attached']['library'][] = array(
    'translation',
    'drupal.translation',
  );

  // Add translation option to content type form.
  $form['language']['node_type_language_translation_enabled'] = array(
    '#type' => 'checkbox',
    '#title' => t('Enable translation'),
    '#default_value' => variable_get('node_type_language_translation_enabled_' . $form['#node_type']->type, FALSE),
    '#element_validate' => array(
      'translation_node_type_language_translation_enabled_validate',
    ),
    '#prefix' => "<label class='form-item-node-type-language-translation-enabled'>" . t('Translation') . "</label>",
  );
}

/**
 * Checks if translation can be enabled.
 *
 * If language is set to one of the special languages
 * and language selector is not hidden, translation cannot be enabled.
 */
function translation_node_type_language_translation_enabled_validate($element, &$form_state, $form) {
  if (language_is_locked($form_state['values']['language_configuration']['langcode']) && $form_state['values']['language_configuration']['language_hidden'] && $form_state['values']['node_type_language_translation_enabled']) {
    foreach (language_list(LANGUAGE_LOCKED) as $language) {
      $locked_languages[] = $language->name;
    }
    form_set_error('node_type_language_translation_enabled', t('Translation is not supported if language is always one of: @locked_languages', array(
      '@locked_languages' => implode(", ", $locked_languages),
    )));
  }
}

/**
 * Implements hook_form_BASE_FORM_ID_alter() for node_form().
 *
 * Alters language fields on node edit forms when a translation is about to be
 * created.
 *
 * @see node_form()
 */
function translation_form_node_form_alter(&$form, &$form_state) {
  $node = $form_state['controller']
    ->getEntity($form_state);
  if (translation_supported_type($node->type)) {
    if (!empty($node->translation_source)) {

      // We are creating a translation. Add values and lock language field.
      $form['translation_source'] = array(
        '#type' => 'value',
        '#value' => $node->translation_source,
      );
      $form['langcode']['#disabled'] = TRUE;
    }
    elseif (!empty($node->nid) && !empty($node->tnid)) {

      // Disable languages for existing translations, so it is not possible
      // to switch this node to some language which is already in the
      // translation set. Also remove the language neutral option.
      unset($form['langcode']['#options'][LANGUAGE_NOT_SPECIFIED]);
      foreach (translation_node_get_translations($node->tnid) as $langcode => $translation) {
        if ($translation->nid != $node->nid) {
          unset($form['langcode']['#options'][$langcode]);
        }
      }

      // Add translation values and workflow options.
      $form['tnid'] = array(
        '#type' => 'value',
        '#value' => $node->tnid,
      );
      $form['translation'] = array(
        '#type' => 'details',
        '#title' => t('Translation settings'),
        '#access' => translation_user_can_translate_node($node),
        '#collapsible' => TRUE,
        '#collapsed' => !$node->translate,
        '#tree' => TRUE,
        '#weight' => 30,
      );
      if ($node->tnid == $node->nid) {

        // This is the source node of the translation.
        $form['translation']['retranslate'] = array(
          '#type' => 'checkbox',
          '#title' => t('Flag translations as outdated'),
          '#default_value' => 0,
          '#description' => t('If you made a significant change, which means translations should be updated, you can flag all translations of this post as outdated. This will not change any other property of those posts, like whether they are published or not.'),
        );
        $form['translation']['status'] = array(
          '#type' => 'value',
          '#value' => 0,
        );
      }
      else {
        $form['translation']['status'] = array(
          '#type' => 'checkbox',
          '#title' => t('This translation needs to be updated'),
          '#default_value' => $node->translate,
          '#description' => t('When this option is checked, this translation needs to be updated because the source post has changed. Uncheck when the translation is up to date again.'),
        );
      }
    }
  }
}

/**
 * Implements hook_node_view().
 *
 * Displays translation links with language names if this node is part of a
 * translation set. If no language provider is enabled, "fall back" to simple
 * links built through the result of translation_node_get_translations().
 */
function translation_node_view(Node $node, $view_mode) {

  // If the site has no translations or is not multilingual we have no content
  // translation links to display.
  if (isset($node->tnid) && language_multilingual() && ($translations = translation_node_get_translations($node->tnid))) {
    $languages = language_list(LANGUAGE_ALL);

    // There might be a language provider enabled defining custom language
    // switch links which need to be taken into account while generating the
    // content translation links. As custom language switch links are available
    // only for configurable language types and interface language is the only
    // configurable language type in core, we use it as default. Contributed
    // modules can change this behavior by setting the system variable below.
    $type = config('translation.settings')
      ->get('language_type');
    $custom_links = language_negotiation_get_switch_links($type, "node/{$node->nid}");
    $links = array();
    foreach ($translations as $langcode => $translation) {

      // Do not show links to the same node or to unpublished translations.
      if ($translation->status && isset($languages[$langcode]) && $langcode != $node->langcode) {
        $key = "translation_{$langcode}";
        if (isset($custom_links->links[$langcode])) {
          $links[$key] = $custom_links->links[$langcode];
        }
        else {
          $links[$key] = array(
            'href' => "node/{$translation->nid}",
            'title' => language_name($langcode),
            'language' => $languages[$langcode],
          );
        }

        // Custom switch links are more generic than content translation links,
        // hence we override existing attributes with the ones below.
        $links[$key] += array(
          'attributes' => array(),
        );
        $attributes = array(
          'title' => $translation->title,
          'class' => array(
            'translation-link',
          ),
        );
        $links[$key]['attributes'] = $attributes + $links[$key]['attributes'];
      }
    }
    $node->content['links']['translation'] = array(
      '#theme' => 'links__node__translation',
      '#links' => $links,
      '#attributes' => array(
        'class' => array(
          'links',
          'inline',
        ),
      ),
    );
  }
}

/**
 * Implements hook_node_prepare().
 */
function translation_node_prepare(Node $node) {

  // Only act if we are dealing with a content type supporting translations.
  if (translation_supported_type($node->type) && empty($node->nid) && isset($_GET['translation']) && isset($_GET['target']) && is_numeric($_GET['translation'])) {
    $source_node = node_load($_GET['translation']);
    $language_list = language_list();
    $langcode = $_GET['target'];
    if (!isset($language_list[$langcode]) || $source_node->langcode == $langcode) {

      // If not supported language, or same language as source node, break.
      return;
    }

    // Ensure we don't have an existing translation in this language.
    if (!empty($source_node->tnid)) {
      $translations = translation_node_get_translations($source_node->tnid);
      if (isset($translations[$langcode])) {
        drupal_set_message(t('A translation of %title in %language already exists, a new %type will be created instead of a translation.', array(
          '%title' => $source_node
            ->label(),
          '%language' => $language_list[$langcode]->name,
          '%type' => $node->type,
        )), 'error');
        return;
      }
    }

    // Populate fields based on source node.
    $node->langcode = $langcode;
    $node->translation_source = $source_node;
    $node->title = $source_node->title;

    // Add field translations and let other modules module add custom translated
    // fields.
    field_attach_prepare_translation('node', $node, $node->langcode, $source_node, $source_node->langcode);
  }
}

/**
 * Implements hook_node_insert().
 */
function translation_node_insert(Node $node) {

  // Only act if we are dealing with a content type supporting translations.
  if (translation_supported_type($node->type)) {
    if (!empty($node->translation_source)) {
      if ($node->translation_source->tnid) {

        // Add node to existing translation set.
        $tnid = $node->translation_source->tnid;
      }
      else {

        // Create new translation set, using nid from the source node.
        $tnid = $node->translation_source->nid;
        db_update('node')
          ->fields(array(
          'tnid' => $tnid,
          'translate' => 0,
        ))
          ->condition('nid', $node->translation_source->nid)
          ->execute();
      }
      db_update('node')
        ->fields(array(
        'tnid' => $tnid,
        'translate' => 0,
      ))
        ->condition('nid', $node->nid)
        ->execute();

      // Save tnid to avoid loss in case of resave.
      $node->tnid = $tnid;
    }
  }
}

/**
 * Implements hook_node_update().
 */
function translation_node_update(Node $node) {

  // Only act if we are dealing with a content type supporting translations.
  if (translation_supported_type($node->type)) {
    if (isset($node->translation) && $node->translation && !empty($node->langcode) && $node->tnid) {

      // Update translation information.
      db_update('node')
        ->fields(array(
        'tnid' => $node->tnid,
        'translate' => $node->translation['status'],
      ))
        ->condition('nid', $node->nid)
        ->execute();
      if (!empty($node->translation['retranslate'])) {

        // This is the source node, asking to mark all translations outdated.
        db_update('node')
          ->fields(array(
          'translate' => 1,
        ))
          ->condition('nid', $node->nid, '<>')
          ->condition('tnid', $node->tnid)
          ->execute();
      }
    }
  }
}

/**
 * Implements hook_node_validate().
 *
 * Ensures that duplicate translations can't be created for the same source.
 */
function translation_node_validate(Node $node, $form, &$form_state) {

  // Only act on translatable nodes with a tnid or translation_source.
  $form_node = $form_state['controller']
    ->getEntity($form_state);
  if (translation_supported_type($node->type) && (!empty($node->tnid) || !empty($form_node->translation_source->nid))) {
    $tnid = !empty($node->tnid) ? $node->tnid : $form_node->translation_source->nid;
    $translations = translation_node_get_translations($tnid);
    if (isset($translations[$node->langcode]) && $translations[$node->langcode]->nid != $node->nid) {
      form_set_error('langcode', t('There is already a translation in this language.'));
    }
  }
}

/**
 * Implements hook_node_predelete().
 */
function translation_node_predelete(Node $node) {

  // Only act if we are dealing with a content type supporting translations.
  if (translation_supported_type($node->type)) {
    translation_remove_from_set($node);
  }
}

/**
 * Removes a node from its translation set and updates accordingly.
 *
 * @param $node
 *   A node entity.
 */
function translation_remove_from_set($node) {
  if (isset($node->tnid)) {
    $query = db_update('node')
      ->fields(array(
      'tnid' => 0,
      'translate' => 0,
    ));
    if (db_query('SELECT COUNT(*) FROM {node} WHERE tnid = :tnid', array(
      ':tnid' => $node->tnid,
    ))
      ->fetchField() == 1) {

      // There is only one node left in the set: remove the set altogether.
      $query
        ->condition('tnid', $node->tnid)
        ->execute();
    }
    else {
      $query
        ->condition('nid', $node->nid)
        ->execute();

      // If the node being removed was the source of the translation set,
      // we pick a new source - preferably one that is up to date.
      if ($node->tnid == $node->nid) {
        $new_tnid = db_query('SELECT nid FROM {node} WHERE tnid = :tnid ORDER BY translate ASC, nid ASC', array(
          ':tnid' => $node->tnid,
        ))
          ->fetchField();
        db_update('node')
          ->fields(array(
          'tnid' => $new_tnid,
        ))
          ->condition('tnid', $node->tnid)
          ->execute();
      }
    }
  }
}

/**
 * Gets all nodes in a given translation set.
 *
 * @param $tnid
 *   The translation source nid of the translation set, the identifier of the
 *   node used to derive all translations in the set.
 *
 * @return
 *   Array of partial node objects (nid, title, langcode) representing all
 *   nodes in the translation set, in effect all translations of node $tnid,
 *   including node $tnid itself. Because these are partial nodes, you need to
 *   node_load() the full node, if you need more properties. The array is
 *   indexed by language code.
 */
function translation_node_get_translations($tnid) {
  if (is_numeric($tnid) && $tnid) {
    $translations =& drupal_static(__FUNCTION__, array());
    if (!isset($translations[$tnid])) {
      $translations[$tnid] = array();
      $result = db_select('node', 'n')
        ->fields('n', array(
        'nid',
        'type',
        'uid',
        'status',
        'title',
        'langcode',
      ))
        ->condition('n.tnid', $tnid)
        ->addTag('node_access')
        ->execute();
      foreach ($result as $node) {
        $translations[$tnid][$node->langcode] = $node;
      }
    }
    return $translations[$tnid];
  }
}

/**
 * Returns whether the given content type has support for translations.
 *
 * @return
 *   TRUE if translation is supported, and FALSE if not.
 */
function translation_supported_type($type) {
  return variable_get('node_type_language_translation_enabled_' . $type, FALSE);
}

/**
 * Returns the paths of all translations of a node, based on its Drupal path.
 *
 * @param $path
 *   A Drupal path, for example node/432.
 *
 * @return
 *   An array of paths of translations of the node accessible to the current
 *   user, keyed with language codes.
 */
function translation_path_get_translations($path) {
  $paths = array();

  // Check for a node related path, and for its translations.
  if (preg_match("!^node/(\\d+)(/.+|)\$!", $path, $matches) && ($node = node_load((int) $matches[1])) && !empty($node->tnid)) {
    foreach (translation_node_get_translations($node->tnid) as $language => $translation_node) {
      $paths[$language] = 'node/' . $translation_node->nid . $matches[2];
    }
  }
  return $paths;
}

/**
 * Implements hook_language_switch_links_alter().
 *
 * Replaces links with pointers to translated versions of the content.
 */
function translation_language_switch_links_alter(array &$links, $type, $path) {
  $language_type = config('translation.settings')
    ->get('language_type');
  if ($type == $language_type && preg_match("!^node/(\\d+)(/.+|)!", $path, $matches)) {
    $node = node_load((int) $matches[1]);
    if (empty($node->tnid)) {

      // If the node cannot be found nothing needs to be done. If it does not
      // have translations it might be a language neutral node, in which case we
      // must leave the language switch links unaltered. This is true also for
      // nodes not having translation support enabled.
      if (empty($node) || $node->langcode == LANGUAGE_NOT_SPECIFIED || !translation_supported_type($node->type)) {
        return;
      }
      $translations = array(
        $node->langcode => $node,
      );
    }
    else {
      $translations = translation_node_get_translations($node->tnid);
    }
    foreach ($links as $langcode => $link) {
      if (isset($translations[$langcode]) && $translations[$langcode]->status) {

        // Translation in a different node.
        $links[$langcode]['href'] = 'node/' . $translations[$langcode]->nid . $matches[2];
      }
      else {

        // No translation in this language, or no permission to view.
        unset($links[$langcode]['href']);
        $links[$langcode]['attributes']['class'][] = 'locale-untranslated';
      }
    }
  }
}

/**
 * Implements hook_library_info().
 */
function translation_library_info() {
  $libraries['drupal.translation'] = array(
    'title' => 'Translation',
    'version' => VERSION,
    'js' => array(
      drupal_get_path('module', 'translation') . '/translation.js' => array(),
    ),
    'dependencies' => array(
      array(
        'system',
        'jquery',
      ),
      array(
        'system',
        'drupal',
      ),
    ),
  );
  return $libraries;
}

Functions

Namesort descending Description
translation_admin_paths Implements hook_admin_paths().
translation_form_node_form_alter Implements hook_form_BASE_FORM_ID_alter() for node_form().
translation_form_node_type_form_alter Implements hook_form_FORM_ID_alter() for node_type_form().
translation_help Implements hook_help().
translation_language_switch_links_alter Implements hook_language_switch_links_alter().
translation_library_info Implements hook_library_info().
translation_menu Implements hook_menu().
translation_node_access Implements hook_node_access().
translation_node_get_translations Gets all nodes in a given translation set.
translation_node_insert Implements hook_node_insert().
translation_node_predelete Implements hook_node_predelete().
translation_node_prepare Implements hook_node_prepare().
translation_node_type_language_translation_enabled_validate Checks if translation can be enabled.
translation_node_update Implements hook_node_update().
translation_node_validate Implements hook_node_validate().
translation_node_view Implements hook_node_view().
translation_path_get_translations Returns the paths of all translations of a node, based on its Drupal path.
translation_permission Implements hook_permission().
translation_remove_from_set Removes a node from its translation set and updates accordingly.
translation_supported_type Returns whether the given content type has support for translations.
translation_user_can_translate_node Check if the user has permissions to translate a node.
_translation_tab_access Access callback: Checks that the user has permission to 'translate all content' or to 'translate own content' and has created the node being translated.