Projet

Général

Profil

Paste
Télécharger (22,1 ko) Statistiques
| Branche: | Révision:

root / drupal7 / modules / translation / translation.module @ f7a2490e

1
<?php
2

    
3
/**
4
 * @file
5
 * Manages content translations.
6
 *
7
 * Translations are managed in sets of posts, which represent the same
8
 * information in different languages. Only content types for which the
9
 * administrator has explicitly enabled translations could have translations
10
 * associated. Translations are managed in sets with exactly one source post
11
 * per set. The source post is used to translate to different languages, so if
12
 * the source post is significantly updated, the editor can decide to mark all
13
 * translations outdated.
14
 *
15
 * The node table stores the values used by this module:
16
 * - tnid: Integer for the translation set ID, which equals the node ID of the
17
 *   source post.
18
 * - translate: Integer flag, either indicating that the translation is up to
19
 *   date (0) or needs to be updated (1).
20
 */
21

    
22
/**
23
 * Identifies a content type which has translation support enabled.
24
 */
25
define('TRANSLATION_ENABLED', 2);
26

    
27
/**
28
 * Implements hook_help().
29
 */
30
function translation_help($path, $arg) {
31
  switch ($path) {
32
    case 'admin/help#translation':
33
      $output = '';
34
      $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
      $output .= '<h3>' . t('Uses') . '</h3>';
37
      $output .= '<dl>';
38
      $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
      $output .= '<dt>' . t('Assigning a language to content') . '</dt>';
41
      $output .= '<dd>' . t('Use the <em>Language</em> drop down to select the appropriate language when creating or editing content.') . '</dd>';
42
      $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>Translation</em> tab when viewing the content, select the language for which you wish to provide content, and then enter the content.') . '</dd>';
44
      $output .= '<dt>' . t('Maintaining translations') . '</dt>';
45
      $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>';
46
      $output .= '</dl>';
47
      return $output;
48
    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
      return $output;
51
  }
52
}
53

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

    
72
/**
73
 * Access callback: Checks that the user has permission to 'translate content'.
74
 *
75
 * Only displays the translation tab for nodes that are not language-neutral
76
 * of types that have translation enabled.
77
 *
78
 * @param $node
79
 *   A node object.
80
 *
81
 * @return
82
 *   TRUE if the translation tab should be displayed, FALSE otherwise.
83
 *
84
 * @see translation_menu()
85
 */
86
function _translation_tab_access($node) {
87
  if (entity_language('node', $node) != LANGUAGE_NONE && translation_supported_type($node->type) && node_access('view', $node)) {
88
    return user_access('translate content');
89
  }
90
  return FALSE;
91
}
92

    
93
/**
94
 * Implements hook_admin_paths().
95
 */
