CommentController.php 12.8 KB
Newer Older
1 2 3 4 5
<?php

namespace Drupal\comment\Controller;

use Drupal\comment\CommentInterface;
6
use Drupal\comment\CommentManagerInterface;
7
use Drupal\comment\Plugin\Field\FieldType\CommentItemInterface;
8
use Drupal\Core\Access\AccessResult;
9
use Drupal\Core\Cache\CacheableResponseInterface;
10
use Drupal\Core\Controller\ControllerBase;
11
use Drupal\Core\Entity\EntityInterface;
12
use Drupal\Core\Entity\EntityManagerInterface;
13
use Symfony\Component\DependencyInjection\ContainerInterface;
14
use Symfony\Component\HttpFoundation\JsonResponse;
15 16 17
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
18 19
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\HttpKernelInterface;
20 21 22 23

/**
 * Controller for the comment entity.
 *
24
 * @see \Drupal\comment\Entity\Comment.
25
 */
26
class CommentController extends ControllerBase {
27 28

  /**
29
   * The HTTP kernel.
30
   *
31
   * @var \Symfony\Component\HttpKernel\HttpKernelInterface
32
   */
33
  protected $httpKernel;
34

35 36 37
  /**
   * The comment manager service.
   *
38
   * @var \Drupal\comment\CommentManagerInterface
39 40 41
   */
  protected $commentManager;

42 43 44 45 46 47 48
  /**
   * The entity manager.
   *
   * @var \Drupal\Core\Entity\EntityStorageInterface
   */
  protected $entityManager;

49 50 51
  /**
   * Constructs a CommentController object.
   *
52
   * @param \Symfony\Component\HttpKernel\HttpKernelInterface $http_kernel
53
   *   HTTP kernel to handle requests.
54
   * @param \Drupal\comment\CommentManagerInterface $comment_manager
55
   *   The comment manager service.
56 57
   * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
   *   The entity manager service.
58
   */
59
  public function __construct(HttpKernelInterface $http_kernel, CommentManagerInterface $comment_manager, EntityManagerInterface $entity_manager) {
60
    $this->httpKernel = $http_kernel;
61
    $this->commentManager = $comment_manager;
62
    $this->entityManager = $entity_manager;
63
  }
64

65 66 67 68
  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
69
    return new static(
70
      $container->get('http_kernel'),
71 72
      $container->get('comment.manager'),
      $container->get('entity.manager')
73
    );
74 75 76 77 78 79 80 81
  }

  /**
   * Publishes the specified comment.
   *
   * @param \Drupal\comment\CommentInterface $comment
   *   A comment entity.
   *
82
   * @return \Symfony\Component\HttpFoundation\RedirectResponse
83
   */
84
  public function commentApprove(CommentInterface $comment) {
85
    $comment->setPublished(TRUE);
86 87
    $comment->save();

88
    drupal_set_message($this->t('Comment approved.'));
89
    $permalink_uri = $comment->permalink();
90 91
    $permalink_uri->setAbsolute();
    return new RedirectResponse($permalink_uri->toString());
92 93
  }

94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
  /**
   * Redirects comment links to the correct page depending on comment settings.
   *
   * Since comments are paged there is no way to guarantee which page a comment
   * appears on. Comment paging and threading settings may be changed at any
   * time. With threaded comments, an individual comment may move between pages
   * as comments can be added either before or after it in the overall
   * discussion. Therefore we use a central routing function for comment links,
   * which calculates the page number based on current comment settings and
   * returns the full comment view with the pager set dynamically.
   *
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   The request of the page.
   * @param \Drupal\comment\CommentInterface $comment
   *   A comment entity.
   *
   * @return \Symfony\Component\HttpFoundation\Response
   *   The comment listing set to the page on which the comment appears.
112 113 114
   *
   * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
   * @throws \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException
115 116
   */
  public function commentPermalink(Request $request, CommentInterface $comment) {
117
    if ($entity = $comment->getCommentedEntity()) {
118 119
      // Check access permissions for the entity.
      if (!$entity->access('view')) {
120 121
        throw new AccessDeniedHttpException();
      }
122
      $field_definition = $this->entityManager()->getFieldDefinitions($entity->getEntityTypeId(), $entity->bundle())[$comment->getFieldName()];
123

124
      // Find the current display page for this comment.
125
      $page = $this->entityManager()->getStorage('comment')->getDisplayOrdinal($comment, $field_definition->getSetting('default_mode'), $field_definition->getSetting('per_page'));
126
      // @todo: Cleaner sub request handling.
127
      $subrequest_url = $entity->urlInfo()->setOption('query', ['page' => $page])->toString(TRUE);
128
      $redirect_request = Request::create($subrequest_url->getGeneratedUrl(), 'GET', $request->query->all(), $request->cookies->all(), [], $request->server->all());
129 130 131 132
      // Carry over the session to the subrequest.
      if ($session = $request->getSession()) {
        $redirect_request->setSession($session);
      }
133
      $request->query->set('page', $page);
134 135 136 137 138 139 140 141 142 143
      $response = $this->httpKernel->handle($redirect_request, HttpKernelInterface::SUB_REQUEST);
      if ($response instanceof CacheableResponseInterface) {
        // @todo Once path aliases have cache tags (see
        //   https://www.drupal.org/node/2480077), add test coverage that
        //   the cache tag for a commented entity's path alias is added to the
        //   comment's permalink response, because there can be blocks or
        //   other content whose renderings depend on the subrequest's URL.
        $response->addCacheableDependency($subrequest_url);
      }
      return $response;
144 145 146 147
    }
    throw new NotFoundHttpException();
  }

