diff --git a/core/modules/comment/src/CommentForm.php b/core/modules/comment/src/CommentForm.php index 15d1ece..90987f0 100644 --- a/core/modules/comment/src/CommentForm.php +++ b/core/modules/comment/src/CommentForm.php @@ -323,12 +323,33 @@ protected function getEditedFieldNames(FormStateInterface $form_state) { /** * {@inheritdoc} */ + public function validateForm(array &$form, FormStateInterface $form_state) { + /* @var \Drupal\Core\Entity\ContentEntityInterface $entity */ + $entity = $this->buildEntity($form, $form_state); + + $violations = $entity->validate(); + + if (!isset($form['uid']) || $form['uid']['#access'] == FALSE) { + $form_state->setTemporaryValue('name_violations', $violations->getByField('name')); + } + return parent::validateForm($form, $form_state); + } + + /** + * {@inheritdoc} + */ protected function flagViolations(EntityConstraintViolationListInterface $violations, array $form, FormStateInterface $form_state) { // Manually flag violations of fields not handled by the form display. foreach ($violations->getByField('created') as $violation) { $form_state->setErrorByName('date', $violation->getMessage()); } - foreach ($violations->getByField('name') as $violation) { + if (!$name_violations = $form_state->getTemporaryValue('name_violations')) { + $name_violations = $name_violations->getByField('name'); + } + else { + $form_state->setTemporaryValue('name_violations', NULL); + } + foreach ($name_violations as $violation) { $form_state->setErrorByName('name', $violation->getMessage()); } parent::flagViolations($violations, $form, $form_state); diff --git a/core/modules/comment/src/Tests/CommentAnonymousTest.php b/core/modules/comment/src/Tests/CommentAnonymousTest.php index 60e243b..9049731 100644 --- a/core/modules/comment/src/Tests/CommentAnonymousTest.php +++ b/core/modules/comment/src/Tests/CommentAnonymousTest.php @@ -44,6 +44,16 @@ function testAnonymous() { $anonymous_comment1 = $this->postComment($this->node, $this->randomMachineName(), $this->randomMachineName()); $this->assertTrue($this->commentExists($anonymous_comment1), 'Anonymous comment without contact info found.'); + // Ensure anonymous users cannot post in the name of registered users. + $edit = array( + 'name' => $this->adminUser->getUsername(), + 'comment_body[0][value]' => $this->randomMachineName(), + ); + $this->drupalPostForm('comment/reply/node/' . $this->node->id() . '/comment', $edit, t('Save')); + $this->assertRaw(t('The name you used (%name) belongs to a registered user.', [ + '%name' => $this->adminUser->getUsername(), + ])); + // Allow contact info. $this->drupalLogin($this->adminUser); $this->setCommentAnonymous(COMMENT_ANONYMOUS_MAY_CONTACT);