CommentStorage.php 11.8 KB
Newer Older
1 2 3 4
<?php

/**
 * @file
5
 * Definition of Drupal\comment\CommentStorage.
6 7
 */

8
namespace Drupal\comment;
9

10
use Drupal\Core\Cache\CacheBackendInterface;
11
use Drupal\Core\Database\Connection;
12
use Drupal\Core\Entity\EntityManagerInterface;
13
use Drupal\Core\Entity\EntityTypeInterface;
14 15
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\FieldableEntityInterface;
16
use Drupal\Core\Entity\Sql\SqlContentEntityStorage;
17
use Drupal\Core\Session\AccountInterface;
18
use Drupal\Core\Language\LanguageManagerInterface;
19
use Symfony\Component\DependencyInjection\ContainerInterface;
20 21 22 23

/**
 * Defines the controller class for comments.
 *
24
 * This extends the Drupal\Core\Entity\Sql\SqlContentEntityStorage class,
25
 * adding required special handling for comment entities.
26
 */
27
class CommentStorage extends SqlContentEntityStorage implements CommentStorageInterface {
28

29 30 31 32 33 34 35
  /**
   * The current user.
   *
   * @var \Drupal\Core\Session\AccountInterface
   */
  protected $currentUser;

36
  /**
37
   * Constructs a CommentStorage object.
38 39 40 41 42
   *
   * @param \Drupal\Core\Entity\EntityTypeInterface $entity_info
   *   An array of entity info for the entity type.
   * @param \Drupal\Core\Database\Connection $database
   *   The database connection to be used.
43 44
   * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
   *   The entity manager.
45 46
   * @param \Drupal\Core\Cache\CacheBackendInterface $cache_backend
   *   Cache backend instance to use.
47 48
   * @param \Drupal\Core\Session\AccountInterface $current_user
   *   The current user.
49 50
   * @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
   *   The language manager.
51
   */
52 53
  public function __construct(EntityTypeInterface $entity_info, Connection $database, EntityManagerInterface $entity_manager, AccountInterface $current_user, CacheBackendInterface $cache, LanguageManagerInterface $language_manager) {
    parent::__construct($entity_info, $database, $entity_manager, $cache, $language_manager);
54
    $this->currentUser = $current_user;
55 56 57 58 59 60 61 62 63
  }

  /**
   * {@inheritdoc}
   */
  public static function createInstance(ContainerInterface $container, EntityTypeInterface $entity_info) {
    return new static(
      $entity_info,
      $container->get('database'),
64
      $container->get('entity.manager'),
65
      $container->get('current_user'),
66 67
      $container->get('cache.entity'),
      $container->get('language_manager')
68 69 70
    );
  }

71 72 73
  /**
   * {@inheritdoc}
   */
74
  public function getMaxThread(CommentInterface $comment) {
75
    $query = $this->database->select('comment_field_data', 'c')
76
      ->condition('entity_id', $comment->getCommentedEntityId())
77
      ->condition('field_name', $comment->getFieldName())
78 79
      ->condition('entity_type', $comment->getCommentedEntityTypeId())
      ->condition('default_langcode', 1);
80 81 82
    $query->addExpression('MAX(thread)', 'thread');
    return $query->execute()
      ->fetchField();
83 84 85 86 87
  }

