Skip to content
comment.module 52.9 KiB
Newer Older
Dries Buytaert's avatar
Dries Buytaert committed

Dries Buytaert's avatar
Dries Buytaert committed
/**
 * @file
Dries Buytaert's avatar
 
Dries Buytaert committed
 * Enables users to comment on published content.
Dries Buytaert's avatar
Dries Buytaert committed
 *
 * 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.
use Drupal\comment\CommentInterface;
use Drupal\comment\Entity\Comment;
use Drupal\comment\Entity\CommentType;
use Drupal\comment\Plugin\Field\FieldType\CommentItemInterface;
use Drupal\Component\Utility\String;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\entity\Entity\EntityViewDisplay;
use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
use Drupal\field\Entity\FieldConfig;
use Drupal\field\FieldInstanceConfigInterface;
use Drupal\field\FieldConfigInterface;
use Drupal\user\EntityOwnerInterface;
/**
 * Comments are displayed in a flat list - expanded.
 */

/**
 * Comments are displayed as a threaded list - expanded.
 */
 * Anonymous posters cannot enter their contact information.
const COMMENT_ANONYMOUS_MAYNOT_CONTACT = 0;

/**
 * Anonymous posters may leave their contact information.
 */
const COMMENT_ANONYMOUS_MAY_CONTACT = 1;
 * Anonymous posters are required to leave their contact information.
const COMMENT_ANONYMOUS_MUST_CONTACT = 2;
 * Comment form should be displayed on a separate page.
const COMMENT_FORM_SEPARATE_PAGE = 0;

/**
 * Comment form should be shown below post or list of comments.
 */
/**
 * 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);
function comment_help($route_name, RouteMatchInterface $route_match) {
  switch ($route_name) {
    case 'help.page.comment':
      $output = '<h3>' . t('About') . '</h3>';
      $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 <a href="!comment">online documentation for the Comment module</a>.', array('!comment' => 'https://drupal.org/documentation/modules/comment')) . '</p>';
      $output .= '<h3>' . t('Uses') . '</h3>';
      $output .= '<dl>';
      $output .= '<dt>' . t('Enabling commenting and configuring defaults') . '</dt>';
      $output .= '<dd>' . t('Comment functionality can be enabled for any <a href="!entity-help" title="Entity module help">entity sub-type</a> (for example, a <a href="!content-type">content type</a>). On the Manage fields page for each entity sub-type, you can enable commenting by adding a Comments field. The entity sub-types each have their own default comment settings configured as: <em>Open</em> to allow new comments, <em>Closed</em> to view existing comments, but prevent new comments, or <em>Hidden</em> to hide existing comments and prevent new comments.', array('!content-type' => \Drupal::url('node.overview_types'), '!entity-help' => \Drupal::url('help.page', array('name' => 'entity')))) . '</dd>';
      $output .= '<dt>' . t('Overriding default settings') . '</dt>';
      $output .= '<dd>' . t('When you create an entity item, you can override the default comment settings. Changing the entity sub-type defaults will not affect existing entity items, whether they used the default settings or had overrides.') . '</dd>';
      $output .= '<dt>' . t('Approving and managing comments') . '</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 and comment settings</em> publishes or deletes them. Published comments can be bulk managed on the <a href="!admin-comment">Published comments</a> administration page. When a comment has no replies, it remains editable by its author, as long as the author has <em>Edit own comments</em> permission.', array('!comment-approval' => \Drupal::url('comment.admin_approval'), '!admin-comment' => \Drupal::url('comment.admin'))) . '</dd>';
    case 'comment.type_list':
      $output = '<p>' . t('This page provides a list of all comment types on the site and allows you to manage the fields, form and display settings for each.') . '</p>';
Dries Buytaert's avatar
 
Dries Buytaert committed
}

    array('fragment' => 'comment-' . $comment->id())
 * Implements hook_entity_extra_field_info().
function comment_entity_extra_field_info() {
  $return = array();
  foreach (CommentType::loadMultiple() as $comment_type) {
    $return['comment'][$comment_type->id()] = array(
      'form' => array(
        'author' => array(
          'label' => t('Author'),
          'description' => t('Author textfield'),
          'weight' => -2,
        'subject' => array(
          'label' => t('Subject'),
          'description' => t('Subject textfield'),
          'weight' => -1,
        ),
      ),
    );
 */
