translation.module 22 KB
Newer Older
1
2
3
4
<?php

/**
 * @file
5
 * Manages content translations.
6
 *
7
8
9
10
11
12
13
 * 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.
14
 *
15
16
17
18
19
 * 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).
20
21
22
23
24
 */

/**
 * Identifies a content type which has translation support enabled.
 */
25
const TRANSLATION_ENABLED = 2;
26
27

/**
28
 * Implements hook_help().
29
 */
30
31
function translation_help($path, $arg) {
  switch ($path) {
32
    case 'admin/help#translation':
33
34
      $output = '';
      $output .= '<h3>' . t('About') . '</h3>';
35
      $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>';
36
37
38
      $output .= '<h3>' . t('Uses') . '</h3>';
      $output .= '<dl>';
      $output .= '<dt>' . t('Configuring content types for translation') . '</dt>';
39
      $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>';
40
41
42
      $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>';
43
      $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>Translations</em> tab when viewing the content, select the language for which you wish to provide content, and then enter the content.') . '</dd>';
44
45
46
      $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>';
47
48
      return $output;
    case 'node/%/translate':
49
      $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>';
50
51
52
53
54
      return $output;
  }
}

/**
55
 * Implements hook_menu().
56
57
58
59
 */
function translation_menu() {
  $items = array();
  $items['node/%node/translate'] = array(
60
    'title' => 'Translations',
61
62
63
64
65
66
    'page callback' => 'translation_node_overview',
    'page arguments' => array(1),
    'access callback' => '_translation_tab_access',
    'access arguments' => array(1),
    'type' => MENU_LOCAL_TASK,
    'weight' => 2,
67
    'file' => 'translation.pages.inc',
68
69
70
71
72
  );
  return $items;
}

/**
73
 * Access callback: Checks that the user has permission to 'translate content'.
74
 *
75
76
77
78
79
80
81
82
83
84
 * 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()
85
 */
86
function _translation_tab_access($node) {
87
  if ($node->langcode != LANGUAGE_NOT_SPECIFIED && translation_supported_type($node->type) && node_access('view', $node)) {
88
89
90
91
92
    return user_access('translate content');
  }
  return FALSE;
}

93
94
95
96
/**
 * Implements hook_admin_paths().
 */
function translation_admin_paths() {
97
98
99
100
101
102
  if (variable_get('node_admin_theme')) {
    $paths = array(
      'node/*/translate' => TRUE,
    );
    return $paths;
  }
103
104
}

105
/**
106
 * Implements hook_permission().
107
 */
108
function translation_permission() {
109
  return array(
110
    'translate content' => array(
111
      'title' => t('Translate content'),
112
    ),
113
  );
114
115
}

116
/**
117
 * Implements hook_form_FORM_ID_alter() for node_type_form().
118
119
120
 */
function translation_form_node_type_form_alter(&$form, &$form_state) {
  // Add translation option to content type form.
121
122
123
124
  $form['workflow']['node_type_language']['#type'] = 'radios';
  $form['workflow']['node_type_language']['#options'] = array(t('Disabled'), t('Enabled'), TRANSLATION_ENABLED => t('Enabled, with translation'));
  // Description based on text from node.module.
  $form['workflow']['node_type_language']['#description'] = t('Add a language selection field 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')));
125
126
}

127
/**
128
 * Implements hook_form_BASE_FORM_ID_alter() for node_form().
129
 *
130
131
132
133
 * Alters language fields on node edit forms when a translation is about to be
 * created.
 *
 * @see node_form()
134
 */
135
136
function translation_form_node_form_alter(&$form, &$form_state) {
  if (translation_supported_type($form['#node']->type)) {
137
    $node = $form['#node'];
138
139
140
141
142
143
144
145
146

    // Build two lists with the disabled and enabled languages.
    $languages = language_list();
    $grouped_languages = array();
    foreach ($languages as $langcode => $language) {
      $grouped_languages[(int) $language->enabled][$langcode] = $language;
    }

    $translator_widget = !empty($grouped_languages[0]) && user_access('translate content');
147
148
149
150
151
    $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) {
152
      $options = array($groups[1] => array(LANGUAGE_NOT_SPECIFIED => t('- None -')));
153
154
      foreach (array(1, 0) as $status) {
        $group = $groups[$status];
155
156
        foreach ($grouped_languages[$status] as $langcode => $language) {
          $options[$group][$langcode] = $language->name;
157
158
        }
      }
159
      $form['langcode']['#options'] = $options;
160
    }
161
162
163
    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);
164
      $form['langcode']['#disabled'] = TRUE;
165
166
167
168
169
    }
    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.
