CommentViewBuilder.php 12.3 KB
Newer Older
1 2 3 4
<?php

/**
 * @file
5
 * Definition of Drupal\comment\CommentViewBuilder.
6 7 8 9
 */

namespace Drupal\comment;

10
use Drupal\Core\Access\CsrfTokenGenerator;
11
use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
12
use Drupal\Core\Entity\EntityInterface;
13
use Drupal\Core\Entity\EntityManagerInterface;
14
use Drupal\Core\Entity\EntityTypeInterface;
15
use Drupal\Core\Entity\EntityViewBuilder;
16
use Drupal\Core\Language\LanguageManagerInterface;
17 18
use Drupal\field\FieldInfo;
use Symfony\Component\DependencyInjection\ContainerInterface;
19 20 21 22

/**
 * Render controller for comments.
 */
23
class CommentViewBuilder extends EntityViewBuilder {
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38

  /**
   * The field info service.
   *
   * @var \Drupal\field\FieldInfo
   */
  protected $fieldInfo;

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

39 40 41 42 43 44 45
  /**
   * The CSRF token manager service.
   *
   * @var \Drupal\Core\Access\CsrfTokenGenerator
   */
  protected $csrfToken;

46 47 48
  /**
   * {@inheritdoc}
   */
49
  public static function createInstance(ContainerInterface $container, EntityTypeInterface $entity_type) {
50
    return new static(
51
      $entity_type,
52
      $container->get('entity.manager'),
53
      $container->get('language_manager'),
54
      $container->get('field.info'),
55
      $container->get('csrf_token')
56 57 58 59
    );
  }

  /**
60
   * Constructs a new CommentViewBuilder.
61
   *
62 63
   * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
   *   The entity type definition.
64
   * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
65
   *   The entity manager service.
66 67
   * @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
   *   The language manager.
68 69
   * @param \Drupal\field\FieldInfo $field_info
   *   The field info service.
70 71
   * @param \Drupal\Core\Access\CsrfTokenGenerator $csrf_token
   *   The CSRF token manager service.
72
   */
73 74
  public function __construct(EntityTypeInterface $entity_type, EntityManagerInterface $entity_manager, LanguageManagerInterface $language_manager, FieldInfo $field_info, CsrfTokenGenerator $csrf_token) {
    parent::__construct($entity_type, $entity_manager, $language_manager);
75
    $this->fieldInfo = $field_info;
76
    $this->csrfToken = $csrf_token;
77
  }
78 79

