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