comment.module 54.8 KB
Newer Older
1
<?php
2

Dries's avatar
Dries committed
3 4
/**
 * @file
5
 * Enables users to comment on published content.
Dries's avatar
Dries committed
6
 *
7 8 9 10
 * When enabled, the Comment module creates a field that facilitates a
 * discussion board for each Drupal entity to which a comment field is attached.
 * Users can post comments to discuss a forum topic, story, collaborative
 * book page, user etc.
Dries's avatar
Dries committed
11 12
 */

13
use Drupal\comment\CommentInterface;
14 15
use Drupal\comment\Plugin\Field\FieldType\CommentItemInterface;
use Drupal\Core\Entity\EntityInterface;
16
use Drupal\entity\Entity\EntityViewDisplay;
17
use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
18
use Drupal\Core\Field\FieldDefinitionInterface;
19
use Drupal\Core\Render\Element;
20
use Drupal\Core\Url;
21 22
use Drupal\field\FieldInstanceConfigInterface;
use Drupal\field\FieldConfigInterface;
23
use Drupal\file\FileInterface;
24
use Drupal\user\EntityOwnerInterface;
25
use Drupal\node\NodeInterface;
26
use Symfony\Component\HttpFoundation\Request;
27

28 29 30
/**
 * Comments are displayed in a flat list - expanded.
 */
31
const COMMENT_MODE_FLAT = 0;
32 33 34 35

/**
 * Comments are displayed as a threaded list - expanded.
 */
36
const COMMENT_MODE_THREADED = 1;
37 38

/**
39
 * Anonymous posters cannot enter their contact information.
40
 */
41
const COMMENT_ANONYMOUS_MAYNOT_CONTACT = 0;
42 43 44 45

/**
 * Anonymous posters may leave their contact information.
 */
46
const COMMENT_ANONYMOUS_MAY_CONTACT = 1;
47 48

/**
49
 * Anonymous posters are required to leave their contact information.
50
 */
51
const COMMENT_ANONYMOUS_MUST_CONTACT = 2;
52 53

/**
54
 * Comment form should be displayed on a separate page.
55
 */
56
const COMMENT_FORM_SEPARATE_PAGE = 0;
57 58 59 60

/**
 * Comment form should be shown below post or list of comments.
 */
61
const COMMENT_FORM_BELOW = 1;
62

63 64 65 66 67 68 69 70 71 72
/**
 * The time cutoff for comments marked as read for entity types other node.
 *
 * Comments changed before this time are always marked as read.
 * Comments changed after this time may be marked new, updated, or read,
 * depending on their state for the current user. Defaults to 30 days ago.
 *
 * @todo Remove when http://drupal.org/node/1029708 lands.
 */
define('COMMENT_NEW_LIMIT', REQUEST_TIME - 30 * 24 * 60 * 60);
73

74
/**
75
 * Implements hook_help().
76
 */
77 78 79
function comment_help($route_name, Request $request) {
  switch ($route_name) {
    case 'help.page.comment':
80
      $output = '<h3>' . t('About') . '</h3>';
81
      $output .= '<p>' . t('The Comment module allows users to comment on site content, set commenting defaults and permissions, and moderate comments. For more information, see the online handbook entry for <a href="@comment">Comment module</a>.', array('@comment' => 'http://drupal.org/documentation/modules/comment')) . '</p>';
82 83 84
      $output .= '<h3>' . t('Uses') . '</h3>';
      $output .= '<dl>';
      $output .= '<dt>' . t('Default and custom settings') . '</dt>';
85
      $output .= '<dd>' . t("Comment functionality can be attached to any Drupal entity, eg. a content <a href='@content-type'>type</a> and the behavior can be customised to suit. Each entity can have its own default comment settings configured as: <em>Open</em> to allow new comments, <em>Hidden</em> to hide existing comments and prevent new comments, or <em>Closed</em> to view existing comments, but prevent new comments. These defaults will apply to all new content created (changes to the settings on existing content must be done manually). Other comment settings can also be customized per content type and entity, and can be overridden for any given item of content. When a comment has no replies, it remains editable by its author, as long as the author has a user account and is logged in.", array('@content-type' => url('admin/structure/types'))) . '</dd>';
86 87
      $output .= '<dt>' . t('Comment approval') . '</dt>';
      $output .= '<dd>' . t("Comments from users who have the <em>Skip comment approval</em> permission are published immediately. All other comments are placed in the <a href='@comment-approval'>Unapproved comments</a> queue, until a user who has permission to <em>Administer comments</em> publishes or deletes them. Published comments can be bulk managed on the <a href='@admin-comment'>Published comments</a> administration page.", array('@comment-approval' => url('admin/content/comment/approval'), '@admin-comment' => url('admin/content/comment'))) . '</dd>';
88
      $output .= '</dl>';
89
      return $output;
90

91
    case 'comment.bundle_list':
92 93
      $output = '<p>' . t('This page provides a list of all comment forms on the site and allows you to manage the fields, form and display settings for each.') . '</p>';
      return $output;
94
  }
95 96
}