170
      unset($form['langcode']['#options'][LANGUAGE_NOT_SPECIFIED]);
171
      foreach (translation_node_get_translations($node->tnid) as $langcode => $translation) {
172
        if ($translation->nid != $node->nid) {
173
174
          if ($translator_widget) {
            $group = $groups[(int)!isset($disabled_languages[$langcode])];
175
            unset($form['langcode']['#options'][$group][$langcode]);
176
177
          }
          else {
178
            unset($form['langcode']['#options'][$langcode]);
179
          }
180
181
182
        }
      }
      // Add translation values and workflow options.
183
      $form['tnid'] = array('#type' => 'value', '#value' => $node->tnid);
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
      $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.'),
        );
      }
    }
  }
}

/**
216
 * Implements hook_node_view().
217
 *
218
219
220
 * 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().
221
 */
222
function translation_node_view($node, $view_mode) {
223
224
  // If the site has no translations or is not multilingual we have no content
  // translation links to display.
225
  if (isset($node->tnid) && language_multilingual() && $translations = translation_node_get_translations($node->tnid)) {
226
    $languages = language_list(TRUE);
227
228
229
230
231
232
233
234
235
236
237
238
239
240

    // 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.
241
      if ($translation->status && isset($languages[$langcode]) && $langcode != $node->langcode) {
242
243
244
245
246
247
248
249
250
        $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}",
251
            'title' => $language->name,
252
253
254
255
256
257
258
259
260
261
262
263
264
            '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'];
      }
265
    }
266

267
268
269
270
271
    $node->content['links']['translation'] = array(
      '#theme' => 'links__node__translation',
      '#links' => $links,
      '#attributes' => array('class' => array('links', 'inline')),
    );
272
273
274
275
  }
}

/**
276
 * Implements hook_node_prepare().
277
 */
278
function translation_node_prepare($node) {
279
  // Only act if we are dealing with a content type supporting translations.
280
281
282
283
284
285
286
  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']) &&
287
    isset($_GET['target']) &&
288
    is_numeric($_GET['translation'])) {
289

290
291
292
293
294
295
296
    $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;
    }
297

298
    $language_list = language_list();
299
    $langcode = $_GET['target'];
300
    if (!isset($language_list[$langcode]) || ($source_node->langcode == $langcode)) {
301
302
303
      // If not supported language, or same language as source node, break.
      return;
    }
304

305
306
307
    // Ensure we don't have an existing translation in this language.
    if (!empty($source_node->tnid)) {
      $translations = translation_node_get_translations($source_node->tnid);
308
309
      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');
310
        return;
311
      }
312
    }
313

314
    // Populate fields based on source node.
315
    $node->langcode = $langcode;
316
317
318
    $node->translation_source = $source_node;
    $node->title = $source_node->title;

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

325
/**
326
 * Implements hook_node_insert().
327
 */
328
function translation_node_insert($node) {
329
330
331
332
333
334
  // 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;
335
      }
336
337
338
      else {
        // Create new translation set, using nid from the source node.
        $tnid = $node->translation_source->nid;
339
340
341
342
343
344
345
        db_update('node')
          ->fields(array(
            'tnid' => $tnid,
            'translate' => 0,
          ))
          ->condition('nid', $node->translation_source->nid)
          ->execute();
346
      }
347
348
349
350
351
352
353
      db_update('node')
        ->fields(array(
          'tnid' => $tnid,
          'translate' => 0,
        ))
        ->condition('nid', $node->nid)
        ->execute();
354
355
      // Save tnid to avoid loss in case of resave.
      $node->tnid = $tnid;
356
357
358
    }
  }
}
359

360
/**
361
 * Implements hook_node_update().
362
 */
363
function translation_node_update($node) {
364
365
  // Only act if we are dealing with a content type supporting translations.
  if (translation_supported_type($node->type)) {
366
    if (isset($node->translation) && $node->translation && !empty($node->langcode) && $node->tnid) {
367
      // Update translation information.
368
369
370
371
372
373
374
      db_update('node')
        ->fields(array(
          'tnid' => $node->tnid,
          'translate' => $node->translation['status'],
        ))
        ->condition('nid', $node->nid)
        ->execute();
375
376
      if (!empty($node->translation['retranslate'])) {
        // This is the source node, asking to mark all translations outdated.
377
378
379
380
381
        db_update('node')
          ->fields(array('translate' => 1))
          ->condition('nid', $node->nid, '<>')
          ->condition('tnid', $node->tnid)
          ->execute();
382
      }
383
    }
384
385
386
  }
}

387
/**
388
 * Implements hook_node_validate().
389
 *
390
 * Ensures that duplicate translations can't be created for the same source.
391
 */
