NodeTranslationUITest.php 18 KB
Newer Older
1
2
3
4
<?php

/**
 * @file
5
 * Contains \Drupal\node\Tests\NodeTranslationUITest.
6
7
8
9
 */

namespace Drupal\node\Tests;

10
use Drupal\Core\Entity\EntityInterface;
11
use Drupal\content_translation\Tests\ContentTranslationUITestBase;
12
use Drupal\Core\Language\LanguageInterface;
13
use Drupal\Core\Url;
14
use Drupal\node\Entity\Node;
15
use Drupal\language\Entity\ConfigurableLanguage;
16
17
18

/**
 * Tests the Node Translation UI.
19
20
 *
 * @group node
21
 */
22
class NodeTranslationUITest extends ContentTranslationUITestBase {
23

24
25
26
27
28
  /**
   * {inheritdoc}
   */
  protected $defaultCacheContexts = [
    'languages:language_interface',
29
    'session',
30
    'theme',
31
    'route',
32
    'timezone',
33
34
    'url.path',
    'url.query_args:_wrapper_format',
35
    'user'
36
37
  ];

38
39
40
41
42
  /**
   * Modules to enable.
   *
   * @var array
   */
43
  public static $modules = array('block', 'language', 'content_translation', 'node', 'datetime', 'field_ui', 'help');
44

45
46
47
48
49
50
51
  /**
   * The profile to install as a basis for testing.
   *
   * @var string
   */
  protected $profile = 'standard';

52
  protected function setUp() {
53
    $this->entityTypeId = 'node';
54
55
    $this->bundle = 'article';
    parent::setUp();
56
57

    // Ensure the help message is shown even with prefixed paths.
58
    $this->drupalPlaceBlock('help_block', array('region' => 'content'));
59

60
61
    // Display the language selector.
    $this->drupalLogin($this->administrator);
62
    $edit = array('language_configuration[language_alterable]' => TRUE);
63
64
    $this->drupalPostForm('admin/structure/types/manage/article', $edit, t('Save content type'));
    $this->drupalLogin($this->translator);
65
66
  }

67
68
69
  /**
   * Tests the basic translation UI.
   */
70
  public function testTranslationUI() {
71
72
73
74
    parent::testTranslationUI();
    $this->doUninstallTest();
  }

75
76
77
  /**
   * Tests changing the published status on a node without fields.
   */
78
  public function testPublishedStatusNoFields() {
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
    // Test changing the published status of an article without fields.
    $this->drupalLogin($this->administrator);
    // Delete all fields.
    $this->drupalGet('admin/structure/types/manage/article/fields');
    $this->drupalPostForm('admin/structure/types/manage/article/fields/node.article.' . $this->fieldName . '/delete', array(), t('Delete'));
    $this->drupalPostForm('admin/structure/types/manage/article/fields/node.article.field_tags/delete', array(), t('Delete'));
    $this->drupalPostForm('admin/structure/types/manage/article/fields/node.article.field_image/delete', array(), t('Delete'));

    // Add a node.
    $default_langcode = $this->langcodes[0];
    $values[$default_langcode] = array('title' => array(array('value' => $this->randomMachineName())));
    $entity_id = $this->createEntity($values[$default_langcode], $default_langcode);
    $entity = entity_load($this->entityTypeId, $entity_id, TRUE);

    // Add a content translation.
    $langcode = 'fr';
    $language = ConfigurableLanguage::load($langcode);
    $values[$langcode] = array('title' => array(array('value' => $this->randomMachineName())));

98
99
    $entity_type_id = $entity->getEntityTypeId();
    $add_url = Url::fromRoute("entity.$entity_type_id.content_translation_add", [
100
101
102
103
104
105
106
107
108
109
110
111
      $entity->getEntityTypeId() => $entity->id(),
      'source' => $default_langcode,
      'target' => $langcode
    ], array('language' => $language));
    $this->drupalPostForm($add_url, $this->getEditValues($values, $langcode), t('Save and unpublish (this translation)'));

    $entity = entity_load($this->entityTypeId, $this->entityId, TRUE);
    $translation = $entity->getTranslation($langcode);
    // Make sure we unpublished the node correctly.
    $this->assertFalse($this->manager->getTranslationMetadata($translation)->isPublished(), 'The translation has been correctly unpublished.');
  }

112
  /**
113
   * {@inheritdoc}
114
   */
115
116
  protected function getTranslatorPermissions() {
    return array_merge(parent::getTranslatorPermissions(), array('administer nodes', "edit any $this->bundle content"));
117
118
  }

119
120
121
122
123
124
125
126
127
128
129
  /**
   * {@inheritdoc}
   */
  protected function getEditorPermissions() {
    return array('administer nodes', 'create article content');
  }

