View source
<?php
namespace Drupal\comment_perm;
use Drupal\comment\CommentForm as CommentFormBase;
use Drupal\comment\CommentInterface;
use Drupal\comment\Plugin\Field\FieldType\CommentItemInterface;
use Drupal\Component\Utility\Html;
use Drupal\Component\Utility\Unicode;
use Drupal\Core\Datetime\DrupalDateTime;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Link;
use Drupal\Core\Url;
class CommentForm extends CommentFormBase {
use CommentAccessTrait;
public function form(array $form, FormStateInterface $form_state) {
$comment = $this->entity;
$comment_type = $comment
->bundle();
$entity = $this->entityTypeManager
->getStorage($comment
->getCommentedEntityTypeId())
->load($comment
->getCommentedEntityId());
$field_name = $comment
->getFieldName();
$field_definition = $this->entityFieldManager
->getFieldDefinitions($entity
->getEntityTypeId(), $entity
->bundle())[$comment
->getFieldName()];
$config = $this
->config('user.settings');
$form['#cache']['contexts'][] = 'user.permissions';
$form['#cache']['contexts'][] = 'user.roles:authenticated';
$this->renderer
->addCacheableDependency($form, $config);
$this->renderer
->addCacheableDependency($form, $field_definition
->getConfig($entity
->bundle()));
$form['#id'] = Html::getUniqueId('comment_form');
$form['#theme'] = [
'comment_form__' . $entity
->getEntityTypeId() . '__' . $entity
->bundle() . '__' . $field_name,
'comment_form',
];
$anonymous_contact = $field_definition
->getSetting('anonymous');
$is_admin = $comment
->id() && $this
->accessAdministerComment($this->currentUser, $comment_type);
if (!$this->currentUser
->isAuthenticated() && $anonymous_contact != CommentInterface::ANONYMOUS_MAYNOT_CONTACT) {
$form['#attached']['library'][] = 'core/drupal.form';
$form['#attributes']['data-user-info-from-browser'] = TRUE;
}
if (!$comment
->id() && !$comment
->hasParentComment()) {
$form['#action'] = Url::fromRoute('comment.reply', [
'entity_type' => $entity
->getEntityTypeId(),
'entity' => $entity
->id(),
'field_name' => $field_name,
])
->toString();
}
$comment_preview = $form_state
->get('comment_preview');
if (isset($comment_preview)) {
$form += $comment_preview;
}
$form['author'] = [];
if ($is_admin) {
$form['author'] += [
'#type' => 'details',
'#title' => $this
->t('Administration'),
];
}
$author = '';
if ($is_admin) {
if (!$comment
->getOwnerId()) {
$author = $comment
->getAuthorName();
}
$status = $comment
->isPublished() ? CommentInterface::PUBLISHED : CommentInterface::NOT_PUBLISHED;
if (empty($comment_preview)) {
$form['#title'] = $this
->t('Edit comment %title', [
'%title' => $comment
->getSubject(),
]);
}
}
else {
$status = $this
->accessSkipCommentApproval($this->currentUser, $comment_type) ? CommentInterface::PUBLISHED : CommentInterface::NOT_PUBLISHED;
}
$date = '';
if ($comment
->id()) {
$date = !empty($comment->date) ? $comment->date : DrupalDateTime::createFromTimestamp($comment
->getCreatedTime());
}
$owner = $comment
->getOwner();
$form['author']['uid'] = [
'#type' => 'entity_autocomplete',
'#target_type' => 'user',
'#default_value' => $owner
->isAnonymous() ? NULL : $owner,
'#selection_settings' => [
'include_anonymous' => FALSE,
],
'#title' => $this
->t('Authored by'),
'#description' => $this
->t('Leave blank for %anonymous.', [
'%anonymous' => $config
->get('anonymous'),
]),
'#access' => $is_admin,
];
$form['author']['name'] = [
'#type' => 'textfield',
'#title' => $is_admin ? $this
->t('Name for @anonymous', [
'@anonymous' => $config
->get('anonymous'),
]) : $this
->t('Your name'),
'#default_value' => $author,
'#required' => $this->currentUser
->isAnonymous() && $anonymous_contact == CommentInterface::ANONYMOUS_MUST_CONTACT,
'#maxlength' => 60,
'#access' => $this->currentUser
->isAnonymous() || $is_admin,
'#size' => 30,
'#attributes' => [
'data-drupal-default-value' => $config
->get('anonymous'),
],
];
if ($is_admin) {
$form['author']['name']['#states'] = [
'visible' => [
':input[name="uid"]' => [
'empty' => TRUE,
],
],
];
}
$form['author']['mail'] = [
'#type' => 'email',
'#title' => $this
->t('Email'),
'#default_value' => $comment
->getAuthorEmail(),
'#required' => $this->currentUser
->isAnonymous() && $anonymous_contact == CommentInterface::ANONYMOUS_MUST_CONTACT,
'#maxlength' => 64,
'#size' => 30,
'#description' => $this
->t('The content of this field is kept private and will not be shown publicly.'),
'#access' => $comment
->getOwner()
->isAnonymous() && $is_admin || $this->currentUser
->isAnonymous() && $anonymous_contact != CommentInterface::ANONYMOUS_MAYNOT_CONTACT,
];
$form['author']['homepage'] = [
'#type' => 'url',
'#title' => $this
->t('Homepage'),
'#default_value' => $comment
->getHomepage(),
'#maxlength' => 255,
'#size' => 30,
'#access' => $is_admin || $this->currentUser
->isAnonymous() && $anonymous_contact != CommentInterface::ANONYMOUS_MAYNOT_CONTACT,
];
$form['author']['date'] = [
'#type' => 'datetime',
'#title' => $this
->t('Authored on'),
'#default_value' => $date,
'#size' => 20,
'#access' => $is_admin,
];
$form['author']['status'] = [
'#type' => 'radios',
'#title' => $this
->t('Status'),
'#default_value' => $status,
'#options' => [
CommentInterface::PUBLISHED => $this
->t('Published'),
CommentInterface::NOT_PUBLISHED => $this
->t('Not published'),
],
'#access' => $is_admin,
];
return parent::form($form, $form_state, $comment);
}
protected function actions(array $form, FormStateInterface $form_state) {
$element = parent::actions($form, $form_state);
$comment = $this->entity;
$entity = $comment
->getCommentedEntity();
$field_definition = $this->entityFieldManager
->getFieldDefinitions($entity
->getEntityTypeId(), $entity
->bundle())[$comment
->getFieldName()];
$preview_mode = $field_definition
->getSetting('preview');
$element['submit']['#access'] = $comment
->id() && $this
->accessAdministerComment($this->currentUser, $entity
->bundle()) || $preview_mode != DRUPAL_REQUIRED || $form_state
->get('comment_preview');
return $element;
}
public function buildEntity(array $form, FormStateInterface $form_state) {
$comment = parent::buildEntity($form, $form_state);
if (!$form_state
->isValueEmpty('date') && $form_state
->getValue('date') instanceof DrupalDateTime) {
$comment
->setCreatedTime($form_state
->getValue('date')
->getTimestamp());
}
else {
$comment
->setCreatedTime($this->time
->getRequestTime());
}
$author_id = $form_state
->getValue('uid');
if ($comment
->id() && $this
->accessAdministerComment($this->currentUser, $comment
->bundle())) {
$author_id = $author_id ?: 0;
}
if (!is_null($author_id)) {
if ($author_id === 0 && $form['author']['name']['#access']) {
$comment
->setAuthorName($form_state
->getValue('name'));
}
else {
$comment
->setAuthorName(NULL);
}
}
else {
$author_id = $this->currentUser
->id();
}
$comment
->setOwnerId($author_id);
if (trim($comment
->getSubject()) == '') {
if ($comment
->hasField('comment_body')) {
$comment_text = $comment->comment_body->processed;
$comment
->setSubject(Unicode::truncate(trim(Html::decodeEntities(strip_tags($comment_text))), 29, TRUE, TRUE));
}
if ($comment
->getSubject() == '') {
$comment
->setSubject($this
->t('(No subject)'));
}
}
return $comment;
}
public function save(array $form, FormStateInterface $form_state) {
$comment = $this->entity;
$comment_type = $comment
->bundle();
$entity = $comment
->getCommentedEntity();
$field_name = $comment
->getFieldName();
$uri = $entity
->toUrl();
$logger = $this
->logger('comment');
if ($this
->accessPostComment($this->currentUser, $comment_type) && ($this
->accessAdministerComment($this->currentUser, $comment_type) || $entity->{$field_name}->status == CommentItemInterface::OPEN)) {
$comment
->save();
$form_state
->setValue('cid', $comment
->id());
$logger
->notice('Comment posted: %subject.', [
'%subject' => $comment
->getSubject(),
'link' => Link::fromTextAndUrl(t('View'), $comment
->toUrl()
->setOption('fragment', 'comment-' . $comment
->id()))
->toString(),
]);
if (!$comment
->isPublished()) {
if ($this
->noAccessAdministerComment($this->currentUser, $comment_type)) {
$this
->messenger()
->addStatus($this
->t('Your comment has been queued for review by site administrators and will be published after approval.'));
}
}
else {
$this
->messenger()
->addStatus($this
->t('Your comment has been posted.'));
}
$query = [];
$field_definition = $this->entityFieldManager
->getFieldDefinitions($entity
->getEntityTypeId(), $entity
->bundle())[$field_name];
$page = $this->entityTypeManager
->getStorage('comment')
->getDisplayOrdinal($comment, $field_definition
->getSetting('default_mode'), $field_definition
->getSetting('per_page'));
if ($page > 0) {
$query['page'] = $page;
}
$uri
->setOption('query', $query);
$uri
->setOption('fragment', 'comment-' . $comment
->id());
}
else {
$logger
->warning('Comment: unauthorized comment submitted or comment submitted to a closed post %subject.', [
'%subject' => $comment
->getSubject(),
]);
$this
->messenger()
->addError($this
->t('Comment: unauthorized comment submitted or comment submitted to a closed post %subject.', [
'%subject' => $comment
->getSubject(),
]));
}
$form_state
->setRedirectUrl($uri);
}
}