3 namespace Drupal\comment;
5 use Drupal\comment\Plugin\Field\FieldType\CommentItemInterface;
6 use Drupal\Core\Config\ConfigFactoryInterface;
7 use Drupal\Core\Entity\EntityInterface;
8 use Drupal\Core\Entity\EntityManagerInterface;
9 use Drupal\Core\Entity\FieldableEntityInterface;
10 use Drupal\Core\Extension\ModuleHandlerInterface;
11 use Drupal\Core\Routing\UrlGeneratorInterface;
12 use Drupal\Core\Routing\UrlGeneratorTrait;
13 use Drupal\Core\Session\AccountInterface;
14 use Drupal\Core\StringTranslation\StringTranslationTrait;
15 use Drupal\Core\StringTranslation\TranslationInterface;
16 use Drupal\field\Entity\FieldStorageConfig;
17 use Drupal\field\Entity\FieldConfig;
18 use Drupal\user\RoleInterface;
21 * Comment manager contains common functions to manage comment fields.
23 class CommentManager implements CommentManagerInterface {
24 use StringTranslationTrait;
25 use UrlGeneratorTrait;
28 * The entity manager service.
30 * @var \Drupal\Core\Entity\EntityManagerInterface
32 protected $entityManager;
35 * Whether the \Drupal\user\RoleInterface::AUTHENTICATED_ID can post comments.
39 protected $authenticatedCanPostComments;
42 * The user settings config object.
44 * @var \Drupal\Core\Config\Config
46 protected $userConfig;
49 * The module handler service.
51 * @var \Drupal\Core\Extension\ModuleHandlerInterface
53 protected $moduleHandler;
58 * @var \Drupal\Core\Session\AccountInterface
60 protected $currentUser;
63 * Construct the CommentManager object.
65 * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
66 * The entity manager service.
67 * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
69 * @param \Drupal\Core\StringTranslation\TranslationInterface $string_translation
70 * The string translation service.
71 * @param \Drupal\Core\Routing\UrlGeneratorInterface $url_generator
72 * The url generator service.
73 * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
74 * The module handler service.
75 * @param \Drupal\Core\Session\AccountInterface $current_user
78 public function __construct(EntityManagerInterface $entity_manager, ConfigFactoryInterface $config_factory, TranslationInterface $string_translation, UrlGeneratorInterface $url_generator, ModuleHandlerInterface $module_handler, AccountInterface $current_user) {
79 $this->entityManager = $entity_manager;
80 $this->userConfig = $config_factory->get('user.settings');
81 $this->stringTranslation = $string_translation;
82 $this->urlGenerator = $url_generator;
83 $this->moduleHandler = $module_handler;
84 $this->currentUser = $current_user;
90 public function getFields($entity_type_id) {
91 $entity_type = $this->entityManager->getDefinition($entity_type_id);
92 if (!$entity_type->entityClassImplements(FieldableEntityInterface::class)) {
96 $map = $this->entityManager->getFieldMapByFieldType('comment');
97 return isset($map[$entity_type_id]) ? $map[$entity_type_id] : [];
103 public function addBodyField($comment_type_id) {
104 if (!FieldConfig::loadByName('comment', $comment_type_id, 'comment_body')) {
105 // Attaches the body field by default.
106 $field = $this->entityManager->getStorage('field_config')->create([
107 'label' => 'Comment',
108 'bundle' => $comment_type_id,
110 'field_storage' => FieldStorageConfig::loadByName('comment', 'comment_body'),
114 // Assign widget settings for the 'default' form mode.
115 entity_get_form_display('comment', $comment_type_id, 'default')
116 ->setComponent('comment_body', [
117 'type' => 'text_textarea',
121 // Assign display settings for the 'default' view mode.
122 entity_get_display('comment', $comment_type_id, 'default')
123 ->setComponent('comment_body', [
125 'type' => 'text_default',
135 public function forbiddenMessage(EntityInterface $entity, $field_name) {
136 if (!isset($this->authenticatedCanPostComments)) {
137 // We only output a link if we are certain that users will get the
138 // permission to post comments by logging in.
139 $this->authenticatedCanPostComments = $this->entityManager
140 ->getStorage('user_role')
141 ->load(RoleInterface::AUTHENTICATED_ID)
142 ->hasPermission('post comments');
145 if ($this->authenticatedCanPostComments) {
146 // We cannot use the redirect.destination service here because these links
147 // sometimes appear on /node and taxonomy listing pages.
148 if ($entity->get($field_name)->getFieldDefinition()->getSetting('form_location') == CommentItemInterface::FORM_SEPARATE_PAGE) {
149 $comment_reply_parameters = [
150 'entity_type' => $entity->getEntityTypeId(),
151 'entity' => $entity->id(),
152 'field_name' => $field_name,
154 $destination = ['destination' => $this->url('comment.reply', $comment_reply_parameters, ['fragment' => 'comment-form'])];
157 $destination = ['destination' => $entity->url('canonical', ['fragment' => 'comment-form'])];
160 if ($this->userConfig->get('register') != USER_REGISTER_ADMINISTRATORS_ONLY) {
161 // Users can register themselves.
162 return $this->t('<a href=":login">Log in</a> or <a href=":register">register</a> to post comments', [
163 ':login' => $this->urlGenerator->generateFromRoute('user.login', [], ['query' => $destination]),
164 ':register' => $this->urlGenerator->generateFromRoute('user.register', [], ['query' => $destination]),
168 // Only admins can add new users, no public registration.
169 return $this->t('<a href=":login">Log in</a> to post comments', [
170 ':login' => $this->urlGenerator->generateFromRoute('user.login', [], ['query' => $destination]),
180 public function getCountNewComments(EntityInterface $entity, $field_name = NULL, $timestamp = 0) {
181 // @todo Replace module handler with optional history service injection
182 // after https://www.drupal.org/node/2081585.
183 if ($this->currentUser->isAuthenticated() && $this->moduleHandler->moduleExists('history')) {
184 // Retrieve the timestamp at which the current user last viewed this entity.
186 if ($entity->getEntityTypeId() == 'node') {
187 $timestamp = history_read($entity->id());
190 $function = $entity->getEntityTypeId() . '_last_viewed';
191 if (function_exists($function)) {
192 $timestamp = $function($entity->id());
195 // Default to 30 days ago.
196 // @todo Remove once https://www.drupal.org/node/1029708 lands.
197 $timestamp = COMMENT_NEW_LIMIT;
201 $timestamp = ($timestamp > HISTORY_READ_LIMIT ? $timestamp : HISTORY_READ_LIMIT);
203 // Use the timestamp to retrieve the number of new comments.
204 $query = $this->entityManager->getStorage('comment')->getQuery()
205 ->condition('entity_type', $entity->getEntityTypeId())
206 ->condition('entity_id', $entity->id())
207 ->condition('created', $timestamp, '>')
208 ->condition('status', CommentInterface::PUBLISHED);
210 // Limit to a particular field.
211 $query->condition('field_name', $field_name);
214 return $query->count()->execute();