CommentLinkBuilder.php 9.5 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
<?php

/**
 * @file
 * Contains \Drupal\comment\CommentLinkBuilder.
 */

namespace Drupal\comment;

use Drupal\comment\Plugin\Field\FieldType\CommentItemInterface;
11
12
use Drupal\Component\Utility\NestedArray;
use Drupal\Core\Entity\EntityManagerInterface;
13
use Drupal\Core\Entity\FieldableEntityInterface;
14
15
16
17
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\StringTranslation\TranslationInterface;
18
use Drupal\Core\Url;
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49

/**
 * Defines a class for building markup for comment links on a commented entity.
 *
 * Comment links include 'login to post new comment', 'add new comment' etc.
 */
class CommentLinkBuilder implements CommentLinkBuilderInterface {

  use StringTranslationTrait;

  /**
   * Current user.
   *
   * @var \Drupal\Core\Session\AccountInterface
   */
  protected $currentUser;

  /**
   * Comment manager service.
   *
   * @var \Drupal\comment\CommentManagerInterface
   */
  protected $commentManager;

  /**
   * Module handler service.
   *
   * @var \Drupal\Core\Extension\ModuleHandlerInterface
   */
  protected $moduleHandler;

50
51
52
53
54
55
56
  /**
   * The entity manager service.
   *
   * @var \Drupal\Core\Entity\EntityManagerInterface
   */
  protected $entityManager;

57
58
59
60
61
62
63
64
65
66
67
  /**
   * Constructs a new CommentLinkBuilder object.
   *
   * @param \Drupal\Core\Session\AccountInterface $current_user
   *   Current user.
   * @param \Drupal\comment\CommentManagerInterface $comment_manager
   *   Comment manager service.
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
   *   Module handler service.
   * @param \Drupal\Core\StringTranslation\TranslationInterface $string_translation
   *   String translation service.
68
69
   * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
   *   The entity manager service.
70
   */
71
  public function __construct(AccountInterface $current_user, CommentManagerInterface $comment_manager, ModuleHandlerInterface $module_handler, TranslationInterface $string_translation, EntityManagerInterface $entity_manager) {
72
73
74
75
    $this->currentUser = $current_user;
    $this->commentManager = $comment_manager;
    $this->moduleHandler = $module_handler;
    $this->stringTranslation = $string_translation;
76
    $this->entityManager = $entity_manager;
77
78
79
80
81
  }

