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

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