  /**
   * {@inheritdoc}
   */
  protected function getAdministratorPermissions() {
130
    return array_merge(parent::getAdministratorPermissions(), array('access administration pages', 'administer content types', 'administer node fields', 'access content overview', 'bypass node access', 'administer languages', 'administer themes', 'view the administration theme'));
131
132
  }

133
  /**
134
   * {@inheritdoc}
135
136
   */
  protected function getNewEntityValues($langcode) {
137
    return array('title' => array(array('value' => $this->randomMachineName()))) + parent::getNewEntityValues($langcode);
138
139
140
  }

  /**
141
   * {@inheritdoc}
142
   */
143
144
145
146
147
148
  protected function getFormSubmitAction(EntityInterface $entity, $langcode) {
    if ($entity->getTranslation($langcode)->isPublished()) {
      return t('Save and keep published') . $this->getFormSubmitSuffix($entity, $langcode);
    }
    else {
      return t('Save and keep unpublished') . $this->getFormSubmitSuffix($entity, $langcode);
149
    }
150
151
152
  }

  /**
153
   * {@inheritdoc}
154
   */
155
  protected function doTestPublishedStatus() {
156
    $entity = entity_load($this->entityTypeId, $this->entityId, TRUE);
157
    $languages = $this->container->get('language_manager')->getLanguages();
158
159

    $actions = array(
160
161
      t('Save and keep published'),
      t('Save and unpublish'),
162
163
    );

164
    foreach ($actions as $index => $action) {
165
166
167
      // (Un)publish the node translations and check that the translation
      // statuses are (un)published accordingly.
      foreach ($this->langcodes as $langcode) {
168
169
170
        $options = array('language' => $languages[$langcode]);
        $url = $entity->urlInfo('edit-form', $options);
        $this->drupalPostForm($url, array(), $action . $this->getFormSubmitSuffix($entity, $langcode), $options);
171
      }
172
      $entity = entity_load($this->entityTypeId, $this->entityId, TRUE);
173
      foreach ($this->langcodes as $langcode) {
174
        // The node is created as unpublished thus we switch to the published
175
176
        // status first.
        $status = !$index;
177
        $translation = $entity->getTranslation($langcode);
178
        $this->assertEqual($status, $this->manager->getTranslationMetadata($translation)->isPublished(), 'The translation has been correctly unpublished.');
179
180
181
182
183
      }
    }
  }