97 98 99 100 101
/**
 * Implements hook_entity_bundle_info().
 */
function comment_entity_bundle_info() {
  $bundles = array();
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
  $ids = \Drupal::entityQuery('field_config')
    ->condition('type', 'comment')
    ->execute();
  $config_factory = \Drupal::configFactory();
  foreach ($ids as $id) {
    // @todo: We can not rely on the field map here, so we need to manually look
    //   for a matching field instance to use for the label. Remove this in
    //   https://drupal.org/node/2228763.
    list($entity_type_id, $field_name) = explode('.', $id);
    $instance_ids = $config_factory->listAll('field.instance.' . $entity_type_id . '.');
    // Look for an instance for this field.
    foreach ($instance_ids as $instance_id) {
      $instance_field_name = substr($instance_id, strrpos($instance_id, '.') + 1);
      if ($instance_field_name == $field_name) {
        $config = \Drupal::config($instance_id);
        $bundles['comment'][$entity_type_id . '__' . $field_name] = array(
          'label' => $config->get('label'),
        );
      }
121
    }
122
  }
123
  return $bundles;
124 125
}

126
/**
127
 * Entity URI callback.
128
 */
129
function comment_uri(CommentInterface $comment) {
130 131 132
  return new Url(
    'comment.permalink',
    array(
133 134
      'comment' => $comment->id(),
    ),
135
    array('fragment' => 'comment-' . $comment->id())
136
  );
137 138
}

139
/**
140
 * Implements hook_entity_extra_field_info().
141
 */
142
function comment_entity_extra_field_info() {
143
  $return = array();
144 145 146
  foreach (\Drupal::service('comment.manager')->getAllFields() as $entity_type => $fields) {
    foreach ($fields as $field_name => $field_info) {
      $return['comment'][$entity_type . '__' . $field_name] = array(
147 148 149 150 151 152
        'form' => array(
          'author' => array(
            'label' => t('Author'),
            'description' => t('Author textfield'),
            'weight' => -2,
          ),
153
          'subject' => array(
154 155 156 157
            'label' => t('Subject'),
            'description' => t('Subject textfield'),
            'weight' => -1,
          ),
158 159 160 161 162 163 164 165
        ),
      );
    }
  }

  return $return;
}

166
/**
167
 * Implements hook_theme().
168 169 170 171
 */
function comment_theme() {
  return array(
    'comment' => array(
172
      'render element' => 'elements',
173
      'template' => 'comment',
174 175
    ),
    'comment_wrapper' => array(
176
      'render element' => 'content',
177
      'template' => 'comment-wrapper',
178 179 180 181
    ),
  );
}

182
/**
183
 * Implements hook_menu_link_defaults_alter()
184
 */
185 186
function comment_menu_link_defaults_alter(&$links) {
  if (isset($links['node.content_overview'])) {
187
    // Add comments to the description for admin/content if any.
188
    $links['node.content_overview']['description'] = 'Administer content and comments.';
189
  }
190 191 192
  if (\Drupal::moduleHandler()->moduleExists('node')) {
    $links['comment.admin']['parent'] = 'node.content_overview';
  }
193 194
}

195 196
/**
 * Returns a menu title which includes the number of unapproved comments.
197 198
 *
 * @todo Move to the comment manager and replace by a entity query?
199 200 201
 */
function comment_count_unpublished() {
  $count = db_query('SELECT COUNT(cid) FROM {comment} WHERE status = :status', array(
202
    ':status' => CommentInterface::NOT_PUBLISHED,
203 204 205 206
  ))->fetchField();
  return t('Unapproved comments (@count)', array('@count' => $count));
}

207
/**
208
 * Implements hook_ENTITY_TYPE_insert() for 'field_instance_config'.
209
 */
