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

/**
 * @file
 * Contains \Drupal\comment\Controller\CommentController.
 */

namespace Drupal\comment\Controller;

use Drupal\comment\CommentInterface;
11
use Drupal\comment\CommentManagerInterface;
12
use Drupal\comment\Plugin\Field\FieldType\CommentItemInterface;
13
use Drupal\Core\Controller\ControllerBase;
14
use Drupal\Core\Entity\EntityInterface;
15
use Drupal\Core\Entity\EntityManagerInterface;
16
use Symfony\Component\DependencyInjection\ContainerInterface;
17
use Symfony\Component\HttpFoundation\JsonResponse;
18 19 20
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
21 22
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\HttpKernelInterface;
23 24 25 26

/**
 * Controller for the comment entity.
 *
27
 * @see \Drupal\comment\Entity\Comment.
28
 */
29
class CommentController extends ControllerBase {
30 31

  /**
32
   * The HTTP kernel.
33
   *
34
   * @var \Symfony\Component\HttpKernel\HttpKernelInterface
35
   */
36
  protected $httpKernel;
37

38 39 40
  /**
   * The comment manager service.
   *
41
   * @var \Drupal\comment\CommentManagerInterface
42 43 44
   */
  protected $commentManager;

45 46 47 48 49 50 51
  /**
   * The entity manager.
   *
   * @var \Drupal\Core\Entity\EntityStorageInterface
   */
  protected $entityManager;

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

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

  /**
   * Publishes the specified comment.
   *
   * @param \Drupal\comment\CommentInterface $comment
   *   A comment entity.
   *
   * @return \Symfony\Component\HttpFoundation\RedirectResponse.
86
   *   Redirects to the permalink URL for this comment.
87
   */
88
  public function commentApprove(CommentInterface $comment) {
89
    $comment->setPublished(TRUE);
90 91
    $comment->save();

92
    drupal_set_message($this->t('Comment approved.'));
93
    $permalink_uri = $comment->permalink();
94 95
    $permalink_uri->setAbsolute();
    return new RedirectResponse($permalink_uri->toString());
96 97
  }

98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
  /**
   * 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.
   *
   * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
   * @throws \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException
   *
   * @return \Symfony\Component\HttpFoundation\Response
   *   The comment listing set to the page on which the comment appears.
   */
  public function commentPermalink(Request $request, CommentInterface $comment) {
121
    if ($entity = $comment->getCommentedEntity()) {
122 123
      // Check access permissions for the entity.
      if (!$entity->access('view')) {
124 125
        throw new AccessDeniedHttpException();
      }
126
      $field_definition = $this->entityManager()->getFieldDefinitions($entity->getEntityTypeId(), $entity->bundle())[$comment->getFieldName()];
127

128
      // Find the current display page for this comment.
129
      $page = $this->entityManager()->getStorage('comment')->getDisplayOrdinal($comment, $field_definition->getSetting('default_mode'), $field_definition->getSetting('per_page'));
130
      // @todo: Cleaner sub request handling.
131
      $redirect_request = Request::create($entity->getSystemPath(), 'GET', $request->query->all(), $request->cookies->all(), array(), $request->server->all());
132 133 134 135 136 137 138 139
      $redirect_request->query->set('page', $page);
      // @todo: Convert the pager to use the request object.
      $request->query->set('page', $page);
      return $this->httpKernel->handle($redirect_request, HttpKernelInterface::SUB_REQUEST);
    }
    throw new NotFoundHttpException();
  }

140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
  /**
   * Redirects legacy node links to the new path.
   *
   * @param \Drupal\Core\Entity\EntityInterface $node
   *   The node object identified by the legacy URL.
   *
   * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
   *
   * @return \Symfony\Component\HttpFoundation\RedirectResponse
   *   Redirects user to new url.
   */
  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))) {
156 157
      return $this->redirect('comment.reply', array(
        'entity_type' => 'node',
158
        'entity' => $node->id(),
159 160
        'field_name' => $field_name,
      ));
161 162 163 164
    }
    throw new NotFoundHttpException();
  }

165 166 167
  /**
   * Form constructor for the comment reply form.
   *
168 169 170 171
   * There are several cases that have to be handled, including:
   *   - replies to comments
   *   - replies to entities
   *   - attempts to reply to entities that can no longer accept comments
172 173
   *   - respecting access permissions ('access comments', 'post comments',
   *     etc.)
174 175 176
   *
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   The current request object.
177 178
   * @param \Drupal\Core\Entity\EntityInterface $entity
   *   The entity this comment belongs to.
179 180
   * @param string $field_name
   *   The field_name to which the comment belongs.
181 182
   * @param int $pid
   *   (optional) Some comments are replies to other comments. In those cases,
183
   *   $pid is the parent comment's comment ID. Defaults to NULL.
184
   *
185
   * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
186 187
   * @return array|\Symfony\Component\HttpFoundation\RedirectResponse
   *   One of the following:
188 189 190 191 192
   *   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.
193
   *   - An associative array containing:
194 195
   *     - An array for rendering the entity or parent comment.
   *        - comment_entity: If the comment is a reply to the entity.
196 197 198 199
   *        - comment_parent: If the comment is a reply to another comment.
   *     - comment_form: The comment form as a renderable array.
   *   - A redirect response to current node:
   *     - If user is not authorized to post comments.
200
   *     - If parent comment doesn't belong to current entity.
201
   *     - If user is not authorized to view comments.
202
   *     - If current entity comments are disable.
203
   */
