annotate core/modules/comment/src/CommentForm.php @ 0:4c8ae668cc8c

Initial import (non-working)
author Chris Cannam
date Wed, 29 Nov 2017 16:09:58 +0000
parents
children 1fec387a4317
rev   line source
Chris@0 1 <?php
Chris@0 2
Chris@0 3 namespace Drupal\comment;
Chris@0 4
Chris@0 5 use Drupal\comment\Plugin\Field\FieldType\CommentItemInterface;
Chris@0 6 use Drupal\Component\Datetime\TimeInterface;
Chris@0 7 use Drupal\Component\Utility\Html;
Chris@0 8 use Drupal\Component\Utility\Unicode;
Chris@0 9 use Drupal\Core\Datetime\DrupalDateTime;
Chris@0 10 use Drupal\Core\Entity\ContentEntityForm;
Chris@0 11 use Drupal\Core\Entity\EntityConstraintViolationListInterface;
Chris@0 12 use Drupal\Core\Entity\EntityManagerInterface;
Chris@0 13 use Drupal\Core\Entity\EntityTypeBundleInfoInterface;
Chris@0 14 use Drupal\Core\Form\FormStateInterface;
Chris@0 15 use Drupal\Core\Render\RendererInterface;
Chris@0 16 use Drupal\Core\Session\AccountInterface;
Chris@0 17 use Symfony\Component\DependencyInjection\ContainerInterface;
Chris@0 18
Chris@0 19 /**
Chris@0 20 * Base handler for comment forms.
Chris@0 21 */
Chris@0 22 class CommentForm extends ContentEntityForm {
Chris@0 23
Chris@0 24 /**
Chris@0 25 * The current user.
Chris@0 26 *
Chris@0 27 * @var \Drupal\Core\Session\AccountInterface
Chris@0 28 */
Chris@0 29 protected $currentUser;
Chris@0 30
Chris@0 31 /**
Chris@0 32 * The renderer.
Chris@0 33 *
Chris@0 34 * @var \Drupal\Core\Render\RendererInterface
Chris@0 35 */
Chris@0 36 protected $renderer;
Chris@0 37
Chris@0 38 /**
Chris@0 39 * {@inheritdoc}
Chris@0 40 */
Chris@0 41 public static function create(ContainerInterface $container) {
Chris@0 42 return new static(
Chris@0 43 $container->get('entity.manager'),
Chris@0 44 $container->get('current_user'),
Chris@0 45 $container->get('renderer'),
Chris@0 46 $container->get('entity_type.bundle.info'),
Chris@0 47 $container->get('datetime.time')
Chris@0 48 );
Chris@0 49 }
Chris@0 50
Chris@0 51 /**
Chris@0 52 * Constructs a new CommentForm.
Chris@0 53 *
Chris@0 54 * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
Chris@0 55 * The entity manager service.
Chris@0 56 * @param \Drupal\Core\Session\AccountInterface $current_user
Chris@0 57 * The current user.
Chris@0 58 * @param \Drupal\Core\Render\RendererInterface $renderer
Chris@0 59 * The renderer.
Chris@0 60 * @param \Drupal\Core\Entity\EntityTypeBundleInfoInterface $entity_type_bundle_info
Chris@0 61 * The entity type bundle service.
Chris@0 62 * @param \Drupal\Component\Datetime\TimeInterface $time
Chris@0 63 * The time service.
Chris@0 64 */
Chris@0 65 public function __construct(EntityManagerInterface $entity_manager, AccountInterface $current_user, RendererInterface $renderer, EntityTypeBundleInfoInterface $entity_type_bundle_info = NULL, TimeInterface $time = NULL) {
Chris@0 66 parent::__construct($entity_manager, $entity_type_bundle_info, $time);
Chris@0 67 $this->currentUser = $current_user;
Chris@0 68 $this->renderer = $renderer;
Chris@0 69 }
Chris@0 70
Chris@0 71 /**
Chris@0 72 * {@inheritdoc}
Chris@0 73 */
Chris@0 74 public function form(array $form, FormStateInterface $form_state) {
Chris@0 75 /** @var \Drupal\comment\CommentInterface $comment */
Chris@0 76 $comment = $this->entity;
Chris@0 77 $entity = $this->entityManager->getStorage($comment->getCommentedEntityTypeId())->load($comment->getCommentedEntityId());
Chris@0 78 $field_name = $comment->getFieldName();
Chris@0 79 $field_definition = $this->entityManager->getFieldDefinitions($entity->getEntityTypeId(), $entity->bundle())[$comment->getFieldName()];
Chris@0 80 $config = $this->config('user.settings');
Chris@0 81
Chris@0 82 // In several places within this function, we vary $form on:
Chris@0 83 // - The current user's permissions.
Chris@0 84 // - Whether the current user is authenticated or anonymous.
Chris@0 85 // - The 'user.settings' configuration.
Chris@0 86 // - The comment field's definition.
Chris@0 87 $form['#cache']['contexts'][] = 'user.permissions';
Chris@0 88 $form['#cache']['contexts'][] = 'user.roles:authenticated';
Chris@0 89 $this->renderer->addCacheableDependency($form, $config);
Chris@0 90 $this->renderer->addCacheableDependency($form, $field_definition->getConfig($entity->bundle()));
Chris@0 91
Chris@0 92 // Use #comment-form as unique jump target, regardless of entity type.
Chris@0 93 $form['#id'] = Html::getUniqueId('comment_form');
Chris@0 94 $form['#theme'] = ['comment_form__' . $entity->getEntityTypeId() . '__' . $entity->bundle() . '__' . $field_name, 'comment_form'];
Chris@0 95
Chris@0 96 $anonymous_contact = $field_definition->getSetting('anonymous');
Chris@0 97 $is_admin = $comment->id() && $this->currentUser->hasPermission('administer comments');
Chris@0 98
Chris@0 99 if (!$this->currentUser->isAuthenticated() && $anonymous_contact != COMMENT_ANONYMOUS_MAYNOT_CONTACT) {
Chris@0 100 $form['#attached']['library'][] = 'core/drupal.form';
Chris@0 101 $form['#attributes']['data-user-info-from-browser'] = TRUE;
Chris@0 102 }
Chris@0 103
Chris@0 104 // If not replying to a comment, use our dedicated page callback for new
Chris@0 105 // Comments on entities.
Chris@0 106 if (!$comment->id() && !$comment->hasParentComment()) {
Chris@0 107 $form['#action'] = $this->url('comment.reply', ['entity_type' => $entity->getEntityTypeId(), 'entity' => $entity->id(), 'field_name' => $field_name]);
Chris@0 108 }
Chris@0 109
Chris@0 110 $comment_preview = $form_state->get('comment_preview');
Chris@0 111 if (isset($comment_preview)) {
Chris@0 112 $form += $comment_preview;
Chris@0 113 }
Chris@0 114
Chris@0 115 $form['author'] = [];
Chris@0 116 // Display author information in a details element for comment moderators.
Chris@0 117 if ($is_admin) {
Chris@0 118 $form['author'] += [
Chris@0 119 '#type' => 'details',
Chris@0 120 '#title' => $this->t('Administration'),
Chris@0 121 ];
Chris@0 122 }
Chris@0 123
Chris@0 124 // Prepare default values for form elements.
Chris@0 125 $author = '';
Chris@0 126 if ($is_admin) {
Chris@0 127 if (!$comment->getOwnerId()) {
Chris@0 128 $author = $comment->getAuthorName();
Chris@0 129 }
Chris@0 130 $status = $comment->getStatus();
Chris@0 131 if (empty($comment_preview)) {
Chris@0 132 $form['#title'] = $this->t('Edit comment %title', [
Chris@0 133 '%title' => $comment->getSubject(),
Chris@0 134 ]);
Chris@0 135 }
Chris@0 136 }
Chris@0 137 else {
Chris@0 138 $status = ($this->currentUser->hasPermission('skip comment approval') ? CommentInterface::PUBLISHED : CommentInterface::NOT_PUBLISHED);
Chris@0 139 }
Chris@0 140
Chris@0 141 $date = '';
Chris@0 142 if ($comment->id()) {
Chris@0 143 $date = !empty($comment->date) ? $comment->date : DrupalDateTime::createFromTimestamp($comment->getCreatedTime());
Chris@0 144 }
Chris@0 145
Chris@0 146 // The uid field is only displayed when a user with the permission
Chris@0 147 // 'administer comments' is editing an existing comment from an
Chris@0 148 // authenticated user.
Chris@0 149 $owner = $comment->getOwner();
Chris@0 150 $form['author']['uid'] = [
Chris@0 151 '#type' => 'entity_autocomplete',
Chris@0 152 '#target_type' => 'user',
Chris@0 153 '#default_value' => $owner->isAnonymous() ? NULL : $owner,
Chris@0 154 // A comment can be made anonymous by leaving this field empty therefore
Chris@0 155 // there is no need to list them in the autocomplete.
Chris@0 156 '#selection_settings' => ['include_anonymous' => FALSE],
Chris@0 157 '#title' => $this->t('Authored by'),
Chris@0 158 '#description' => $this->t('Leave blank for %anonymous.', ['%anonymous' => $config->get('anonymous')]),
Chris@0 159 '#access' => $is_admin,
Chris@0 160 ];
Chris@0 161
Chris@0 162 // The name field is displayed when an anonymous user is adding a comment or
Chris@0 163 // when a user with the permission 'administer comments' is editing an
Chris@0 164 // existing comment from an anonymous user.
Chris@0 165 $form['author']['name'] = [
Chris@0 166 '#type' => 'textfield',
Chris@0 167 '#title' => $is_admin ? $this->t('Name for @anonymous', ['@anonymous' => $config->get('anonymous')]) : $this->t('Your name'),
Chris@0 168 '#default_value' => $author,
Chris@0 169 '#required' => ($this->currentUser->isAnonymous() && $anonymous_contact == COMMENT_ANONYMOUS_MUST_CONTACT),
Chris@0 170 '#maxlength' => 60,
Chris@0 171 '#access' => $this->currentUser->isAnonymous() || $is_admin,
Chris@0 172 '#size' => 30,
Chris@0 173 '#attributes' => [
Chris@0 174 'data-drupal-default-value' => $config->get('anonymous'),
Chris@0 175 ],
Chris@0 176 ];
Chris@0 177
Chris@0 178 if ($is_admin) {
Chris@0 179 // When editing a comment only display the name textfield if the uid field
Chris@0 180 // is empty.
Chris@0 181 $form['author']['name']['#states'] = [
Chris@0 182 'visible' => [
Chris@0 183 ':input[name="uid"]' => ['empty' => TRUE],
Chris@0 184 ],
Chris@0 185 ];
Chris@0 186 }
Chris@0 187
Chris@0 188 // Add author email and homepage fields depending on the current user.
Chris@0 189 $form['author']['mail'] = [
Chris@0 190 '#type' => 'email',
Chris@0 191 '#title' => $this->t('Email'),
Chris@0 192 '#default_value' => $comment->getAuthorEmail(),
Chris@0 193 '#required' => ($this->currentUser->isAnonymous() && $anonymous_contact == COMMENT_ANONYMOUS_MUST_CONTACT),
Chris@0 194 '#maxlength' => 64,
Chris@0 195 '#size' => 30,
Chris@0 196 '#description' => $this->t('The content of this field is kept private and will not be shown publicly.'),
Chris@0 197 '#access' => ($comment->getOwner()->isAnonymous() && $is_admin) || ($this->currentUser->isAnonymous() && $anonymous_contact != COMMENT_ANONYMOUS_MAYNOT_CONTACT),
Chris@0 198 ];
Chris@0 199
Chris@0 200 $form['author']['homepage'] = [
Chris@0 201 '#type' => 'url',
Chris@0 202 '#title' => $this->t('Homepage'),
Chris@0 203 '#default_value' => $comment->getHomepage(),
Chris@0 204 '#maxlength' => 255,
Chris@0 205 '#size' => 30,
Chris@0 206 '#access' => $is_admin || ($this->currentUser->isAnonymous() && $anonymous_contact != COMMENT_ANONYMOUS_MAYNOT_CONTACT),
Chris@0 207 ];
Chris@0 208
Chris@0 209 // Add administrative comment publishing options.
Chris@0 210 $form['author']['date'] = [
Chris@0 211 '#type' => 'datetime',
Chris@0 212 '#title' => $this->t('Authored on'),
Chris@0 213 '#default_value' => $date,
Chris@0 214 '#size' => 20,
Chris@0 215 '#access' => $is_admin,
Chris@0 216 ];
Chris@0 217
Chris@0 218 $form['author']['status'] = [
Chris@0 219 '#type' => 'radios',
Chris@0 220 '#title' => $this->t('Status'),
Chris@0 221 '#default_value' => $status,
Chris@0 222 '#options' => [
Chris@0 223 CommentInterface::PUBLISHED => $this->t('Published'),
Chris@0 224 CommentInterface::NOT_PUBLISHED => $this->t('Not published'),
Chris@0 225 ],
Chris@0 226 '#access' => $is_admin,
Chris@0 227 ];
Chris@0 228
Chris@0 229 return parent::form($form, $form_state, $comment);
Chris@0 230 }
Chris@0 231
Chris@0 232 /**
Chris@0 233 * {@inheritdoc}
Chris@0 234 */
Chris@0 235 protected function actions(array $form, FormStateInterface $form_state) {
Chris@0 236 $element = parent::actions($form, $form_state);
Chris@0 237 /* @var \Drupal\comment\CommentInterface $comment */
Chris@0 238 $comment = $this->entity;
Chris@0 239 $entity = $comment->getCommentedEntity();
Chris@0 240 $field_definition = $this->entityManager->getFieldDefinitions($entity->getEntityTypeId(), $entity->bundle())[$comment->getFieldName()];
Chris@0 241 $preview_mode = $field_definition->getSetting('preview');
Chris@0 242
Chris@0 243 // No delete action on the comment form.
Chris@0 244 unset($element['delete']);
Chris@0 245
Chris@0 246 // Mark the submit action as the primary action, when it appears.
Chris@0 247 $element['submit']['#button_type'] = 'primary';
Chris@0 248
Chris@0 249 // Only show the save button if comment previews are optional or if we are
Chris@0 250 // already previewing the submission.
Chris@0 251 $element['submit']['#access'] = ($comment->id() && $this->currentUser->hasPermission('administer comments')) || $preview_mode != DRUPAL_REQUIRED || $form_state->get('comment_preview');
Chris@0 252
Chris@0 253 $element['preview'] = [
Chris@0 254 '#type' => 'submit',
Chris@0 255 '#value' => $this->t('Preview'),
Chris@0 256 '#access' => $preview_mode != DRUPAL_DISABLED,
Chris@0 257 '#submit' => ['::submitForm', '::preview'],
Chris@0 258 ];
Chris@0 259
Chris@0 260 return $element;
Chris@0 261 }
Chris@0 262
Chris@0 263 /**
Chris@0 264 * {@inheritdoc}
Chris@0 265 */
Chris@0 266 public function buildEntity(array $form, FormStateInterface $form_state) {
Chris@0 267 /** @var \Drupal\comment\CommentInterface $comment */
Chris@0 268 $comment = parent::buildEntity($form, $form_state);
Chris@0 269 if (!$form_state->isValueEmpty('date') && $form_state->getValue('date') instanceof DrupalDateTime) {
Chris@0 270 $comment->setCreatedTime($form_state->getValue('date')->getTimestamp());
Chris@0 271 }
Chris@0 272 else {
Chris@0 273 $comment->setCreatedTime(REQUEST_TIME);
Chris@0 274 }
Chris@0 275 // Empty author ID should revert to anonymous.
Chris@0 276 $author_id = $form_state->getValue('uid');
Chris@0 277 if ($comment->id() && $this->currentUser->hasPermission('administer comments')) {
Chris@0 278 // Admin can leave the author ID blank to revert to anonymous.
Chris@0 279 $author_id = $author_id ?: 0;
Chris@0 280 }
Chris@0 281 if (!is_null($author_id)) {
Chris@0 282 if ($author_id === 0 && $form['author']['name']['#access']) {
Chris@0 283 // Use the author name value when the form has access to the element and
Chris@0 284 // the author ID is anonymous.
Chris@0 285 $comment->setAuthorName($form_state->getValue('name'));
Chris@0 286 }
Chris@0 287 else {
Chris@0 288 // Ensure the author name is not set.
Chris@0 289 $comment->setAuthorName(NULL);
Chris@0 290 }
Chris@0 291 }
Chris@0 292 else {
Chris@0 293 $author_id = $this->currentUser->id();
Chris@0 294 }
Chris@0 295 $comment->setOwnerId($author_id);
Chris@0 296
Chris@0 297 // Validate the comment's subject. If not specified, extract from comment
Chris@0 298 // body.
Chris@0 299 if (trim($comment->getSubject()) == '') {
Chris@0 300 if ($comment->hasField('comment_body')) {
Chris@0 301 // The body may be in any format, so:
Chris@0 302 // 1) Filter it into HTML
Chris@0 303 // 2) Strip out all HTML tags
Chris@0 304 // 3) Convert entities back to plain-text.
Chris@0 305 $comment_text = $comment->comment_body->processed;
Chris@0 306 $comment->setSubject(Unicode::truncate(trim(Html::decodeEntities(strip_tags($comment_text))), 29, TRUE, TRUE));
Chris@0 307 }
Chris@0 308 // Edge cases where the comment body is populated only by HTML tags will
Chris@0 309 // require a default subject.
Chris@0 310 if ($comment->getSubject() == '') {
Chris@0 311 $comment->setSubject($this->t('(No subject)'));
Chris@0 312 }
Chris@0 313 }
Chris@0 314 return $comment;
Chris@0 315 }
Chris@0 316
Chris@0 317 /**
Chris@0 318 * {@inheritdoc}
Chris@0 319 */
Chris@0 320 protected function getEditedFieldNames(FormStateInterface $form_state) {
Chris@0 321 return array_merge(['created', 'name'], parent::getEditedFieldNames($form_state));
Chris@0 322 }
Chris@0 323
Chris@0 324 /**
Chris@0 325 * {@inheritdoc}
Chris@0 326 */
Chris@0 327 protected function flagViolations(EntityConstraintViolationListInterface $violations, array $form, FormStateInterface $form_state) {
Chris@0 328 // Manually flag violations of fields not handled by the form display.
Chris@0 329 foreach ($violations->getByField('created') as $violation) {
Chris@0 330 $form_state->setErrorByName('date', $violation->getMessage());
Chris@0 331 }
Chris@0 332 foreach ($violations->getByField('name') as $violation) {
Chris@0 333 $form_state->setErrorByName('name', $violation->getMessage());
Chris@0 334 }
Chris@0 335 parent::flagViolations($violations, $form, $form_state);
Chris@0 336 }
Chris@0 337
Chris@0 338 /**
Chris@0 339 * Form submission handler for the 'preview' action.
Chris@0 340 *
Chris@0 341 * @param array $form
Chris@0 342 * An associative array containing the structure of the form.
Chris@0 343 * @param \Drupal\Core\Form\FormStateInterface $form_state
Chris@0 344 * The current state of the form.
Chris@0 345 */
Chris@0 346 public function preview(array &$form, FormStateInterface $form_state) {
Chris@0 347 $comment_preview = comment_preview($this->entity, $form_state);
Chris@0 348 $comment_preview['#title'] = $this->t('Preview comment');
Chris@0 349 $form_state->set('comment_preview', $comment_preview);
Chris@0 350 $form_state->setRebuild();
Chris@0 351 }
Chris@0 352
Chris@0 353 /**
Chris@0 354 * {@inheritdoc}
Chris@0 355 */
Chris@0 356 public function save(array $form, FormStateInterface $form_state) {
Chris@0 357 $comment = $this->entity;
Chris@0 358 $entity = $comment->getCommentedEntity();
Chris@0 359 $field_name = $comment->getFieldName();
Chris@0 360 $uri = $entity->urlInfo();
Chris@0 361 $logger = $this->logger('comment');
Chris@0 362
Chris@0 363 if ($this->currentUser->hasPermission('post comments') && ($this->currentUser->hasPermission('administer comments') || $entity->{$field_name}->status == CommentItemInterface::OPEN)) {
Chris@0 364 $comment->save();
Chris@0 365 $form_state->setValue('cid', $comment->id());
Chris@0 366
Chris@0 367 // Add a log entry.
Chris@0 368 $logger->notice('Comment posted: %subject.', [
Chris@0 369 '%subject' => $comment->getSubject(),
Chris@0 370 'link' => $this->l(t('View'), $comment->urlInfo()->setOption('fragment', 'comment-' . $comment->id()))
Chris@0 371 ]);
Chris@0 372
Chris@0 373 // Explain the approval queue if necessary.
Chris@0 374 if (!$comment->isPublished()) {
Chris@0 375 if (!$this->currentUser->hasPermission('administer comments')) {
Chris@0 376 drupal_set_message($this->t('Your comment has been queued for review by site administrators and will be published after approval.'));
Chris@0 377 }
Chris@0 378 }
Chris@0 379 else {
Chris@0 380 drupal_set_message($this->t('Your comment has been posted.'));
Chris@0 381 }
Chris@0 382 $query = [];
Chris@0 383 // Find the current display page for this comment.
Chris@0 384 $field_definition = $this->entityManager->getFieldDefinitions($entity->getEntityTypeId(), $entity->bundle())[$field_name];
Chris@0 385 $page = $this->entityManager->getStorage('comment')->getDisplayOrdinal($comment, $field_definition->getSetting('default_mode'), $field_definition->getSetting('per_page'));
Chris@0 386 if ($page > 0) {
Chris@0 387 $query['page'] = $page;
Chris@0 388 }
Chris@0 389 // Redirect to the newly posted comment.
Chris@0 390 $uri->setOption('query', $query);
Chris@0 391 $uri->setOption('fragment', 'comment-' . $comment->id());
Chris@0 392 }
Chris@0 393 else {
Chris@0 394 $logger->warning('Comment: unauthorized comment submitted or comment submitted to a closed post %subject.', ['%subject' => $comment->getSubject()]);
Chris@0 395 drupal_set_message($this->t('Comment: unauthorized comment submitted or comment submitted to a closed post %subject.', ['%subject' => $comment->getSubject()]), 'error');
Chris@0 396 // Redirect the user to the entity they are commenting on.
Chris@0 397 }
Chris@0 398 $form_state->setRedirectUrl($uri);
Chris@0 399 }
Chris@0 400
Chris@0 401 }