  /**
   * {@inheritdoc}
   */
82
  public function buildCommentedEntityLinks(FieldableEntityInterface $entity, array &$context) {
83
84
    $entity_links = array();
    $view_mode = $context['view_mode'];
85
    if ($view_mode == 'search_index' || $view_mode == 'search_result' || $view_mode == 'print' || $view_mode == 'rss') {
86
87
88
89
      // Do not add any links if the entity is displayed for:
      // - search indexing.
      // - constructing a search result excerpt.
      // - print.
90
      // - rss.
91
92
93
94
95
96
97
98
99
100
101
102
103
104
      return array();
    }

    $fields = $this->commentManager->getFields($entity->getEntityTypeId());
    foreach ($fields as $field_name => $detail) {
      // Skip fields that the entity does not have.
      if (!$entity->hasField($field_name)) {
        continue;
      }
      $links = array();
      $commenting_status = $entity->get($field_name)->status;
      if ($commenting_status != CommentItemInterface::HIDDEN) {
        // Entity has commenting status open or closed.
        $field_definition = $entity->getFieldDefinition($field_name);
105
        if ($view_mode == 'teaser') {
106
107
108
109
110
111
112
          // Teaser view: display the number of comments that have been posted,
          // or a link to add new comments if the user has permission, the
          // entity is open to new comments, and there currently are none.
          if ($this->currentUser->hasPermission('access comments')) {
            if (!empty($entity->get($field_name)->comment_count)) {
              $links['comment-comments'] = array(
                'title' => $this->formatPlural($entity->get($field_name)->comment_count, '1 comment', '@count comments'),
113
                'attributes' => array('title' => $this->t('Jump to the first comment.')),
114
                'fragment' => 'comments',
115
116
                'url' => $entity->urlInfo(),
              );
117
118
119
              if ($this->moduleHandler->moduleExists('history')) {
                $links['comment-new-comments'] = array(
                  'title' => '',
120
                  'url' => Url::fromRoute('<current>'),
121
122
                  'attributes' => array(
                    'class' => 'hidden',
123
                    'title' => $this->t('Jump to the first new comment.'),
124
125
126
127
128
129
130
131
132
133
134
135
136
137
                    'data-history-node-last-comment-timestamp' => $entity->get($field_name)->last_comment_timestamp,
                    'data-history-node-field-name' => $field_name,
                  ),
                );
              }
            }
          }
          // Provide a link to new comment form.
          if ($commenting_status == CommentItemInterface::OPEN) {
            $comment_form_location = $field_definition->getSetting('form_location');
            if ($this->currentUser->hasPermission('post comments')) {
              $links['comment-add'] = array(
                'title' => $this->t('Add new comment'),
                'language' => $entity->language(),
138
                'attributes' => array('title' => $this->t('Share your thoughts and opinions.')),
139
140
141
                'fragment' => 'comment-form',
              );
              if ($comment_form_location == CommentItemInterface::FORM_SEPARATE_PAGE) {
142
                $links['comment-add']['url'] = Url::fromRoute('comment.reply', [
143
                  'entity_type' => $entity->getEntityTypeId(),
144
                  'entity' => $entity->id(),
145
                  'field_name' => $field_name,
146
                ]);
147
148
              }
              else {
149
                $links['comment-add'] += ['url' => $entity->urlInfo()];
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
              }
            }
            elseif ($this->currentUser->isAnonymous()) {
              $links['comment-forbidden'] = array(
                'title' => $this->commentManager->forbiddenMessage($entity, $field_name),
              );
            }
          }
        }
        else {
          // Entity in other view modes: add a "post comment" link if the user
          // is allowed to post comments and if this entity is allowing new
          // comments.
          if ($commenting_status == CommentItemInterface::OPEN) {
            $comment_form_location = $field_definition->getSetting('form_location');
            if ($this->currentUser->hasPermission('post comments')) {
              // Show the "post comment" link if the form is on another page, or
              // if there are existing comments that the link will skip past.
              if ($comment_form_location == CommentItemInterface::FORM_SEPARATE_PAGE || (!empty($entity->get($field_name)->comment_count) && $this->currentUser->hasPermission('access comments'))) {
                $links['comment-add'] = array(
                  'title' => $this->t('Add new comment'),
171
                  'attributes' => array('title' => $this->t('Share your thoughts and opinions.')),
172
173
174
                  'fragment' => 'comment-form',
                );
                if ($comment_form_location == CommentItemInterface::FORM_SEPARATE_PAGE) {
175
                  $links['comment-add']['url'] = Url::fromRoute('comment.reply', [
176
                    'entity_type' => $entity->getEntityTypeId(),
177
                    'entity' => $entity->id(),
178
                    'field_name' => $field_name,
179
                  ]);
180
181
                }
                else {
182
                  $links['comment-add']['url'] = $entity->urlInfo();
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
                }
              }
            }
            elseif ($this->currentUser->isAnonymous()) {
              $links['comment-forbidden'] = array(
                'title' => $this->commentManager->forbiddenMessage($entity, $field_name),
              );
            }
          }
        }
      }

      if (!empty($links)) {
        $entity_links['comment__' . $field_name] = array(
          '#theme' => 'links__entity__comment__' . $field_name,
          '#links' => $links,
          '#attributes' => array('class' => array('links', 'inline')),
        );
        if ($view_mode == 'teaser' && $this->moduleHandler->moduleExists('history') && $this->currentUser->isAuthenticated()) {
202
          $entity_links['comment__' . $field_name]['#cache']['contexts'][] = 'user';
203
204
205
          $entity_links['comment__' . $field_name]['#attached']['library'][] = 'comment/drupal.node-new-comments-link';
          // Embed the metadata for the "X new comments" link (if any) on this
          // entity.
206
207
208
209
210
          $entity_links['comment__' . $field_name]['#attached']['drupalSettings']['history']['lastReadTimestamps'][$entity->id()] = (int) history_read($entity->id());
          $new_comments = $this->commentManager->getCountNewComments($entity);
          if ($new_comments > 0) {
            $page_number = $this->entityManager
              ->getStorage('comment')
211
              ->getNewCommentPageNumber($entity->{$field_name}->comment_count, $new_comments, $entity, $field_name);
212
213
214
215
216
217
218
219
220
221
222
            $query = $page_number ? ['page' => $page_number] : NULL;
            $value = [
              'new_comment_count' => (int) $new_comments,
              'first_new_comment_link' => $entity->url('canonical', [
                'query' => $query,
                'fragment' => 'new',
              ]),
            ];
            $parents = ['comment', 'newCommentsLinks', $entity->getEntityTypeId(), $field_name, $entity->id()];
            NestedArray::setValue($entity_links['comment__' . $field_name]['#attached']['drupalSettings'], $parents, $value);
          }
223
224
225
226
227
228
229
        }
      }
    }
    return $entity_links;
  }

}