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