148 149 150 151 152 153 154 155 156 157 158 159 160
  /**
   * The _title_callback for the page that renders the comment permalink.
   *
   * @param \Drupal\comment\CommentInterface $comment
   *   The current comment.
   *
   * @return string
   *   The translated comment subject.
   */
  public function commentPermalinkTitle(CommentInterface $comment) {
    return $this->entityManager()->getTranslationFromContext($comment)->label();
  }

161 162 163 164 165 166 167 168
  /**
   * Redirects legacy node links to the new path.
   *
   * @param \Drupal\Core\Entity\EntityInterface $node
   *   The node object identified by the legacy URL.
   *
   * @return \Symfony\Component\HttpFoundation\RedirectResponse
   *   Redirects user to new url.
169 170
   *
   * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
171 172 173 174 175 176
   */
  public function redirectNode(EntityInterface $node) {
    $fields = $this->commentManager->getFields('node');
    // Legacy nodes only had a single comment field, so use the first comment
    // field on the entity.
    if (!empty($fields) && ($field_names = array_keys($fields)) && ($field_name = reset($field_names))) {
177
      return $this->redirect('comment.reply', [
178
        'entity_type' => 'node',
179
        'entity' => $node->id(),
180
        'field_name' => $field_name,
181
      ]);
182 183 184 185
    }
    throw new NotFoundHttpException();
  }

186 187 188
  /**
   * Form constructor for the comment reply form.
   *
189 190 191
   * There are several cases that have to be handled, including:
   *   - replies to comments
   *   - replies to entities
192 193 194
   *
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   The current request object.
195 196
   * @param \Drupal\Core\Entity\EntityInterface $entity
   *   The entity this comment belongs to.
197 198
   * @param string $field_name
   *   The field_name to which the comment belongs.
199 200
   * @param int $pid
   *   (optional) Some comments are replies to other comments. In those cases,
201
   *   $pid is the parent comment's comment ID. Defaults to NULL.
202 203
   *
   * @return array|\Symfony\Component\HttpFoundation\RedirectResponse
204 205 206 207 208
   *   An associative array containing:
   *   - An array for rendering the entity or parent comment.
   *     - comment_entity: If the comment is a reply to the entity.
   *     - comment_parent: If the comment is a reply to another comment.
   *   - comment_form: The comment form as a renderable array.
209 210
   *
   * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
211
   */
