CommentForm.php 15 KB
Newer Older
1 2 3 4
<?php

/**
 * @file
5
 * Contains \Drupal\comment\CommentForm.
6 7 8 9
 */

namespace Drupal\comment;

10
use Drupal\comment\Plugin\Field\FieldType\CommentItemInterface;
11
use Drupal\Component\Utility\Html;
12
use Drupal\Component\Utility\Unicode;
13
use Drupal\Core\Datetime\DrupalDateTime;
14
use Drupal\Core\Entity\ContentEntityForm;
15
use Drupal\Core\Entity\EntityConstraintViolationListInterface;
16
use Drupal\Core\Entity\EntityManagerInterface;
17
use Drupal\Core\Form\FormStateInterface;
18
use Drupal\Core\Render\RendererInterface;
19 20
use Drupal\Core\Session\AccountInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
21 22

/**
23
 * Base handler for comment forms.
24
 */
25
class CommentForm extends ContentEntityForm {
26

27 28 29 30 31 32 33
  /**
   * The current user.
   *
   * @var \Drupal\Core\Session\AccountInterface
   */
  protected $currentUser;

34 35 36 37 38 39 40
  /**
   * The renderer.
   *
   * @var \Drupal\Core\Render\RendererInterface
   */
  protected $renderer;

41 42 43 44 45 46
  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('entity.manager'),
47 48
      $container->get('current_user'),
      $container->get('renderer')
49 50 51 52
    );
  }

  /**
53
   * Constructs a new CommentForm.
54
   *
55
   * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
56 57 58
   *   The entity manager service.
   * @param \Drupal\Core\Session\AccountInterface $current_user
   *   The current user.
59 60
   * @param \Drupal\Core\Render\RendererInterface $renderer
   *   The renderer.
61
   */
62
  public function __construct(EntityManagerInterface $entity_manager, AccountInterface $current_user, RendererInterface $renderer) {
63
    parent::__construct($entity_manager);
64
    $this->currentUser = $current_user;
65
    $this->renderer = $renderer;
66 67
  }

68
  /**
69
   * {@inheritdoc}
70
   */
