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