212
  public function getReplyForm(Request $request, EntityInterface $entity, $field_name, $pid = NULL) {
213
    $account = $this->currentUser();
214
    $build = [];
215 216 217 218 219 220 221

    // The user is not just previewing a comment.
    if ($request->request->get('op') != $this->t('Preview')) {

      // $pid indicates that this is a reply to a comment.
      if ($pid) {
        // Load the parent comment.
222
        $comment = $this->entityManager()->getStorage('comment')->load($pid);
223
        // Display the parent comment.
224
        $build['comment_parent'] = $this->entityManager()->getViewBuilder('comment')->view($comment);
225 226
      }

227 228 229 230
      // The comment is in response to a entity.
      elseif ($entity->access('view', $account)) {
        // We make sure the field value isn't set so we don't end up with a
        // redirect loop.
231
        $entity = clone $entity;
232
        $entity->{$field_name}->status = CommentItemInterface::HIDDEN;
233
        // Render array of the entity full view mode.
234
        $build['commented_entity'] = $this->entityManager()->getViewBuilder($entity->getEntityTypeId())->view($entity, 'full');
235
        unset($build['commented_entity']['#cache']);
236 237 238 239 240 241 242
      }
    }
    else {
      $build['#title'] = $this->t('Preview comment');
    }

    // Show the actual reply box.
243
    $comment = $this->entityManager()->getStorage('comment')->create([
244
      'entity_id' => $entity->id(),
245
      'pid' => $pid,
246
      'entity_type' => $entity->getEntityTypeId(),
247
      'field_name' => $field_name,
248
    ]);
249
    $build['comment_form'] = $this->entityFormBuilder()->getForm($comment);
250 251 252 253

    return $build;
  }

254 255 256 257 258 259 260 261 262 263 264 265 266
  /**
   * Access check for the reply form.
   *
   * @param \Drupal\Core\Entity\EntityInterface $entity
   *   The entity this comment belongs to.
   * @param string $field_name
   *   The field_name to which the comment belongs.
   * @param int $pid
   *   (optional) Some comments are replies to other comments. In those cases,
   *   $pid is the parent comment's comment ID. Defaults to NULL.
   *
   * @return \Drupal\Core\Access\AccessResultInterface
   *   An access result
267 268
   *
   * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283
   */
  public function replyFormAccess(EntityInterface $entity, $field_name, $pid = NULL) {
    // Check if entity and field exists.
    $fields = $this->commentManager->getFields($entity->getEntityTypeId());
    if (empty($fields[$field_name])) {
      throw new NotFoundHttpException();
    }

    $account = $this->currentUser();

    // Check if the user has the proper permissions.
    $access = AccessResult::allowedIfHasPermission($account, 'post comments');

    $status = $entity->{$field_name}->status;
    $access = $access->andIf(AccessResult::allowedIf($status == CommentItemInterface::OPEN)
284
      ->addCacheableDependency($entity));
285 286 287 288 289 290

    // $pid indicates that this is a reply to a comment.
    if ($pid) {
      // Check if the user has the proper permissions.
      $access = $access->andIf(AccessResult::allowedIfHasPermission($account, 'access comments'));

291
      // Load the parent comment.
292 293 294 295
      $comment = $this->entityManager()->getStorage('comment')->load($pid);
      // Check if the parent comment is published and belongs to the entity.
      $access = $access->andIf(AccessResult::allowedIf($comment && $comment->isPublished() && $comment->getCommentedEntityId() == $entity->id()));
      if ($comment) {
296
        $access->addCacheableDependency($comment);
297 298 299 300 301
      }
    }
    return $access;
  }

302 303 304 305 306 307
  /**
   * Returns a set of nodes' last read timestamps.
   *
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   The request of the page.
   *
308
   * @return \Symfony\Component\HttpFoundation\JsonResponse
309
   *   The JSON response.
310 311 312
   *
   * @throws \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException
   * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
313 314
   */
  public function renderNewCommentsNodeLinks(Request $request) {
315
    if ($this->currentUser()->isAnonymous()) {
316 317 318 319
      throw new AccessDeniedHttpException();
    }

    $nids = $request->request->get('node_ids');
320
    $field_name = $request->request->get('field_name');
321 322 323 324 325 326
    if (!isset($nids)) {
      throw new NotFoundHttpException();
    }
    // Only handle up to 100 nodes.
    $nids = array_slice($nids, 0, 100);

327
    $links = [];
328
    foreach ($nids as $nid) {
329
      $node = $this->entityManager->getStorage('node')->load($nid);
330
      $new = $this->commentManager->getCountNewComments($node);
331
      $page_number = $this->entityManager()->getStorage('comment')
332
        ->getNewCommentPageNumber($node->{$field_name}->comment_count, $new, $node, $field_name);
333 334
      $query = $page_number ? ['page' => $page_number] : NULL;
      $links[$nid] = [
335
        'new_comment_count' => (int) $new,
336 337
        'first_new_comment_link' => $this->getUrlGenerator()->generateFromRoute('entity.node.canonical', ['node' => $node->id()], ['query' => $query, 'fragment' => 'new']),
      ];
338 339 340 341 342
    }

    return new JsonResponse($links);
  }

343
}