  /**
80
   * Overrides Drupal\Core\Entity\EntityViewBuilder::buildContent().
81 82
   *
   * In addition to modifying the content key on entities, this implementation
83 84 85 86
   * will also set the comment entity key which all comments carry.
   *
   * @throws \InvalidArgumentException
   *   Thrown when a comment is attached to an entity that no longer exists.
87
   */
88
  public function buildContent(array $entities, array $displays, $view_mode, $langcode = NULL) {
89
    /** @var \Drupal\comment\CommentInterface[] $entities */
90 91 92 93 94
    $return = array();
    if (empty($entities)) {
      return $return;
    }

95 96 97
    // Pre-load associated users into cache to leverage multiple loading.
    $uids = array();
    foreach ($entities as $entity) {
98
      $uids[] = $entity->getOwnerId();
99
    }
100
    $this->entityManager->getStorageController('user')->loadMultiple(array_unique($uids));
101

102
    parent::buildContent($entities, $displays, $view_mode, $langcode);
103

104 105 106
    // Load all the entities that have comments attached.
    $commented_entity_ids = array();
    $commented_entities = array();
107
    foreach ($entities as $entity) {
108
      $commented_entity_ids[$entity->getCommentedEntityTypeId()][] = $entity->getCommentedEntityId();
109 110
    }
    // Load entities in bulk. This is more performant than using
111
    // $comment->getCommentedEntity() as we can load them in bulk per type.
112 113
    foreach ($commented_entity_ids as $entity_type => $entity_ids) {
      $commented_entities[$entity_type] = $this->entityManager->getStorageController($entity_type)->loadMultiple($entity_ids);
114
    }
115

116
    foreach ($entities as $entity) {
117 118
      if (isset($commented_entities[$entity->getCommentedEntityTypeId()][$entity->getCommentedEntityId()])) {
        $commented_entity = $commented_entities[$entity->getCommentedEntityTypeId()][$entity->getCommentedEntityId()];
119 120
      }
      else {
121
        throw new \InvalidArgumentException(t('Invalid entity for comment.'));
122
      }
123
      $entity->content['#entity'] = $entity;
124
      $entity->content['#theme'] = 'comment__' . $entity->getFieldId() . '__' . $commented_entity->bundle();
125
      $entity->content['links'] = array(
126 127 128 129 130 131
        '#type' => 'render_cache_placeholder',
        '#callback' => '\Drupal\comment\CommentViewBuilder::renderLinks',
        '#context' => array(
          'comment_entity_id' => $entity->id(),
          'view_mode' => $view_mode,
          'langcode' => $langcode,
132
          'commented_entity_type' => $commented_entity->getEntityTypeId(),
133 134 135
          'commented_entity_id' => $commented_entity->id(),
          'in_preview' => !empty($entity->in_preview),
        ),
136
      );
137 138 139 140

      if (!isset($entity->content['#attached'])) {
        $entity->content['#attached'] = array();
      }
141
      $entity->content['#attached']['library'][] = 'comment/drupal.comment-by-viewer';
142
      if ($this->moduleHandler->moduleExists('history') &&  \Drupal::currentUser()->isAuthenticated()) {
143
        $entity->content['#attached']['library'][] = 'comment/drupal.comment-new-indicator';
144 145 146 147 148

        // Embed the metadata for the comment "new" indicators on this node.
        $entity->content['#post_render_cache']['history_attach_timestamp'] = array(
          array('node_id' => $commented_entity->id()),
        );
149
      }
150 151 152
    }
  }

153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
  /**
   * #post_render_cache callback; replaces the placeholder with comment links.
   *
   * Renders the links on a comment.
   *
   * @param array $context
   *   An array with the following keys:
   *   - comment_entity_id: a comment entity ID
   *   - view_mode: the view mode in which the comment entity is being viewed
   *   - langcode: in which language the comment entity is being viewed
   *   - commented_entity_type: the entity type to which the comment is attached
   *   - commented_entity_id: the entity ID to which the comment is attached
   *   - in_preview: whether the comment is currently being previewed
   *
   * @return array
   *   A renderable array representing the comment links.
   */
  public static function renderLinks(array $context) {
    $links = array(
      '#theme' => 'links__comment',
      '#pre_render' => array('drupal_pre_render_links'),
      '#attributes' => array('class' => array('links', 'inline')),
    );

    if (!$context['in_preview']) {
      $entity = entity_load('comment', $context['comment_entity_id']);
      $commented_entity = entity_load($context['commented_entity_type'], $context['commented_entity_id']);

      $links['comment'] = self::buildLinks($entity, $commented_entity);

      // Allow other modules to alter the comment links.
      $hook_context = array(
        'view_mode' => $context['view_mode'],
        'langcode' => $context['langcode'],
        'commented_entity' => $commented_entity
      );
      \Drupal::moduleHandler()->alter('comment_links', $links, $entity, $hook_context);
    }

    return $links;
  }

195 196 197
  /**
   * Build the default links (reply, edit, delete …) for a comment.
   *
198
   * @param \Drupal\comment\CommentInterface $entity
199 200 201 202 203 204 205
   *   The comment object.
   * @param \Drupal\Core\Entity\EntityInterface $commented_entity
   *   The entity to which the comment is attached.
   *
   * @return array
   *   An array that can be processed by drupal_pre_render_links().
   */
206
  protected static function buildLinks(CommentInterface $entity, EntityInterface $commented_entity) {
207
    $links = array();
208
    $status = $commented_entity->get($entity->getFieldName())->status;
209

210 211
    $container = \Drupal::getContainer();

212 213 214
    if ($status == COMMENT_OPEN) {
      if ($entity->access('delete')) {
        $links['comment-delete'] = array(
215
          'title' => t('Delete'),
216 217 218 219 220 221 222
          'href' => "comment/{$entity->id()}/delete",
          'html' => TRUE,
        );
      }

      if ($entity->access('update')) {
        $links['comment-edit'] = array(
223
          'title' => t('Edit'),
224 225 226 227 228 229
          'href' => "comment/{$entity->id()}/edit",
          'html' => TRUE,
        );
      }
      if ($entity->access('create')) {
        $links['comment-reply'] = array(
230
          'title' => t('Reply'),
231
          'href' => "comment/reply/{$entity->getCommentedEntityTypeId()}/{$entity->getCommentedEntityId()}/{$entity->getFieldName()}/{$entity->id()}",
232 233 234
          'html' => TRUE,
        );
      }
235
      if (!$entity->isPublished() && $entity->access('approve')) {
236
        $links['comment-approve'] = array(
237
          'title' => t('Approve'),
238 239
          'route_name' => 'comment.approve',
          'route_parameters' => array('comment' => $entity->id()),
240 241 242 243
          'html' => TRUE,
        );
      }
      if (empty($links)) {
244
        $links['comment-forbidden']['title'] = \Drupal::service('comment.manager')->forbiddenMessage($commented_entity, $entity->getFieldName());
245 246 247 248 249
        $links['comment-forbidden']['html'] = TRUE;
      }
    }

    // Add translations link for translation-enabled comment bundles.
250
    if ($container->get('module_handler')->moduleExists('content_translation') && content_translation_translate_access($entity)) {
251
      $links['comment-translations'] = array(
252
        'title' => t('Translate'),
253 254 255 256 257 258 259 260 261 262 263 264 265 266
        'href' => 'comment/' . $entity->id() . '/translations',
        'html' => TRUE,
      );
    }

    return array(
      '#theme' => 'links__comment__comment',
      // The "entity" property is specified to be present, so no need to
      // check.
      '#links' => $links,
      '#attributes' => array('class' => array('links', 'inline')),
    );
  }

267
  /**
268
   * {@inheritdoc}
269
   */
270
  protected function alterBuild(array &$build, EntityInterface $comment, EntityViewDisplayInterface $display, $view_mode, $langcode = NULL) {
271
    parent::alterBuild($build, $comment, $display, $view_mode, $langcode);
272 273
    if (empty($comment->in_preview)) {
      $prefix = '';
274 275
      $commented_entity = $comment->getCommentedEntity();
      $instance = $this->fieldInfo->getInstance($commented_entity->getEntityTypeId(), $commented_entity->bundle(), $comment->getFieldName());
276
      $is_threaded = isset($comment->divs)
277
        && $instance->getSetting('default_mode') == COMMENT_MODE_THREADED;
278 279 280

      // Add indentation div or close open divs as needed.
      if ($is_threaded) {
281
        $build['#attached']['css'][] = drupal_get_path('module', 'comment') . '/css/comment.theme.css';
282 283 284 285
        $prefix .= $comment->divs <= 0 ? str_repeat('</div>', abs($comment->divs)) : "\n" . '<div class="indented">';
      }

      // Add anchor for each comment.
286
      $prefix .= "<a id=\"comment-{$comment->id()}\"></a>\n";
287 288 289 290 291 292 293 294
      $build['#prefix'] = $prefix;

      // Close all open divs.
      if ($is_threaded && !empty($comment->divs_final)) {
        $build['#suffix'] = str_repeat('</div>', $comment->divs_final);
      }
    }
  }
295

296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346
  /**
   * #post_render_cache callback; attaches "X new comments" link metadata.
   *
   * @param array $element
   *   A render array with the following keys:
   *   - #markup
   *   - #attached
   * @param array $context
   *   An array with the following keys:
   *   - entity_type: an entity type
   *   - entity_id: an entity ID
   *   - field_name: a comment field name
   *
   * @return array $element
   *   The updated $element.
   */
  public static function attachNewCommentsLinkMetadata(array $element, array $context) {
    // Build "X new comments" link metadata.
    $new = (int)comment_num_new($context['entity_id'], $context['entity_type']);
    // Early-return if there are zero new comments for the current user.
    if ($new === 0) {
      return $element;
    }
    $entity = \Drupal::entityManager()
      ->getStorageController($context['entity_type'])
      ->load($context['entity_id']);
    $field_name = $context['field_name'];
    $query = comment_new_page_count($entity->{$field_name}->comment_count, $new, $entity);

    // Attach metadata.
    $element['#attached']['js'][] = array(
      'type' => 'setting',
      'data' => array(
        'comment' => array(
          'newCommentsLinks' => array(
            $context['entity_type'] => array(
              $context['field_name'] => array(
                $context['entity_id'] => array(
                  'new_comment_count' => (int)$new,
                  'first_new_comment_link' => \Drupal::urlGenerator()->generateFromPath('node/' . $entity->id(), array('query' => $query, 'fragment' => 'new')),
                )
              )
            ),
          )
        ),
      ),
    );

    return $element;
  }

347
}