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