translation.module 18.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
<?php
// $Id$

/**
 * @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 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' is the translation set id, which equals the node id
 *      of the source post.
 *    - 'translate' is a 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.
 */
26
define('TRANSLATION_ENABLED', 2);
27 28

/**
29
 * Implements hook_help().
30
 */
31 32
function translation_help($path, $arg) {
  switch ($path) {
33
    case 'admin/help#translation':
34 35 36 37 38 39 40 41 42 43 44 45 46 47
      $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/handbook/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'))) . '</li></ul><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>';
48 49
      return $output;
    case 'node/%/translate':
50
      $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>';
51 52 53 54 55
      return $output;
  }
}

/**
56
 * Implements hook_menu().
57 58 59 60 61 62 63 64 65 66 67
 */
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,
68
    'file' => 'translation.pages.inc',
69 70 71 72 73 74 75 76 77 78 79
  );
  return $items;
}

/**
 * Menu access callback.
 *
 * Only display translation tab for node types, which have translation enabled
 * and where the current node is not language neutral (which should span
 * all languages).
 */
80
function _translation_tab_access($node) {
81
  if ($node->language != LANGUAGE_NONE && translation_supported_type($node->type) && node_access('view', $node)) {
82 83 84 85 86
    return user_access('translate content');
  }
  return FALSE;
}

87 88 89 90 91 92 93 94 95 96
/**
 * Implements hook_admin_paths().
 */
function translation_admin_paths() {
  $paths = array(
    'node/*/translate' => TRUE,
  );
  return $paths;
}

97
/**
98
 * Implements hook_permission().
99
 */
100
function translation_permission() {
101
  return array(
102
    'translate content' => array(
103
      'title' => t('Translate content'),
104
    ),
105
  );
106 107
}

108
/**
109
 * Implements hook_form_FORM_ID_alter().
110 111 112 113 114
 */
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.
115
  $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 enabled 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')));
116 117
}

118
/**
119
 * Implements hook_form_alter().
120 121 122 123 124
 *
 * - Add translation option to content type form.
 * - Alters language fields on node forms when a translation
 *   is about to be created.
 */
125 126
function translation_form_alter(&$form, &$form_state, $form_id) {
  if (isset($form['#id']) && $form['#id'] == 'node-form' && translation_supported_type($form['#node']->type)) {
127 128 129 130 131 132 133 134 135 136
    $node = $form['#node'];
    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.
137
      unset($form['language']['#options'][LANGUAGE_NONE]);
138 139 140 141 142 143
      foreach (translation_node_get_translations($node->tnid) as $translation) {
        if ($translation->nid != $node->nid) {
          unset($form['language']['#options'][$translation->language]);
        }
      }
      // Add translation values and workflow options.
144
      $form['tnid'] = array('#type' => 'value', '#value' => $node->tnid);
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
      $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.'),
        );
      }
    }
  }
}

/**
177
 * Implements hook_node_view().
178 179 180 181
 *
 * Display translation links with native language names, if this node
 * is part of a translation set.
 */
182
function translation_node_view($node, $view_mode) {
183
  if (isset($node->tnid) && $translations = translation_node_get_translations($node->tnid)) {
184 185 186 187 188 189 190 191 192 193 194
    $path = 'node/' . $node->nid;
    $links = language_negotiation_get_switch_links(LANGUAGE_TYPE_CONTENT, $path);
    if (is_object($links)) {
      $links = $links->links;
      // Do not show link to the same node.
      unset($links[$node->language]);
      $node->content['links']['translation'] = array(
        '#theme' => 'links',
        '#links' => $links,
        '#attributes' => array('class' => array('links', 'inline')),
      );
195 196 197 198 199
    }
  }
}

/**
200
 * Implements hook_node_prepare().
201
 */
202
function translation_node_prepare($node) {
203
  // Only act if we are dealing with a content type supporting translations.
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233
  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['language']) &&
    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();
    if (!isset($language_list[$_GET['language']]) || ($source_node->language == $_GET['language'])) {
      // 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[$_GET['language']])) {
        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_NONE][0]['value'], '%language' => $language_list[$_GET['language']]->name, '%type' => $node->type)), 'error');
        return;
234
      }
235
    }
236 237 238 239 240 241 242 243 244 245 246 247 248
    
    // Populate fields based on source node.
    $node->language = $_GET['language'];
    $node->translation_source = $source_node;
    $node->title = $source_node->title;

    // If user has no access to the filter used for the body, Drupal core
    // does not let the edit form to appear, so we should avoid exposing
    // the source text here too.
    $formats = filter_formats();
    $node->body = (filter_access($formats[$source_node->body[$source_node->language][0]['format']])) ? $source_node->body : '';
    // Let every module add custom translated fields.
    module_invoke_all('node_prepare_translation', $node);
249
  }
250
}
251

252
/**
253
 * Implements hook_node_insert().
254
 */
255
function translation_node_insert($node) {
256 257 258 259 260 261
  // 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;
262
      }
263 264 265
      else {
        // Create new translation set, using nid from the source node.
        $tnid = $node->translation_source->nid;
266 267 268 269 270 271 272
        db_update('node')
          ->fields(array(
            'tnid' => $tnid,
            'translate' => 0,
          ))
          ->condition('nid', $node->translation_source->nid)
          ->execute();
273
      }