71
  public function form(array $form, FormStateInterface $form_state) {
72
    /** @var \Drupal\comment\CommentInterface $comment */
73
    $comment = $this->entity;
74
    $entity = $this->entityManager->getStorage($comment->getCommentedEntityTypeId())->load($comment->getCommentedEntityId());
75
    $field_name = $comment->getFieldName();
76
    $field_definition = $this->entityManager->getFieldDefinitions($entity->getEntityTypeId(), $entity->bundle())[$comment->getFieldName()];
77
    $config = $this->config('user.settings');
78

79 80 81 82 83 84 85 86 87 88
    // In several places within this function, we vary $form on:
    // - The current user's permissions.
    // - Whether the current user is authenticated or anonymous.
    // - The 'user.settings' configuration.
    // - The comment field's definition.
    $form['#cache']['contexts'][] = 'user.permissions';
    $form['#cache']['contexts'][] = 'user.roles:authenticated';
    $this->renderer->addCacheableDependency($form, $config);
    $this->renderer->addCacheableDependency($form, $field_definition->getConfig($entity->bundle()));

89
    // Use #comment-form as unique jump target, regardless of entity type.
90
    $form['#id'] = Html::getUniqueId('comment_form');
91
    $form['#theme'] = array('comment_form__' . $entity->getEntityTypeId() . '__' . $entity->bundle() . '__' . $field_name, 'comment_form');
92

93
    $anonymous_contact = $field_definition->getSetting('anonymous');
94
    $is_admin = $comment->id() && $this->currentUser->hasPermission('administer comments');
95

96
    if (!$this->currentUser->isAuthenticated() && $anonymous_contact != COMMENT_ANONYMOUS_MAYNOT_CONTACT) {
97 98
      $form['#attached']['library'][] = 'core/drupal.form';
      $form['#attributes']['data-user-info-from-browser'] = TRUE;
99 100 101
    }

    // If not replying to a comment, use our dedicated page callback for new
102
    // Comments on entities.
103
    if (!$comment->id() && !$comment->hasParentComment()) {
104
      $form['#action'] = $this->url('comment.reply', array('entity_type' => $entity->getEntityTypeId(), 'entity' => $entity->id(), 'field_name' => $field_name));
105 106
    }

107 108 109
    $comment_preview = $form_state->get('comment_preview');
    if (isset($comment_preview)) {
      $form += $comment_preview;
110 111
    }

112
    $form['author'] = array();
113
    // Display author information in a details element for comment moderators.
114 115
    if ($is_admin) {
      $form['author'] += array(
116
        '#type' => 'details',
117
        '#title' => $this->t('Administration'),
118 119 120 121
      );
    }

    // Prepare default values for form elements.
122
    $author = '';
123
    if ($is_admin) {
124 125 126
      if (!$comment->getOwnerId()) {
        $author = $comment->getAuthorName();
      }
127
      $status = $comment->getStatus();
128
      if (empty($comment_preview)) {
129
        $form['#title'] = $this->t('Edit comment %title', array(
130
          '%title' => $comment->getSubject(),
131 132
        ));
      }
133 134
    }
    else {
135
      $status = ($this->currentUser->hasPermission('skip comment approval') ? CommentInterface::PUBLISHED : CommentInterface::NOT_PUBLISHED);
136 137 138 139
    }

    $date = '';
    if ($comment->id()) {
140
      $date = !empty($comment->date) ? $comment->date : DrupalDateTime::createFromTimestamp($comment->getCreatedTime());
141 142
    }

143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
    // The uid field is only displayed when a user with the permission
    // 'administer comments' is editing an existing comment from an
    // authenticated user.
    $owner = $comment->getOwner();
    $form['author']['uid'] = [
      '#type' => 'entity_autocomplete',
      '#target_type' => 'user',
      '#default_value' => $owner->isAnonymous() ? NULL : $owner,
      // A comment can be made anonymous by leaving this field empty therefore
      // there is no need to list them in the autocomplete.
      '#selection_settings' => ['include_anonymous' => FALSE],
      '#title' => $this->t('Authored by'),
      '#description' => $this->t('Leave blank for %anonymous.', ['%anonymous' => $config->get('anonymous')]),
      '#access' => $is_admin,
    ];

    // The name field is displayed when an anonymous user is adding a comment or
    // when a user with the permission 'administer comments' is editing an
    // existing comment from an anonymous user.
162 163
    $form['author']['name'] = array(
      '#type' => 'textfield',
164
      '#title' => $is_admin ? $this->t('Name for @anonymous', ['@anonymous' => $config->get('anonymous')]) : $this->t('Your name'),
165
      '#default_value' => $author,
166
      '#required' => ($this->currentUser->isAnonymous() && $anonymous_contact == COMMENT_ANONYMOUS_MUST_CONTACT),
167
      '#maxlength' => 60,
168
      '#access' => $this->currentUser->isAnonymous() || $is_admin,
169
      '#size' => 30,
170 171 172
      '#attributes'=> [
        'data-drupal-default-value' => $config->get('anonymous'),
      ],
173
    );
174

175
    if ($is_admin) {
176 177 178 179 180 181 182
      // When editing a comment only display the name textfield if the uid field
      // is empty.
      $form['author']['name']['#states'] = [
        'visible' => [
          ':input[name="uid"]' => array('empty' => TRUE),
        ],
      ];
183
    }
184

185
    // Add author email and homepage fields depending on the current user.
186 187
    $form['author']['mail'] = array(
      '#type' => 'email',
188
      '#title' => $this->t('Email'),
189
      '#default_value' => $comment->getAuthorEmail(),
190
      '#required' => ($this->currentUser->isAnonymous() && $anonymous_contact == COMMENT_ANONYMOUS_MUST_CONTACT),
191 192
      '#maxlength' => 64,
      '#size' => 30,
193
      '#description' => $this->t('The content of this field is kept private and will not be shown publicly.'),
194
      '#access' => ($comment->getOwner()->isAnonymous() && $is_admin) || ($this->currentUser->isAnonymous() && $anonymous_contact != COMMENT_ANONYMOUS_MAYNOT_CONTACT),
195 196 197 198
    );

    $form['author']['homepage'] = array(
      '#type' => 'url',
199
      '#title' => $this->t('Homepage'),
200
      '#default_value' => $comment->getHomepage(),
201 202
      '#maxlength' => 255,
      '#size' => 30,
203
      '#access' => $is_admin || ($this->currentUser->isAnonymous() && $anonymous_contact != COMMENT_ANONYMOUS_MAYNOT_CONTACT),
204 205 206 207
    );

    // Add administrative comment publishing options.
    $form['author']['date'] = array(
208
      '#type' => 'datetime',
209
      '#title' => $this->t('Authored on'),
210 211 212 213 214 215 216
      '#default_value' => $date,
      '#size' => 20,
      '#access' => $is_admin,
    );

    $form['author']['status'] = array(
      '#type' => 'radios',
217
      '#title' => $this->t('Status'),
218 219
      '#default_value' => $status,
      '#options' => array(
220 221
        CommentInterface::PUBLISHED => $this->t('Published'),
        CommentInterface::NOT_PUBLISHED => $this->t('Not published'),
222 223 224 225 226 227 228 229
      ),
      '#access' => $is_admin,
    );

    return parent::form($form, $form_state, $comment);
  }

  /**
230
   * {@inheritdoc}
231
   */