function comment_theme() {
  return array(
    'comment' => array(
 * Implements hook_ENTITY_TYPE_create() for 'field_instance_config'.
function comment_field_instance_config_create(FieldInstanceConfigInterface $instance) {
  if ($instance->getType() == 'comment' && !$instance->isSyncing()) {
    // Assign default values for the field instance.
    if (!isset($instance->default_value)) {
      $instance->default_value = array();
    }
    $instance->default_value += array(array());
    $instance->default_value[0] += array(
      'status' => CommentItemInterface::OPEN,
      'cid' => 0,
      'last_comment_timestamp' => 0,
      'last_comment_name' => '',
      'last_comment_uid' => 0,
      'comment_count' => 0,
 * Implements hook_ENTITY_TYPE_update() for 'field_instance_config'.
function comment_field_instance_config_update(FieldInstanceConfigInterface $instance) {
    // Comment field settings also affects the rendering of *comment* entities,
    // not only the *commented* entities.
    \Drupal::entityManager()->getViewBuilder('comment')->resetCache();
/**
 * Implements hook_ENTITY_TYPE_insert() for 'field_config'.
 */
function comment_field_config_insert(FieldConfigInterface $field) {
  if ($field->getType() == 'comment') {
    // Check that the target entity type uses an integer ID.
    $entity_type_id = $field->getTargetEntityTypeId();
    if (!_comment_entity_uses_integer_id($entity_type_id)) {
      throw new \UnexpectedValueException('You cannot attach a comment field to an entity with a non-integer ID field');
    }
 * Implements hook_ENTITY_TYPE_delete() for 'field_instance_config'.
function comment_field_instance_config_delete(FieldInstanceConfigInterface $instance) {
    // Delete all comments that used by the entity bundle.
    $comments = db_query("SELECT cid FROM {comment} WHERE entity_type = :entity_type AND field_name = :field_name", array(
      ':entity_type' => $instance->getEntityTypeId(),
      ':field_name' => $instance->getName(),
    ))->fetchCol();
    entity_delete_multiple('comment', $comments);
Dries Buytaert's avatar
 
Dries Buytaert committed
/**
Dries Buytaert's avatar
 
Dries Buytaert committed
 */
function comment_permission() {
      'title' => t('Administer comments and comment settings'),
    'administer comment types' => array(
      'title' => t('Administer comment types and settings'),
      'restrict access' => TRUE,
    ),
    'skip comment approval' => array(
      'title' => t('Skip comment approval'),
    'edit own comments' => array(
      'title' => t('Edit own comments'),
    ),
Dries Buytaert's avatar
 
Dries Buytaert committed
}

 * Calculates the page number for the first new comment.
 * @param \Drupal\Core\Entity\ContentEntityInterface $entity
 *   The first new comment entity.
 * @param string $field_name
 *   The field name on the entity to which comments are attached to.
 *   An array "page=X" if the page number is greater than zero; NULL otherwise.
function comment_new_page_count($num_comments, $new_replies, ContentEntityInterface $entity, $field_name = 'comment') {
  $field_definition = $entity->getFieldDefinition($field_name);
  $mode = $field_definition->getSetting('default_mode');
  $comments_per_page = $field_definition->getSetting('per_page');
  $flat = $mode == COMMENT_MODE_FLAT ? TRUE : FALSE;
  if ($num_comments <= $comments_per_page) {
    // Only one page of comments.
  elseif ($flat) {
    // Flat comments.
    $count = $num_comments - $new_replies;
    $pageno = $count / $comments_per_page;
    // 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'))
      ->condition('entity_id', $entity->id())
      ->condition('entity_type', $entity->getEntityTypeId())
      ->condition('field_name', $field_name)
      ->condition('status', CommentInterface::PUBLISHED)
      ->orderBy('created', 'DESC')
      ->orderBy('cid', 'DESC')
      ->range(0, $new_replies);

    // 2. Find the first thread.
    $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
      ->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.
    $count = db_query('SELECT COUNT(*) FROM {comment} WHERE entity_id = :entity_id
                      AND entity_type = :entity_type
                      AND status = :status AND SUBSTRING(thread, 1, (LENGTH(thread) - 1)) < :thread', array(
      ':status' => CommentInterface::PUBLISHED,
      ':entity_type' => $entity->getEntityTypeId(),
    $pageno = $count / $comments_per_page;
    $pagenum = array('page' => intval($pageno));
 * Implements hook_entity_build_defaults_alter().
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);
  // 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')) {
    foreach ($entity->getFieldDefinitions() as $field_name => $definition) {
      if ($definition->getType() === 'comment' && ($display_options = $display->getComponent($field_name))) {
        $pager_id = $display_options['settings']['pager_id'];
        $page = pager_find_page($pager_id);
        $build['#cache']['keys'][] = $field_name . '-pager-' . $page;
      }
    }
  }
Dries Buytaert's avatar
 
Dries Buytaert committed
/**
Dries Buytaert's avatar
 
Dries Buytaert committed
 */
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'];
  if ($view_mode == 'search_index' || $view_mode == 'search_result' || $view_mode == 'print') {
    // Do not add any links if the node displayed for:
    // - search indexing.
    // - constructing a search result excerpt.
    // - print.
    return;
  }
  $fields = \Drupal::service('comment.manager')->getFields('node');
  foreach ($fields as $field_name => $detail) {
    // Skip fields that the node does not have.
    if (!$node->hasField($field_name)) {
    $commenting_status = $node->get($field_name)->status;
      $field_definition = $node->getFieldDefinition($field_name);
      if ($view_mode == 'rss') {
        // Add a comments RSS element which is a URL to the comments of this node.
        $options = array(
          'fragment' => 'comments',
          'absolute' => TRUE,
        );
          'value' => $node->url('canonical', $options),
      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')) {
          if (!empty($node->get($field_name)->comment_count)) {
            $links['comment-comments'] = array(
              'title' => format_plural($node->get($field_name)->comment_count, '1 comment', '@count comments'),
              'attributes' => array('title' => t('Jump to the first comment of this posting.')),
              'fragment' => 'comments',
              'html' => TRUE,
            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.'),
                  'data-history-node-last-comment-timestamp' => $node->get($field_name)->last_comment_timestamp,
                  'data-history-node-field-name' => $field_name,
                ),
                'html' => TRUE,
              );
            }
        // Provide a link to new comment form.
        if ($commenting_status == CommentItemInterface::OPEN) {
          $comment_form_location = $field_definition->getSetting('form_location');
          if (user_access('post comments')) {
            $links['comment-add'] = array(
              'title' => t('Add new comment'),
              'attributes' => array('title' => t('Add a new comment to this page.')),
              'fragment' => 'comment-form',
            );
            if ($comment_form_location == COMMENT_FORM_SEPARATE_PAGE) {
              $links['comment-add']['route_name'] = 'comment.reply';
              $links['comment-add']['route_parameters'] = array(
                'entity_type' => $node->getEntityTypeId(),
                'entity_id' => $node->id(),
              $links['comment-add'] += $node->urlInfo()->toArray();
          elseif (\Drupal::currentUser()->isAnonymous()) {
            $links['comment-forbidden'] = array(
              'title' => \Drupal::service('comment.manager')->forbiddenMessage($node, $field_name),
Dries Buytaert's avatar
 
Dries Buytaert committed
        }
        // 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.
        if ($commenting_status == CommentItemInterface::OPEN) {
          $comment_form_location = $field_definition->getSetting('form_location');
          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.
            if ($comment_form_location == COMMENT_FORM_SEPARATE_PAGE || (!empty($node->get($field_name)->comment_count) && user_access('access comments'))) {
              $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) {
                $links['comment-add']['route_name'] = 'comment.reply';
                $links['comment-add']['route_parameters'] = array(
                  'entity_type' => $node->getEntityTypeId(),
                  'entity_id' => $node->id(),
                $links['comment-add'] += $node->urlInfo()->toArray();
          elseif (\Drupal::currentUser()->isAnonymous()) {
            $links['comment-forbidden'] = array(
              'title' => \Drupal::service('comment.manager')->forbiddenMessage($node, $field_name),
Dries Buytaert's avatar
 
Dries Buytaert committed
        }
      }
    }
    if (!empty($links)) {
      $node_links['comment__' . $field_name] = array(
        '#theme' => 'links__entity__comment__' . $field_name,
        '#links' => $links,
        '#attributes' => array('class' => array('links', 'inline')),
      if ($view_mode == 'teaser' && \Drupal::moduleHandler()->moduleExists('history') && \Drupal::currentUser()->isAuthenticated()) {
        $node_links['comment__' . $field_name]['#attached']['library'][] = 'comment/drupal.node-new-comments-link';

        // 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),
        );
      }
Dries Buytaert's avatar
 
Dries Buytaert committed
}

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

 * Returns a rendered form to comment the given entity.
 * @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.
 * @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 array
 *   The renderable array for the comment addition form.
 */
function comment_add(EntityInterface $entity, $field_name = 'comment', $pid = NULL) {
  $field = Fieldconfig::loadByName($entity->getEntityTypeId(), $field_name);
    'entity_type' => $entity->getEntityTypeId(),
    'field_name' => $field_name,
    'comment_type' => $field->getSetting('bundle'),
  $comment = entity_create('comment', $values);
  return \Drupal::service('entity.form_builder')->getForm($comment);
 * Retrieves comments for a thread.
 * @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
 *   The comment display mode; COMMENT_MODE_FLAT or COMMENT_MODE_THREADED.
 *   The amount of comments to display per page.
 * @param int $pager_id
 *   (optional) Pager id to use in case of multiple pagers on the one page.
 *   Defaults to 0.
 *   An array of the IDs of the comment to be displayed.
 *
 * 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.
 */
function comment_get_thread(EntityInterface $entity, $field_name, $mode, $comments_per_page, $pager_id = 0) {
  $query = db_select('comment', 'c')
    ->extend('Drupal\Core\Database\Query\PagerSelectExtender');
  if ($pager_id) {
    $query->element($pager_id);
  }
    ->condition('c.entity_id', $entity->id())
    ->condition('c.entity_type', $entity->getEntityTypeId())
    ->condition('c.field_name', $field_name)
    ->addTag('comment_filter')
    ->addMetaData('base_table', 'comment')
    ->addMetaData('entity', $entity)
    ->addMetaData('field_name', $field_name)
    ->limit($comments_per_page);

  $count_query = db_select('comment', '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)
    ->addTag('comment_filter')
    ->addMetaData('base_table', 'comment')
    ->addMetaData('entity', $entity)
    ->addMetaData('field_name', $field_name);
    $query->condition('c.status', CommentInterface::PUBLISHED);
    $count_query->condition('c.status', CommentInterface::PUBLISHED);
  if ($mode == 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');
  return $query->execute()->fetchCol();
 * 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.
 *   An array of comment objects, keyed by comment ID.
 */
function comment_prepare_thread(&$comments) {
  // A counter that helps track how indented we are.
  $divs = 0;

  foreach ($comments as $key => &$comment) {
    // The $divs element instructs #prefix whether to add an indent div or
    // close existing divs (a negative value).
    $comment->depth = count(explode('.', $comment->getThread())) - 1;
    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;
}

/**
 * Generates an array for rendering a comment.
 * @param \Drupal\comment\CommentInterface $comment
 *   (optional) View mode, e.g. 'full', 'teaser'... Defaults to 'full'.
 * @param $langcode
 *   (optional) A language code to use for rendering. Defaults to the global
 *   content language of the current request.
 *   An array as expected by drupal_render().
 */
function comment_view(CommentInterface $comment, $view_mode = 'full', $langcode = NULL) {
  return entity_view($comment, $view_mode, $langcode);
 * Constructs render array from an array of loaded comments.
 *   An array of comments as returned by entity_load_multiple().
 * @param $view_mode
 *   View mode, e.g. 'full', 'teaser'...
 *   (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.
 *   An array in the format expected by drupal_render().
function comment_view_multiple($comments, $view_mode = 'full', $langcode = NULL) {
  return entity_view_multiple($comments, $view_mode, $langcode);
 * Implements hook_form_FORM_ID_alter().
function comment_form_field_ui_field_overview_form_alter(&$form, $form_state) {
  $request = \Drupal::request();
  if ($form['#entity_type'] == 'comment' && $request->attributes->has('commented_entity_type')) {
    $form['#title'] = \Drupal::service('comment.manager')->getFieldUIPageTitle($request->attributes->get('commented_entity_type'), $request->attributes->get('field_name'));
  $entity_type_id = $form['#entity_type'];
  if (!_comment_entity_uses_integer_id($entity_type_id)) {
    // You cannot use comment fields on entity types with non-integer IDs.
    unset($form['fields']['_add_new_field']['type']['#options']['comment']);
  }
 * Implements hook_form_FORM_ID_alter().
function comment_form_field_ui_form_display_overview_form_alter(&$form, $form_state) {
  $request = \Drupal::request();
  if ($form['#entity_type'] == 'comment' && $request->attributes->has('commented_entity_type')) {
    $form['#title'] = \Drupal::service('comment.manager')->getFieldUIPageTitle($request->attributes->get('commented_entity_type'), $request->attributes->get('field_name'));
Dries Buytaert's avatar
 
Dries Buytaert committed
/**
 * Implements hook_form_FORM_ID_alter().
Dries Buytaert's avatar
 
Dries Buytaert committed
 */
function comment_form_field_ui_display_overview_form_alter(&$form, $form_state) {
  $request = \Drupal::request();
  if ($form['#entity_type'] == 'comment' && $request->attributes->has('commented_entity_type')) {
    $form['#title'] = \Drupal::service('comment.manager')->getFieldUIPageTitle($request->attributes->get('commented_entity_type'), $request->attributes->get('field_name'));
/**
 * Implements hook_form_FORM_ID_alter().
 */
function comment_form_field_ui_field_edit_form_alter(&$form, $form_state) {
    // We only support posting one comment at the time so it doesn't make sense
    // to let the site builder choose anything else.
    $form['field']['cardinality_container']['cardinality']['#options'] = array(1 => 1);
    $form['field']['cardinality_container']['#access'] = FALSE;
 * @see \Drupal\comment\Plugin\Field\FieldType\CommentItem::propertyDefinitions()
function comment_entity_load($entities, $entity_type) {
  // Comments can only be attached to content entities, so skip others.
  if (!\Drupal::entityManager()->getDefinition($entity_type)->isSubclassOf('Drupal\Core\Entity\ContentEntityInterface')) {
    return;
  }
  if (!\Drupal::service('comment.manager')->getFields($entity_type)) {
    // Do not query database when entity has no comment fields.
    return;
  }
  // 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);
    // Skip fields that entity does not have.
    if (!$entities[$record->entity_id]->hasField($record->field_name)) {
    $comment_statistics = $entities[$record->entity_id]->get($record->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;
 * Implements hook_entity_insert().
function comment_entity_insert(EntityInterface $entity) {
  // Allow bulk updates and inserts to temporarily disable the
  // maintenance of the {comment_entity_statistics} table.
  if (\Drupal::state()->get('comment.maintain_entity_statistics') &&
    $fields = \Drupal::service('comment.manager')->getFields($entity->getEntityTypeId())) {
    \Drupal::service('comment.statistics')->create($entity, $fields);
 * Implements hook_entity_predelete().
function comment_entity_predelete(EntityInterface $entity) {
  // Entities can have non-numeric IDs, but {comment} and
  // {comment_entity_statistics} tables have integer columns for entity ID, and
  // PostgreSQL throws exceptions if you attempt query conditions with
  // mismatched types. So, we need to verify that the ID is numeric (even for an
  // entity type that has an integer ID, $entity->id() might be a string
  // containing a number), and then cast it to an integer when querying.
  if ($entity->getEntityType()->isFieldable() && is_numeric($entity->id())) {
    $entity_query = \Drupal::entityQuery('comment');
    $entity_query->condition('entity_id', (int) $entity->id());
    $entity_query->condition('entity_type', $entity->getEntityTypeId());
    $cids = $entity_query->execute();
    entity_delete_multiple('comment', $cids);
    \Drupal::service('comment.statistics')->delete($entity);
/**
 * Determines if an entity type is using an integer-based ID definition.
 *
 * @param string $entity_type_id
 *   The ID the represents the entity type.
 *
 * @return bool
 *   Returns TRUE if the entity type has an integer-based ID definition and
 *   FALSE otherwise.
 */
function _comment_entity_uses_integer_id($entity_type_id) {
  $entity_type = \Drupal::entityManager()->getDefinition($entity_type_id);
  $entity_type_id_key = $entity_type->getKey('id');
  if ($entity_type_id_key === FALSE) {
    return FALSE;
  }
  $field_definitions = \Drupal::entityManager()->getBaseFieldDefinitions($entity_type->id());
  $entity_type_id_definition = $field_definitions[$entity_type_id_key];
  return $entity_type_id_definition->getType() === 'integer';
}

function comment_node_update_index(EntityInterface $node, $langcode) {
  $index_comments = &drupal_static(__FUNCTION__);

  if ($index_comments === NULL) {
    // Do not index in the following three cases:
    // 1. 'Authenticated user' can search content but can't access comments.
    // 2. 'Anonymous user' can search content but can't access comments.
    // 3. Any role can search content but can't access comments and access
    // comments is not granted by the 'authenticated user' role. In this case
    // all users might have both permissions from various roles but it is also
    // possible to set up a user to have only search content and so a user
    // edit could change the security situation so it is not safe to index the
    // comments.
    $roles = \Drupal::entityManager()->getStorage('user_role')->loadMultiple();
    $authenticated_can_access = $roles[DRUPAL_AUTHENTICATED_RID]->hasPermission('access comments');
    foreach ($roles as $rid => $role) {
      if ($role->hasPermission('search content') && !$role->hasPermission('access comments')) {
        if ($rid == DRUPAL_AUTHENTICATED_RID || $rid == DRUPAL_ANONYMOUS_RID || !$authenticated_can_access) {
          $index_comments = FALSE;
          break;
        }
    foreach (\Drupal::service('comment.manager')->getFields('node') as $field_name => $info) {
      // Skip fields that entity does not have.
      if (!$node->hasField($field_name)) {
      $field_definition = $node->getFieldDefinition($field_name);
      $mode = $field_definition->getSetting('default_mode');
      $comments_per_page = $field_definition->getSetting('per_page');
      if ($node->get($field_name)->status && $cids = comment_get_thread($node, $field_name, $mode, $comments_per_page)) {
        $comments = entity_load_multiple('comment', $cids);
        comment_prepare_thread($comments);
        $build = comment_view_multiple($comments);
        $return .= drupal_render($build);
      }
function comment_cron() {
  // Store the maximum possible comments per thread (used for node search
  // ranking by reply count).
  \Drupal::state()->set('comment.node_comment_statistics_scale', 1.0 / max(1, \Drupal::service('comment.statistics')->getMaximumCount('node')));
 *
 * Formats a comment count string and returns it, for display with search
 * results.
function comment_node_search_result(EntityInterface $node) {
  $comment_fields = \Drupal::service('comment.manager')->getFields('node');
  $comments = 0;
  $open = FALSE;
  foreach ($comment_fields as $field_name => $info) {
    // Skip fields that entity does not have.
    if (!$node->hasField($field_name)) {
      continue;
    }
    // Do not make a string if comments are hidden.
    $status = $node->get($field_name)->status;
    if (\Drupal::currentUser()->hasPermission('access comments') && $status != CommentItemInterface::HIDDEN) {
      if ($status == CommentItemInterface::OPEN) {
        // At least one comment field is open.
        $open = TRUE;
      }
      $comments += $node->get($field_name)->comment_count;
  // Do not make a string if there are no comment fields, or no comments exist
  // or all comment fields are hidden.
  if ($comments > 0 || $open) {
    return array('comment' => format_plural($comments, '1 comment', '@count comments'));
  }
Dries Buytaert's avatar
 
Dries Buytaert committed
/**
Dries Buytaert's avatar
 
Dries Buytaert committed
 */
function comment_user_cancel($edit, $account, $method) {
  switch ($method) {
    case 'user_cancel_block_unpublish':
      $comments = entity_load_multiple_by_properties('comment', array('uid' => $account->id()));
        $comment->setPublished(CommentInterface::NOT_PUBLISHED);
      /** @var \Drupal\comment\CommentInterface[] $comments */
      $comments = entity_load_multiple_by_properties('comment', array('uid' => $account->id()));
Dries Buytaert's avatar
 
Dries Buytaert committed
}

function comment_user_predelete($account) {
  $entity_query = \Drupal::entityQuery('comment');
  $entity_query->condition('uid', $account->id());
  $cids = $entity_query->execute();
  entity_delete_multiple('comment', $cids);
Dries Buytaert's avatar
 
Dries Buytaert committed
/**
 * Loads comment entities from the database.
 * @deprecated in Drupal 8.x, will be removed before Drupal 9.0.
 *   Use \Drupal\comment\Entity\Comment::loadMultiple().
 * @param array $cids
 *   (optional) An array of entity IDs. If omitted, all entities are loaded.
 *   (optional) Whether to reset the internal static entity cache.
 *   An array of comment objects, indexed by comment ID.
 *
 * @see entity_load()