  /**
184
   * {@inheritdoc}
185
   */
186
  protected function doTestAuthoringInfo() {
187
    $entity = entity_load($this->entityTypeId, $this->entityId, TRUE);
188
    $languages = $this->container->get('language_manager')->getLanguages();
189
190
    $values = array();

191
    // Post different base field information for each translation.
192
    foreach ($this->langcodes as $langcode) {
193
194
      $user = $this->drupalCreateUser();
      $values[$langcode] = array(
195
        'uid' => $user->id(),
196
        'created' => REQUEST_TIME - mt_rand(0, 1000),
197
198
        'sticky' => (bool) mt_rand(0, 1),
        'promote' => (bool) mt_rand(0, 1),
199
200
      );
      $edit = array(
201
202
203
204
205
        'uid[0][target_id]' => $user->getUsername(),
        'created[0][value][date]' => format_date($values[$langcode]['created'], 'custom', 'Y-m-d'),
        'created[0][value][time]' => format_date($values[$langcode]['created'], 'custom', 'H:i:s'),
        'sticky[value]' => $values[$langcode]['sticky'],
        'promote[value]' => $values[$langcode]['promote'],
206
      );
207
208
209
      $options = array('language' => $languages[$langcode]);
      $url = $entity->urlInfo('edit-form', $options);
      $this->drupalPostForm($url, $edit, $this->getFormSubmitAction($entity, $langcode), $options);
210
211
    }

212
    $entity = entity_load($this->entityTypeId, $this->entityId, TRUE);
213
    foreach ($this->langcodes as $langcode) {
214
      $translation = $entity->getTranslation($langcode);
215
216
217
      $metadata = $this->manager->getTranslationMetadata($translation);
      $this->assertEqual($metadata->getAuthor()->id(), $values[$langcode]['uid'], 'Translation author correctly stored.');
      $this->assertEqual($metadata->getCreatedTime(), $values[$langcode]['created'], 'Translation date correctly stored.');
218
219
      $this->assertEqual($translation->isSticky(), $values[$langcode]['sticky'], 'Sticky of Translation correctly stored.');
      $this->assertEqual($translation->isPromoted(), $values[$langcode]['promote'], 'Promoted of Translation correctly stored.');
220
    }
221
222
  }

223
224
225
  /**
   * Tests that translation page inherits admin status of edit page.
   */
226
  public function testTranslationLinkTheme() {
227
228
229
230
    $this->drupalLogin($this->administrator);
    $article = $this->drupalCreateNode(array('type' => 'article', 'langcode' => $this->langcodes[0]));

    // Set up Seven as the admin theme and use it for node editing.
231
    $this->container->get('theme_handler')->install(array('seven'));
232
233
234
235
236
    $edit = array();
    $edit['admin_theme'] = 'seven';
    $edit['use_admin_theme'] = TRUE;
    $this->drupalPostForm('admin/appearance', $edit, t('Save configuration'));
    $this->drupalGet('node/' . $article->id() . '/translations');
237
    $this->assertRaw('core/themes/seven/css/base/elements.css', 'Translation uses admin theme if edit is admin.');
238
239
240
241
242

    // Turn off admin theme for editing, assert inheritance to translations.
    $edit['use_admin_theme'] = FALSE;
    $this->drupalPostForm('admin/appearance', $edit, t('Save configuration'));
    $this->drupalGet('node/' . $article->id() . '/translations');
243
    $this->assertNoRaw('core/themes/seven/css/base/elements.css', 'Translation uses frontend theme if edit is frontend.');
244
245
246

    // Assert presence of translation page itself (vs. DisabledBundle below).
    $this->assertResponse(200);
247
248
  }

249
  /**
250
   * Tests that no metadata is stored for a disabled bundle.
251
252
253
   */
  public function testDisabledBundle() {
    // Create a bundle that does not have translation enabled.
254
    $disabledBundle = $this->randomMachineName();
255
256
257
    $this->drupalCreateContentType(array('type' => $disabledBundle, 'name' => $disabledBundle));

    // Create a node for each bundle.
258
259
260
261
    $node = $this->drupalCreateNode(array(
      'type' => $this->bundle,
      'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED,
    ));
262

263
    // Make sure that nothing was inserted into the {content_translation} table.
264
    $rows = db_query('SELECT nid, count(nid) AS count FROM {node_field_data} WHERE type <> :type GROUP BY nid HAVING count(nid) >= 2', array(':type' => $this->bundle))->fetchAll();
265
266
267
268
269
    $this->assertEqual(0, count($rows));

    // Ensure the translation tab is not accessible.
    $this->drupalGet('node/' . $node->id() . '/translations');
    $this->assertResponse(403);
270
271
  }

272
273
274
  /**
   * Tests that translations are rendered properly.
   */
275
  public function testTranslationRendering() {
276
277
278
    $default_langcode = $this->langcodes[0];
    $values[$default_langcode] = $this->getNewEntityValues($default_langcode);
    $this->entityId = $this->createEntity($values[$default_langcode], $default_langcode);
279
    $node = \Drupal::entityManager()->getStorage($this->entityTypeId)->load($this->entityId);
280
281
282
283
284
285
    $node->setPromoted(TRUE);

    // Create translations.
    foreach (array_diff($this->langcodes, array($default_langcode)) as $langcode) {
      $values[$langcode] = $this->getNewEntityValues($langcode);
      $translation = $node->addTranslation($langcode, $values[$langcode]);
286
      // Publish and promote the translation to frontpage.
287
      $translation->setPromoted(TRUE);
288
      $translation->setPublished(TRUE);
289
290
291
292
    }
    $node->save();

    // Test that the frontpage view displays the correct translations.
293
    \Drupal::service('module_installer')->install(array('views'), TRUE);
294
295
296
    $this->rebuildContainer();
    $this->doTestTranslations('node', $values);

297
    // Enable the translation language renderer.
298
    $view = \Drupal::entityManager()->getStorage('view')->load('frontpage');
299
    $display = &$view->getDisplay('default');
300
    $display['display_options']['rendering_language'] = '***LANGUAGE_entity_translation***';
301
302
    $view->save();

303
304
305
306
307
308
309
310
311
    // Need to check from the beginning, including the base_path, in the url
    // since the pattern for the default language might be a substring of
    // the strings for other languages.
    $base_path = base_path();

    // Check the frontpage for 'Read more' links to each translation.
    // See also assertTaxonomyPage() in NodeAccessBaseTableTest.
    $node_href = 'node/' . $node->id();
    foreach ($this->langcodes as $langcode) {
312
      $this->drupalGet('node', array('language' => \Drupal::languageManager()->getLanguage($langcode)));
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
      $num_match_found = 0;
      if ($langcode == 'en') {
        // Site default language does not have langcode prefix in the URL.
        $expected_href = $base_path . $node_href;
      }
      else {
        $expected_href = $base_path . $langcode . '/' . $node_href;
      }
      $pattern = '|^' . $expected_href . '$|';
      foreach ($this->xpath("//a[text()='Read more']") as $link) {
        if (preg_match($pattern, (string) $link['href'], $matches) == TRUE) {
          $num_match_found++;
        }
      }
      $this->assertTrue($num_match_found == 1, 'There is 1 Read more link, ' . $expected_href . ', for the ' . $langcode . ' translation of a node on the frontpage. (Found ' . $num_match_found . '.)');
    }

    // Check the frontpage for 'Add new comment' links that include the
    // language.
    $comment_form_href = 'node/' . $node->id() . '#comment-form';
    foreach ($this->langcodes as $langcode) {
334
      $this->drupalGet('node', array('language' => \Drupal::languageManager()->getLanguage($langcode)));
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
      $num_match_found = 0;
      if ($langcode == 'en') {
        // Site default language does not have langcode prefix in the URL.
        $expected_href = $base_path . $comment_form_href;
      }
      else {
        $expected_href = $base_path . $langcode . '/' . $comment_form_href;
      }
      $pattern = '|^' . $expected_href . '$|';
      foreach ($this->xpath("//a[text()='Add new comment']") as $link) {
        if (preg_match($pattern, (string) $link['href'], $matches) == TRUE) {
          $num_match_found++;
        }
      }
      $this->assertTrue($num_match_found == 1, 'There is 1 Add new comment link, ' . $expected_href . ', for the ' . $langcode . ' translation of a node on the frontpage. (Found ' . $num_match_found . '.)');
    }

352
353
    // Test that the node page displays the correct translations.
    $this->doTestTranslations('node/' . $node->id(), $values);
354
355

    // Test that the node page has the correct alternate hreflang links.
356
    $this->doTestAlternateHreflangLinks($node->urlInfo());
357
358
359
  }