392
function translation_node_validate($node, $form) {
393
394
395
396
  // 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);
397
398
    if (isset($translations[$node->langcode]) && $translations[$node->langcode]->nid != $node->nid ) {
      form_set_error('langcode', t('There is already a translation in this language.'));
399
400
401
402
    }
  }
}

403
/**
404
 * Implements hook_node_predelete().
405
 */
406
function translation_node_predelete($node) {
407
408
409
410
411
  // Only act if we are dealing with a content type supporting translations.
  if (translation_supported_type($node->type)) {
    translation_remove_from_set($node);
  }
}
412

413
/**
414
415
416
417
 * Removes a node from its translation set and updates accordingly.
 *
 * @param $node
 *   A node object.
418
 */
419
function translation_remove_from_set($node) {
420
  if (isset($node->tnid)) {
421
422
423
424
425
426
    $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) {
427
      // There is only one node left in the set: remove the set altogether.
428
429
430
      $query
        ->condition('tnid', $node->tnid)
        ->execute();
431
432
    }
    else {
433
434
435
      $query
        ->condition('nid', $node->nid)
        ->execute();
436
437
438
439

      // 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) {
440
441
442
443
444
        $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();
445
446
      }
    }
447
448
449
  }
}

450
/**
451
 * Gets all nodes in a given translation set.
452
453
 *
 * @param $tnid
454
455
456
 *   The translation source nid of the translation set, the identifier of the
 *   node used to derive all translations in the set.
 *
457
 * @return
458
459
460
461
462
 *   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.
463
464
465
 */
function translation_node_get_translations($tnid) {
  if (is_numeric($tnid) && $tnid) {
466
467
    $translations = &drupal_static(__FUNCTION__, array());

468
469
    if (!isset($translations[$tnid])) {
      $translations[$tnid] = array();
470
      $result = db_select('node', 'n')
471
        ->fields('n', array('nid', 'type', 'uid', 'status', 'title', 'langcode'))
472
473
474
475
476
        ->condition('n.tnid', $tnid)
        ->addTag('node_access')
        ->execute();

      foreach ($result as $node) {
477
        $translations[$tnid][$node->langcode] = $node;
478
479
480
481
482
483
484
485
486
487
      }
    }
    return $translations[$tnid];
  }
}

/**
 * Returns whether the given content type has support for translations.
 *
 * @return
488
 *   TRUE if translation is supported, and FALSE if not.
489
490
 */
function translation_supported_type($type) {
491
  return variable_get('node_type_language_' . $type, 0) == TRANSLATION_ENABLED;
492
}
493
494

/**
495
 * Returns the paths of all translations of a node, based on its Drupal path.
496
497
498
 *
 * @param $path
 *   A Drupal path, for example node/432.
499
 *
500
 * @return
501
502
 *   An array of paths of translations of the node accessible to the current
 *   user, keyed with language codes.
503
504
505
506
 */
function translation_path_get_translations($path) {
  $paths = array();
  // Check for a node related path, and for its translations.
507
  if ((preg_match("!^node/(\d+)(/.+|)$!", $path, $matches)) && ($node = node_load((int) $matches[1])) && !empty($node->tnid)) {
508
    foreach (translation_node_get_translations($node->tnid) as $language => $translation_node) {
509
      $paths[$language] = 'node/' . $translation_node->nid . $matches[2];
510
511
512
513
514
515
    }
  }
  return $paths;
}

/**
516
 * Implements hook_language_switch_links_alter().
517
518
519
 *
 * Replaces links with pointers to translated versions of the content.
 */
520
function translation_language_switch_links_alter(array &$links, $type, $path) {
521
  $language_type = variable_get('translation_language_type', LANGUAGE_TYPE_INTERFACE);
522
523
524
525
526
527
528
529
530

  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.
531
      if (empty($node) || $node->langcode == LANGUAGE_NOT_SPECIFIED || !translation_supported_type($node->type)) {
532
533
        return;
      }
534
      $translations = array($node->langcode => $node);
535
536
537
538
    }
    else {
      $translations = translation_node_get_translations($node->tnid);
    }
539

540
    foreach ($links as $langcode => $link) {
541
      if (isset($translations[$langcode]) && $translations[$langcode]->status) {
542
        // Translation in a different node.
543
        $links[$langcode]['href'] = 'node/' . $translations[$langcode]->nid . $matches[2];
544
545
546
      }
      else {
        // No translation in this language, or no permission to view.
547
        unset($links[$langcode]['href']);
548
        $links[$langcode]['attributes']['class'][] = 'locale-untranslated';
549
550
551
552
      }
    }
  }
}