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.
22 class CommentForm extends ContentEntityForm {
27 * @var \Drupal\Core\Session\AccountInterface
29 protected $currentUser;
34 * @var \Drupal\Core\Render\RendererInterface
41 public static function create(ContainerInterface $container) {
43 $container->get('entity.manager'),
44 $container->get('current_user'),
45 $container->get('renderer'),
46 $container->get('entity_type.bundle.info'),
47 $container->get('datetime.time')
52 * Constructs a new CommentForm.
54 * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
55 * The entity manager service.
56 * @param \Drupal\Core\Session\AccountInterface $current_user
58 * @param \Drupal\Core\Render\RendererInterface $renderer
60 * @param \Drupal\Core\Entity\EntityTypeBundleInfoInterface $entity_type_bundle_info
61 * The entity type bundle service.
62 * @param \Drupal\Component\Datetime\TimeInterface $time
65 public function __construct(EntityManagerInterface $entity_manager, AccountInterface $current_user, RendererInterface $renderer, EntityTypeBundleInfoInterface $entity_type_bundle_info = NULL, TimeInterface $time = NULL) {
66 parent::__construct($entity_manager, $entity_type_bundle_info, $time);
67 $this->currentUser = $current_user;
68 $this->renderer = $renderer;
74 public function form(array $form, FormStateInterface $form_state) {
75 /** @var \Drupal\comment\CommentInterface $comment */
76 $comment = $this->entity;
77 $entity = $this->entityManager->getStorage($comment->getCommentedEntityTypeId())->load($comment->getCommentedEntityId());
78 $field_name = $comment->getFieldName();
79 $field_definition = $this->entityManager->getFieldDefinitions($entity->getEntityTypeId(), $entity->bundle())[$comment->getFieldName()];
80 $config = $this->config('user.settings');
82 // In several places within this function, we vary $form on:
83 // - The current user's permissions.
84 // - Whether the current user is authenticated or anonymous.
85 // - The 'user.settings' configuration.
86 // - The comment field's definition.
87 $form['#cache']['contexts'][] = 'user.permissions';
88 $form['#cache']['contexts'][] = 'user.roles:authenticated';
89 $this->renderer->addCacheableDependency($form, $config);
90 $this->renderer->addCacheableDependency($form, $field_definition->getConfig($entity->bundle()));
92 // Use #comment-form as unique jump target, regardless of entity type.
93 $form['#id'] = Html::getUniqueId('comment_form');
94 $form['#theme'] = ['comment_form__' . $entity->getEntityTypeId() . '__' . $entity->bundle() . '__' . $field_name, 'comment_form'];
96 $anonymous_contact = $field_definition->getSetting('anonymous');
97 $is_admin = $comment->id() && $this->currentUser->hasPermission('administer comments');
99 if (!$this->currentUser->isAuthenticated() && $anonymous_contact != COMMENT_ANONYMOUS_MAYNOT_CONTACT) {
100 $form['#attached']['library'][] = 'core/drupal.form';
101 $form['#attributes']['data-user-info-from-browser'] = TRUE;
104 // If not replying to a comment, use our dedicated page callback for new
105 // Comments on entities.
106 if (!$comment->id() && !$comment->hasParentComment()) {
107 $form['#action'] = $this->url('comment.reply', ['entity_type' => $entity->getEntityTypeId(), 'entity' => $entity->id(), 'field_name' => $field_name]);
110 $comment_preview = $form_state->get('comment_preview');
111 if (isset($comment_preview)) {
112 $form += $comment_preview;
115 $form['author'] = [];
116 // Display author information in a details element for comment moderators.
119 '#type' => 'details',
120 '#title' => $this->t('Administration'),
124 // Prepare default values for form elements.
127 if (!$comment->getOwnerId()) {
128 $author = $comment->getAuthorName();
130 $status = $comment->getStatus();
131 if (empty($comment_preview)) {
132 $form['#title'] = $this->t('Edit comment %title', [
133 '%title' => $comment->getSubject(),
138 $status = ($this->currentUser->hasPermission('skip comment approval') ? CommentInterface::PUBLISHED : CommentInterface::NOT_PUBLISHED);
142 if ($comment->id()) {
143 $date = !empty($comment->date) ? $comment->date : DrupalDateTime::createFromTimestamp($comment->getCreatedTime());
146 // The uid field is only displayed when a user with the permission
147 // 'administer comments' is editing an existing comment from an
148 // authenticated user.
149 $owner = $comment->getOwner();
150 $form['author']['uid'] = [
151 '#type' => 'entity_autocomplete',
152 '#target_type' => 'user',
153 '#default_value' => $owner->isAnonymous() ? NULL : $owner,
154 // A comment can be made anonymous by leaving this field empty therefore
155 // there is no need to list them in the autocomplete.
156 '#selection_settings' => ['include_anonymous' => FALSE],
157 '#title' => $this->t('Authored by'),
158 '#description' => $this->t('Leave blank for %anonymous.', ['%anonymous' => $config->get('anonymous')]),
159 '#access' => $is_admin,
162 // The name field is displayed when an anonymous user is adding a comment or
163 // when a user with the permission 'administer comments' is editing an
164 // existing comment from an anonymous user.
165 $form['author']['name'] = [
166 '#type' => 'textfield',
167 '#title' => $is_admin ? $this->t('Name for @anonymous', ['@anonymous' => $config->get('anonymous')]) : $this->t('Your name'),
168 '#default_value' => $author,
169 '#required' => ($this->currentUser->isAnonymous() && $anonymous_contact == COMMENT_ANONYMOUS_MUST_CONTACT),
171 '#access' => $this->currentUser->isAnonymous() || $is_admin,
174 'data-drupal-default-value' => $config->get('anonymous'),
179 // When editing a comment only display the name textfield if the uid field
181 $form['author']['name']['#states'] = [
183 ':input[name="uid"]' => ['empty' => TRUE],
188 // Add author email and homepage fields depending on the current user.
189 $form['author']['mail'] = [
191 '#title' => $this->t('Email'),
192 '#default_value' => $comment->getAuthorEmail(),
193 '#required' => ($this->currentUser->isAnonymous() && $anonymous_contact == COMMENT_ANONYMOUS_MUST_CONTACT),
196 '#description' => $this->t('The content of this field is kept private and will not be shown publicly.'),
197 '#access' => ($comment->getOwner()->isAnonymous() && $is_admin) || ($this->currentUser->isAnonymous() && $anonymous_contact != COMMENT_ANONYMOUS_MAYNOT_CONTACT),
200 $form['author']['homepage'] = [
202 '#title' => $this->t('Homepage'),
203 '#default_value' => $comment->getHomepage(),
206 '#access' => $is_admin || ($this->currentUser->isAnonymous() && $anonymous_contact != COMMENT_ANONYMOUS_MAYNOT_CONTACT),
209 // Add administrative comment publishing options.
210 $form['author']['date'] = [
211 '#type' => 'datetime',
212 '#title' => $this->t('Authored on'),
213 '#default_value' => $date,
215 '#access' => $is_admin,
218 $form['author']['status'] = [
220 '#title' => $this->t('Status'),
221 '#default_value' => $status,
223 CommentInterface::PUBLISHED => $this->t('Published'),
224 CommentInterface::NOT_PUBLISHED => $this->t('Not published'),
226 '#access' => $is_admin,
229 return parent::form($form, $form_state, $comment);
235 protected function actions(array $form, FormStateInterface $form_state) {
236 $element = parent::actions($form, $form_state);
237 /* @var \Drupal\comment\CommentInterface $comment */
238 $comment = $this->entity;
239 $entity = $comment->getCommentedEntity();
240 $field_definition = $this->entityManager->getFieldDefinitions($entity->getEntityTypeId(), $entity->bundle())[$comment->getFieldName()];
241 $preview_mode = $field_definition->getSetting('preview');
243 // No delete action on the comment form.
244 unset($element['delete']);
246 // Mark the submit action as the primary action, when it appears.
247 $element['submit']['#button_type'] = 'primary';
249 // Only show the save button if comment previews are optional or if we are
250 // already previewing the submission.
251 $element['submit']['#access'] = ($comment->id() && $this->currentUser->hasPermission('administer comments')) || $preview_mode != DRUPAL_REQUIRED || $form_state->get('comment_preview');
253 $element['preview'] = [
255 '#value' => $this->t('Preview'),
256 '#access' => $preview_mode != DRUPAL_DISABLED,
257 '#submit' => ['::submitForm', '::preview'],
266 public function buildEntity(array $form, FormStateInterface $form_state) {
267 /** @var \Drupal\comment\CommentInterface $comment */
268 $comment = parent::buildEntity($form, $form_state);
269 if (!$form_state->isValueEmpty('date') && $form_state->getValue('date') instanceof DrupalDateTime) {
270 $comment->setCreatedTime($form_state->getValue('date')->getTimestamp());
273 $comment->setCreatedTime(REQUEST_TIME);
275 // Empty author ID should revert to anonymous.
276 $author_id = $form_state->getValue('uid');
277 if ($comment->id() && $this->currentUser->hasPermission('administer comments')) {
278 // Admin can leave the author ID blank to revert to anonymous.
279 $author_id = $author_id ?: 0;
281 if (!is_null($author_id)) {
282 if ($author_id === 0 && $form['author']['name']['#access']) {
283 // Use the author name value when the form has access to the element and
284 // the author ID is anonymous.
285 $comment->setAuthorName($form_state->getValue('name'));
288 // Ensure the author name is not set.
289 $comment->setAuthorName(NULL);
293 $author_id = $this->currentUser->id();
295 $comment->setOwnerId($author_id);
297 // Validate the comment's subject. If not specified, extract from comment
299 if (trim($comment->getSubject()) == '') {
300 if ($comment->hasField('comment_body')) {
301 // The body may be in any format, so:
302 // 1) Filter it into HTML
303 // 2) Strip out all HTML tags
304 // 3) Convert entities back to plain-text.
305 $comment_text = $comment->comment_body->processed;
306 $comment->setSubject(Unicode::truncate(trim(Html::decodeEntities(strip_tags($comment_text))), 29, TRUE, TRUE));
308 // Edge cases where the comment body is populated only by HTML tags will
309 // require a default subject.
310 if ($comment->getSubject() == '') {
311 $comment->setSubject($this->t('(No subject)'));
320 protected function getEditedFieldNames(FormStateInterface $form_state) {
321 return array_merge(['created', 'name'], parent::getEditedFieldNames($form_state));
327 protected function flagViolations(EntityConstraintViolationListInterface $violations, array $form, FormStateInterface $form_state) {
328 // Manually flag violations of fields not handled by the form display.
329 foreach ($violations->getByField('created') as $violation) {
330 $form_state->setErrorByName('date', $violation->getMessage());
332 foreach ($violations->getByField('name') as $violation) {
333 $form_state->setErrorByName('name', $violation->getMessage());
335 parent::flagViolations($violations, $form, $form_state);
339 * Form submission handler for the 'preview' action.
342 * An associative array containing the structure of the form.
343 * @param \Drupal\Core\Form\FormStateInterface $form_state
344 * The current state of the form.
346 public function preview(array &$form, FormStateInterface $form_state) {
347 $comment_preview = comment_preview($this->entity, $form_state);
348 $comment_preview['#title'] = $this->t('Preview comment');
349 $form_state->set('comment_preview', $comment_preview);
350 $form_state->setRebuild();
356 public function save(array $form, FormStateInterface $form_state) {
357 $comment = $this->entity;
358 $entity = $comment->getCommentedEntity();
359 $field_name = $comment->getFieldName();
360 $uri = $entity->urlInfo();
361 $logger = $this->logger('comment');
363 if ($this->currentUser->hasPermission('post comments') && ($this->currentUser->hasPermission('administer comments') || $entity->{$field_name}->status == CommentItemInterface::OPEN)) {
365 $form_state->setValue('cid', $comment->id());
368 $logger->notice('Comment posted: %subject.', [
369 '%subject' => $comment->getSubject(),
370 'link' => $this->l(t('View'), $comment->urlInfo()->setOption('fragment', 'comment-' . $comment->id()))
373 // Explain the approval queue if necessary.
374 if (!$comment->isPublished()) {
375 if (!$this->currentUser->hasPermission('administer comments')) {
376 drupal_set_message($this->t('Your comment has been queued for review by site administrators and will be published after approval.'));
380 drupal_set_message($this->t('Your comment has been posted.'));
383 // Find the current display page for this comment.
384 $field_definition = $this->entityManager->getFieldDefinitions($entity->getEntityTypeId(), $entity->bundle())[$field_name];
385 $page = $this->entityManager->getStorage('comment')->getDisplayOrdinal($comment, $field_definition->getSetting('default_mode'), $field_definition->getSetting('per_page'));
387 $query['page'] = $page;
389 // Redirect to the newly posted comment.
390 $uri->setOption('query', $query);
391 $uri->setOption('fragment', 'comment-' . $comment->id());
394 $logger->warning('Comment: unauthorized comment submitted or comment submitted to a closed post %subject.', ['%subject' => $comment->getSubject()]);
395 drupal_set_message($this->t('Comment: unauthorized comment submitted or comment submitted to a closed post %subject.', ['%subject' => $comment->getSubject()]), 'error');
396 // Redirect the user to the entity they are commenting on.
398 $form_state->setRedirectUrl($uri);