210
function comment_field_instance_config_insert(FieldInstanceConfigInterface $instance) {
211 212
  if ($instance->getType() == 'comment' && !$instance->isSyncing()) {
    \Drupal::service('comment.manager')->addBodyField($instance->entity_type, $instance->getName());
213 214 215 216
  }
}

/**
217
 * Implements hook_ENTITY_TYPE_create() for 'field_instance_config'.
218
 */
219
function comment_field_instance_config_create(FieldInstanceConfigInterface $instance) {
220
  if ($instance->getType() == 'comment' && !$instance->isSyncing()) {
221
    // Assign default values for the field instance.
222 223 224 225 226
    if (!isset($instance->default_value)) {
      $instance->default_value = array();
    }
    $instance->default_value += array(array());
    $instance->default_value[0] += array(
227
      'status' => CommentItemInterface::OPEN,
228 229 230 231 232
      'cid' => 0,
      'last_comment_timestamp' => 0,
      'last_comment_name' => '',
      'last_comment_uid' => 0,
      'comment_count' => 0,
233
    );
234
  }
235
}
236

237
/**
238
 * Implements hook_ENTITY_TYPE_update() for 'field_instance_config'.
239
 */
240
function comment_field_instance_config_update(FieldInstanceConfigInterface $instance) {
241
  if ($instance->getType() == 'comment') {
242 243 244
    // Comment field settings also affects the rendering of *comment* entities,
    // not only the *commented* entities.
    \Drupal::entityManager()->getViewBuilder('comment')->resetCache();
245 246
  }
}
247

248
/**
249
 * Implements hook_ENTITY_TYPE_delete() for 'field_config'.
250
 */
251
function comment_field_config_delete(FieldConfigInterface $field) {
252
  if ($field->getType() == 'comment') {
253
    // Delete all fields and displays attached to the comment bundle.
254
    entity_invoke_bundle_hook('delete', 'comment', $field->entity_type . '__' . $field->getName());
255 256 257
  }
}

258
/**
259
 * Implements hook_ENTITY_TYPE_delete() for 'field_instance_config'.
260
 */
261
function comment_field_instance_config_delete(FieldInstanceConfigInterface $instance) {
262
  if ($instance->getType() == 'comment') {
263 264
    // Delete all comments that used by the entity bundle.
    $comments = db_query("SELECT cid FROM {comment} WHERE entity_type = :entity_type AND field_id = :field_id", array(
265 266
      ':entity_type' => $instance->getEntityTypeId(),
      ':field_id' => $instance->getEntityTypeId() . '__' . $instance->getName(),
267 268
    ))->fetchCol();
    entity_delete_multiple('comment', $comments);
269
  }
270 271
}

272
/**
273
 * Implements hook_permission().
274
 */
275
function comment_permission() {
276
  return array(
277
    'administer comments' => array(
278
      'title' => t('Administer comments and comment settings'),
279 280
    ),
    'access comments' => array(
281
      'title' => t('View comments'),
282 283
    ),
    'post comments' => array(
284
      'title' => t('Post comments'),
285
    ),
286 287
    'skip comment approval' => array(
      'title' => t('Skip comment approval'),
288
    ),
289 290 291
    'edit own comments' => array(
      'title' => t('Edit own comments'),
    ),
292
  );
293 294
}

295
/**
296
 * Calculates the page number for the first new comment.
297
 *
298
 * @param int $num_comments
299
 *   Number of comments.
300
 * @param int $new_replies
301
 *   Number of new replies.
302 303 304 305
 * @param \Drupal\Core\Entity\EntityInterface $entity
 *   The first new comment entity.
 * @param string $field_name
 *   The field name on the entity to which comments are attached to.
306
 *
307
 * @return array|null
308
 *   An array "page=X" if the page number is greater than zero; NULL otherwise.
309
 */