96
function translation_admin_paths() {
97
  if (variable_get('node_admin_theme')) {
98
    $paths = array(
99
      'node/*/translate' => TRUE,
100
    );
101
    return $paths;
102
  }
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
function translation_form_node_type_form_alter(&$form, &$form_state) {
120
  // Add translation option to content type form.
121
  $form['workflow']['language_content_type']['#options'][TRANSLATION_ENABLED] = t('Enabled, with translation');
122
  // Description based on text from locale.module.
123
  $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')));
124
}
125

    
126
/**
127
 * Implements hook_form_BASE_FORM_ID_alter() for node_form().
128
 *
129
 * Alters language fields on node edit forms when a translation is about to be
130
 * created.
131
 *
132
 * @see node_form()
133
 */
134
function translation_form_node_form_alter(&$form, &$form_state) {
135
  if (translation_supported_type($form['#node']->type)) {
136
    $node = $form['#node'];
137
    $languages = language_list('enabled');
138
    $disabled_languages = isset($languages[0]) ? $languages[0] : FALSE;
139
    $translator_widget = $disabled_languages && user_access('translate content');
140
    $groups = array(t('Disabled'), t('Enabled'));
141
    // Allow translators to enter content in disabled languages. Translators
142
    // might need to distinguish between enabled and disabled languages, hence
143
    // we divide them in two option groups.
144
    if ($translator_widget) {
145
      $options = array($groups[1] => array(LANGUAGE_NONE => t('Language neutral')));
146
      $language_list = locale_language_list('name', TRUE);
147
      foreach (array(1, 0) as $status) {
148
        $group = $groups[$status];
149
        foreach ($languages[$status] as $langcode => $language) {
150
          $options[$group][$langcode] = $language_list[$langcode];
151
        }
152
      }
153
      $form['language']['#options'] = $options;
154
    }
155
    if (!empty($node->translation_source)) {
156
      // We are creating a translation. Add values and lock language field.
157
      $form['translation_source'] = array('#type' => 'value', '#value' => $node->translation_source);
158
      $form['language']['#disabled'] = TRUE;
159
    }
160
    elseif (!empty($node->nid) && !empty($node->tnid)) {
161
      // Disable languages for existing translations, so it is not possible to switch this
162
      // node to some language which is already in the translation set. Also remove the
163
      // language neutral option.
164
      unset($form['language']['#options'][LANGUAGE_NONE]);
165
      foreach (translation_node_get_translations($node->tnid) as $langcode => $translation) {
166
        if ($translation->nid != $node->nid) {
167
          if ($translator_widget) {
168
            $group = $groups[(int)!isset($disabled_languages[$langcode])];
169
            unset($form['language']['#options'][$group][$langcode]);
170
          }
171
          else {
172
            unset($form['language']['#options'][$langcode]);
173
          }
174
        }
175
      }
176
      // Add translation values and workflow options.
177
      $form['tnid'] = array('#type' => 'value', '#value' => $node->tnid);
178
      $form['translation'] = array(
179
        '#type' => 'fieldset',
180
        '#title' => t('Translation settings'),
181
        '#access' => user_access('translate content'),
182
        '#collapsible' => TRUE,
183
        '#collapsed' => !$node->translate,
184
        '#tree' => TRUE,
185
        '#weight' => 30,
186
      );
187
      if ($node->tnid == $node->nid) {
188
        // This is the source node of the translation
189
        $form['translation']['retranslate'] = array(
190
          '#type' => 'checkbox',
191
          '#title' => t('Flag translations as outdated'),
192
          '#default_value' => 0,
193
          '#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.'),
194
        );
195
        $form['translation']['status'] = array('#type' => 'value', '#value' => 0);
196
      }
197
      else {
198
        $form['translation']['status'] = array(
199
          '#type' => 'checkbox',
200
          '#title' => t('This translation needs to be updated'),
201
          '#default_value' => $node->translate,
202
          '#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.'),
203
        );
204
      }
205
    }
206
  }
207
}
208

    
209
/**
210
 * Implements hook_node_view().
211
 *
212
 * Displays translation links with language names if this node is part of a
213
 * translation set. If no language provider is enabled, "fall back" to simple
214
 * links built through the result of translation_node_get_translations().
215
 */
216
function translation_node_view($node, $view_mode) {
217
  // If the site has no translations or is not multilingual we have no content
218
  // translation links to display.
219
  if (isset($node->tnid) && drupal_multilingual() && $translations = translation_node_get_translations($node->tnid)) {
220
    $languages = language_list('enabled');
221
    $languages = $languages[1];
222

    
223
    // There might be a language provider enabled defining custom language
224
    // switch links which need to be taken into account while generating the
225
    // content translation links. As custom language switch links are available
226
    // only for configurable language types and interface language is the only
227
    // configurable language type in core, we use it as default. Contributed
228
    // modules can change this behavior by setting the system variable below.
229
    $type = variable_get('translation_language_type', LANGUAGE_TYPE_INTERFACE);
230
    $custom_links = language_negotiation_get_switch_links($type, "node/$node->nid");
231
    $links = array();
232

    
233
    foreach ($translations as $langcode => $translation) {
234
      // Do not show links to the same node, to unpublished translations or to
235
      // translations in disabled languages.
236
      if ($translation->status && isset($languages[$langcode]) && $langcode != entity_language('node', $node)) {
237
        $language = $languages[$langcode];
238
        $key = "translation_$langcode";
239

    
240
        if (isset($custom_links->links[$langcode])) {
241
          $links[$key] = $custom_links->links[$langcode];
242
        }
243
        else {
244
          $links[$key] = array(
245
            'href' => "node/{$translation->nid}",
246
            'title' => $language->native,
247
            'language' => $language,
248
          );
249
        }
250

    
251
        // Custom switch links are more generic than content translation links,
252
        // hence we override existing attributes with the ones below.
253
        $links[$key] += array('attributes' => array());
254
        $attributes = array(
255
          'title' => $translation->title,
256
          'class' => array('translation-link'),
257
        );
258
        $links[$key]['attributes'] = $attributes + $links[$key]['attributes'];
259
      }
260
    }
261

    
262
    $node->content['links']['translation'] = array(
263
      '#theme' => 'links__node__translation',
264
      '#links' => $links,
265
      '#attributes' => array('class' => array('links', 'inline')),
266
    );
267
  }
268
}
269

    
270
/**
271
 * Implements hook_node_prepare().
272
 */