232
  protected function actions(array $form, FormStateInterface $form_state) {
233
    $element = parent::actions($form, $form_state);
234
    /* @var \Drupal\comment\CommentInterface $comment */
235
    $comment = $this->entity;
236
    $entity = $comment->getCommentedEntity();
237 238
    $field_definition = $this->entityManager->getFieldDefinitions($entity->getEntityTypeId(), $entity->bundle())[$comment->getFieldName()];
    $preview_mode = $field_definition->getSetting('preview');
239 240 241 242

    // No delete action on the comment form.
    unset($element['delete']);

243 244 245
    // Mark the submit action as the primary action, when it appears.
    $element['submit']['#button_type'] = 'primary';

246 247
    // Only show the save button if comment previews are optional or if we are
    // already previewing the submission.
248
    $element['submit']['#access'] = ($comment->id() && $this->currentUser->hasPermission('administer comments')) || $preview_mode != DRUPAL_REQUIRED || $form_state->get('comment_preview');
249 250 251

    $element['preview'] = array(
      '#type' => 'submit',
252
      '#value' => $this->t('Preview'),
253
      '#access' => $preview_mode != DRUPAL_DISABLED,
254
      '#submit' => array('::submitForm', '::preview'),
255 256 257 258 259 260
    );

    return $element;
  }

  /**
261
   * {@inheritdoc}
262
   */
263
  public function buildEntity(array $form, FormStateInterface $form_state) {
264
    /** @var \Drupal\comment\CommentInterface $comment */
265
    $comment = parent::buildEntity($form, $form_state);
266
    if (!$form_state->isValueEmpty('date') && $form_state->getValue('date') instanceof DrupalDateTime) {
267
      $comment->setCreatedTime($form_state->getValue('date')->getTimestamp());
268 269
    }
    else {
270
      $comment->setCreatedTime(REQUEST_TIME);
271
    }
272 273 274 275 276
    // Empty author ID should revert to anonymous.
    $author_id = $form_state->getValue('uid');
    if ($comment->id() && $this->currentUser->hasPermission('administer comments')) {
      // Admin can leave the author ID blank to revert to anonymous.
      $author_id = $author_id ?: 0;
277
    }
278 279 280 281 282 283 284 285 286 287 288 289 290
    if (!is_null($author_id)) {
      if ($author_id === 0 && $form['author']['name']['#access']) {
        // Use the author name value when the form has access to the element and
        // the author ID is anonymous.
        $comment->setAuthorName($form_state->getValue('name'));
      }
      else {
        // Ensure the author name is not set.
        $comment->setAuthorName(NULL);
      }
    }
    else {
      $author_id = $this->currentUser->id();
291
    }
292
    $comment->setOwnerId($author_id);
293 294 295

    // Validate the comment's subject. If not specified, extract from comment
    // body.
296
    if (trim($comment->getSubject()) == '') {
297 298 299 300 301 302 303 304
      if ($comment->hasField('comment_body')) {
        // The body may be in any format, so:
        // 1) Filter it into HTML
        // 2) Strip out all HTML tags
        // 3) Convert entities back to plain-text.
        $comment_text = $comment->comment_body->processed;
        $comment->setSubject(Unicode::truncate(trim(Html::decodeEntities(strip_tags($comment_text))), 29, TRUE, TRUE));
      }
305 306
      // Edge cases where the comment body is populated only by HTML tags will
      // require a default subject.
307 308
      if ($comment->getSubject() == '') {
        $comment->setSubject($this->t('(No subject)'));
309 310 311 312 313
      }
    }
    return $comment;
  }