310
function comment_new_page_count($num_comments, $new_replies, EntityInterface $entity, $field_name = 'comment') {
311
  $instance = \Drupal::service('field.info')->getInstance($entity->getEntityTypeId(), $entity->bundle(), $field_name);
312 313
  $mode = $instance->getSetting('default_mode');
  $comments_per_page = $instance->getSetting('per_page');
314
  $pagenum = NULL;
315
  $flat = $mode == COMMENT_MODE_FLAT ? TRUE : FALSE;
316 317
  if ($num_comments <= $comments_per_page) {
    // Only one page of comments.
318
    $pageno = 0;
319
  }
320 321 322
  elseif ($flat) {
    // Flat comments.
    $count = $num_comments - $new_replies;
323
    $pageno = $count / $comments_per_page;
324
  }
325
  else {
326 327 328 329 330 331
    // Threaded comments: we build a query with a subquery to find the first
    // thread with a new comment.

    // 1. Find all the threads with a new comment.
    $unread_threads_query = db_select('comment')
      ->fields('comment', array('thread'))
332
      ->condition('entity_id', $entity->id())
333 334
      ->condition('entity_type', $entity->getEntityTypeId())
      ->condition('field_id', $entity->getEntityTypeId() . '__' . $field_name)
335
      ->condition('status', CommentInterface::PUBLISHED)
336 337
      ->orderBy('created', 'DESC')
      ->orderBy('cid', 'DESC')
338 339 340
      ->range(0, $new_replies);

    // 2. Find the first thread.
341 342 343
    $first_thread_query = db_select($unread_threads_query, 'thread');
    $first_thread_query->addExpression('SUBSTRING(thread, 1, (LENGTH(thread) - 1))', 'torder');
    $first_thread = $first_thread_query
344
      ->fields('thread', array('thread'))
345
      ->orderBy('torder')
346 347 348 349 350 351 352 353
      ->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.
354 355 356 357
    $count = db_query('SELECT COUNT(*) FROM {comment} WHERE entity_id = :entity_id
                      AND entity_type = :entity_type
                      AND field_id = :field_id
                      AND status = :status AND SUBSTRING(thread, 1, (LENGTH(thread) - 1)) < :thread', array(
358
      ':status' => CommentInterface::PUBLISHED,
359
      ':entity_id' => $entity->id(),
360 361
      ':field_id' => $entity->getEntityTypeId() . '__' . $field_name,
      ':entity_type' => $entity->getEntityTypeId(),
362
      ':thread' => $first_thread,
363
    ))->fetchField();
364

365
    $pageno = $count / $comments_per_page;
366
  }
367

368
  if ($pageno >= 1) {
369
    $pagenum = array('page' => intval($pageno));
370
  }
371

372 373 374
  return $pagenum;
}

375
/**
376
 * Implements hook_entity_build_defaults_alter().
377
 */
378 379 380
function comment_entity_build_defaults_alter(array &$build, EntityInterface $entity, $view_mode = 'full', $langcode = NULL) {
  // Get the corresponding display settings.
  $display = EntityViewDisplay::collectRenderDisplay($entity, $view_mode);
381 382
  // Add the comment page number to the cache key if render caching is enabled.
  if (isset($build['#cache']) && isset($build['#cache']['keys']) && \Drupal::request()->query->has('page')) {
383
    foreach ($entity->getFieldDefinitions() as $field_name => $definition) {
384
      if ($definition->getType() === 'comment' && ($display_options = $display->getComponent($field_name))) {
385 386 387 388 389 390
        $pager_id = $display_options['settings']['pager_id'];
        $page = pager_find_page($pager_id);
        $build['#cache']['keys'][] = $field_name . '-pager-' . $page;
      }
    }
  }
391
  return $build;
392 393
}

394
/**
395
 * Implements hook_node_links_alter().
396
 */