  /**
   * {@inheritdoc}
   */
88
  public function getMaxThreadPerThread(CommentInterface $comment) {
89
    $query = $this->database->select('comment_field_data', 'c')
90
      ->condition('entity_id', $comment->getCommentedEntityId())
91
      ->condition('field_name', $comment->getFieldName())
92
      ->condition('entity_type', $comment->getCommentedEntityTypeId())
93 94
      ->condition('thread', $comment->getParentComment()->getThread() . '.%', 'LIKE')
      ->condition('default_langcode', 1);
95 96 97
    $query->addExpression('MAX(thread)', 'thread');
    return $query->execute()
      ->fetchField();
98 99
  }

100 101 102 103 104 105
  /**
   * {@inheritdoc}
   */
  public function getDisplayOrdinal(CommentInterface $comment, $comment_mode, $divisor = 1) {
    // Count how many comments (c1) are before $comment (c2) in display order.
    // This is the 0-based display ordinal.
106 107
    $query = $this->database->select('comment_field_data', 'c1');
    $query->innerJoin('comment_field_data', 'c2', 'c2.entity_id = c1.entity_id AND c2.entity_type = c1.entity_type AND c2.field_name = c1.field_name');
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
    $query->addExpression('COUNT(*)', 'count');
    $query->condition('c2.cid', $comment->id());
    if (!$this->currentUser->hasPermission('administer comments')) {
      $query->condition('c1.status', CommentInterface::PUBLISHED);
    }

    if ($comment_mode == CommentManagerInterface::COMMENT_MODE_FLAT) {
      // For rendering flat comments, cid is used for ordering comments due to
      // unpredictable behavior with timestamp, so we make the same assumption
      // here.
      $query->condition('c1.cid', $comment->id(), '<');
    }
    else {
      // For threaded comments, the c.thread column is used for ordering. We can
      // use the sorting code for comparison, but must remove the trailing
      // slash.
      $query->where('SUBSTRING(c1.thread, 1, (LENGTH(c1.thread) - 1)) < SUBSTRING(c2.thread, 1, (LENGTH(c2.thread) - 1))');
    }

127 128 129
    $query->condition('c1.default_langcode', 1);
    $query->condition('c2.default_langcode', 1);

130 131 132 133 134
    $ordinal = $query->execute()->fetchField();

    return ($divisor > 1) ? floor($ordinal / $divisor) : $ordinal;
  }

135 136 137
  /**
   * {@inheritdoc}
   */
138
  public function getNewCommentPageNumber($total_comments, $new_comments, FieldableEntityInterface $entity, $field_name = 'comment') {
139 140
    $field = $entity->getFieldDefinition($field_name);
    $comments_per_page = $field->getSetting('per_page');
141 142 143 144 145

    if ($total_comments <= $comments_per_page) {
      // Only one page of comments.
      $count = 0;
    }
146
    elseif ($field->getSetting('default_mode') == CommentManagerInterface::COMMENT_MODE_FLAT) {
147 148 149 150 151 152 153
      // Flat comments.
      $count = $total_comments - $new_comments;
    }
    else {
      // Threaded comments.

      // 1. Find all the threads with a new comment.
154
      $unread_threads_query = $this->database->select('comment_field_data', 'comment')
155 156 157 158 159
        ->fields('comment', array('thread'))
        ->condition('entity_id', $entity->id())
        ->condition('entity_type', $entity->getEntityTypeId())
        ->condition('field_name', $field_name)
        ->condition('status', CommentInterface::PUBLISHED)
160
        ->condition('default_langcode', 1)
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
        ->orderBy('created', 'DESC')
        ->orderBy('cid', 'DESC')
        ->range(0, $new_comments);

      // 2. Find the first thread.
      $first_thread_query = $this->database->select($unread_threads_query, 'thread');
      $first_thread_query->addExpression('SUBSTRING(thread, 1, (LENGTH(thread) - 1))', 'torder');
      $first_thread = $first_thread_query
        ->fields('thread', array('thread'))
        ->orderBy('torder')
        ->range(0, 1)
        ->execute()
        ->fetchField();

      // Remove the final '/'.
      $first_thread = substr($first_thread, 0, -1);

      // Find the number of the first comment of the first unread thread.
179
      $count = $this->database->query('SELECT COUNT(*) FROM {comment_field_data} WHERE entity_id = :entity_id
180 181
                        AND entity_type = :entity_type
                        AND field_name = :field_name
182 183 184
                        AND status = :status
                        AND SUBSTRING(thread, 1, (LENGTH(thread) - 1)) < :thread
                        AND default_langcode = 1', array(
185 186 187 188 189 190 191 192 193 194 195
        ':status' => CommentInterface::PUBLISHED,
        ':entity_id' => $entity->id(),
        ':field_name' => $field_name,
        ':entity_type' => $entity->getEntityTypeId(),
        ':thread' => $first_thread,
      ))->fetchField();
    }

    return $comments_per_page > 0 ? (int) ($count / $comments_per_page) : 0;
  }

196 197 198 199
  /**
   * {@inheritdoc}
   */
  public function getChildCids(array $comments) {
200
    return $this->database->select('comment_field_data', 'c')
201 202
      ->fields('c', array('cid'))
      ->condition('pid', array_keys($comments))
203
      ->condition('default_langcode', 1)
204 205 206
      ->execute()
      ->fetchCol();
  }
207

