Initial commit

This commit is contained in:
Mauricio Dinarte 2024-12-04 10:11:27 -06:00
commit c5e731d8ae
2773 changed files with 600767 additions and 0 deletions

View file

@ -0,0 +1,11 @@
name = "Content Translation Test"
description = "Support module for the content translation tests."
core = 7.x
package = Testing
version = VERSION
hidden = TRUE
; Information added by Drupal.org packaging script on 2024-03-06
version = "7.100"
project = "drupal"
datestamp = "1709734591"

View file

@ -0,0 +1,13 @@
<?php
/**
* @file
* Mock module for content translation tests.
*/
/**
* Implements hook_node_insert().
*/
function translation_test_node_insert($node) {
drupal_write_record('node', $node, 'nid');
}

View file

@ -0,0 +1,12 @@
name = Content translation
description = Allows content to be translated into different languages.
dependencies[] = locale
package = Core
version = VERSION
core = 7.x
files[] = translation.test
; Information added by Drupal.org packaging script on 2024-03-06
version = "7.100"
project = "drupal"
datestamp = "1709734591"

View file

@ -0,0 +1,576 @@
<?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).
*/
/**
* Identifies a content type which has translation support enabled.
*/
define('TRANSLATION_ENABLED', 2);
/**
* 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 content</em> permission can translate content, if the content type has been configured to allow translations. To translate content, select the <em>Translation</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' => 'Translate',
'page callback' => 'translation_node_overview',
'page arguments' => array(1),
'access callback' => '_translation_tab_access',
'access arguments' => array(1),
'type' => MENU_LOCAL_TASK,
'weight' => 2,
'file' => 'translation.pages.inc',
);
return $items;
}
/**
* Access callback: Checks that the user has permission to 'translate content'.
*
* Only displays the translation tab for nodes that are not language-neutral
* of types that have translation enabled.
*
* @param $node
* A node object.
*
* @return
* TRUE if the translation tab should be displayed, FALSE otherwise.
*
* @see translation_menu()
*/
function _translation_tab_access($node) {
if (entity_language('node', $node) != LANGUAGE_NONE && translation_supported_type($node->type) && node_access('view', $node)) {
return user_access('translate content');
}
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 content' => array(
'title' => t('Translate content'),
),
);
}
/**
* Implements hook_form_FORM_ID_alter() for node_type_form().
*/
function translation_form_node_type_form_alter(&$form, &$form_state) {
// Add translation option to content type form.
$form['workflow']['language_content_type']['#options'][TRANSLATION_ENABLED] = t('Enabled, with translation');
// Description based on text from locale.module.
$form['workflow']['language_content_type']['#description'] = t('Enable multilingual support for this content type. If enabled, a language selection field will be added to the editing form, allowing you to select from one of the <a href="!languages">enabled languages</a>. You can also turn on translation for this content type, which lets you have content translated to any of the installed languages. If disabled, new posts are saved with the default language. Existing content will not be affected by changing this option.', array('!languages' => url('admin/config/regional/language')));
}
/**
* 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) {
if (translation_supported_type($form['#node']->type)) {
$node = $form['#node'];
$languages = language_list('enabled');
$disabled_languages = isset($languages[0]) ? $languages[0] : FALSE;
$translator_widget = $disabled_languages && user_access('translate content');
$groups = array(t('Disabled'), t('Enabled'));
// Allow translators to enter content in disabled languages. Translators
// might need to distinguish between enabled and disabled languages, hence
// we divide them in two option groups.
if ($translator_widget) {
$options = array($groups[1] => array(LANGUAGE_NONE => t('Language neutral')));
$language_list = locale_language_list('name', TRUE);
foreach (array(1, 0) as $status) {
$group = $groups[$status];
foreach ($languages[$status] as $langcode => $language) {
$options[$group][$langcode] = $language_list[$langcode];
}
}
$form['language']['#options'] = $options;
}
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['language']['#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['language']['#options'][LANGUAGE_NONE]);
foreach (translation_node_get_translations($node->tnid) as $langcode => $translation) {
if ($translation->nid != $node->nid) {
if ($translator_widget) {
$group = $groups[(int)!isset($disabled_languages[$langcode])];
unset($form['language']['#options'][$group][$langcode]);
}
else {
unset($form['language']['#options'][$langcode]);
}
}
}
// Add translation values and workflow options.
$form['tnid'] = array('#type' => 'value', '#value' => $node->tnid);
$form['translation'] = array(
'#type' => 'fieldset',
'#title' => t('Translation settings'),
'#access' => user_access('translate content'),
'#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, $view_mode) {
// If the site has no translations or is not multilingual we have no content
// translation links to display.
if (isset($node->tnid) && drupal_multilingual() && $translations = translation_node_get_translations($node->tnid)) {
$languages = language_list('enabled');
$languages = $languages[1];
// 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 = variable_get('translation_language_type', LANGUAGE_TYPE_INTERFACE);
$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, to unpublished translations or to
// translations in disabled languages.
if ($translation->status && isset($languages[$langcode]) && $langcode != entity_language('node', $node)) {
$language = $languages[$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->native,
'language' => $language,
);
}
// 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) {
// Only act if we are dealing with a content type supporting translations.
if (translation_supported_type($node->type) &&
// And it's a new node.
empty($node->nid) &&
// And the user has permission to translate content.
user_access('translate content') &&
// And the $_GET variables are set properly.
isset($_GET['translation']) &&
isset($_GET['target']) &&
is_numeric($_GET['translation'])) {
$source_node = node_load($_GET['translation']);
if (empty($source_node) || !node_access('view', $source_node)) {
// Source node not found or no access to view. We should not check
// for edit access, since the translator might not have permissions
// to edit the source node but should still be able to translate.
return;
}
$language_list = language_list();
$langcode = $_GET['target'];
if (!isset($language_list[$langcode]) || ($source_node->language == $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->title, '%language' => $language_list[$langcode]->name, '%type' => $node->type)), 'error');
return;
}
}
// Populate fields based on source node.
$node->language = $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, $langcode, $source_node, $source_node->language);
}
}
/**
* Implements hook_node_insert().
*/
function translation_node_insert($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', $tnid)
->execute();
// Flush the (untranslated) source node from the load cache.
entity_get_controller('node')->resetCache(array($tnid));
}
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) {
// Only act if we are dealing with a content type supporting translations.
if (translation_supported_type($node->type)) {
$langcode = entity_language('node', $node);
if (isset($node->translation) && $node->translation && !empty($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.
$translations = db_select('node', 'n')
->fields('n', array('nid'))
->condition('nid', $node->nid, '<>')
->condition('tnid', $node->tnid)
->execute()
->fetchCol();
db_update('node')
->fields(array('translate' => 1))
->condition('nid', $translations, 'IN')
->execute();
// Flush the modified translation nodes from the load cache.
entity_get_controller('node')->resetCache($translations);
}
}
}
}
/**
* Implements hook_node_validate().
*
* Ensures that duplicate translations can't be created for the same source.
*/
function translation_node_validate($node, $form) {
// Only act on translatable nodes with a tnid or translation_source.
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);
$langcode = entity_language('node', $node);
if (isset($translations[$langcode]) && $translations[$langcode]->nid != $node->nid ) {
form_set_error('language', t('There is already a translation in this language.'));
}
}
}
/**
* Implements hook_node_delete().
*/
function translation_node_delete($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 object.
*/
function translation_remove_from_set($node) {
if (isset($node->tnid) && $node->tnid) {
$query = db_update('node')
->fields(array(
'tnid' => 0,
'translate' => 0,
));
// Determine which nodes to apply the update to.
$set_nids = db_query('SELECT nid FROM {node} WHERE tnid = :tnid', array(':tnid' => $node->tnid))->fetchCol();
if (count($set_nids) == 1) {
// There is only one node left in the set: remove the set altogether.
$query
->condition('tnid', $node->tnid)
->execute();
$flush_set = TRUE;
}
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();
$flush_set = TRUE;
}
}
// Flush the modified nodes from the load cache.
$nids = !empty($flush_set) ? $set_nids : array($node->nid);
entity_get_controller('node')->resetCache($nids);
}
}
/**
* 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, language) 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', 'language'))
->condition('n.tnid', $tnid)
->addTag('node_access')
->execute();
foreach ($result as $node) {
$langcode = entity_language('node', $node);
$translations[$tnid][$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('language_content_type_' . $type, 0) == TRANSLATION_ENABLED;
}
/**
* 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 = variable_get('translation_language_type', LANGUAGE_TYPE_INTERFACE);
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) || entity_language('node', $node) == LANGUAGE_NONE || !translation_supported_type($node->type)) {
return;
}
$langcode = entity_language('node', $node);
$translations = array($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';
}
}
}
}

View file

@ -0,0 +1,88 @@
<?php
/**
* @file
* User page callbacks for the Translation module.
*/
/**
* Page callback: Displays a list of a node's translations.
*
* @param $node
* A node object.
*
* @return
* A render array for a page containing a list of content.
*
* @see translation_menu()
*/
function translation_node_overview($node) {
include_once DRUPAL_ROOT . '/includes/language.inc';
if ($node->tnid) {
// Already part of a set, grab that set.
$tnid = $node->tnid;
$translations = translation_node_get_translations($node->tnid);
}
else {
// We have no translation source nid, this could be a new set, emulate that.
$tnid = $node->nid;
$translations = array(entity_language('node', $node) => $node);
}
$type = variable_get('translation_language_type', LANGUAGE_TYPE_INTERFACE);
$header = array(t('Language'), t('Title'), t('Status'), t('Operations'));
foreach (language_list() as $langcode => $language) {
$options = array();
$language_name = $language->name;
if (isset($translations[$langcode])) {
// Existing translation in the translation set: display status.
// We load the full node to check whether the user can edit it.
$translation_node = node_load($translations[$langcode]->nid);
$path = 'node/' . $translation_node->nid;
$links = language_negotiation_get_switch_links($type, $path);
$title = empty($links->links[$langcode]['href']) ? l($translation_node->title, $path) : l($translation_node->title, $links->links[$langcode]['href'], $links->links[$langcode]);
if (node_access('update', $translation_node)) {
$text = t('edit');
$path = 'node/' . $translation_node->nid . '/edit';
$links = language_negotiation_get_switch_links($type, $path);
$options[] = empty($links->links[$langcode]['href']) ? l($text, $path) : l($text, $links->links[$langcode]['href'], $links->links[$langcode]);
}
if (node_access('delete', $translation_node)) {
$text = t('delete');
$path = 'node/' . $translation_node->nid . '/delete';
$links = language_negotiation_get_switch_links($type, $path);
$options[] = empty($links->links[$langcode]['href']) ? l($text, $path) : l($text, $links->links[$langcode]['href'], $links->links[$langcode]);
}
$status = $translation_node->status ? t('Published') : t('Not published');
$status .= $translation_node->translate ? ' - <span class="marker">' . t('outdated') . '</span>' : '';
if ($translation_node->nid == $tnid) {
$language_name = t('<strong>@language_name</strong> (source)', array('@language_name' => $language_name));
}
}
else {
// No such translation in the set yet: help user to create it.
$title = t('n/a');
if (node_access('create', $node)) {
$text = t('add translation');
$path = 'node/add/' . str_replace('_', '-', $node->type);
$links = language_negotiation_get_switch_links($type, $path);
$query = array('query' => array('translation' => $node->nid, 'target' => $langcode));
$options[] = empty($links->links[$langcode]['href']) ? l($text, $path, $query) : l($text, $links->links[$langcode]['href'], array_merge_recursive($links->links[$langcode], $query));
}
$status = t('Not translated');
}
$rows[] = array($language_name, $title, $status, implode(" | ", $options));
}
drupal_set_title(t('Translations of %title', array('%title' => $node->title)), PASS_THROUGH);
$build['translation_node_overview'] = array(
'#theme' => 'table',
'#header' => $header,
'#rows' => $rows,
);
return $build;
}