397 398 399 400 401 402 403 404
function comment_node_links_alter(array &$node_links, NodeInterface $node, array &$context) {
  // Comment links are only added to node entity type for backwards
  // compatibility. Should you require comment links for other entity types you
  // can do so by implementing a new field formatter.
  // @todo Make this configurable from the formatter see
  //   http://drupal.org/node/1901110

  $view_mode = $context['view_mode'];
405
  if ($view_mode == 'search_index' || $view_mode == 'search_result' || $view_mode == 'print') {
406
    // Do not add any links if the node displayed for:
407 408 409 410 411
    // - search indexing.
    // - constructing a search result excerpt.
    // - print.
    return;
  }
412

413 414
  $fields = \Drupal::service('comment.manager')->getFields('node');
  foreach ($fields as $field_name => $detail) {
415 416
    // Skip fields that the node does not have.
    if (!$node->hasField($field_name)) {
417
      continue;
418
    }
419
    $links = array();
420
    $commenting_status = $node->get($field_name)->status;
421
    if ($commenting_status) {
422
      $field_definition = $node->getFieldDefinition($field_name);
423
      // Node have commenting open or close.
424 425
      if ($view_mode == 'rss') {
        // Add a comments RSS element which is a URL to the comments of this node.
426 427 428 429
        $options = array(
          'fragment' => 'comments',
          'absolute' => TRUE,
        );
430
        $node->rss_elements[] = array(
431
          'key' => 'comments',
432
          'value' => $node->url('canonical', $options),
433
        );
434
      }
435 436 437 438 439
      elseif ($view_mode == 'teaser') {
        // Teaser view: display the number of comments that have been posted,
        // or a link to add new comments if the user has permission, the node
        // is open to new comments, and there currently are none.
        if (user_access('access comments')) {
440
          if (!empty($node->get($field_name)->comment_count)) {
441
            $links['comment-comments'] = array(
442
              'title' => format_plural($node->get($field_name)->comment_count, '1 comment', '@count comments'),
443 444 445
              'attributes' => array('title' => t('Jump to the first comment of this posting.')),
              'fragment' => 'comments',
              'html' => TRUE,
446
            ) + $node->urlInfo()->toArray();
447 448 449 450 451 452 453
            if (\Drupal::moduleHandler()->moduleExists('history')) {
              $links['comment-new-comments'] = array(
                'title' => '',
                'href' => '',
                'attributes' => array(
                  'class' => 'hidden',
                  'title' => t('Jump to the first new comment of this posting.'),
454
                  'data-history-node-last-comment-timestamp' => $node->get($field_name)->last_comment_timestamp,
455 456 457 458 459
                  'data-history-node-field-name' => $field_name,
                ),
                'html' => TRUE,
              );
            }
460
          }
461
        }
462
        // Provide a link to new comment form.
463
        if ($commenting_status == CommentItemInterface::OPEN) {
464
          $comment_form_location = $field_definition->getSetting('form_location');
465
          if (user_access('post comments')) {
466 467
            $links['comment-add'] = array(
              'title' => t('Add new comment'),
468
              'language' => $node->language(),
469
              'attributes' => array('title' => t('Add a new comment to this page.')),
470 471 472
              'fragment' => 'comment-form',
            );
            if ($comment_form_location == COMMENT_FORM_SEPARATE_PAGE) {
473 474
              $links['comment-add']['route_name'] = 'comment.reply';
              $links['comment-add']['route_parameters'] = array(
475 476
                'entity_type' => $node->getEntityTypeId(),
                'entity_id' => $node->id(),
477 478 479 480
                'field_name' => $field_name,
              );
            }
            else {
481
              $links['comment-add'] += $node->urlInfo()->toArray();
482
            }
483
          }
484
          elseif (\Drupal::currentUser()->isAnonymous()) {
485
            $links['comment-forbidden'] = array(
486
              'title' => \Drupal::service('comment.manager')->forbiddenMessage($node, $field_name),
487 488 489
              'html' => TRUE,
            );
          }
490
        }
491
      }
492
      else {
493 494
        // Node in other view modes: add a "post comment" link if the user is
        // allowed to post comments and if this node is allowing new comments.
495
        if ($commenting_status == CommentItemInterface::OPEN) {
496
          $comment_form_location = $field_definition->getSetting('form_location');
497 498 499
          if (user_access('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.
500
            if ($comment_form_location == COMMENT_FORM_SEPARATE_PAGE || (!empty($node->get($field_name)->comment_count) && user_access('access comments'))) {
501 502 503 504 505 506
              $links['comment-add'] = array(
                'title' => t('Add new comment'),
                'attributes' => array('title' => t('Share your thoughts and opinions related to this posting.')),
                'fragment' => 'comment-form',
              );
              if ($comment_form_location == COMMENT_FORM_SEPARATE_PAGE) {
507 508
                $links['comment-add']['route_name'] = 'comment.reply';
                $links['comment-add']['route_parameters'] = array(
509 510
                  'entity_type' => $node->getEntityTypeId(),
                  'entity_id' => $node->id(),
511 512 513 514
                  'field_name' => $field_name,
                );
              }
              else {
515
                $links['comment-add'] += $node->urlInfo()->toArray();
516 517 518
              }
            }
          }
519
          elseif (\Drupal::currentUser()->isAnonymous()) {
520
            $links['comment-forbidden'] = array(
521
              'title' => \Drupal::service('comment.manager')->forbiddenMessage($node, $field_name),
522 523 524
              'html' => TRUE,
            );
          }
525 526 527
        }
      }
    }
Dries's avatar
Dries committed
528

529 530 531 532 533
    if (!empty($links)) {
      $node_links['comment__' . $field_name] = array(
        '#theme' => 'links__entity__comment__' . $field_name,
        '#links' => $links,
        '#attributes' => array('class' => array('links', 'inline')),
534
      );
535
      if ($view_mode == 'teaser' && \Drupal::moduleHandler()->moduleExists('history') && \Drupal::currentUser()->isAuthenticated()) {
536
        $node_links['comment__' . $field_name]['#attached']['library'][] = 'comment/drupal.node-new-comments-link';
537 538 539 540 541 542 543 544 545

        // Embed the metadata for the "X new comments" link (if any) on this node.
        $node_links['comment__' . $field_name]['#post_render_cache']['history_attach_timestamp'] = array(
          array('node_id' => $node->id()),
        );
        $node_links['comment__' . $field_name]['#post_render_cache']['Drupal\comment\CommentViewBuilder::attachNewCommentsLinkMetadata'] = array(
          array('entity_type' => $node->getEntityTypeId(), 'entity_id' => $node->id(), 'field_name' => $field_name),
        );
      }
546
    }
547
  }
548 549
}

550 551 552
/**
 * Implements hook_node_view_alter().
 */
553
function comment_node_view_alter(array &$build, EntityInterface $node, EntityViewDisplayInterface $display) {
554
  if (\Drupal::moduleHandler()->moduleExists('history')) {
555 556 557 558
    $build['#attributes']['data-history-node-id'] = $node->id();
  }
}

559
/**
560
 * Returns a rendered form to comment the given entity.
561
 *
562 563 564 565
 * @param \Drupal\Core\Entity\EntityInterface $entity
 *   The entity to which the comments are in reply to.
 * @param string $field_name
 *   The field name where the comments were entered.
566 567 568
 * @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.
569 570 571 572
 *
 * @return array
 *   The renderable array for the comment addition form.
 */
573 574
function comment_add(EntityInterface $entity, $field_name = 'comment', $pid = NULL) {
  $values = array(
575
    'entity_type' => $entity->getEntityTypeId(),
576
    'entity_id' => $entity->id(),
577
    'field_id' => $entity->getEntityTypeId() . '__' . $field_name,
578 579
    'pid' => $pid,
  );
580
  $comment = entity_create('comment', $values);
581
  return \Drupal::service('entity.form_builder')->getForm($comment);
582 583
}

584
/**
585
 * Retrieves comments for a thread.
586
 *
587 588 589 590 591
 * @param \Drupal\Core\Entity\EntityInterface $entity
 *   The entity whose comment(s) needs rendering.
 * @param string $field_name
 *   The field_name whose comment(s) needs rendering.
 * @param int $mode
592
 *   The comment display mode; COMMENT_MODE_FLAT or COMMENT_MODE_THREADED.
593
 * @param int $comments_per_page
594
 *   The amount of comments to display per page.
595 596 597
 * @param int $pager_id
 *   (optional) Pager id to use in case of multiple pagers on the one page.
 *   Defaults to 0.
598
 *
599
 * @return int[]
600 601
 *   An array of the IDs of the comment to be displayed.
 *
602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655
 * 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.
 */
656
function comment_get_thread(EntityInterface $entity, $field_name, $mode, $comments_per_page, $pager_id = 0) {
657 658
  $query = db_select('comment', 'c')
    ->extend('Drupal\Core\Database\Query\PagerSelectExtender');
659 660 661
  if ($pager_id) {
    $query->element($pager_id);
  }
662 663
  $query->addField('c', 'cid');
  $query
664
    ->condition('c.entity_id', $entity->id())
665 666
    ->condition('c.entity_type', $entity->getEntityTypeId())
    ->condition('c.field_id', $entity->getEntityTypeId() . '__' . $field_name)
667
    ->addTag('entity_access')
668
    ->addTag('comment_filter')
669
    ->addMetaData('base_table', 'comment')
670 671
    ->addMetaData('entity', $entity)
    ->addMetaData('field_name', $field_name)
672 673 674 675 676
    ->limit($comments_per_page);

  $count_query = db_select('comment', 'c');
  $count_query->addExpression('COUNT(*)');
  $count_query
677
    ->condition('c.entity_id', $entity->id())
678 679
    ->condition('c.entity_type', $entity->getEntityTypeId())
    ->condition('c.field_id', $entity->getEntityTypeId() . '__' . $field_name)
680
    ->addTag('entity_access')
681
    ->addTag('comment_filter')
682
    ->addMetaData('base_table', 'comment')
683 684
    ->addMetaData('entity', $entity)
    ->addMetaData('field_name', $field_name);
685 686

  if (!user_access('administer comments')) {
687 688
    $query->condition('c.status', CommentInterface::PUBLISHED);
    $count_query->condition('c.status', CommentInterface::PUBLISHED);
689
  }
690
  if ($mode == COMMENT_MODE_FLAT) {
691 692 693 694 695 696
    $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.
697 698
    $query->addExpression('SUBSTRING(c.thread, 1, (LENGTH(c.thread) - 1))', 'torder');
    $query->orderBy('torder', 'ASC');
699 700 701
  }

  $query->setCountQuery($count_query);
702
  return $query->execute()->fetchCol();
703 704 705
}

/**
706 707 708 709 710
 * Calculates the indentation level of each comment in a comment thread.
 *
 * This function loops over an array representing a comment thread. For each
 * comment, the function calculates the indentation level and saves it in the
 * 'divs' property of the comment object.
711 712
 *
 * @param array $comments
713
 *   An array of comment objects, keyed by comment ID.
714 715 716 717 718
 */
function comment_prepare_thread(&$comments) {
  // A counter that helps track how indented we are.
  $divs = 0;

719
  foreach ($comments as $key => &$comment) {
720 721
    // The $divs element instructs #prefix whether to add an indent div or
    // close existing divs (a negative value).
722
    $comment->depth = count(explode('.', $comment->getThread())) - 1;
723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739
    if ($comment->depth > $divs) {
      $comment->divs = 1;
      $divs++;
    }
    else {
      $comment->divs = $comment->depth - $divs;
      while ($comment->depth < $divs) {
        $divs--;
      }
    }
  }

  // The final comment must close up some hanging divs
  $comments[$key]->divs_final = $divs;
}

/**
740
 * Generates an array for rendering a comment.
741
 *
742
 * @param \Drupal\comment\CommentInterface $comment
743
 *   The comment object.
744
 * @param $view_mode
745
 *   (optional) View mode, e.g. 'full', 'teaser'... Defaults to 'full'.
746 747 748
 * @param $langcode
 *   (optional) A language code to use for rendering. Defaults to the global
 *   content language of the current request.
749
 *
750
 * @return array
751 752
 *   An array as expected by drupal_render().
 */
753
function comment_view(CommentInterface $comment, $view_mode = 'full', $langcode = NULL) {
754
  return entity_view($comment, $view_mode, $langcode);
755 756 757
}

/**
758
 * Constructs render array from an array of loaded comments.
759 760
 *
 * @param $comments
761
 *   An array of comments as returned by entity_load_multiple().
762 763
 * @param $view_mode
 *   View mode, e.g. 'full', 'teaser'...
764
 * @param $langcode
765 766 767
 *   (optional) A string indicating the language field values are to be shown
 *   in. If no language is provided the current content language is used.
 *   Defaults to NULL.
768
 *
769
 * @return array
770
 *   An array in the format expected by drupal_render().
771 772
 *
 * @see drupal_render()
773
 */
774 775
function comment_view_multiple($comments, $view_mode = 'full', $langcode = NULL) {
  return entity_view_multiple($comments, $view_mode, $langcode);
776 777
}

778
/**
779
 * Implements hook_form_FORM_ID_alter().
780
 */
781
function comment_form_field_ui_field_instance_edit_form_alter(&$form, $form_state) {
782
  if ($form['#field']->getType() == 'comment') {
783 784
    // Collect translation settings.
    if (\Drupal::moduleHandler()->moduleExists('content_translation')) {
785 786
      array_unshift($form['#submit'], 'comment_translation_configuration_element_submit');
    }
787 788 789

    // Hide required checkbox.
    $form['instance']['required']['#access'] = FALSE;
790
  }
791 792
}

793
/**
794
 * Implements hook_form_FORM_ID_alter().
795
 */
796
function comment_form_field_ui_field_overview_form_alter(&$form, $form_state) {
797 798
  $request = \Drupal::request();
  if ($form['#entity_type'] == 'comment' && $request->attributes->has('commented_entity_type')) {
799
    $form['#title'] = \Drupal::service('comment.manager')->getFieldUIPageTitle($request->attributes->get('commented_entity_type'), $request->attributes->get('field_name'));
800
  }
801 802
}

803
/**
804
 * Implements hook_form_FORM_ID_alter().
805
 */
806
function comment_form_field_ui_form_display_overview_form_alter(&$form, $form_state) {
807 808
  $request = \Drupal::request();
  if ($form['#entity_type'] == 'comment' && $request->attributes->has('commented_entity_type')) {
809
    $form['#title'] = \Drupal::service('comment.manager')->getFieldUIPageTitle($request->attributes->get('commented_entity_type'), $request->attributes->get('field_name'));
810 811 812
  }
}

813
/**
814
 * Implements hook_form_FORM_ID_alter().
815
 */
816
function comment_form_field_ui_display_overview_form_alter(&$form, $form_state) {
817 818
  $request = \Drupal::request();
  if ($form['#entity_type'] == 'comment' && $request->attributes->has('commented_entity_type')) {
819
    $form['#title'] = \Drupal::service('comment.manager')->getFieldUIPageTitle($request->attributes->get('commented_entity_type'), $request->attributes->get('field_name'));
820
  }
821
}
822

823 824 825 826
/**
 * Implements hook_form_FORM_ID_alter().
 */
function comment_form_field_ui_field_edit_form_alter(&$form, $form_state) {
827
  if ($form['#field']->getType() == 'comment') {
828 829
    // We only support posting one comment at the time so it doesn't make sense
    // to let the site builder choose anything else.
830
    $form['field']['cardinality_container']['cardinality']['#options'] = array(1 => 1);
831
    $form['field']['cardinality_container']['#access'] = FALSE;
832 833
  }
}
834

835
/**
836 837 838 839 840 841 842 843 844 845 846 847 848 849 850
 * Form submission handler for field_ui_field_edit_form().
 *
 * This handles the comment translation settings added by
 * _comment_field_instance_settings_form_process().
 *
 * @see _comment_field_instance_settings_form_process()
 */
function comment_translation_configuration_element_submit($form, &$form_state) {
  // The comment translation settings form element is embedded into the instance
  // settings form. Hence we need to provide to the regular submit handler a
  // manipulated form state to make it process comment settings instead of the
  // host entity.
  $key = 'language_configuration';
  $comment_form_state = array(
    'content_translation' => array('key' => $key),
851
    'language' => array($key => array('entity_type' => 'comment', 'bundle' => $form['#field']->name)),
852 853 854 855 856 857 858 859
    'values' => array($key => array('content_translation' => $form_state['values']['content_translation'])),
  );
  content_translation_language_configuration_element_submit($form, $comment_form_state);
}

/**
 * Implements hook_entity_load().
 *
860
 * @see \Drupal\comment\Plugin\Field\FieldType\CommentItem::propertyDefinitions()
861
 */
862
function comment_entity_load($entities, $entity_type) {
863 864 865 866
  // Comments can only be attached to content entities, so skip others.
  if (!\Drupal::entityManager()->getDefinition($entity_type)->isSubclassOf('Drupal\Core\Entity\ContentEntityInterface')) {
    return;
  }
867 868 869 870
  if (!\Drupal::service('comment.manager')->getFields($entity_type)) {
    // Do not query database when entity has no comment fields.
    return;
  }
871 872 873
  // Load comment information from the database and update the entity's
  // comment statistics properties, which are defined on each CommentItem field.
  $result = \Drupal::service('comment.statistics')->read($entities, $entity_type);
874 875 876
  foreach ($result as $record) {
    $parts = explode('__', $record->field_id, 2);
    list(, $field_name) = $parts;
877 878 879 880 881

    // Skip fields that entity does not have.
    if (!$entities[$record->entity_id]->hasField($field_name)) {
      continue;
    }
882 883 884 885 886 887
    $comment_statistics = $entities[$record->entity_id]->get($field_name);
    $comment_statistics->cid = $record->cid;
    $comment_statistics->last_comment_timestamp = $record->last_comment_timestamp;
    $comment_statistics->last_comment_name = $record->last_comment_name;
    $comment_statistics->last_comment_uid = $record->last_comment_uid;
    $comment_statistics->comment_count = $record->comment_count;
888 889
  }
}
890

891
/**
892
 * Implements hook_entity_insert().
893
 */
894
function comment_entity_insert(EntityInterface