  /**
360
   * Tests that the given path displays the correct translation values.
361
362
363
364
365
366
367
   *
   * @param string $path
   *   The path to be tested.
   * @param array $values
   *   The translation values to be found.
   */
  protected function doTestTranslations($path, array $values) {
368
    $languages = $this->container->get('language_manager')->getLanguages();
369
370
    foreach ($this->langcodes as $langcode) {
      $this->drupalGet($path, array('language' => $languages[$langcode]));
371
      $this->assertText($values[$langcode]['title'][0]['value'], format_string('The %langcode node translation is correctly displayed.', array('%langcode' => $langcode)));
372
373
374
    }
  }

375
  /**
376
   * Tests that the given path provides the correct alternate hreflang links.
377
   *
378
379
   * @param \Drupal\Core\Url $url
   *   The path to be tested.
380
   */
381
  protected function doTestAlternateHreflangLinks(Url $url) {
382
    $languages = $this->container->get('language_manager')->getLanguages();
383
384
    $url->setAbsolute();
    $urls = [];
385
    foreach ($this->langcodes as $langcode) {
386
387
      $language_url = clone $url;
      $urls[$langcode] = $language_url->setOption('language', $languages[$langcode]);
388
389
    }
    foreach ($this->langcodes as $langcode) {
390
391
392
393
394
395
      $this->drupalGet($urls[$langcode]);
      foreach ($urls as $alternate_langcode => $language_url) {
        // Retrieve desired link elements from the HTML head.
        $links = $this->xpath('head/link[@rel = "alternate" and @href = :href and @hreflang = :hreflang]',
          array(':href' => $language_url->toString(), ':hreflang' => $alternate_langcode));
        $this->assert(isset($links[0]), format_string('The %langcode node translation has the correct alternate hreflang link for %alternate_langcode: %link.', array('%langcode' => $langcode, '%alternate_langcode' => $alternate_langcode, '%link' => $url->toString())));
396
397
398
399
      }
    }
  }

400
401
402
403
404
405
406
407
408
409
410
411
  /**
   * {@inheritdoc}
   */
  protected function getFormSubmitSuffix(EntityInterface $entity, $langcode) {
    if (!$entity->isNew() && $entity->isTranslatable()) {
      $translations = $entity->getTranslationLanguages();
      if ((count($translations) > 1 || !isset($translations[$langcode])) && ($field = $entity->getFieldDefinition('status'))) {
        return ' ' . ($field->isTranslatable() ? t('(this translation)') : t('(all translations)'));
      }
    }
    return '';
  }
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427