208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 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
  /**
   * {@inheritdoc}
   *
   * To display threaded comments in the correct order we keep a 'thread' field
   * and order by that value. This field keeps this data in
   * a way which is easy to update and convenient to use.
   *
   * A "thread" value starts at "1". If we add a child (A) to this comment,
   * we assign it a "thread" = "1.1". A child of (A) will have "1.1.1". Next
   * brother of (A) will get "1.2". Next brother of the parent of (A) will get
   * "2" and so on.
   *
   * First of all note that the thread field stores the depth of the comment:
   * depth 0 will be "X", depth 1 "X.X", depth 2 "X.X.X", etc.
   *
   * Now to get the ordering right, consider this example:
   *
   * 1
   * 1.1
   * 1.1.1
   * 1.2
   * 2
   *
   * If we "ORDER BY thread ASC" we get the above result, and this is the
   * natural order sorted by time. However, if we "ORDER BY thread DESC"
   * we get:
   *
   * 2
   * 1.2
   * 1.1.1
   * 1.1
   * 1
   *
   * Clearly, this is not a natural way to see a thread, and users will get
   * confused. The natural order to show a thread by time desc would be:
   *
   * 2
   * 1
   * 1.2
   * 1.1
   * 1.1.1
   *
   * which is what we already did before the standard pager patch. To achieve
   * this we simply add a "/" at the end of each "thread" value. This way, the
   * thread fields will look like this:
   *
   * 1/
   * 1.1/
   * 1.1.1/
   * 1.2/
   * 2/
   *
   * we add "/" since this char is, in ASCII, higher than every number, so if
   * now we "ORDER BY thread DESC" we get the correct order. However this would
   * spoil the reverse ordering, "ORDER BY thread ASC" -- here, we do not need
   * to consider the trailing "/" so we use a substring only.
   */
  public function loadThread(EntityInterface $entity, $field_name, $mode, $comments_per_page = 0, $pager_id = 0) {
    $query = $this->database->select('comment_field_data', 'c');
    if ($comments_per_page) {
      $query = $query->extend('Drupal\Core\Database\Query\PagerSelectExtender')
        ->limit($comments_per_page);
      if ($pager_id) {
        $query->element($pager_id);
      }
    }
    $query->addField('c', 'cid');
    $query
      ->condition('c.entity_id', $entity->id())
      ->condition('c.entity_type', $entity->getEntityTypeId())
      ->condition('c.field_name', $field_name)
      ->condition('c.default_langcode', 1)
      ->addTag('entity_access')
      ->addTag('comment_filter')
      ->addMetaData('base_table', 'comment')
      ->addMetaData('entity', $entity)
      ->addMetaData('field_name', $field_name);

    $count_query = $this->database->select('comment_field_data', 'c');
    $count_query->addExpression('COUNT(*)');
    $count_query
      ->condition('c.entity_id', $entity->id())
      ->condition('c.entity_type', $entity->getEntityTypeId())
      ->condition('c.field_name', $field_name)
      ->condition('c.default_langcode', 1)
      ->addTag('entity_access')
      ->addTag('comment_filter')
      ->addMetaData('base_table', 'comment')
      ->addMetaData('entity', $entity)
      ->addMetaData('field_name', $field_name);

    if (!$this->currentUser->hasPermission('administer comments')) {
      $query->condition('c.status', CommentInterface::PUBLISHED);
      $count_query->condition('c.status', CommentInterface::PUBLISHED);
    }
    if ($mode == CommentManagerInterface::COMMENT_MODE_FLAT) {
      $query->orderBy('c.cid', 'ASC');
    }
    else {
      // See comment above. Analysis reveals that this doesn't cost too
      // much. It scales much much better than having the whole comment
      // structure.
      $query->addExpression('SUBSTRING(c.thread, 1, (LENGTH(c.thread) - 1))', 'torder');
      $query->orderBy('torder', 'ASC');
    }

    $query->setCountQuery($count_query);
    $cids = $query->execute()->fetchCol();

    $comments = array();
    if ($cids) {
      $comments = $this->loadMultiple($cids);
    }

    return $comments;
  }

325 326 327 328
  /**
   * {@inheritdoc}
   */
  public function getUnapprovedCount() {
329
    return  $this->database->select('comment_field_data', 'c')
330
      ->condition('status', CommentInterface::NOT_PUBLISHED, '=')
331
      ->condition('default_langcode', 1)
332 333 334 335 336
      ->countQuery()
      ->execute()
      ->fetchField();
  }

337
}