273
function translation_node_prepare($node) {
274
  // Only act if we are dealing with a content type supporting translations.
275
  if (translation_supported_type($node->type) &&
276
    // And it's a new node.
277
    empty($node->nid) &&
278
    // And the user has permission to translate content.
279
    user_access('translate content') &&
280
    // And the $_GET variables are set properly.
281
    isset($_GET['translation']) &&
282
    isset($_GET['target']) &&
283
    is_numeric($_GET['translation'])) {
284

    
285
    $source_node = node_load($_GET['translation']);
286
    if (empty($source_node) || !node_access('view', $source_node)) {
287
      // Source node not found or no access to view. We should not check
288
      // for edit access, since the translator might not have permissions
289
      // to edit the source node but should still be able to translate.
290
      return;
291
    }
292

    
293
    $language_list = language_list();
294
    $langcode = $_GET['target'];
295
    if (!isset($language_list[$langcode]) || ($source_node->language == $langcode)) {
296
      // If not supported language, or same language as source node, break.
297
      return;
298
    }
299

    
300
    // Ensure we don't have an existing translation in this language.
301
    if (!empty($source_node->tnid)) {
302
      $translations = translation_node_get_translations($source_node->tnid);
303
      if (isset($translations[$langcode])) {
304
        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');
305
        return;
306
      }
307
    }
308

    
309
    // Populate fields based on source node.
310
    $node->language = $langcode;
311
    $node->translation_source = $source_node;
312
    $node->title = $source_node->title;
313

    
314
    // Add field translations and let other modules module add custom translated
315
    // fields.
316
    field_attach_prepare_translation('node', $node, $langcode, $source_node, $source_node->language);
317
  }
318
}
319

    
320
/**
321
 * Implements hook_node_insert().
322
 */
323
function translation_node_insert($node) {
324
  // Only act if we are dealing with a content type supporting translations.
325
  if (translation_supported_type($node->type)) {
326
    if (!empty($node->translation_source)) {
327
      if ($node->translation_source->tnid) {
328
        // Add node to existing translation set.
329
        $tnid = $node->translation_source->tnid;
330
      }
331
      else {
332
        // Create new translation set, using nid from the source node.
333
        $tnid = $node->translation_source->nid;
334
        db_update('node')
335
          ->fields(array(
336
            'tnid' => $tnid,
337
            'translate' => 0,
338
          ))
339
          ->condition('nid', $node->translation_source->nid)
340
          ->execute();
341
      }
342
      db_update('node')
343
        ->fields(array(
344
          'tnid' => $tnid,
345
          'translate' => 0,
346
        ))
347
        ->condition('nid', $node->nid)
348
        ->execute();
349
      // Save tnid to avoid loss in case of resave.
350
      $node->tnid = $tnid;
351
    }
352
  }
353
}
354

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

    
383
/**
384
 * Implements hook_node_validate().
385
 *
386
 * Ensures that duplicate translations can't be created for the same source.
387
 */