274 275 276 277 278 279 280
      db_update('node')
        ->fields(array(
          'tnid' => $tnid,
          'translate' => 0,
        ))
        ->condition('nid', $node->nid)
        ->execute();
281 282 283
    }
  }
}
284

285
/**
286
 * Implements hook_node_update().
287
 */
288
function translation_node_update($node) {
289 290 291 292
  // 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->language) && $node->tnid) {
      // Update translation information.
293 294 295 296 297 298 299
      db_update('node')
        ->fields(array(
          'tnid' => $node->tnid,
          'translate' => $node->translation['status'],
        ))
        ->condition('nid', $node->nid)
        ->execute();
300 301
      if (!empty($node->translation['retranslate'])) {
        // This is the source node, asking to mark all translations outdated.
302 303 304 305 306
        db_update('node')
          ->fields(array('translate' => 1))
          ->condition('nid', $node->nid, '<>')
          ->condition('tnid', $node->tnid)
          ->execute();
307
      }
308
    }
309 310 311
  }
}

312
/**
313
 * Implements hook_node_validate().
314 315 316
 *
 * Ensure that duplicate translations can not be created for the same source.
 */
317
function translation_node_validate($node, $form) {
318 319 320 321 322 323 324 325 326 327
  // 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);
    if (isset($translations[$node->language]) && $translations[$node->language]->nid != $node->nid ) {
      form_set_error('language', t('There is already a translation in this language.'));
    }
  }
}

328
/**
329
 * Implements hook_node_delete().
330
 */
331
function translation_node_delete($node) {
332 333 334 335 336
  // Only act if we are dealing with a content type supporting translations.
  if (translation_supported_type($node->type)) {
    translation_remove_from_set($node);
  }
}
337

338 339 340 341
/**
 * Remove a node from its translation set (if any)
 * and update the set accordingly.
 */
342
function translation_remove_from_set($node) {
343
  if (isset($node->tnid)) {
344 345 346 347 348 349
    $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) {
350
      // There is only one node left in the set: remove the set altogether.
351 352 353
      $query
        ->condition('tnid', $node->tnid)
        ->execute();
354 355
    }
    else {
356 357 358
      $query
        ->condition('nid', $node->nid)
        ->execute();
359 360 361 362

      // 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) {
363 364 365 366 367
        $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();
368 369
      }
    }
370 371 372
  }
}

373 374 375 376 377 378 379
/**
 * Get all nodes in a translation set, represented by $tnid.
 *
 * @param $tnid
 *   The translation source nid of the translation set, the identifier
 *   of the node used to derive all translations in the set.
 * @return
380 381 382
 *   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
383
 *   partial nodes, you need to node_load() the full node, if you
384
 *   need more properties. The array is indexed by language code.
385 386 387
 */
function translation_node_get_translations($tnid) {
  if (is_numeric($tnid) && $tnid) {
388 389
    $translations = &drupal_static(__FUNCTION__, array());

390 391
    if (!isset($translations[$tnid])) {
      $translations[$tnid] = array();
392 393 394 395 396 397 398
      $result = db_select('node', 'n')
        ->fields('n', array('nid', 'title', 'language'))
        ->condition('n.tnid', $tnid)
        ->addTag('node_access')
        ->execute();

      foreach ($result as $node) {
399 400 401 402 403 404 405 406 407 408 409 410 411 412
        $translations[$tnid][$node->language] = $node;
      }
    }
    return $translations[$tnid];
  }
}

/**
 * Returns whether the given content type has support for translations.
 *
 * @return
 *   Boolean value.
 */
function translation_supported_type($type) {
413
  return variable_get('language_content_type_' . $type, 0) == TRANSLATION_ENABLED;
414
}
415 416 417

/**
 * Return paths of all translations of a node, based on
418
 * its Drupal path.
419 420 421 422
 *
 * @param $path
 *   A Drupal path, for example node/432.
 * @return
423
 *   An array of paths of translations of the node accessible
424 425 426 427 428 429 430
 *   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/([0-9]+)(/.+|)$!", $path, $matches)) && ($node = node_load((int)$matches[1])) && !empty($node->tnid)) {
    foreach (translation_node_get_translations($node->tnid) as $language => $translation_node) {
431
      $paths[$language] = 'node/' . $translation_node->nid . $matches[2];
432 433 434 435 436 437
    }
  }
  return $paths;
}

/**
438
 * Implements hook_language_switch_link_alter().
439 440 441
 *
 * Replaces links with pointers to translated versions of the content.
 */
442 443
function translation_language_switch_links_alter(array &$links, $type, $path) {
  if ($type == LANGUAGE_TYPE_CONTENT && $paths = translation_path_get_translations($path)) {
444 445 446 447 448 449 450 451 452 453 454 455
    foreach ($links as $langcode => $link) {
      if (isset($paths[$langcode])) {
        // Translation in a different node.
        $links[$langcode]['href'] = $paths[$langcode];
      }
      else {
        // No translation in this language, or no permission to view.
        unset($links[$langcode]);
      }
    }
  }
}