View file

@ -0,0 +1,494 @@
<?php
/**
* @file
* Tests for the Translation module.
*/
/**
* Functional tests for the Translation module.
*/
class TranslationTestCase extends DrupalWebTestCase {
protected $book;
protected $admin_user;
protected $translator;
public static function getInfo() {
return array(
'name' => 'Translation functionality',
'description' => 'Create a basic page with translation, modify the page outdating translation, and update translation.',
'group' => 'Translation'
);
}
function setUp() {
parent::setUp('locale', 'translation', 'translation_test');
// Setup users.
$this->admin_user = $this->drupalCreateUser(array('bypass node access', 'administer nodes', 'administer languages', 'administer content types', 'administer blocks', 'access administration pages', 'translate content'));
$this->translator = $this->drupalCreateUser(array('create page content', 'edit own page content', 'translate content'));
$this->drupalLogin($this->admin_user);
// Add languages.
$this->addLanguage('en');
$this->addLanguage('es');
$this->addLanguage('it');
// Disable Italian to test the translation behavior with disabled languages.
$edit = array('enabled[it]' => FALSE);
$this->drupalPost('admin/config/regional/language', $edit, t('Save configuration'));
// Set "Basic page" content type to use multilingual support with
// translation.
$this->drupalGet('admin/structure/types/manage/page');
$edit = array();
$edit['language_content_type'] = 2;
$this->drupalPost('admin/structure/types/manage/page', $edit, t('Save content type'));
$this->assertRaw(t('The content type %type has been updated.', array('%type' => 'Basic page')), 'Basic page content type has been updated.');
// Enable the language switcher block.
$language_type = LANGUAGE_TYPE_INTERFACE;
$edit = array("blocks[locale_$language_type][region]" => 'sidebar_first');
$this->drupalPost('admin/structure/block', $edit, t('Save blocks'));
// Enable URL language detection and selection to make the language switcher
// block appear.
$edit = array('language[enabled][locale-url]' => TRUE);
$this->drupalPost('admin/config/regional/language/configure', $edit, t('Save settings'));
$this->assertRaw(t('Language negotiation configuration saved.'), 'URL language detection enabled.');
$this->resetCaches();
$this->drupalLogin($this->translator);
}
/**
* Creates, modifies, and updates a basic page with a translation.
*/
function testContentTranslation() {
// Create Basic page in English.
$node_title = $this->randomName();
$node_body = $this->randomName();
$node = $this->createPage($node_title, $node_body, 'en');
// Unpublish the original node to check that this has no impact on the
// translation overview page, publish it again afterwards.
$this->drupalLogin($this->admin_user);
$this->drupalPost('node/' . $node->nid . '/edit', array('status' => FALSE), t('Save'));
$this->drupalGet('node/' . $node->nid . '/translate');
$this->drupalPost('node/' . $node->nid . '/edit', array('status' => NODE_PUBLISHED), t('Save'));
$this->drupalLogin($this->translator);
// Check that the "add translation" link uses a localized path.
$languages = language_list();
$this->drupalGet('node/' . $node->nid . '/translate');
$this->assertLinkByHref($languages['es']->prefix . '/node/add/' . str_replace('_', '-', $node->type), 0, format_string('The "add translation" link for %language points to the localized path of the target language.', array('%language' => $languages['es']->name)));
// Submit translation in Spanish.
$node_translation_title = $this->randomName();
$node_translation_body = $this->randomName();
$node_translation = $this->createTranslation($node, $node_translation_title, $node_translation_body, 'es');
// Check that the "edit translation" and "view node" links use localized
// paths.
$this->drupalGet('node/' . $node->nid . '/translate');
$this->assertLinkByHref($languages['es']->prefix . '/node/' . $node_translation->nid . '/edit', 0, format_string('The "edit" link for the translation in %language points to the localized path of the translation language.', array('%language' => $languages['es']->name)));
$this->assertLinkByHref($languages['es']->prefix . '/node/' . $node_translation->nid, 0, format_string('The "view" link for the translation in %language points to the localized path of the translation language.', array('%language' => $languages['es']->name)));
// Attempt to submit a duplicate translation by visiting the node/add page
// with identical query string.
$this->drupalGet('node/add/page', array('query' => array('translation' => $node->nid, 'target' => 'es')));
$this->assertRaw(t('A translation of %title in %language already exists', array('%title' => $node_title, '%language' => $languages['es']->name)), 'Message regarding attempted duplicate translation is displayed.');
// Attempt a resubmission of the form - this emulates using the back button
// to return to the page then resubmitting the form without a refresh.
$edit = array();
$langcode = LANGUAGE_NONE;
$edit["title"] = $this->randomName();
$edit["body[$langcode][0][value]"] = $this->randomName();
$this->drupalPost('node/add/page', $edit, t('Save'), array('query' => array('translation' => $node->nid, 'language' => 'es')));
$duplicate = $this->drupalGetNodeByTitle($edit["title"]);
$this->assertEqual($duplicate->tnid, 0, 'The node does not have a tnid.');
// Update original and mark translation as outdated.
$node_body = $this->randomName();
$node->body[LANGUAGE_NONE][0]['value'] = $node_body;
$edit = array();
$edit["body[$langcode][0][value]"] = $node_body;
$edit['translation[retranslate]'] = TRUE;
$this->drupalPost('node/' . $node->nid . '/edit', $edit, t('Save'));
$this->assertRaw(t('Basic page %title has been updated.', array('%title' => $node_title)), 'Original node updated.');
// Check to make sure that interface shows translation as outdated.
$this->drupalGet('node/' . $node->nid . '/translate');
$this->assertRaw('<span class="marker">' . t('outdated') . '</span>', 'Translation marked as outdated.');
// Update translation and mark as updated.
$edit = array();
$edit["body[$langcode][0][value]"] = $this->randomName();
$edit['translation[status]'] = FALSE;
$this->drupalPost('node/' . $node_translation->nid . '/edit', $edit, t('Save'));
$this->assertRaw(t('Basic page %title has been updated.', array('%title' => $node_translation_title)), 'Translated node updated.');
// Confirm that disabled languages are an option for translators when
// creating nodes.
$this->drupalGet('node/add/page');
$this->assertFieldByXPath('//select[@name="language"]//option', 'it', 'Italian (disabled) is available in language selection.');
$translation_it = $this->createTranslation($node, $this->randomName(), $this->randomName(), 'it');
$this->assertRaw($translation_it->body[LANGUAGE_NONE][0]['value'], 'Content created in Italian (disabled).');
// Confirm that language neutral is an option for translators when there are
// disabled languages.
$this->drupalGet('node/add/page');
$this->assertFieldByXPath('//select[@name="language"]//option', LANGUAGE_NONE, 'Language neutral is available in language selection with disabled languages.');
$node2 = $this->createPage($this->randomName(), $this->randomName(), LANGUAGE_NONE);
$this->assertRaw($node2->body[LANGUAGE_NONE][0]['value'], 'Language neutral content created with disabled languages available.');
// Leave just one language enabled and check that the translation overview
// page is still accessible.
$this->drupalLogin($this->admin_user);
$edit = array('enabled[es]' => FALSE);
$this->drupalPost('admin/config/regional/language', $edit, t('Save configuration'));
$this->drupalLogin($this->translator);
$this->drupalGet('node/' . $node->nid . '/translate');
$this->assertRaw(t('Translations of %title', array('%title' => $node->title)), 'Translation overview page available with only one language enabled.');
}
/**
* Checks that the language switch links behave properly.
*/
function testLanguageSwitchLinks() {
// Create a Basic page in English and its translations in Spanish and
// Italian.
$node = $this->createPage($this->randomName(), $this->randomName(), 'en');
$translation_es = $this->createTranslation($node, $this->randomName(), $this->randomName(), 'es');
$translation_it = $this->createTranslation($node, $this->randomName(), $this->randomName(), 'it');
// Check that language switch links are correctly shown only for enabled
// languages.
$this->assertLanguageSwitchLinks($node, $translation_es);
$this->assertLanguageSwitchLinks($translation_es, $node);
$this->assertLanguageSwitchLinks($node, $translation_it, FALSE);
// Check that links to the displayed translation appear only in the language
// switcher block.
$this->assertLanguageSwitchLinks($node, $node, FALSE, 'node');
$this->assertLanguageSwitchLinks($node, $node, TRUE, 'block-locale');
// Unpublish the Spanish translation to check that the related language
// switch link is not shown.
$this->drupalLogin($this->admin_user);
$edit = array('status' => FALSE);
$this->drupalPost("node/$translation_es->nid/edit", $edit, t('Save'));
$this->drupalLogin($this->translator);
$this->assertLanguageSwitchLinks($node, $translation_es, FALSE);
// Check that content translation links are shown even when no language
// negotiation is configured.
$this->drupalLogin($this->admin_user);
$edit = array('language[enabled][locale-url]' => FALSE);
$this->drupalPost('admin/config/regional/language/configure', $edit, t('Save settings'));
$this->resetCaches();
$edit = array('status' => TRUE);
$this->drupalPost("node/$translation_es->nid/edit", $edit, t('Save'));
$this->drupalLogin($this->translator);
$this->assertLanguageSwitchLinks($node, $translation_es, TRUE, 'node');
}
/**
* Tests that the language switcher block alterations work as intended.
*/
function testLanguageSwitcherBlockIntegration() {
// Enable Italian to have three items in the language switcher block.
$this->drupalLogin($this->admin_user);
$edit = array('enabled[it]' => TRUE);
$this->drupalPost('admin/config/regional/language', $edit, t('Save configuration'));
$this->drupalLogin($this->translator);
// Create a Basic page in English.
$type = 'block-locale';
$node = $this->createPage($this->randomName(), $this->randomName(), 'en');
$this->assertLanguageSwitchLinks($node, $node, TRUE, $type);
$this->assertLanguageSwitchLinks($node, $this->emptyNode('es'), TRUE, $type);
$this->assertLanguageSwitchLinks($node, $this->emptyNode('it'), TRUE, $type);
// Create the Spanish translation.
$translation_es = $this->createTranslation($node, $this->randomName(), $this->randomName(), 'es');
$this->assertLanguageSwitchLinks($node, $node, TRUE, $type);
$this->assertLanguageSwitchLinks($node, $translation_es, TRUE, $type);
$this->assertLanguageSwitchLinks($node, $this->emptyNode('it'), TRUE, $type);
// Create the Italian translation.
$translation_it = $this->createTranslation($node, $this->randomName(), $this->randomName(), 'it');
$this->assertLanguageSwitchLinks($node, $node, TRUE, $type);
$this->assertLanguageSwitchLinks($node, $translation_es, TRUE, $type);
$this->assertLanguageSwitchLinks($node, $translation_it, TRUE, $type);
// Create a language neutral node and check that the language switcher is
// left untouched.
$node2 = $this->createPage($this->randomName(), $this->randomName(), LANGUAGE_NONE);
$node2_en = (object) array('nid' => $node2->nid, 'language' => 'en');
$node2_es = (object) array('nid' => $node2->nid, 'language' => 'es');
$node2_it = (object) array('nid' => $node2->nid, 'language' => 'it');
$this->assertLanguageSwitchLinks($node2_en, $node2_en, TRUE, $type);
$this->assertLanguageSwitchLinks($node2_en, $node2_es, TRUE, $type);
$this->assertLanguageSwitchLinks($node2_en, $node2_it, TRUE, $type);
// Disable translation support to check that the language switcher is left
// untouched only for new nodes.
$this->drupalLogin($this->admin_user);
$edit = array('language_content_type' => 0);
$this->drupalPost('admin/structure/types/manage/page', $edit, t('Save content type'));
$this->drupalLogin($this->translator);
// Existing translations trigger alterations even if translation support is
// disabled.
$this->assertLanguageSwitchLinks($node, $node, TRUE, $type);
$this->assertLanguageSwitchLinks($node, $translation_es, TRUE, $type);
$this->assertLanguageSwitchLinks($node, $translation_it, TRUE, $type);
// Check that new nodes with a language assigned do not trigger language
// switcher alterations when translation support is disabled.
$node = $this->createPage($this->randomName(), $this->randomName());
$node_es = (object) array('nid' => $node->nid, 'language' => 'es');
$node_it = (object) array('nid' => $node->nid, 'language' => 'it');
$this->assertLanguageSwitchLinks($node, $node, TRUE, $type);
$this->assertLanguageSwitchLinks($node, $node_es, TRUE, $type);
$this->assertLanguageSwitchLinks($node, $node_it, TRUE, $type);
}
/**
* Resets static caches to make the test code match the client-side behavior.
*/
function resetCaches() {
drupal_static_reset('locale_url_outbound_alter');
}
/**
* Returns an empty node data structure.
*
* @param $langcode
* The language code.
*
* @return
* An empty node data structure.
*/
function emptyNode($langcode) {
return (object) array('nid' => NULL, 'language' => $langcode);
}
/**
* Installs the specified language, or enables it if it is already installed.
*
* @param $language_code
* The language code to check.
*/
function addLanguage($language_code) {
// Check to make sure that language has not already been installed.
$this->drupalGet('admin/config/regional/language');
if (strpos($this->drupalGetContent(), 'enabled[' . $language_code . ']') === FALSE) {
// Doesn't have language installed so add it.
$edit = array();
$edit['langcode'] = $language_code;
$this->drupalPost('admin/config/regional/language/add', $edit, t('Add language'));
// Make sure we are not using a stale list.
drupal_static_reset('language_list');
$languages = language_list('language');
$this->assertTrue(array_key_exists($language_code, $languages), 'Language was installed successfully.');
if (array_key_exists($language_code, $languages)) {
$this->assertRaw(t('The language %language has been created and can now be used. More information is available on the <a href="@locale-help">help screen</a>.', array('%language' => $languages[$language_code]->name, '@locale-help' => url('admin/help/locale'))), 'Language has been created.');
}
}
elseif ($this->xpath('//input[@type="checkbox" and @name=:name and @checked="checked"]', array(':name' => 'enabled[' . $language_code . ']'))) {
// It's installed and enabled. No need to do anything.
$this->assertTrue(true, 'Language [' . $language_code . '] already installed and enabled.');
}
else {
// It's installed but not enabled. Enable it.
$this->assertTrue(true, 'Language [' . $language_code . '] already installed.');
$this->drupalPost(NULL, array('enabled[' . $language_code . ']' => TRUE), t('Save configuration'));
$this->assertRaw(t('Configuration saved.'), 'Language successfully enabled.');
}
}
/**
* Creates a "Basic page" in the specified language.
*
* @param $title
* The title of a basic page in the specified language.
* @param $body
* The body of a basic page in the specified language.
* @param $language
* (optional) Language code.
*
* @return
* A node object.
*/
function createPage($title, $body, $language = NULL) {
$edit = array();
$langcode = LANGUAGE_NONE;
$edit["title"] = $title;
$edit["body[$langcode][0][value]"] = $body;
if (!empty($language)) {
$edit['language'] = $language;
}
$this->drupalPost('node/add/page', $edit, t('Save'));
$this->assertRaw(t('Basic page %title has been created.', array('%title' => $title)), 'Basic page created.');
// Check to make sure the node was created.
$node = $this->drupalGetNodeByTitle($title);
$this->assertTrue($node, 'Node found in database.');
return $node;
}
/**
* Creates a translation for a basic page in the specified language.
*
* @param $node
* The basic page to create the translation for.
* @param $title
* The title of a basic page in the specified language.
* @param $body
* The body of a basic page in the specified language.
* @param $language
* Language code.
*
* @return
* Translation object.
*/
function createTranslation($node, $title, $body, $language) {
$this->drupalGet('node/add/page', array('query' => array('translation' => $node->nid, 'target' => $language)));
$langcode = LANGUAGE_NONE;
$body_key = "body[$langcode][0][value]";
$this->assertFieldByXPath('//input[@id="edit-title"]', $node->title, "Original title value correctly populated.");
$this->assertFieldByXPath("//textarea[@name='$body_key']", $node->body[LANGUAGE_NONE][0]['value'], "Original body value correctly populated.");
$edit = array();
$edit["title"] = $title;
$edit[$body_key] = $body;
$this->drupalPost(NULL, $edit, t('Save'));
$this->assertRaw(t('Basic page %title has been created.', array('%title' => $title)), 'Translation created.');
// Check to make sure that translation was successful.
$translation = $this->drupalGetNodeByTitle($title);
$this->assertTrue($translation, 'Node found in database.');
$this->assertTrue($translation->tnid == $node->nid, 'Translation set id correctly stored.');
return $translation;
}
/**
* Asserts an element identified by the given XPath has the given content.
*
* @param $xpath
* The XPath used to find the element.
* @param array $arguments
* An array of arguments with keys in the form ':name' matching the
* placeholders in the query. The values may be either strings or numeric
* values.
* @param $value
* The text content of the matched element to assert.
* @param $message
* The message to display.
* @param $group
* The group this message belongs to.
*
* @return
* TRUE on pass, FALSE on fail.
*/
function assertContentByXPath($xpath, array $arguments = array(), $value = NULL, $message = '', $group = 'Other') {
$found = $this->findContentByXPath($xpath, $arguments, $value);
return $this->assertTrue($found, $message, $group);
}
/**
* Tests whether the specified language switch links are found.
*
* @param $node
* The node to display.
* @param $translation
* The translation whose link has to be checked.
* @param $find
* TRUE if the link must be present in the node page.
* @param $types
* The page areas to be checked.
*
* @return
* TRUE if the language switch links are found, FALSE if not.
*/
function assertLanguageSwitchLinks($node, $translation, $find = TRUE, $types = NULL) {
if (empty($types)) {
$types = array('node', 'block-locale');
}
elseif (is_string($types)) {
$types = array($types);
}
$result = TRUE;
$languages = language_list();
$page_language = $languages[entity_language('node', $node)];
$translation_language = $languages[$translation->language];
$url = url("node/$translation->nid", array('language' => $translation_language));
$this->drupalGet("node/$node->nid", array('language' => $page_language));
foreach ($types as $type) {
$args = array('%translation_language' => $translation_language->native, '%page_language' => $page_language->native, '%type' => $type);
if ($find) {
$message = format_string('[%page_language] Language switch item found for %translation_language language in the %type page area.', $args);
}
else {
$message = format_string('[%page_language] Language switch item not found for %translation_language language in the %type page area.', $args);
}
if (!empty($translation->nid)) {
$xpath = '//div[contains(@class, :type)]//a[@href=:url]';
}
else {
$xpath = '//div[contains(@class, :type)]//span[contains(@class, "locale-untranslated")]';
}
$found = $this->findContentByXPath($xpath, array(':type' => $type, ':url' => $url), $translation_language->native);
$result = $this->assertTrue($found == $find, $message) && $result;
}
return $result;
}
/**
* Searches for elements matching the given xpath and value.
*
* @param $xpath
* The XPath used to find the element.
* @param array $arguments
* An array of arguments with keys in the form ':name' matching the
* placeholders in the query. The values may be either strings or numeric
* values.
* @param $value
* The text content of the matched element to assert.
*
* @return
* TRUE if found, otherwise FALSE.
*/
function findContentByXPath($xpath, array $arguments = array(), $value = NULL) {
$elements = $this->xpath($xpath, $arguments);
$found = TRUE;
if ($value && $elements) {
$found = FALSE;
foreach ($elements as $element) {
if ((string) $element == $value) {
$found = TRUE;
break;
}
}
}
return $elements && $found;
}
}