Chris@0: get('entity.repository'), Chris@0: $container->get('current_user'), Chris@0: $container->get('renderer'), Chris@0: $container->get('entity_type.bundle.info'), Chris@17: $container->get('datetime.time'), Chris@17: $container->get('entity_field.manager') Chris@0: ); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Constructs a new CommentForm. Chris@0: * Chris@17: * @param \Drupal\Core\Entity\EntityRepositoryInterface $entity_repository Chris@17: * The entity repository. Chris@0: * @param \Drupal\Core\Session\AccountInterface $current_user Chris@0: * The current user. Chris@0: * @param \Drupal\Core\Render\RendererInterface $renderer Chris@0: * The renderer. Chris@0: * @param \Drupal\Core\Entity\EntityTypeBundleInfoInterface $entity_type_bundle_info Chris@0: * The entity type bundle service. Chris@0: * @param \Drupal\Component\Datetime\TimeInterface $time Chris@0: * The time service. Chris@0: */ Chris@17: public function __construct(EntityRepositoryInterface $entity_repository, AccountInterface $current_user, RendererInterface $renderer, EntityTypeBundleInfoInterface $entity_type_bundle_info = NULL, TimeInterface $time = NULL, EntityFieldManagerInterface $entity_field_manager = NULL) { Chris@17: parent::__construct($entity_repository, $entity_type_bundle_info, $time); Chris@0: $this->currentUser = $current_user; Chris@0: $this->renderer = $renderer; Chris@17: $this->entityFieldManager = $entity_field_manager ?: \Drupal::service('entity_field.manager'); Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function form(array $form, FormStateInterface $form_state) { Chris@0: /** @var \Drupal\comment\CommentInterface $comment */ Chris@0: $comment = $this->entity; Chris@17: $entity = $this->entityTypeManager->getStorage($comment->getCommentedEntityTypeId())->load($comment->getCommentedEntityId()); Chris@0: $field_name = $comment->getFieldName(); Chris@17: $field_definition = $this->entityFieldManager->getFieldDefinitions($entity->getEntityTypeId(), $entity->bundle())[$comment->getFieldName()]; Chris@0: $config = $this->config('user.settings'); Chris@0: Chris@0: // In several places within this function, we vary $form on: Chris@0: // - The current user's permissions. Chris@0: // - Whether the current user is authenticated or anonymous. Chris@0: // - The 'user.settings' configuration. Chris@0: // - The comment field's definition. Chris@0: $form['#cache']['contexts'][] = 'user.permissions'; Chris@0: $form['#cache']['contexts'][] = 'user.roles:authenticated'; Chris@0: $this->renderer->addCacheableDependency($form, $config); Chris@0: $this->renderer->addCacheableDependency($form, $field_definition->getConfig($entity->bundle())); Chris@0: Chris@0: // Use #comment-form as unique jump target, regardless of entity type. Chris@0: $form['#id'] = Html::getUniqueId('comment_form'); Chris@0: $form['#theme'] = ['comment_form__' . $entity->getEntityTypeId() . '__' . $entity->bundle() . '__' . $field_name, 'comment_form']; Chris@0: Chris@0: $anonymous_contact = $field_definition->getSetting('anonymous'); Chris@0: $is_admin = $comment->id() && $this->currentUser->hasPermission('administer comments'); Chris@0: Chris@18: if (!$this->currentUser->isAuthenticated() && $anonymous_contact != CommentInterface::ANONYMOUS_MAYNOT_CONTACT) { Chris@0: $form['#attached']['library'][] = 'core/drupal.form'; Chris@0: $form['#attributes']['data-user-info-from-browser'] = TRUE; Chris@0: } Chris@0: Chris@0: // If not replying to a comment, use our dedicated page callback for new Chris@0: // Comments on entities. Chris@0: if (!$comment->id() && !$comment->hasParentComment()) { Chris@0: $form['#action'] = $this->url('comment.reply', ['entity_type' => $entity->getEntityTypeId(), 'entity' => $entity->id(), 'field_name' => $field_name]); Chris@0: } Chris@0: Chris@0: $comment_preview = $form_state->get('comment_preview'); Chris@0: if (isset($comment_preview)) { Chris@0: $form += $comment_preview; Chris@0: } Chris@0: Chris@0: $form['author'] = []; Chris@0: // Display author information in a details element for comment moderators. Chris@0: if ($is_admin) { Chris@0: $form['author'] += [ Chris@0: '#type' => 'details', Chris@0: '#title' => $this->t('Administration'), Chris@0: ]; Chris@0: } Chris@0: Chris@0: // Prepare default values for form elements. Chris@0: $author = ''; Chris@0: if ($is_admin) { Chris@0: if (!$comment->getOwnerId()) { Chris@0: $author = $comment->getAuthorName(); Chris@0: } Chris@0: $status = $comment->getStatus(); Chris@0: if (empty($comment_preview)) { Chris@0: $form['#title'] = $this->t('Edit comment %title', [ Chris@0: '%title' => $comment->getSubject(), Chris@0: ]); Chris@0: } Chris@0: } Chris@0: else { Chris@0: $status = ($this->currentUser->hasPermission('skip comment approval') ? CommentInterface::PUBLISHED : CommentInterface::NOT_PUBLISHED); Chris@0: } Chris@0: Chris@0: $date = ''; Chris@0: if ($comment->id()) { Chris@0: $date = !empty($comment->date) ? $comment->date : DrupalDateTime::createFromTimestamp($comment->getCreatedTime()); Chris@0: } Chris@0: Chris@0: // The uid field is only displayed when a user with the permission Chris@0: // 'administer comments' is editing an existing comment from an Chris@0: // authenticated user. Chris@0: $owner = $comment->getOwner(); Chris@0: $form['author']['uid'] = [ Chris@0: '#type' => 'entity_autocomplete', Chris@0: '#target_type' => 'user', Chris@0: '#default_value' => $owner->isAnonymous() ? NULL : $owner, Chris@0: // A comment can be made anonymous by leaving this field empty therefore Chris@0: // there is no need to list them in the autocomplete. Chris@0: '#selection_settings' => ['include_anonymous' => FALSE], Chris@0: '#title' => $this->t('Authored by'), Chris@0: '#description' => $this->t('Leave blank for %anonymous.', ['%anonymous' => $config->get('anonymous')]), Chris@0: '#access' => $is_admin, Chris@0: ]; Chris@0: Chris@0: // The name field is displayed when an anonymous user is adding a comment or Chris@0: // when a user with the permission 'administer comments' is editing an Chris@0: // existing comment from an anonymous user. Chris@0: $form['author']['name'] = [ Chris@0: '#type' => 'textfield', Chris@0: '#title' => $is_admin ? $this->t('Name for @anonymous', ['@anonymous' => $config->get('anonymous')]) : $this->t('Your name'), Chris@0: '#default_value' => $author, Chris@18: '#required' => ($this->currentUser->isAnonymous() && $anonymous_contact == CommentInterface::ANONYMOUS_MUST_CONTACT), Chris@0: '#maxlength' => 60, Chris@0: '#access' => $this->currentUser->isAnonymous() || $is_admin, Chris@0: '#size' => 30, Chris@0: '#attributes' => [ Chris@0: 'data-drupal-default-value' => $config->get('anonymous'), Chris@0: ], Chris@0: ]; Chris@0: Chris@0: if ($is_admin) { Chris@0: // When editing a comment only display the name textfield if the uid field Chris@0: // is empty. Chris@0: $form['author']['name']['#states'] = [ Chris@0: 'visible' => [ Chris@0: ':input[name="uid"]' => ['empty' => TRUE], Chris@0: ], Chris@0: ]; Chris@0: } Chris@0: Chris@0: // Add author email and homepage fields depending on the current user. Chris@0: $form['author']['mail'] = [ Chris@0: '#type' => 'email', Chris@0: '#title' => $this->t('Email'), Chris@0: '#default_value' => $comment->getAuthorEmail(), Chris@18: '#required' => ($this->currentUser->isAnonymous() && $anonymous_contact == CommentInterface::ANONYMOUS_MUST_CONTACT), Chris@0: '#maxlength' => 64, Chris@0: '#size' => 30, Chris@0: '#description' => $this->t('The content of this field is kept private and will not be shown publicly.'), Chris@18: '#access' => ($comment->getOwner()->isAnonymous() && $is_admin) || ($this->currentUser->isAnonymous() && $anonymous_contact != CommentInterface::ANONYMOUS_MAYNOT_CONTACT), Chris@0: ]; Chris@0: Chris@0: $form['author']['homepage'] = [ Chris@0: '#type' => 'url', Chris@0: '#title' => $this->t('Homepage'), Chris@0: '#default_value' => $comment->getHomepage(), Chris@0: '#maxlength' => 255, Chris@0: '#size' => 30, Chris@18: '#access' => $is_admin || ($this->currentUser->isAnonymous() && $anonymous_contact != CommentInterface::ANONYMOUS_MAYNOT_CONTACT), Chris@0: ]; Chris@0: Chris@0: // Add administrative comment publishing options. Chris@0: $form['author']['date'] = [ Chris@0: '#type' => 'datetime', Chris@0: '#title' => $this->t('Authored on'), Chris@0: '#default_value' => $date, Chris@0: '#size' => 20, Chris@0: '#access' => $is_admin, Chris@0: ]; Chris@0: Chris@0: $form['author']['status'] = [ Chris@0: '#type' => 'radios', Chris@0: '#title' => $this->t('Status'), Chris@0: '#default_value' => $status, Chris@0: '#options' => [ Chris@0: CommentInterface::PUBLISHED => $this->t('Published'), Chris@0: CommentInterface::NOT_PUBLISHED => $this->t('Not published'), Chris@0: ], Chris@0: '#access' => $is_admin, Chris@0: ]; Chris@0: Chris@0: return parent::form($form, $form_state, $comment); Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: protected function actions(array $form, FormStateInterface $form_state) { Chris@0: $element = parent::actions($form, $form_state); Chris@0: /* @var \Drupal\comment\CommentInterface $comment */ Chris@0: $comment = $this->entity; Chris@0: $entity = $comment->getCommentedEntity(); Chris@18: $field_definition = $this->entityFieldManager->getFieldDefinitions($entity->getEntityTypeId(), $entity->bundle())[$comment->getFieldName()]; Chris@0: $preview_mode = $field_definition->getSetting('preview'); Chris@0: Chris@0: // No delete action on the comment form. Chris@0: unset($element['delete']); Chris@0: Chris@0: // Mark the submit action as the primary action, when it appears. Chris@0: $element['submit']['#button_type'] = 'primary'; Chris@0: Chris@0: // Only show the save button if comment previews are optional or if we are Chris@0: // already previewing the submission. Chris@0: $element['submit']['#access'] = ($comment->id() && $this->currentUser->hasPermission('administer comments')) || $preview_mode != DRUPAL_REQUIRED || $form_state->get('comment_preview'); Chris@0: Chris@0: $element['preview'] = [ Chris@0: '#type' => 'submit', Chris@0: '#value' => $this->t('Preview'), Chris@0: '#access' => $preview_mode != DRUPAL_DISABLED, Chris@0: '#submit' => ['::submitForm', '::preview'], Chris@0: ]; Chris@0: Chris@0: return $element; Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function buildEntity(array $form, FormStateInterface $form_state) { Chris@0: /** @var \Drupal\comment\CommentInterface $comment */ Chris@0: $comment = parent::buildEntity($form, $form_state); Chris@0: if (!$form_state->isValueEmpty('date') && $form_state->getValue('date') instanceof DrupalDateTime) { Chris@0: $comment->setCreatedTime($form_state->getValue('date')->getTimestamp()); Chris@0: } Chris@0: else { Chris@0: $comment->setCreatedTime(REQUEST_TIME); Chris@0: } Chris@0: // Empty author ID should revert to anonymous. Chris@0: $author_id = $form_state->getValue('uid'); Chris@0: if ($comment->id() && $this->currentUser->hasPermission('administer comments')) { Chris@0: // Admin can leave the author ID blank to revert to anonymous. Chris@0: $author_id = $author_id ?: 0; Chris@0: } Chris@0: if (!is_null($author_id)) { Chris@0: if ($author_id === 0 && $form['author']['name']['#access']) { Chris@0: // Use the author name value when the form has access to the element and Chris@0: // the author ID is anonymous. Chris@0: $comment->setAuthorName($form_state->getValue('name')); Chris@0: } Chris@0: else { Chris@0: // Ensure the author name is not set. Chris@0: $comment->setAuthorName(NULL); Chris@0: } Chris@0: } Chris@0: else { Chris@0: $author_id = $this->currentUser->id(); Chris@0: } Chris@0: $comment->setOwnerId($author_id); Chris@0: Chris@0: // Validate the comment's subject. If not specified, extract from comment Chris@0: // body. Chris@0: if (trim($comment->getSubject()) == '') { Chris@0: if ($comment->hasField('comment_body')) { Chris@0: // The body may be in any format, so: Chris@0: // 1) Filter it into HTML Chris@0: // 2) Strip out all HTML tags Chris@0: // 3) Convert entities back to plain-text. Chris@0: $comment_text = $comment->comment_body->processed; Chris@0: $comment->setSubject(Unicode::truncate(trim(Html::decodeEntities(strip_tags($comment_text))), 29, TRUE, TRUE)); Chris@0: } Chris@0: // Edge cases where the comment body is populated only by HTML tags will Chris@0: // require a default subject. Chris@0: if ($comment->getSubject() == '') { Chris@0: $comment->setSubject($this->t('(No subject)')); Chris@0: } Chris@0: } Chris@0: return $comment; Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: protected function getEditedFieldNames(FormStateInterface $form_state) { Chris@0: return array_merge(['created', 'name'], parent::getEditedFieldNames($form_state)); Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: protected function flagViolations(EntityConstraintViolationListInterface $violations, array $form, FormStateInterface $form_state) { Chris@0: // Manually flag violations of fields not handled by the form display. Chris@0: foreach ($violations->getByField('created') as $violation) { Chris@0: $form_state->setErrorByName('date', $violation->getMessage()); Chris@0: } Chris@0: foreach ($violations->getByField('name') as $violation) { Chris@0: $form_state->setErrorByName('name', $violation->getMessage()); Chris@0: } Chris@0: parent::flagViolations($violations, $form, $form_state); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Form submission handler for the 'preview' action. Chris@0: * Chris@0: * @param array $form Chris@0: * An associative array containing the structure of the form. Chris@0: * @param \Drupal\Core\Form\FormStateInterface $form_state Chris@0: * The current state of the form. Chris@0: */ Chris@0: public function preview(array &$form, FormStateInterface $form_state) { Chris@0: $comment_preview = comment_preview($this->entity, $form_state); Chris@0: $comment_preview['#title'] = $this->t('Preview comment'); Chris@0: $form_state->set('comment_preview', $comment_preview); Chris@0: $form_state->setRebuild(); Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function save(array $form, FormStateInterface $form_state) { Chris@0: $comment = $this->entity; Chris@0: $entity = $comment->getCommentedEntity(); Chris@0: $field_name = $comment->getFieldName(); Chris@18: $uri = $entity->toUrl(); Chris@0: $logger = $this->logger('comment'); Chris@0: Chris@0: if ($this->currentUser->hasPermission('post comments') && ($this->currentUser->hasPermission('administer comments') || $entity->{$field_name}->status == CommentItemInterface::OPEN)) { Chris@0: $comment->save(); Chris@0: $form_state->setValue('cid', $comment->id()); Chris@0: Chris@0: // Add a log entry. Chris@0: $logger->notice('Comment posted: %subject.', [ Chris@0: '%subject' => $comment->getSubject(), Chris@18: 'link' => $this->l(t('View'), $comment->toUrl()->setOption('fragment', 'comment-' . $comment->id())), Chris@0: ]); Chris@0: Chris@0: // Explain the approval queue if necessary. Chris@0: if (!$comment->isPublished()) { Chris@0: if (!$this->currentUser->hasPermission('administer comments')) { Chris@17: $this->messenger()->addStatus($this->t('Your comment has been queued for review by site administrators and will be published after approval.')); Chris@0: } Chris@0: } Chris@0: else { Chris@17: $this->messenger()->addStatus($this->t('Your comment has been posted.')); Chris@0: } Chris@0: $query = []; Chris@0: // Find the current display page for this comment. Chris@17: $field_definition = $this->entityFieldManager->getFieldDefinitions($entity->getEntityTypeId(), $entity->bundle())[$field_name]; Chris@17: $page = $this->entityTypeManager->getStorage('comment')->getDisplayOrdinal($comment, $field_definition->getSetting('default_mode'), $field_definition->getSetting('per_page')); Chris@0: if ($page > 0) { Chris@0: $query['page'] = $page; Chris@0: } Chris@0: // Redirect to the newly posted comment. Chris@0: $uri->setOption('query', $query); Chris@0: $uri->setOption('fragment', 'comment-' . $comment->id()); Chris@0: } Chris@0: else { Chris@0: $logger->warning('Comment: unauthorized comment submitted or comment submitted to a closed post %subject.', ['%subject' => $comment->getSubject()]); Chris@17: $this->messenger()->addError($this->t('Comment: unauthorized comment submitted or comment submitted to a closed post %subject.', ['%subject' => $comment->getSubject()])); Chris@0: // Redirect the user to the entity they are commenting on. Chris@0: } Chris@0: $form_state->setRedirectUrl($uri); Chris@0: } Chris@0: Chris@0: }