388
function translation_node_validate($node, $form) {
389
  // Only act on translatable nodes with a tnid or translation_source.
390
  if (translation_supported_type($node->type) && (!empty($node->tnid) || !empty($form['#node']->translation_source->nid))) {
391
    $tnid = !empty($node->tnid) ? $node->tnid : $form['#node']->translation_source->nid;
392
    $translations = translation_node_get_translations($tnid);
393
    $langcode = entity_language('node', $node);
394
    if (isset($translations[$langcode]) && $translations[$langcode]->nid != $node->nid ) {
395
      form_set_error('language', t('There is already a translation in this language.'));
396
    }
397
  }
398
}
399

    
400
/**
401
 * Implements hook_node_delete().
402
 */
403
function translation_node_delete($node) {
404
  // Only act if we are dealing with a content type supporting translations.
405
  if (translation_supported_type($node->type)) {
406
    translation_remove_from_set($node);
407
  }
408
}
409

    
410
/**
411
 * Removes a node from its translation set and updates accordingly.
412
 *
413
 * @param $node
414
 *   A node object.
415
 */
416
function translation_remove_from_set($node) {
417
  if (isset($node->tnid)) {
418
    $query = db_update('node')
419
      ->fields(array(
420
        'tnid' => 0,
421
        'translate' => 0,
422
      ));
423
    if (db_query('SELECT COUNT(*) FROM {node} WHERE tnid = :tnid', array(':tnid' => $node->tnid))->fetchField() == 1) {
424
      // There is only one node left in the set: remove the set altogether.
425
      $query
426
        ->condition('tnid', $node->tnid)
427
        ->execute();
428
    }
429
    else {
430
      $query
431
        ->condition('nid', $node->nid)
432
        ->execute();
433

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

    
447
/**
448
 * Gets all nodes in a given translation set.
449
 *
450
 * @param $tnid
451
 *   The translation source nid of the translation set, the identifier of the
452
 *   node used to derive all translations in the set.
453
 *
454
 * @return
455
 *   Array of partial node objects (nid, title, language) representing all
456
 *   nodes in the translation set, in effect all translations of node $tnid,
457
 *   including node $tnid itself. Because these are partial nodes, you need to
458
 *   node_load() the full node, if you need more properties. The array is
459
 *   indexed by language code.
460
 */
461
function translation_node_get_translations($tnid) {
462
  if (is_numeric($tnid) && $tnid) {
463
    $translations = &drupal_static(__FUNCTION__, array());
464

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

    
473
      foreach ($result as $node) {
474
        $langcode = entity_language('node', $node);
475
        $translations[$tnid][$langcode] = $node;
476
      }
477
    }
478
    return $translations[$tnid];
479
  }
480
}
481

    
482
/**
483
 * Returns whether the given content type has support for translations.
484
 *
485
 * @return
486
 *   TRUE if translation is supported, and FALSE if not.
487
 */
488
function translation_supported_type($type) {
489
  return variable_get('language_content_type_' . $type, 0) == TRANSLATION_ENABLED;
490
}
491

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

    
513
/**
514
 * Implements hook_language_switch_links_alter().
515
 *
516
 * Replaces links with pointers to translated versions of the content.
517
 */
518
function translation_language_switch_links_alter(array &$links, $type, $path) {
519
  $language_type = variable_get('translation_language_type', LANGUAGE_TYPE_INTERFACE);
520

    
521
  if ($type == $language_type && preg_match("!^node/(\d+)(/.+|)!", $path, $matches)) {
522
    $node = node_load((int) $matches[1]);
523

    
524
    if (empty($node->tnid)) {
525
      // If the node cannot be found nothing needs to be done. If it does not
526
      // have translations it might be a language neutral node, in which case we
527
      // must leave the language switch links unaltered. This is true also for
528
      // nodes not having translation support enabled.
529
      if (empty($node) || entity_language('node', $node) == LANGUAGE_NONE || !translation_supported_type($node->type)) {
530
        return;
531
      }
532
      $langcode = entity_language('node', $node);
533
      $translations = array($langcode => $node);
534
    }
535
    else {
536
      $translations = translation_node_get_translations($node->tnid);
537
    }
538

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