  /**
   * Tests uninstalling content_translation.
   */
  protected function doUninstallTest() {
    // Delete all the nodes so there is no data.
    $nodes = Node::loadMultiple();
    foreach ($nodes as $node) {
      $node->delete();
    }
    $language_count = count(\Drupal::configFactory()->listAll('language.content_settings.'));
    \Drupal::service('module_installer')->uninstall(['content_translation']);
    $this->rebuildContainer();
    $this->assertEqual($language_count, count(\Drupal::configFactory()->listAll('language.content_settings.')), 'Languages have been fixed rather than deleted during content_translation uninstall.');
  }

428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
  /**
   * {@inheritdoc}
   */
  protected function doTestTranslationEdit() {
    $entity = entity_load($this->entityTypeId, $this->entityId, TRUE);
    $languages = $this->container->get('language_manager')->getLanguages();
    $type_name = node_get_type_label($entity);

    foreach ($this->langcodes as $langcode) {
      // We only want to test the title for non-english translations.
      if ($langcode != 'en') {
        $options = array('language' => $languages[$langcode]);
        $url = $entity->urlInfo('edit-form', $options);
        $this->drupalGet($url);

        $title = t('<em>Edit @type</em> @title [%language translation]', array(
          '@type' => $type_name,
          '@title' => $entity->getTranslation($langcode)->label(),
          '%language' => $languages[$langcode]->getName(),
        ));
        $this->assertRaw($title);
      }
    }
  }

453
}