314 315 316
  /**
   * {@inheritdoc}
   */
317 318 319
  protected function getEditedFieldNames(FormStateInterface $form_state) {
    return array_merge(['created', 'name'], parent::getEditedFieldNames($form_state));
  }
320

321 322 323 324 325 326
  /**
   * {@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) {
327 328
      $form_state->setErrorByName('date', $violation->getMessage());
    }
329 330
    foreach ($violations->getByField('name') as $violation) {
      $form_state->setErrorByName('name', $violation->getMessage());
331
    }
332
    parent::flagViolations($violations, $form, $form_state);
333 334
  }

335 336 337
  /**
   * Form submission handler for the 'preview' action.
   *
338
   * @param array $form
339
   *   An associative array containing the structure of the form.
340
   * @param \Drupal\Core\Form\FormStateInterface $form_state
341
   *   The current state of the form.
342
   */
343
  public function preview(array &$form, FormStateInterface $form_state) {
344 345 346 347
    $comment_preview = comment_preview($this->entity, $form_state);
    $comment_preview['#title'] = $this->t('Preview comment');
    $form_state->set('comment_preview', $comment_preview);
    $form_state->setRebuild();
348 349 350
  }

  /**
351
   * {@inheritdoc}
352
   */
353
  public function save(array $form, FormStateInterface $form_state) {
354
    $comment = $this->entity;
355
    $entity = $comment->getCommentedEntity();
356
    $field_name = $comment->getFieldName();
357
    $uri = $entity->urlInfo();
358
    $logger = $this->logger('content');
359

360
    if ($this->currentUser->hasPermission('post comments') && ($this->currentUser->hasPermission('administer comments') || $entity->{$field_name}->status == CommentItemInterface::OPEN)) {
361
      $comment->save();
362
      $form_state->setValue('cid', $comment->id());
363

364
      // Add a log entry.
365 366
      $logger->notice('Comment posted: %subject.', array(
          '%subject' => $comment->getSubject(),
367
          'link' => $this->l(t('View'), $comment->urlInfo()->setOption('fragment', 'comment-' . $comment->id()))
368
        ));
369 370

      // Explain the approval queue if necessary.
371
      if (!$comment->isPublished()) {
372 373
        if (!$this->currentUser->hasPermission('administer comments')) {
          drupal_set_message($this->t('Your comment has been queued for review by site administrators and will be published after approval.'));
374 375 376
        }
      }
      else {
377
        drupal_set_message($this->t('Your comment has been posted.'));
378 379 380
      }
      $query = array();
      // Find the current display page for this comment.
381
      $field_definition = $this->entityManager->getFieldDefinitions($entity->getEntityTypeId(), $entity->bundle())[$field_name];
382
      $page = $this->entityManager->getStorage('comment')->getDisplayOrdinal($comment, $field_definition->getSetting('default_mode'), $field_definition->getSetting('per_page'));
383 384 385 386
      if ($page > 0) {
        $query['page'] = $page;
      }
      // Redirect to the newly posted comment.
387 388
      $uri->setOption('query', $query);
      $uri->setOption('fragment', 'comment-' . $comment->id());
389 390
    }
    else {
391
      $logger->warning('Comment: unauthorized comment submitted or comment submitted to a closed post %subject.', array('%subject' => $comment->getSubject()));
392
      drupal_set_message($this->t('Comment: unauthorized comment submitted or comment submitted to a closed post %subject.', array('%subject' => $comment->getSubject())), 'error');
393
      // Redirect the user to the entity they are commenting on.
394
    }
395
    $form_state->setRedirectUrl($uri);
396 397
  }
}