066193ddab9a34181efc733aa6421b5358739dec
[yaffs-website] / web / core / modules / node / src / Tests / NodeRevisionsTest.php
1 <?php
2
3 namespace Drupal\node\Tests;
4
5 use Drupal\Core\Url;
6 use Drupal\field\Entity\FieldConfig;
7 use Drupal\field\Entity\FieldStorageConfig;
8 use Drupal\language\Entity\ConfigurableLanguage;
9 use Drupal\node\Entity\Node;
10 use Drupal\node\NodeInterface;
11 use Drupal\Component\Serialization\Json;
12
13 /**
14  * Create a node with revisions and test viewing, saving, reverting, and
15  * deleting revisions for users with access for this content type.
16  *
17  * @group node
18  */
19 class NodeRevisionsTest extends NodeTestBase {
20
21   /**
22    * An array of node revisions.
23    *
24    * @var \Drupal\node\NodeInterface[]
25    */
26   protected $nodes;
27
28   /**
29    * Revision log messages.
30    *
31    * @var array
32    */
33   protected $revisionLogs;
34
35   /**
36    * {@inheritdoc}
37    */
38   public static $modules = ['node', 'contextual', 'datetime', 'language', 'content_translation'];
39
40   /**
41    * {@inheritdoc}
42    */
43   protected function setUp() {
44     parent::setUp();
45
46     // Enable additional languages.
47     ConfigurableLanguage::createFromLangcode('de')->save();
48     ConfigurableLanguage::createFromLangcode('it')->save();
49
50     $field_storage_definition = [
51       'field_name' => 'untranslatable_string_field',
52       'entity_type' => 'node',
53       'type' => 'string',
54       'cardinality' => 1,
55       'translatable' => FALSE,
56     ];
57     $field_storage = FieldStorageConfig::create($field_storage_definition);
58     $field_storage->save();
59
60     $field_definition = [
61       'field_storage' => $field_storage,
62       'bundle' => 'page',
63     ];
64     $field = FieldConfig::create($field_definition);
65     $field->save();
66
67     // Enable translation for page nodes.
68     \Drupal::service('content_translation.manager')->setEnabled('node', 'page', TRUE);
69
70     // Create and log in user.
71     $web_user = $this->drupalCreateUser(
72       [
73         'view page revisions',
74         'revert page revisions',
75         'delete page revisions',
76         'edit any page content',
77         'delete any page content',
78         'access contextual links',
79         'translate any entity',
80         'administer content types',
81       ]
82     );
83
84     $this->drupalLogin($web_user);
85
86     // Create initial node.
87     $node = $this->drupalCreateNode();
88     $settings = get_object_vars($node);
89     $settings['revision'] = 1;
90     $settings['isDefaultRevision'] = TRUE;
91
92     $nodes = [];
93     $logs = [];
94
95     // Get original node.
96     $nodes[] = clone $node;
97
98     // Create three revisions.
99     $revision_count = 3;
100     for ($i = 0; $i < $revision_count; $i++) {
101       $logs[] = $node->revision_log = $this->randomMachineName(32);
102
103       // Create revision with a random title and body and update variables.
104       $node->title = $this->randomMachineName();
105       $node->body = [
106         'value' => $this->randomMachineName(32),
107         'format' => filter_default_format(),
108       ];
109       $node->untranslatable_string_field->value = $this->randomString();
110       $node->setNewRevision();
111
112       // Edit the 2nd revision with a different user.
113       if ($i == 1) {
114         $editor = $this->drupalCreateUser();
115         $node->setRevisionUserId($editor->id());
116       }
117       else {
118         $node->setRevisionUserId($web_user->id());
119       }
120
121       $node->save();
122
123       // Make sure we get revision information.
124       $node = Node::load($node->id());
125       $nodes[] = clone $node;
126     }
127
128     $this->nodes = $nodes;
129     $this->revisionLogs = $logs;
130   }
131
132   /**
133    * Checks node revision related operations.
134    */
135   public function testRevisions() {
136     $node_storage = $this->container->get('entity.manager')->getStorage('node');
137     $nodes = $this->nodes;
138     $logs = $this->revisionLogs;
139
140     // Get last node for simple checks.
141     $node = $nodes[3];
142
143     // Confirm the correct revision text appears on "view revisions" page.
144     $this->drupalGet("node/" . $node->id() . "/revisions/" . $node->getRevisionId() . "/view");
145     $this->assertText($node->body->value, 'Correct text displays for version.');
146
147     // Confirm the correct log message appears on "revisions overview" page.
148     $this->drupalGet("node/" . $node->id() . "/revisions");
149     foreach ($logs as $revision_log) {
150       $this->assertText($revision_log, 'Revision log message found.');
151     }
152     // Original author, and editor names should appear on revisions overview.
153     $web_user = $nodes[0]->revision_uid->entity;
154     $this->assertText(t('by @name', ['@name' => $web_user->getAccountName()]));
155     $editor = $nodes[2]->revision_uid->entity;
156     $this->assertText(t('by @name', ['@name' => $editor->getAccountName()]));
157
158     // Confirm that this is the default revision.
159     $this->assertTrue($node->isDefaultRevision(), 'Third node revision is the default one.');
160
161     // Confirm that the "Edit" and "Delete" contextual links appear for the
162     // default revision.
163     $ids = ['node:node=' . $node->id() . ':changed=' . $node->getChangedTime()];
164     $json = $this->renderContextualLinks($ids, 'node/' . $node->id());
165     $this->verbose($json[$ids[0]]);
166
167     $expected = '<li class="entitynodeedit-form"><a href="' . base_path() . 'node/' . $node->id() . '/edit">Edit</a></li>';
168     $this->assertTrue(strstr($json[$ids[0]], $expected), 'The "Edit" contextual link is shown for the default revision.');
169     $expected = '<li class="entitynodedelete-form"><a href="' . base_path() . 'node/' . $node->id() . '/delete">Delete</a></li>';
170     $this->assertTrue(strstr($json[$ids[0]], $expected), 'The "Delete" contextual link is shown for the default revision.');
171
172     // Confirm that revisions revert properly.
173     $this->drupalPostForm("node/" . $node->id() . "/revisions/" . $nodes[1]->getRevisionid() . "/revert", [], t('Revert'));
174     $this->assertRaw(t('@type %title has been reverted to the revision from %revision-date.', [
175       '@type' => 'Basic page',
176       '%title' => $nodes[1]->label(),
177       '%revision-date' => format_date($nodes[1]->getRevisionCreationTime())
178     ]), 'Revision reverted.');
179     $node_storage->resetCache([$node->id()]);
180     $reverted_node = $node_storage->load($node->id());
181     $this->assertTrue(($nodes[1]->body->value == $reverted_node->body->value), 'Node reverted correctly.');
182
183     // Confirm that this is not the default version.
184     $node = node_revision_load($node->getRevisionId());
185     $this->assertFalse($node->isDefaultRevision(), 'Third node revision is not the default one.');
186
187     // Confirm that "Edit" and "Delete" contextual links don't appear for
188     // non-default revision.
189     $ids = ['node_revision::node=' . $node->id() . '&node_revision=' . $node->getRevisionId() . ':'];
190     $json = $this->renderContextualLinks($ids, 'node/' . $node->id() . '/revisions/' . $node->getRevisionId() . '/view');
191     $this->verbose($json[$ids[0]]);
192
193     $this->assertFalse(strstr($json[$ids[0]], '<li class="entitynodeedit-form">'), 'The "Edit" contextual link is not shown for a non-default revision.');
194     $this->assertFalse(strstr($json[$ids[0]], '<li class="entitynodedelete-form">'), 'The "Delete" contextual link is not shown for a non-default revision.');
195
196     // Confirm revisions delete properly.
197     $this->drupalPostForm("node/" . $node->id() . "/revisions/" . $nodes[1]->getRevisionId() . "/delete", [], t('Delete'));
198     $this->assertRaw(t('Revision from %revision-date of @type %title has been deleted.', [
199       '%revision-date' => format_date($nodes[1]->getRevisionCreationTime()),
200       '@type' => 'Basic page',
201       '%title' => $nodes[1]->label(),
202     ]), 'Revision deleted.');
203     $this->assertTrue(db_query('SELECT COUNT(vid) FROM {node_revision} WHERE nid = :nid and vid = :vid', [':nid' => $node->id(), ':vid' => $nodes[1]->getRevisionId()])->fetchField() == 0, 'Revision not found.');
204     $this->assertTrue(db_query('SELECT COUNT(vid) FROM {node_field_revision} WHERE nid = :nid and vid = :vid', [':nid' => $node->id(), ':vid' => $nodes[1]->getRevisionId()])->fetchField() == 0, 'Field revision not found.');
205
206     // Set the revision timestamp to an older date to make sure that the
207     // confirmation message correctly displays the stored revision date.
208     $old_revision_date = REQUEST_TIME - 86400;
209     db_update('node_revision')
210       ->condition('vid', $nodes[2]->getRevisionId())
211       ->fields([
212         'revision_timestamp' => $old_revision_date,
213       ])
214       ->execute();
215     $this->drupalPostForm("node/" . $node->id() . "/revisions/" . $nodes[2]->getRevisionId() . "/revert", [], t('Revert'));
216     $this->assertRaw(t('@type %title has been reverted to the revision from %revision-date.', [
217       '@type' => 'Basic page',
218       '%title' => $nodes[2]->label(),
219       '%revision-date' => format_date($old_revision_date),
220     ]));
221
222     // Make a new revision and set it to not be default.
223     // This will create a new revision that is not "front facing".
224     $new_node_revision = clone $node;
225     $new_body = $this->randomMachineName();
226     $new_node_revision->body->value = $new_body;
227     // Save this as a non-default revision.
228     $new_node_revision->setNewRevision();
229     $new_node_revision->isDefaultRevision = FALSE;
230     $new_node_revision->save();
231
232     $this->drupalGet('node/' . $node->id());
233     $this->assertNoText($new_body, 'Revision body text is not present on default version of node.');
234
235     // Verify that the new body text is present on the revision.
236     $this->drupalGet("node/" . $node->id() . "/revisions/" . $new_node_revision->getRevisionId() . "/view");
237     $this->assertText($new_body, 'Revision body text is present when loading specific revision.');
238
239     // Verify that the non-default revision vid is greater than the default
240     // revision vid.
241     $default_revision = db_select('node', 'n')
242       ->fields('n', ['vid'])
243       ->condition('nid', $node->id())
244       ->execute()
245       ->fetchCol();
246     $default_revision_vid = $default_revision[0];
247     $this->assertTrue($new_node_revision->getRevisionId() > $default_revision_vid, 'Revision vid is greater than default revision vid.');
248
249     // Create an 'EN' node with a revision log message.
250     $node = $this->drupalCreateNode();
251     $node->title = 'Node title in EN';
252     $node->revision_log = 'Simple revision message (EN)';
253     $node->save();
254
255     $this->drupalGet("node/" . $node->id() . "/revisions");
256     $this->assertResponse(403);
257
258     // Create a new revision and new log message.
259     $node = Node::load($node->id());
260     $node->body->value = 'New text (EN)';
261     $node->revision_log = 'New revision message (EN)';
262     $node->setNewRevision();
263     $node->save();
264
265     // Check both revisions are shown on the node revisions overview page.
266     $this->drupalGet("node/" . $node->id() . "/revisions");
267     $this->assertText('Simple revision message (EN)');
268     $this->assertText('New revision message (EN)');
269
270     // Create an 'EN' node with a revision log message.
271     $node = $this->drupalCreateNode();
272     $node->langcode = 'en';
273     $node->title = 'Node title in EN';
274     $node->revision_log = 'Simple revision message (EN)';
275     $node->save();
276
277     $this->drupalGet("node/" . $node->id() . "/revisions");
278     $this->assertResponse(403);
279
280     // Add a translation in 'DE' and create a new revision and new log message.
281     $translation = $node->addTranslation('de');
282     $translation->title->value = 'Node title in DE';
283     $translation->body->value = 'New text (DE)';
284     $translation->revision_log = 'New revision message (DE)';
285     $translation->setNewRevision();
286     $translation->save();
287
288     // View the revision UI in 'IT', only the original node revision is shown.
289     $this->drupalGet("it/node/" . $node->id() . "/revisions");
290     $this->assertText('Simple revision message (EN)');
291     $this->assertNoText('New revision message (DE)');
292
293     // View the revision UI in 'DE', only the translated node revision is shown.
294     $this->drupalGet("de/node/" . $node->id() . "/revisions");
295     $this->assertNoText('Simple revision message (EN)');
296     $this->assertText('New revision message (DE)');
297
298     // View the revision UI in 'EN', only the original node revision is shown.
299     $this->drupalGet("node/" . $node->id() . "/revisions");
300     $this->assertText('Simple revision message (EN)');
301     $this->assertNoText('New revision message (DE)');
302   }
303
304   /**
305    * Checks that revisions are correctly saved without log messages.
306    */
307   public function testNodeRevisionWithoutLogMessage() {
308     $node_storage = $this->container->get('entity.manager')->getStorage('node');
309     // Create a node with an initial log message.
310     $revision_log = $this->randomMachineName(10);
311     $node = $this->drupalCreateNode(['revision_log' => $revision_log]);
312
313     // Save over the same revision and explicitly provide an empty log message
314     // (for example, to mimic the case of a node form submitted with no text in
315     // the "log message" field), and check that the original log message is
316     // preserved.
317     $new_title = $this->randomMachineName(10) . 'testNodeRevisionWithoutLogMessage1';
318
319     $node = clone $node;
320     $node->title = $new_title;
321     $node->revision_log = '';
322     $node->setNewRevision(FALSE);
323
324     $node->save();
325     $this->drupalGet('node/' . $node->id());
326     $this->assertText($new_title, 'New node title appears on the page.');
327     $node_storage->resetCache([$node->id()]);
328     $node_revision = $node_storage->load($node->id());
329     $this->assertEqual($node_revision->revision_log->value, $revision_log, 'After an existing node revision is re-saved without a log message, the original log message is preserved.');
330
331     // Create another node with an initial revision log message.
332     $node = $this->drupalCreateNode(['revision_log' => $revision_log]);
333
334     // Save a new node revision without providing a log message, and check that
335     // this revision has an empty log message.
336     $new_title = $this->randomMachineName(10) . 'testNodeRevisionWithoutLogMessage2';
337
338     $node = clone $node;
339     $node->title = $new_title;
340     $node->setNewRevision();
341     $node->revision_log = NULL;
342
343     $node->save();
344     $this->drupalGet('node/' . $node->id());
345     $this->assertText($new_title, 'New node title appears on the page.');
346     $node_storage->resetCache([$node->id()]);
347     $node_revision = $node_storage->load($node->id());
348     $this->assertTrue(empty($node_revision->revision_log->value), 'After a new node revision is saved with an empty log message, the log message for the node is empty.');
349   }
350
351   /**
352    * Gets server-rendered contextual links for the given contextual links IDs.
353    *
354    * @param string[] $ids
355    *   An array of contextual link IDs.
356    * @param string $current_path
357    *   The Drupal path for the page for which the contextual links are rendered.
358    *
359    * @return string
360    *   The decoded JSON response body.
361    */
362   protected function renderContextualLinks(array $ids, $current_path) {
363     $post = [];
364     for ($i = 0; $i < count($ids); $i++) {
365       $post['ids[' . $i . ']'] = $ids[$i];
366     }
367     $response = $this->drupalPost('contextual/render', 'application/json', $post, ['query' => ['destination' => $current_path]]);
368
369     return Json::decode($response);
370   }
371
372   /**
373    * Tests the revision translations are correctly reverted.
374    */
375   public function testRevisionTranslationRevert() {
376     // Create a node and a few revisions.
377     $node = $this->drupalCreateNode(['langcode' => 'en']);
378
379     $initial_revision_id = $node->getRevisionId();
380     $initial_title = $node->label();
381     $this->createRevisions($node, 2);
382
383     // Translate the node and create a few translation revisions.
384     $translation = $node->addTranslation('it');
385     $this->createRevisions($translation, 3);
386     $revert_id = $node->getRevisionId();
387     $translated_title = $translation->label();
388     $untranslatable_string = $node->untranslatable_string_field->value;
389
390     // Create a new revision for the default translation in-between a series of
391     // translation revisions.
392     $this->createRevisions($node, 1);
393     $default_translation_title = $node->label();
394
395     // And create a few more translation revisions.
396     $this->createRevisions($translation, 2);
397     $translation_revision_id = $translation->getRevisionId();
398
399     // Now revert the a translation revision preceding the last default
400     // translation revision, and check that the desired value was reverted but
401     // the default translation value was preserved.
402     $revert_translation_url = Url::fromRoute('node.revision_revert_translation_confirm', [
403       'node' => $node->id(),
404       'node_revision' => $revert_id,
405       'langcode' => 'it',
406     ]);
407     $this->drupalPostForm($revert_translation_url, [], t('Revert'));
408     /** @var \Drupal\node\NodeStorage $node_storage */
409     $node_storage = $this->container->get('entity.manager')->getStorage('node');
410     $node_storage->resetCache();
411     /** @var \Drupal\node\NodeInterface $node */
412     $node = $node_storage->load($node->id());
413     $this->assertTrue($node->getRevisionId() > $translation_revision_id);
414     $this->assertEqual($node->label(), $default_translation_title);
415     $this->assertEqual($node->getTranslation('it')->label(), $translated_title);
416     $this->assertNotEqual($node->untranslatable_string_field->value, $untranslatable_string);
417
418     $latest_revision_id = $translation->getRevisionId();
419
420     // Now revert the a translation revision preceding the last default
421     // translation revision again, and check that the desired value was reverted
422     // but the default translation value was preserved. But in addition the
423     // untranslated field will be reverted as well.
424     $this->drupalPostForm($revert_translation_url, ['revert_untranslated_fields' => TRUE], t('Revert'));
425     $node_storage->resetCache();
426     /** @var \Drupal\node\NodeInterface $node */
427     $node = $node_storage->load($node->id());
428     $this->assertTrue($node->getRevisionId() > $latest_revision_id);
429     $this->assertEqual($node->label(), $default_translation_title);
430     $this->assertEqual($node->getTranslation('it')->label(), $translated_title);
431     $this->assertEqual($node->untranslatable_string_field->value, $untranslatable_string);
432
433     $latest_revision_id = $translation->getRevisionId();
434
435     // Now revert the entity revision to the initial one where the translation
436     // didn't exist.
437     $revert_url = Url::fromRoute('node.revision_revert_confirm', [
438       'node' => $node->id(),
439       'node_revision' => $initial_revision_id,
440     ]);
441     $this->drupalPostForm($revert_url, [], t('Revert'));
442     $node_storage->resetCache();
443     /** @var \Drupal\node\NodeInterface $node */
444     $node = $node_storage->load($node->id());
445     $this->assertTrue($node->getRevisionId() > $latest_revision_id);
446     $this->assertEqual($node->label(), $initial_title);
447     $this->assertFalse($node->hasTranslation('it'));
448   }
449
450   /**
451    * Creates a series of revisions for the specified node.
452    *
453    * @param \Drupal\node\NodeInterface $node
454    *   The node object.
455    * @param $count
456    *   The number of revisions to be created.
457    */
458   protected function createRevisions(NodeInterface $node, $count) {
459     for ($i = 0; $i < $count; $i++) {
460       $node->title = $this->randomString();
461       $node->untranslatable_string_field->value = $this->randomString();
462       $node->setNewRevision(TRUE);
463       $node->save();
464     }
465   }
466
467 }