204
  public function getReplyForm(Request $request, EntityInterface $entity, $field_name, $pid = NULL) {
205
    // Check if entity and field exists.
206 207
    $fields = $this->commentManager->getFields($entity->getEntityTypeId());
    if (empty($fields[$field_name])) {
208 209
      throw new NotFoundHttpException();
    }
210

211
    $account = $this->currentUser();
212
    $uri = $entity->urlInfo()->setAbsolute();
213
    $build = array();
214 215 216 217

    // Check if the user has the proper permissions.
    if (!$account->hasPermission('post comments')) {
      drupal_set_message($this->t('You are not authorized to post comments.'), 'error');
218
      return new RedirectResponse($uri->toString());
219 220 221 222
    }

    // The user is not just previewing a comment.
    if ($request->request->get('op') != $this->t('Preview')) {
223
      $status = $entity->{$field_name}->status;
224
      if ($status != CommentItemInterface::OPEN) {
225
        drupal_set_message($this->t("This discussion is closed: you can't post new comments."), 'error');
226
        return new RedirectResponse($uri->toString());
227 228 229 230 231 232 233
      }

      // $pid indicates that this is a reply to a comment.
      if ($pid) {
        // Check if the user has the proper permissions.
        if (!$account->hasPermission('access comments')) {
          drupal_set_message($this->t('You are not authorized to view comments.'), 'error');
234
          return new RedirectResponse($uri->toString());
235 236
        }
        // Load the parent comment.
237
        $comment = $this->entityManager()->getStorage('comment')->load($pid);
238
        // Check if the parent comment is published and belongs to the entity.
239
        if (!$comment->isPublished() || ($comment->getCommentedEntityId() != $entity->id())) {
240
          drupal_set_message($this->t('The comment you are replying to does not exist.'), 'error');
241
          return new RedirectResponse($uri->toString());
242 243
        }
        // Display the parent comment.
244
        $build['comment_parent'] = $this->entityManager()->getViewBuilder('comment')->view($comment);
245 246
      }

247 248 249 250
      // 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.
251
        $entity = clone $entity;
252
        $entity->{$field_name}->status = CommentItemInterface::HIDDEN;
253
        // Render array of the entity full view mode.
254
        $build['commented_entity'] = $this->entityManager()->getViewBuilder($entity->getEntityTypeId())->view($entity, 'full');
255
        unset($build['commented_entity']['#cache']);
256 257 258 259 260 261 262
      }
    }
    else {
      $build['#title'] = $this->t('Preview comment');
    }

    // Show the actual reply box.
263
    $comment = $this->entityManager()->getStorage('comment')->create(array(
264
      'entity_id' => $entity->id(),
265
      'pid' => $pid,
266
      'entity_type' => $entity->getEntityTypeId(),
267
      'field_name' => $field_name,
268
    ));
269
    $build['comment_form'] = $this->entityFormBuilder()->getForm($comment);
270 271 272 273

    return $build;
  }

274 275 276 277 278 279
  /**
   * Returns a set of nodes' last read timestamps.
   *
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   The request of the page.
   *
280 281
   * @throws \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException
   * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
282
   * @return \Symfony\Component\HttpFoundation\JsonResponse
283 284 285
   *   The JSON response.
   */
  public function renderNewCommentsNodeLinks(Request $request) {
286
    if ($this->currentUser()->isAnonymous()) {
287 288 289 290
      throw new AccessDeniedHttpException();
    }

    $nids = $request->request->get('node_ids');
291
    $field_name = $request->request->get('field_name');
292 293 294 295 296 297 298 299
    if (!isset($nids)) {
      throw new NotFoundHttpException();
    }
    // Only handle up to 100 nodes.
    $nids = array_slice($nids, 0, 100);

    $links = array();
    foreach ($nids as $nid) {
300
      $node = $this->entityManager->getStorage('node')->load($nid);
301
      $new = $this->commentManager->getCountNewComments($node);
302 303 304
      $page_number = $this->entityManager()->getStorage('comment')
        ->getNewCommentPageNumber($node->{$field_name}->comment_count, $new, $node);
      $query = $page_number ? array('page' => $page_number) : NULL;
305
      $links[$nid] = array(
306
        'new_comment_count' => (int) $new,
307
        'first_new_comment_link' => $this->getUrlGenerator()->generateFromPath('node/' . $node->id(), array('query' => $query, 'fragment' => 'new')),
308 309 310 311 312 313
      );
    }

    return new JsonResponse($links);
  }

314
}