3 namespace Drupal\comment;
5 use Drupal\comment\Plugin\Field\FieldType\CommentItemInterface;
6 use Drupal\Component\Datetime\TimeInterface;
7 use Drupal\Component\Utility\Html;
8 use Drupal\Component\Utility\Unicode;
9 use Drupal\Core\Datetime\DrupalDateTime;
10 use Drupal\Core\Entity\ContentEntityForm;
11 use Drupal\Core\Entity\EntityConstraintViolationListInterface;
12 use Drupal\Core\Entity\EntityManagerInterface;
13 use Drupal\Core\Entity\EntityTypeBundleInfoInterface;
14 use Drupal\Core\Form\FormStateInterface;
15 use Drupal\Core\Render\RendererInterface;
16 use Drupal\Core\Session\AccountInterface;
17 use Symfony\Component\DependencyInjection\ContainerInterface;
20 * Base handler for comment forms.
24 class CommentForm extends ContentEntityForm {
29 * @var \Drupal\Core\Session\AccountInterface
31 protected $currentUser;
36 * @var \Drupal\Core\Render\RendererInterface
43 public static function create(ContainerInterface $container) {
45 $container->get('entity.manager'),
46 $container->get('current_user'),
47 $container->get('renderer'),
48 $container->get('entity_type.bundle.info'),
49 $container->get('datetime.time')
54 * Constructs a new CommentForm.
56 * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
57 * The entity manager service.
58 * @param \Drupal\Core\Session\AccountInterface $current_user
60 * @param \Drupal\Core\Render\RendererInterface $renderer
62 * @param \Drupal\Core\Entity\EntityTypeBundleInfoInterface $entity_type_bundle_info
63 * The entity type bundle service.
64 * @param \Drupal\Component\Datetime\TimeInterface $time
67 public function __construct(EntityManagerInterface $entity_manager, AccountInterface $current_user, RendererInterface $renderer, EntityTypeBundleInfoInterface $entity_type_bundle_info = NULL, TimeInterface $time = NULL) {
68 parent::__construct($entity_manager, $entity_type_bundle_info, $time);
69 $this->currentUser = $current_user;
70 $this->renderer = $renderer;
76 public function form(array $form, FormStateInterface $form_state) {
77 /** @var \Drupal\comment\CommentInterface $comment */
78 $comment = $this->entity;
79 $entity = $this->entityManager->getStorage($comment->getCommentedEntityTypeId())->load($comment->getCommentedEntityId());
80 $field_name = $comment->getFieldName();
81 $field_definition = $this->entityManager->getFieldDefinitions($entity->getEntityTypeId(), $entity->bundle())[$comment->getFieldName()];
82 $config = $this->config('user.settings');
84 // In several places within this function, we vary $form on:
85 // - The current user's permissions.
86 // - Whether the current user is authenticated or anonymous.
87 // - The 'user.settings' configuration.
88 // - The comment field's definition.
89 $form['#cache']['contexts'][] = 'user.permissions';
90 $form['#cache']['contexts'][] = 'user.roles:authenticated';
91 $this->renderer->addCacheableDependency($form, $config);
92 $this->renderer->addCacheableDependency($form, $field_definition->getConfig($entity->bundle()));
94 // Use #comment-form as unique jump target, regardless of entity type.
95 $form['#id'] = Html::getUniqueId('comment_form');
96 $form['#theme'] = ['comment_form__' . $entity->getEntityTypeId() . '__' . $entity->bundle() . '__' . $field_name, 'comment_form'];
98 $anonymous_contact = $field_definition->getSetting('anonymous');
99 $is_admin = $comment->id() && $this->currentUser->hasPermission('administer comments');
101 if (!$this->currentUser->isAuthenticated() && $anonymous_contact != COMMENT_ANONYMOUS_MAYNOT_CONTACT) {
102 $form['#attached']['library'][] = 'core/drupal.form';
103 $form['#attributes']['data-user-info-from-browser'] = TRUE;
106 // If not replying to a comment, use our dedicated page callback for new
107 // Comments on entities.
108 if (!$comment->id() && !$comment->hasParentComment()) {
109 $form['#action'] = $this->url('comment.reply', ['entity_type' => $entity->getEntityTypeId(), 'entity' => $entity->id(), 'field_name' => $field_name]);
112 $comment_preview = $form_state->get('comment_preview');
113 if (isset($comment_preview)) {
114 $form += $comment_preview;
117 $form['author'] = [];
118 // Display author information in a details element for comment moderators.
121 '#type' => 'details',
122 '#title' => $this->t('Administration'),
126 // Prepare default values for form elements.
129 if (!$comment->getOwnerId()) {
130 $author = $comment->getAuthorName();
132 $status = $comment->getStatus();
133 if (empty($comment_preview)) {
134 $form['#title'] = $this->t('Edit comment %title', [
135 '%title' => $comment->getSubject(),
140 $status = ($this->currentUser->hasPermission('skip comment approval') ? CommentInterface::PUBLISHED : CommentInterface::NOT_PUBLISHED);
144 if ($comment->id()) {
145 $date = !empty($comment->date) ? $comment->date : DrupalDateTime::createFromTimestamp($comment->getCreatedTime());
148 // The uid field is only displayed when a user with the permission
149 // 'administer comments' is editing an existing comment from an
150 // authenticated user.
151 $owner = $comment->getOwner();
152 $form['author']['uid'] = [
153 '#type' => 'entity_autocomplete',
154 '#target_type' => 'user',
155 '#default_value' => $owner->isAnonymous() ? NULL : $owner,
156 // A comment can be made anonymous by leaving this field empty therefore
157 // there is no need to list them in the autocomplete.
158 '#selection_settings' => ['include_anonymous' => FALSE],
159 '#title' => $this->t('Authored by'),
160 '#description' => $this->t('Leave blank for %anonymous.', ['%anonymous' => $config->get('anonymous')]),
161 '#access' => $is_admin,
164 // The name field is displayed when an anonymous user is adding a comment or
165 // when a user with the permission 'administer comments' is editing an
166 // existing comment from an anonymous user.
167 $form['author']['name'] = [
168 '#type' => 'textfield',
169 '#title' => $is_admin ? $this->t('Name for @anonymous', ['@anonymous' => $config->get('anonymous')]) : $this->t('Your name'),
170 '#default_value' => $author,
171 '#required' => ($this->currentUser->isAnonymous() && $anonymous_contact == COMMENT_ANONYMOUS_MUST_CONTACT),
173 '#access' => $this->currentUser->isAnonymous() || $is_admin,
176 'data-drupal-default-value' => $config->get('anonymous'),
181 // When editing a comment only display the name textfield if the uid field
183 $form['author']['name']['#states'] = [
185 ':input[name="uid"]' => ['empty' => TRUE],
190 // Add author email and homepage fields depending on the current user.
191 $form['author']['mail'] = [
193 '#title' => $this->t('Email'),
194 '#default_value' => $comment->getAuthorEmail(),
195 '#required' => ($this->currentUser->isAnonymous() && $anonymous_contact == COMMENT_ANONYMOUS_MUST_CONTACT),
198 '#description' => $this->t('The content of this field is kept private and will not be shown publicly.'),
199 '#access' => ($comment->getOwner()->isAnonymous() && $is_admin) || ($this->currentUser->isAnonymous() && $anonymous_contact != COMMENT_ANONYMOUS_MAYNOT_CONTACT),
202 $form['author']['homepage'] = [
204 '#title' => $this->t('Homepage'),
205 '#default_value' => $comment->getHomepage(),
208 '#access' => $is_admin || ($this->currentUser->isAnonymous() && $anonymous_contact != COMMENT_ANONYMOUS_MAYNOT_CONTACT),
211 // Add administrative comment publishing options.
212 $form['author']['date'] = [
213 '#type' => 'datetime',
214 '#title' => $this->t('Authored on'),
215 '#default_value' => $date,
217 '#access' => $is_admin,
220 $form['author']['status'] = [
222 '#title' => $this->t('Status'),
223 '#default_value' => $status,
225 CommentInterface::PUBLISHED => $this->t('Published'),
226 CommentInterface::NOT_PUBLISHED => $this->t('Not published'),
228 '#access' => $is_admin,
231 return parent::form($form, $form_state, $comment);
237 protected function actions(array $form, FormStateInterface $form_state) {
238 $element = parent::actions($form, $form_state);
239 /* @var \Drupal\comment\CommentInterface $comment */
240 $comment = $this->entity;
241 $entity = $comment->getCommentedEntity();
242 $field_definition = $this->entityManager->getFieldDefinitions($entity->getEntityTypeId(), $entity->bundle())[$comment->getFieldName()];
243 $preview_mode = $field_definition->getSetting('preview');
245 // No delete action on the comment form.
246 unset($element['delete']);
248 // Mark the submit action as the primary action, when it appears.
249 $element['submit']['#button_type'] = 'primary';
251 // Only show the save button if comment previews are optional or if we are
252 // already previewing the submission.
253 $element['submit']['#access'] = ($comment->id() && $this->currentUser->hasPermission('administer comments')) || $preview_mode != DRUPAL_REQUIRED || $form_state->get('comment_preview');
255 $element['preview'] = [
257 '#value' => $this->t('Preview'),
258 '#access' => $preview_mode != DRUPAL_DISABLED,
259 '#submit' => ['::submitForm', '::preview'],
268 public function buildEntity(array $form, FormStateInterface $form_state) {
269 /** @var \Drupal\comment\CommentInterface $comment */
270 $comment = parent::buildEntity($form, $form_state);
271 if (!$form_state->isValueEmpty('date') && $form_state->getValue('date') instanceof DrupalDateTime) {
272 $comment->setCreatedTime($form_state->getValue('date')->getTimestamp());
275 $comment->setCreatedTime(REQUEST_TIME);
277 // Empty author ID should revert to anonymous.
278 $author_id = $form_state->getValue('uid');
279 if ($comment->id() && $this->currentUser->hasPermission('administer comments')) {
280 // Admin can leave the author ID blank to revert to anonymous.
281 $author_id = $author_id ?: 0;
283 if (!is_null($author_id)) {
284 if ($author_id === 0 && $form['author']['name']['#access']) {
285 // Use the author name value when the form has access to the element and
286 // the author ID is anonymous.
287 $comment->setAuthorName($form_state->getValue('name'));
290 // Ensure the author name is not set.
291 $comment->setAuthorName(NULL);
295 $author_id = $this->currentUser->id();
297 $comment->setOwnerId($author_id);
299 // Validate the comment's subject. If not specified, extract from comment
301 if (trim($comment->getSubject()) == '') {
302 if ($comment->hasField('comment_body')) {
303 // The body may be in any format, so:
304 // 1) Filter it into HTML
305 // 2) Strip out all HTML tags
306 // 3) Convert entities back to plain-text.
307 $comment_text = $comment->comment_body->processed;
308 $comment->setSubject(Unicode::truncate(trim(Html::decodeEntities(strip_tags($comment_text))), 29, TRUE, TRUE));
310 // Edge cases where the comment body is populated only by HTML tags will
311 // require a default subject.
312 if ($comment->getSubject() == '') {
313 $comment->setSubject($this->t('(No subject)'));
322 protected function getEditedFieldNames(FormStateInterface $form_state) {
323 return array_merge(['created', 'name'], parent::getEditedFieldNames($form_state));
329 protected function flagViolations(EntityConstraintViolationListInterface $violations, array $form, FormStateInterface $form_state) {
330 // Manually flag violations of fields not handled by the form display.
331 foreach ($violations->getByField('created') as $violation) {
332 $form_state->setErrorByName('date', $violation->getMessage());
334 foreach ($violations->getByField('name') as $violation) {
335 $form_state->setErrorByName('name', $violation->getMessage());
337 parent::flagViolations($violations, $form, $form_state);
341 * Form submission handler for the 'preview' action.
344 * An associative array containing the structure of the form.
345 * @param \Drupal\Core\Form\FormStateInterface $form_state
346 * The current state of the form.
348 public function preview(array &$form, FormStateInterface $form_state) {
349 $comment_preview = comment_preview($this->entity, $form_state);
350 $comment_preview['#title'] = $this->t('Preview comment');
351 $form_state->set('comment_preview', $comment_preview);
352 $form_state->setRebuild();
358 public function save(array $form, FormStateInterface $form_state) {
359 $comment = $this->entity;
360 $entity = $comment->getCommentedEntity();
361 $field_name = $comment->getFieldName();
362 $uri = $entity->urlInfo();
363 $logger = $this->logger('comment');
365 if ($this->currentUser->hasPermission('post comments') && ($this->currentUser->hasPermission('administer comments') || $entity->{$field_name}->status == CommentItemInterface::OPEN)) {
367 $form_state->setValue('cid', $comment->id());
370 $logger->notice('Comment posted: %subject.', [
371 '%subject' => $comment->getSubject(),
372 'link' => $this->l(t('View'), $comment->urlInfo()->setOption('fragment', 'comment-' . $comment->id()))
375 // Explain the approval queue if necessary.
376 if (!$comment->isPublished()) {
377 if (!$this->currentUser->hasPermission('administer comments')) {
378 drupal_set_message($this->t('Your comment has been queued for review by site administrators and will be published after approval.'));
382 drupal_set_message($this->t('Your comment has been posted.'));
385 // Find the current display page for this comment.
386 $field_definition = $this->entityManager->getFieldDefinitions($entity->getEntityTypeId(), $entity->bundle())[$field_name];
387 $page = $this->entityManager->getStorage('comment')->getDisplayOrdinal($comment, $field_definition->getSetting('default_mode'), $field_definition->getSetting('per_page'));
389 $query['page'] = $page;
391 // Redirect to the newly posted comment.
392 $uri->setOption('query', $query);
393 $uri->setOption('fragment', 'comment-' . $comment->id());
396 $logger->warning('Comment: unauthorized comment submitted or comment submitted to a closed post %subject.', ['%subject' => $comment->getSubject()]);
397 drupal_set_message($this->t('Comment: unauthorized comment submitted or comment submitted to a closed post %subject.', ['%subject' => $comment->getSubject()]), 'error');
398 // Redirect the user to the entity they are commenting on.
400 $form_state->setRedirectUrl($uri);