comment.module

Enables users to comment on published content.

When enabled, the Comment module creates a discussion board for each Drupal node. Users can post comments to discuss a forum topic, story, collaborative book page, etc.

File

drupal/core/modules/comment/comment.module
View source
<?php

/**
 * @file
 * Enables users to comment on published content.
 *
 * When enabled, the Comment module creates a discussion board for each Drupal
 * node. Users can post comments to discuss a forum topic, story, collaborative
 * book page, etc.
 */
use Drupal\node\Plugin\Core\Entity\Node;
use Drupal\file\Plugin\Core\Entity\File;
use Drupal\Core\Entity\EntityInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\HttpKernelInterface;

/**
 * Comment is awaiting approval.
 */
const COMMENT_NOT_PUBLISHED = 0;

/**
 * Comment is published.
 */
const COMMENT_PUBLISHED = 1;

/**
 * Comments are displayed in a flat list - expanded.
 */
const COMMENT_MODE_FLAT = 0;

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

/**
 * 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.
 */
const COMMENT_FORM_BELOW = 1;

/**
 * Comments for this node are hidden.
 */
const COMMENT_NODE_HIDDEN = 0;

/**
 * Comments for this node are closed.
 */
const COMMENT_NODE_CLOSED = 1;

/**
 * Comments for this node are open.
 */
const COMMENT_NODE_OPEN = 2;
use Drupal\comment\Plugin\Core\Entity\Comment;

/**
 * Implements hook_help().
 */
function comment_help($path, $arg) {
  switch ($path) {
    case 'admin/help#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 online handbook entry for <a href="@comment">Comment module</a>.', array(
        '@comment' => 'http://drupal.org/documentation/modules/comment',
      )) . '</p>';
      $output .= '<h3>' . t('Uses') . '</h3>';
      $output .= '<dl>';
      $output .= '<dt>' . t('Default and custom settings') . '</dt>';
      $output .= '<dd>' . t("Each <a href='@content-type'>content type</a> 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 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>';
      $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>';
      $output .= '</dl>';
      return $output;
  }
}

/**
 * Implements hook_entity_info().
 */
function comment_entity_info(&$info) {
  foreach (node_type_get_names() as $type => $name) {
    $info['comment']['bundles']['comment_node_' . $type] = array(
      'label' => t('@node_type comment', array(
        '@node_type' => $name,
      )),
      // Provide the node type/bundle name for other modules, so it does not
      // have to be extracted manually from the bundle name.
      'node bundle' => $type,
      'admin' => array(
        // Place the Field UI paths for comments one level below the
        // corresponding paths for nodes, so that they appear in the same set
        // of local tasks. Note that the paths use a different placeholder name
        // and thus a different menu loader callback, so that Field UI page
        // callbacks get a comment bundle name from the node type in the URL.
        // See comment_node_type_load() and comment_menu_alter().
        'path' => 'admin/structure/types/manage/%comment_node_type/comment',
        'bundle argument' => 4,
        'real path' => 'admin/structure/types/manage/' . $type . '/comment',
        'access arguments' => array(
          'administer content types',
        ),
      ),
    );
  }
}

/**
 * Loads the comment bundle name corresponding a given content type.
 *
 * This function is used as a menu loader callback in comment_menu().
 *
 * @param $name
 *   The machine name of the node type whose comment fields are to be edited.
 *
 * @return
 *   The comment bundle name corresponding to the node type.
 *
 * @see comment_menu_alter()
 */
function comment_node_type_load($name) {
  if ($type = node_type_load($name)) {
    return 'comment_node_' . $type->type;
  }
}

/**
 * Entity URI callback.
 */
function comment_uri(Comment $comment) {
  return array(
    'path' => 'comment/' . $comment->cid,
    'options' => array(
      'fragment' => 'comment-' . $comment->cid,
    ),
  );
}

/**
 * Implements hook_field_extra_fields().
 */
function comment_field_extra_fields() {
  $return = array();
  foreach (node_type_get_types() as $type) {
    if (variable_get('comment_subject_field_' . $type->type, 1) == 1) {
      $return['comment']['comment_node_' . $type->type] = 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,
          ),
        ),
      );
    }
  }
  return $return;
}

/**
 * Implements hook_theme().
 */
function comment_theme() {
  return array(
    'comment_block' => array(
      'variables' => array(),
    ),
    'comment_preview' => array(
      'variables' => array(
        'comment' => NULL,
      ),
    ),
    'comment' => array(
      'template' => 'comment',
      'render element' => 'elements',
    ),
    'comment_post_forbidden' => array(
      'variables' => array(
        'node' => NULL,
      ),
    ),
    'comment_wrapper' => array(
      'template' => 'comment-wrapper',
      'render element' => 'content',
    ),
  );
}

/**
 * Implements hook_menu().
 */
function comment_menu() {
  $items['admin/content/comment'] = array(
    'title' => 'Comments',
    'description' => 'List and edit site comments and the comment approval queue.',
    'page callback' => 'comment_admin',
    'access arguments' => array(
      'administer comments',
    ),
    'type' => MENU_LOCAL_TASK | MENU_NORMAL_ITEM,
    'file' => 'comment.admin.inc',
  );

  // Tabs begin here.
  $items['admin/content/comment/new'] = array(
    'title' => 'Published comments',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10,
  );
  $items['admin/content/comment/approval'] = array(
    'title' => 'Unapproved comments',
    'title callback' => 'comment_count_unpublished',
    'page arguments' => array(
      'approval',
    ),
    'access arguments' => array(
      'administer comments',
    ),
    'type' => MENU_LOCAL_TASK,
  );
  $items['comment/%'] = array(
    'title' => 'Comment permalink',
    'page callback' => 'comment_permalink',
    'page arguments' => array(
      1,
    ),
    'access arguments' => array(
      'access comments',
    ),
  );
  $items['comment/%/view'] = array(
    'title' => 'View comment',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10,
  );

  // Every other comment path uses %, but this one loads the comment directly,
  // so we don't end up loading it twice (in the page and access callback).
  $items['comment/%comment/edit'] = array(
    'title' => 'Edit',
    'page callback' => 'comment_edit_page',
    'page arguments' => array(
      1,
    ),
    'access callback' => 'comment_access',
    'access arguments' => array(
      'edit',
      1,
    ),
    'type' => MENU_LOCAL_TASK,
    'weight' => 0,
  );
  $items['comment/%/approve'] = array(
    'title' => 'Approve',
    'page callback' => 'comment_approve',
    'page arguments' => array(
      1,
    ),
    'access arguments' => array(
      'administer comments',
    ),
    'file' => 'comment.pages.inc',
    'weight' => 1,
  );
  $items['comment/%/delete'] = array(
    'title' => 'Delete',
    'page callback' => 'comment_confirm_delete_page',
    'page arguments' => array(
      1,
    ),
    'access arguments' => array(
      'administer comments',
    ),
    'type' => MENU_LOCAL_TASK,
    'file' => 'comment.admin.inc',
    'weight' => 2,
  );
  $items['comment/reply/%node'] = array(
    'title' => 'Add new comment',
    'page callback' => 'comment_reply',
    'page arguments' => array(
      2,
    ),
    'access callback' => 'node_access',
    'access arguments' => array(
      'view',
      2,
    ),
    'file' => 'comment.pages.inc',
  );
  return $items;
}

/**
 * Implements hook_menu_alter().
 */
function comment_menu_alter(&$items) {

  // Add comments to the description for admin/content.
  $items['admin/content']['description'] = 'Administer content and comments.';

  // Adjust the Field UI tabs on admin/structure/types/manage/[node-type].
  // See comment_entity_info().
  $items['admin/structure/types/manage/%comment_node_type/comment/fields']['title'] = 'Comment fields';
  $items['admin/structure/types/manage/%comment_node_type/comment/fields']['weight'] = 3;
  $items['admin/structure/types/manage/%comment_node_type/comment/display']['title'] = 'Comment display';
  $items['admin/structure/types/manage/%comment_node_type/comment/display']['weight'] = 4;
}

/**
 * Returns a menu title which includes the number of unapproved comments.
 */
function comment_count_unpublished() {
  $count = db_query('SELECT COUNT(cid) FROM {comment} WHERE status = :status', array(
    ':status' => COMMENT_NOT_PUBLISHED,
  ))
    ->fetchField();
  return t('Unapproved comments (@count)', array(
    '@count' => $count,
  ));
}

/**
 * Implements hook_node_type_insert().
 *
 * Creates a comment body field for a node type created while the Comment module
 * is enabled. For node types created before the Comment module is enabled,
 * hook_modules_enabled() serves to create the body fields.
 *
 * @see comment_modules_enabled()
 */
function comment_node_type_insert($info) {
  _comment_body_field_create($info);
}

/**
 * Implements hook_node_type_update().
 */
function comment_node_type_update($info) {
  if (!empty($info->old_type) && $info->type != $info->old_type) {
    field_attach_rename_bundle('comment', 'comment_node_' . $info->old_type, 'comment_node_' . $info->type);
  }
}

/**
 * Implements hook_node_type_delete().
 */
function comment_node_type_delete($info) {
  field_attach_delete_bundle('comment', 'comment_node_' . $info->type);
  $settings = array(
    'comment',
    'comment_default_mode',
    'comment_default_per_page',
    'comment_anonymous',
    'comment_subject_field',
    'comment_preview',
    'comment_form_location',
  );
  foreach ($settings as $setting) {
    variable_del($setting . '_' . $info->type);
  }
}

/**
 * Creates a comment_body field instance for a given node type.
 *
 * @param $info
 *   An object representing the content type. The only property that is
 *   currently used is $info->type, which is the machine name of the content
 *   type for which the body field (instance) is to be created.
 */
function _comment_body_field_create($info) {

  // Create the field if needed.
  if (!field_read_field('comment_body', array(
    'include_inactive' => TRUE,
  ))) {
    $field = array(
      'field_name' => 'comment_body',
      'type' => 'text_long',
      'entity_types' => array(
        'comment',
      ),
    );
    field_create_field($field);
  }

  // Create the instance if needed.
  if (!field_read_instance('comment', 'comment_body', 'comment_node_' . $info->type, array(
    'include_inactive' => TRUE,
  ))) {
    field_attach_create_bundle('comment', 'comment_node_' . $info->type);

    // Attaches the body field by default.
    $instance = array(
      'field_name' => 'comment_body',
      'label' => 'Comment',
      'entity_type' => 'comment',
      'bundle' => 'comment_node_' . $info->type,
      'settings' => array(
        'text_processing' => 1,
      ),
      'required' => TRUE,
      'display' => array(
        'default' => array(
          'label' => 'hidden',
          'type' => 'text_default',
          'weight' => 0,
        ),
      ),
    );
    field_create_instance($instance);
  }
}

/**
 * Implements hook_permission().
 */
function comment_permission() {
  return array(
    'administer comments' => array(
      'title' => t('Administer comments and comment settings'),
    ),
    'access comments' => array(
      'title' => t('View comments'),
    ),
    'post comments' => array(
      'title' => t('Post comments'),
    ),
    'skip comment approval' => array(
      'title' => t('Skip comment approval'),
    ),
    'edit own comments' => array(
      'title' => t('Edit own comments'),
    ),
  );
}

/**
 * Implements hook_block_info().
 */
function comment_block_info() {
  $blocks['recent']['info'] = t('Recent comments');
  $blocks['recent']['properties']['administrative'] = TRUE;
  return $blocks;
}

/**
 * Implements hook_block_configure().
 */
function comment_block_configure($delta = '') {
  $form['comment_block_count'] = array(
    '#type' => 'select',
    '#title' => t('Number of recent comments'),
    '#default_value' => variable_get('comment_block_count', 10),
    '#options' => drupal_map_assoc(array(
      2,
      3,
      4,
      5,
      6,
      7,
      8,
      9,
      10,
      11,
      12,
      13,
      14,
      15,
      16,
      17,
      18,
      19,
      20,
      25,
      30,
    )),
  );
  return $form;
}

/**
 * Implements hook_block_save().
 */
function comment_block_save($delta = '', $edit = array()) {
  variable_set('comment_block_count', (int) $edit['comment_block_count']);
}

/**
 * Implements hook_block_view().
 *
 * Generates a block with the most recent comments.
 */
function comment_block_view($delta = '') {
  if (user_access('access comments')) {
    $block['subject'] = t('Recent comments');
    $block['content'] = theme('comment_block');
    return $block;
  }
}

/**
 * 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 $cid
 *   A comment identifier.
 *
 * @return
 *   The comment listing set to the page on which the comment appears.
 */
function comment_permalink($cid) {
  if (($comment = comment_load($cid)) && ($node = node_load($comment->nid))) {

    // Find the current display page for this comment.
    $page = comment_get_display_page($comment->cid, $node->type);

    // @todo: Cleaner sub request handling.
    $request = drupal_container()
      ->get('request');
    $subrequest = Request::create('/node/' . $node->nid, 'GET', $request->query
      ->all(), $request->cookies
      ->all(), array(), $request->server
      ->all());
    $subrequest->query
      ->set('page', $page);

    // @todo: Convert the pager to use the request object.
    $_GET['page'] = $page;
    return drupal_container()
      ->get('http_kernel')
      ->handle($subrequest, HttpKernelInterface::SUB_REQUEST);
  }
  throw new NotFoundHttpException();
}

/**
 * Finds the most recent comments that are available to the current user.
 *
 * @param integer $number
 *   (optional) The maximum number of comments to find. Defaults to 10.
 *
 * @return
 *   An array of comment objects or an empty array if there are no recent
 *   comments visible to the current user.
 */
function comment_get_recent($number = 10) {
  $query = db_select('comment', 'c');
  $query
    ->innerJoin('node', 'n', 'n.nid = c.nid');
  $query
    ->addTag('node_access');
  $query
    ->addMetaData('base_table', 'comment');
  $comments = $query
    ->fields('c')
    ->condition('c.status', COMMENT_PUBLISHED)
    ->condition('n.status', NODE_PUBLISHED)
    ->orderBy('c.created', 'DESC')
    ->orderBy('c.cid', 'DESC')
    ->range(0, $number)
    ->execute()
    ->fetchAll();
  return $comments ? $comments : array();
}

/**
 * Calculates the page number for the first new comment.
 *
 * @param $num_comments
 *   Number of comments.
 * @param $new_replies
 *   Number of new replies.
 * @param Drupal\node\Node $node
 *   The first new comment node.
 *
 * @return
 *   "page=X" if the page number is greater than zero; empty string otherwise.
 */
function comment_new_page_count($num_comments, $new_replies, Node $node) {
  $mode = variable_get('comment_default_mode_' . $node->type, COMMENT_MODE_THREADED);
  $comments_per_page = variable_get('comment_default_per_page_' . $node->type, 50);
  $pagenum = NULL;
  $flat = $mode == COMMENT_MODE_FLAT ? TRUE : FALSE;
  if ($num_comments <= $comments_per_page) {

    // Only one page of comments.
    $pageno = 0;
  }
  elseif ($flat) {

    // Flat comments.
    $count = $num_comments - $new_replies;
    $pageno = $count / $comments_per_page;
  }
  else {

    // 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('nid', $node->nid)
      ->condition('status', COMMENT_PUBLISHED)
      ->orderBy('created', 'DESC')
      ->orderBy('cid', 'DESC')
      ->range(0, $new_replies);

    // 2. Find the first thread.
    $first_thread = db_select($unread_threads_query, 'thread')
      ->fields('thread', array(
      'thread',
    ))
      ->orderBy('SUBSTRING(thread, 1, (LENGTH(thread) - 1))')
      ->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 nid = :nid AND status = :status AND SUBSTRING(thread, 1, (LENGTH(thread) - 1)) < :thread', array(
      ':status' => COMMENT_PUBLISHED,
      ':nid' => $node->nid,
      ':thread' => $first_thread,
    ))
      ->fetchField();
    $pageno = $count / $comments_per_page;
  }
  if ($pageno >= 1) {
    $pagenum = array(
      'page' => intval($pageno),
    );
  }
  return $pagenum;
}

/**
 * Returns HTML for a list of recent comments.
 *
 * @ingroup themeable
 */
function theme_comment_block() {
  $items = array();
  $number = variable_get('comment_block_count', 10);
  foreach (comment_get_recent($number) as $comment) {
    $items[] = l($comment->subject, 'comment/' . $comment->cid, array(
      'fragment' => 'comment-' . $comment->cid,
    )) . '&nbsp;<span>' . t('@time ago', array(
      '@time' => format_interval(REQUEST_TIME - $comment->changed),
    )) . '</span>';
  }
  if ($items) {
    return theme('item_list', array(
      'items' => $items,
    ));
  }
  else {
    return t('No comments available.');
  }
}

/**
 * Implements hook_node_view().
 */
function comment_node_view(Node $node, $view_mode) {
  $links = array();
  if ($node->comment != COMMENT_NODE_HIDDEN) {
    if ($view_mode == 'rss') {

      // Add a comments RSS element which is a URL to the comments of this node.
      $node->rss_elements[] = array(
        'key' => 'comments',
        'value' => url('node/' . $node->nid, array(
          'fragment' => 'comments',
          'absolute' => TRUE,
        )),
      );
    }
    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->comment_count)) {
          $links['comment-comments'] = array(
            'title' => format_plural($node->comment_count, '1 comment', '@count comments'),
            'href' => "node/{$node->nid}",
            'attributes' => array(
              'title' => t('Jump to the first comment of this posting.'),
            ),
            'fragment' => 'comments',
            'html' => TRUE,
          );

          // Show a link to the first new comment.
          if ($new = comment_num_new($node->nid)) {
            $links['comment-new-comments'] = array(
              'title' => format_plural($new, '1 new comment', '@count new comments'),
              'href' => "node/{$node->nid}",
              'query' => comment_new_page_count($node->comment_count, $new, $node),
              'attributes' => array(
                'title' => t('Jump to the first new comment of this posting.'),
              ),
              'fragment' => 'new',
              'html' => TRUE,
            );
          }
        }
      }
      if ($node->comment == COMMENT_NODE_OPEN) {
        $comment_form_location = variable_get('comment_form_location_' . $node->type, COMMENT_FORM_BELOW);
        if (user_access('post comments')) {
          $links['comment-add'] = array(
            'title' => t('Add new comment'),
            'href' => "node/{$node->nid}",
            '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']['href'] = "comment/reply/{$node->nid}";
          }
        }
        else {
          $links['comment-forbidden'] = array(
            'title' => theme('comment_post_forbidden', array(
              'node' => $node,
            )),
            'html' => TRUE,
          );
        }
      }
    }
    elseif ($view_mode != 'search_index' && $view_mode != 'search_result') {

      // 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.
      // But we don't want this link if we're building the node for search
      // indexing or constructing a search result excerpt.
      if ($node->comment == COMMENT_NODE_OPEN) {
        $comment_form_location = variable_get('comment_form_location_' . $node->type, COMMENT_FORM_BELOW);
        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->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.'),
              ),
              'href' => "node/{$node->nid}",
              'fragment' => 'comment-form',
            );
            if ($comment_form_location == COMMENT_FORM_SEPARATE_PAGE) {
              $links['comment-add']['href'] = "comment/reply/{$node->nid}";
            }
          }
        }
        else {
          $links['comment-forbidden'] = array(
            'title' => theme('comment_post_forbidden', array(
              'node' => $node,
            )),
            'html' => TRUE,
          );
        }
      }
    }
    $node->content['links']['comment'] = array(
      '#theme' => 'links__node__comment',
      '#links' => $links,
      '#attributes' => array(
        'class' => array(
          'links',
          'inline',
        ),
      ),
    );

    // Only append comments when we are building a node on its own node detail
    // page. We compare $node and $page_node to ensure that comments are not
    // appended to other nodes shown on the page, for example a node_reference
    // displayed in 'full' view mode within another node.
    if ($node->comment && $view_mode == 'full' && node_is_page($node) && empty($node->in_preview)) {
      $node->content['comments'] = comment_node_page_additions($node);
    }
  }
}

/**
 * Builds the comment-related elements for node detail pages.
 *
 * @param Drupal\node\Node $node
 *   The node entity for which to build the comment-related elements.
 *
 * @return
 *   A renderable array representing the comment-related page elements for the
 *   node.
 */
function comment_node_page_additions(Node $node) {
  $additions = array();

  // Only attempt to render comments if the node has visible comments.
  // Unpublished comments are not included in $node->comment_count, so show
  // comments unconditionally if the user is an administrator.
  if ($node->comment_count && user_access('access comments') || user_access('administer comments')) {
    $mode = variable_get('comment_default_mode_' . $node->type, COMMENT_MODE_THREADED);
    $comments_per_page = variable_get('comment_default_per_page_' . $node->type, 50);
    if ($cids = comment_get_thread($node, $mode, $comments_per_page)) {
      $comments = comment_load_multiple($cids);
      comment_prepare_thread($comments);
      $build = comment_view_multiple($comments);
      $build['pager']['#theme'] = 'pager';
      $additions['comments'] = $build;
    }
  }

  // Append comment form if needed.
  if (user_access('post comments') && $node->comment == COMMENT_NODE_OPEN && variable_get('comment_form_location_' . $node->type, COMMENT_FORM_BELOW) == COMMENT_FORM_BELOW) {
    $additions['comment_form'] = comment_add($node);
  }
  if ($additions) {
    $additions += array(
      '#theme' => 'comment_wrapper__node_' . $node->type,
      '#node' => $node,
      'comments' => array(),
      'comment_form' => array(),
    );
  }
  return $additions;
}

/**
 * Returns a rendered form to comment the given node.
 *
 * @param Drupal\node\Node $node
 *   The node entity to be commented.
 * @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(Node $node, $pid = NULL) {
  $values = array(
    'nid' => $node->nid,
    'pid' => $pid,
    'node_type' => 'comment_node_' . $node->type,
  );
  $comment = entity_create('comment', $values);
  return entity_get_form($comment);
}

/**
 * Retrieves comments for a thread.
 *
 * @param Drupal\node\Node $node
 *   The node whose comment(s) needs rendering.
 * @param $mode
 *   The comment display mode; COMMENT_MODE_FLAT or COMMENT_MODE_THREADED.
 * @param $comments_per_page
 *   The amount of comments to display per page.
 *
 * @return
 *   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(Node $node, $mode, $comments_per_page) {
  $query = db_select('comment', 'c')
    ->extend('Drupal\\Core\\Database\\Query\\PagerSelectExtender');
  $query
    ->addField('c', 'cid');
  $query
    ->condition('c.nid', $node->nid)
    ->addTag('node_access')
    ->addTag('comment_filter')
    ->addMetaData('base_table', 'comment')
    ->addMetaData('node', $node)
    ->limit($comments_per_page);
  $count_query = db_select('comment', 'c');
  $count_query
    ->addExpression('COUNT(*)');
  $count_query
    ->condition('c.nid', $node->nid)
    ->addTag('node_access')
    ->addTag('comment_filter')
    ->addMetaData('base_table', 'comment')
    ->addMetaData('node', $node);
  if (!user_access('administer comments')) {
    $query
      ->condition('c.status', COMMENT_PUBLISHED);
    $count_query
      ->condition('c.status', COMMENT_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');
  }
  $query
    ->setCountQuery($count_query);
  $cids = $query
    ->execute()
    ->fetchCol();
  return $cids;
}

/**
 * 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.
 *
 * @param array $comments
 *   An array of comment objects, keyed by comment ID.
 */
function comment_prepare_thread(&$comments) {

  // A flag stating if we are still searching for first new comment on the thread.
  $first_new = TRUE;

  // A counter that helps track how indented we are.
  $divs = 0;
  foreach ($comments as $key => $comment) {
    if ($first_new && $comment->new != MARK_READ) {

      // Assign the anchor only for the first new comment. This avoids duplicate
      // id attributes on a page.
      $first_new = FALSE;
      $comment->first_new = TRUE;
    }

    // The $divs element instructs #prefix whether to add an indent div or
    // close existing divs (a negative value).
    $comment->depth = count(explode('.', $comment->thread)) - 1;
    if ($comment->depth > $divs) {
      $comment->divs = 1;
      $divs++;
    }
    else {
      $comment->divs = $comment->depth - $divs;
      while ($comment->depth < $divs) {
        $divs--;
      }
    }
    $comments[$key] = $comment;
  }

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

/**
 * Generates an array for rendering a comment.
 *
 * @param Drupal\comment\Comment $comment
 *   The comment object.
 * @param $view_mode
 *   View mode, e.g. 'full', 'teaser'...
 * @param $langcode
 *   (optional) A language code to use for rendering. Defaults to the global
 *   content language of the current request.
 *
 * @return
 *   An array as expected by drupal_render().
 */
function comment_view(Comment $comment, $view_mode = 'full', $langcode = NULL) {
  return entity_view($comment, $view_mode, $langcode);
}

/**
 * Adds reply, edit, delete, etc. links, depending on user permissions.
 *
 * @param Drupal\comment\Comment $comment
 *   The comment object.
 * @param Drupal\node\Node $node
 *   The node the comment is attached to.
 *
 * @return
 *   A structured array of links.
 */
function comment_links(Comment $comment, Node $node) {
  $links = array();
  if ($node->comment == COMMENT_NODE_OPEN) {
    if (user_access('administer comments') && user_access('post comments')) {
      $links['comment-delete'] = array(
        'title' => t('delete'),
        'href' => "comment/{$comment->cid}/delete",
        'html' => TRUE,
      );
      $links['comment-edit'] = array(
        'title' => t('edit'),
        'href' => "comment/{$comment->cid}/edit",
        'html' => TRUE,
      );
      $links['comment-reply'] = array(
        'title' => t('reply'),
        'href' => "comment/reply/{$comment->nid}/{$comment->cid}",
        'html' => TRUE,
      );
      if ($comment->status == COMMENT_NOT_PUBLISHED) {
        $links['comment-approve'] = array(
          'title' => t('approve'),
          'href' => "comment/{$comment->cid}/approve",
          'html' => TRUE,
          'query' => array(
            'token' => drupal_get_token("comment/{$comment->cid}/approve"),
          ),
        );
      }
    }
    elseif (user_access('post comments')) {
      if (comment_access('edit', $comment)) {
        $links['comment-edit'] = array(
          'title' => t('edit'),
          'href' => "comment/{$comment->cid}/edit",
          'html' => TRUE,
        );
      }
      $links['comment-reply'] = array(
        'title' => t('reply'),
        'href' => "comment/reply/{$comment->nid}/{$comment->cid}",
        'html' => TRUE,
      );
    }
    else {
      $links['comment-forbidden']['title'] = theme('comment_post_forbidden', array(
        'node' => $node,
      ));
      $links['comment-forbidden']['html'] = TRUE;
    }
  }

  // Add translations link for translation-enabled comment bundles.
  if (module_exists('translation_entity') && translation_entity_translate_access($comment)) {
    $links['comment-translations'] = array(
      'title' => t('translations'),
      'href' => 'comment/' . $comment
        ->id() . '/translations',
      'html' => TRUE,
    );
  }
  return $links;
}

/**
 * Constructs render array from an array of loaded comments.
 *
 * @param $comments
 *   An array of comments as returned by comment_load_multiple().
 * @param $view_mode
 *   View mode, e.g. 'full', 'teaser'...
 * @param $langcode
 *   A string indicating the language field values are to be shown in. If no
 *   language is provided the current content language is used.
 *
 * @return
 *   An array in the format expected by drupal_render().
 *
 * @see 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_node_type_form_alter(&$form, $form_state) {
  if (isset($form['type'])) {
    $form['comment'] = array(
      '#type' => 'details',
      '#title' => t('Comment settings'),
      '#collapsible' => TRUE,
      '#collapsed' => TRUE,
      '#group' => 'additional_settings',
      '#attributes' => array(
        'class' => array(
          'comment-node-type-settings-form',
        ),
      ),
      '#attached' => array(
        'library' => array(
          array(
            'comment',
            'drupal.comment',
          ),
        ),
      ),
    );

    // Unlike coment_form_node_form_alter(), all of these settings are applied
    // as defaults to all new nodes. Therefore, it would be wrong to use #states
    // to hide the other settings based on the primary comment setting.
    $form['comment']['comment'] = array(
      '#type' => 'select',
      '#title' => t('Default comment setting for new content'),
      '#default_value' => variable_get('comment_' . $form['#node_type']->type, COMMENT_NODE_OPEN),
      '#options' => array(
        COMMENT_NODE_OPEN => t('Open'),
        COMMENT_NODE_CLOSED => t('Closed'),
        COMMENT_NODE_HIDDEN => t('Hidden'),
      ),
    );
    $form['comment']['comment_default_mode'] = array(
      '#type' => 'checkbox',
      '#title' => t('Threading'),
      '#default_value' => variable_get('comment_default_mode_' . $form['#node_type']->type, COMMENT_MODE_THREADED),
      '#description' => t('Show comment replies in a threaded list.'),
    );
    $form['comment']['comment_default_per_page'] = array(
      '#type' => 'select',
      '#title' => t('Comments per page'),
      '#default_value' => variable_get('comment_default_per_page_' . $form['#node_type']->type, 50),
      '#options' => _comment_per_page(),
    );
    $form['comment']['comment_anonymous'] = array(
      '#type' => 'select',
      '#title' => t('Anonymous commenting'),
      '#default_value' => variable_get('comment_anonymous_' . $form['#node_type']->type, COMMENT_ANONYMOUS_MAYNOT_CONTACT),
      '#options' => array(
        COMMENT_ANONYMOUS_MAYNOT_CONTACT => t('Anonymous posters may not enter their contact information'),
        COMMENT_ANONYMOUS_MAY_CONTACT => t('Anonymous posters may leave their contact information'),
        COMMENT_ANONYMOUS_MUST_CONTACT => t('Anonymous posters must leave their contact information'),
      ),
      '#access' => user_access('post comments', drupal_anonymous_user()),
    );
    $form['comment']['comment_subject_field'] = array(
      '#type' => 'checkbox',
      '#title' => t('Allow comment title'),
      '#default_value' => variable_get('comment_subject_field_' . $form['#node_type']->type, 1),
    );
    $form['comment']['comment_form_location'] = array(
      '#type' => 'checkbox',
      '#title' => t('Show reply form on the same page as comments'),
      '#default_value' => variable_get('comment_form_location_' . $form['#node_type']->type, COMMENT_FORM_BELOW),
    );
    $form['comment']['comment_preview'] = array(
      '#type' => 'radios',
      '#title' => t('Preview comment'),
      '#default_value' => variable_get('comment_preview_' . $form['#node_type']->type, DRUPAL_OPTIONAL),
      '#options' => array(
        DRUPAL_DISABLED => t('Disabled'),
        DRUPAL_OPTIONAL => t('Optional'),
        DRUPAL_REQUIRED => t('Required'),
      ),
    );

    // @todo Remove this check once language settings are generalized.
    if (module_exists('translation_entity')) {
      $comment_form = $form;
      $comment_form_state['translation_entity']['key'] = 'language_configuration';
      $form['comment'] += translation_entity_enable_widget('comment', 'comment_node_' . $form['#node_type']->type, $comment_form, $comment_form_state);
      array_unshift($form['#submit'], 'comment_translation_configuration_element_submit');
    }
  }
}

/**
 * Form submission handler for node_type_form().
 *
 * This handles the comment translation settings added by
 * comment_form_node_type_form_alter().
 *
 * @see comment_form_node_type_form_alter()
 */
function comment_translation_configuration_element_submit($form, &$form_state) {

  // The comment translation settings form element is embedded into the node
  // type form. Hence we need to provide to the regular submit handler a
  // manipulated form state to make it process comment settings instead of node
  // settings.
  $key = 'language_configuration';
  $comment_form_state = array(
    'translation_entity' => array(
      'key' => $key,
    ),
    'language' => array(
      $key => array(
        'entity_type' => 'comment',
        'bundle' => 'comment_node_' . $form['#node_type']->type,
      ),
    ),
    'values' => array(
      $key => array(
        'translation_entity' => $form_state['values']['translation_entity'],
      ),
    ),
  );
  translation_entity_language_configuration_element_submit($form, $comment_form_state);
}

/**
 * Implements hook_form_BASE_FORM_ID_alter().
 */
function comment_form_node_form_alter(&$form, $form_state) {
  $node = $form_state['controller']
    ->getEntity($form_state);
  $form['comment_settings'] = array(
    '#type' => 'details',
    '#access' => user_access('administer comments'),
    '#title' => t('Comment settings'),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
    '#group' => 'additional_settings',
    '#attributes' => array(
      'class' => array(
        'comment-node-settings-form',
      ),
    ),
    '#attached' => array(
      'library' => array(
        array(
          'comment',
          'drupal.comment',
        ),
      ),
    ),
    '#weight' => 30,
  );
  $comment_count = isset($node->nid) ? db_query('SELECT comment_count FROM {node_comment_statistics} WHERE nid = :nid', array(
    ':nid' => $node->nid,
  ))
    ->fetchField() : 0;
  $comment_settings = $node->comment == COMMENT_NODE_HIDDEN && empty($comment_count) ? COMMENT_NODE_CLOSED : $node->comment;
  $form['comment_settings']['comment'] = array(
    '#type' => 'radios',
    '#title' => t('Comments'),
    '#title_display' => 'invisible',
    '#parents' => array(
      'comment',
    ),
    '#default_value' => $comment_settings,
    '#options' => array(
      COMMENT_NODE_OPEN => t('Open'),
      COMMENT_NODE_CLOSED => t('Closed'),
      COMMENT_NODE_HIDDEN => t('Hidden'),
    ),
    COMMENT_NODE_OPEN => array(
      '#description' => t('Users with the "Post comments" permission can post comments.'),
    ),
    COMMENT_NODE_CLOSED => array(
      '#description' => t('Users cannot post comments, but existing comments will be displayed.'),
    ),
    COMMENT_NODE_HIDDEN => array(
      '#description' => t('Comments are hidden from view.'),
    ),
  );

  // If the node doesn't have any comments, the "hidden" option makes no
  // sense, so don't even bother presenting it to the user.
  if (empty($comment_count)) {
    $form['comment_settings']['comment'][COMMENT_NODE_HIDDEN]['#access'] = FALSE;

    // Also adjust the description of the "closed" option.
    $form['comment_settings']['comment'][COMMENT_NODE_CLOSED]['#description'] = t('Users cannot post comments.');
  }
}

/**
 * Implements hook_node_load().
 */
function comment_node_load($nodes, $types) {
  $comments_enabled = array();

  // Check if comments are enabled for each node. If comments are disabled,
  // assign values without hitting the database.
  foreach ($nodes as $node) {

    // Store whether comments are enabled for this node.
    if ($node->comment != COMMENT_NODE_HIDDEN) {
      $comments_enabled[] = $node->nid;
    }
    else {
      $node->cid = 0;
      $node->last_comment_timestamp = $node->created;
      $node->last_comment_name = '';
      $node->last_comment_uid = $node->uid;
      $node->comment_count = 0;
    }
  }

  // For nodes with comments enabled, fetch information from the database.
  if (!empty($comments_enabled)) {
    $result = db_query('SELECT nid, cid, last_comment_timestamp, last_comment_name, last_comment_uid, comment_count FROM {node_comment_statistics} WHERE nid IN (:comments_enabled)', array(
      ':comments_enabled' => $comments_enabled,
    ));
    foreach ($result as $record) {
      $nodes[$record->nid]->cid = $record->cid;
      $nodes[$record->nid]->last_comment_timestamp = $record->last_comment_timestamp;
      $nodes[$record->nid]->last_comment_name = $record->last_comment_name;
      $nodes[$record->nid]->last_comment_uid = $record->last_comment_uid;
      $nodes[$record->nid]->comment_count = $record->comment_count;
    }
  }
}

/**
 * Implements hook_node_prepare().
 */
function comment_node_prepare(Node $node) {
  if (!isset($node->comment)) {
    $node->comment = variable_get("comment_{$node->type}", COMMENT_NODE_OPEN);
  }
}

/**
 * Implements hook_node_insert().
 */
function comment_node_insert(Node $node) {

  // Allow bulk updates and inserts to temporarily disable the
  // maintenance of the {node_comment_statistics} table.
  if (variable_get('comment_maintain_node_statistics', TRUE)) {
    db_insert('node_comment_statistics')
      ->fields(array(
      'nid' => $node->nid,
      'cid' => 0,
      'last_comment_timestamp' => $node->changed,
      'last_comment_name' => NULL,
      'last_comment_uid' => $node->uid,
      'comment_count' => 0,
    ))
      ->execute();
  }
}

/**
 * Implements hook_node_predelete().
 */
function comment_node_predelete(Node $node) {
  $cids = db_query('SELECT cid FROM {comment} WHERE nid = :nid', array(
    ':nid' => $node->nid,
  ))
    ->fetchCol();
  comment_delete_multiple($cids);
  db_delete('node_comment_statistics')
    ->condition('nid', $node->nid)
    ->execute();
}

/**
 * Implements hook_node_update_index().
 */
function comment_node_update_index(Node $node, $langcode) {
  $index_comments =& drupal_static(__FUNCTION__);
  if ($index_comments === NULL) {

    // Find and save roles that can 'access comments' or 'search content'.
    $perms = array(
      'access comments' => array(),
      'search content' => array(),
    );
    $result = db_query("SELECT rid, permission FROM {role_permission} WHERE permission IN ('access comments', 'search content')");
    foreach ($result as $record) {
      $perms[$record->permission][$record->rid] = $record->rid;
    }

    // Prevent indexing of comments if there are any roles that can search but
    // not view comments.
    $index_comments = TRUE;
    foreach ($perms['search content'] as $rid) {
      if (!isset($perms['access comments'][$rid]) && ($rid == DRUPAL_AUTHENTICATED_RID || $rid == DRUPAL_ANONYMOUS_RID || !isset($perms['access comments'][DRUPAL_AUTHENTICATED_RID]))) {
        $index_comments = FALSE;
        break;
      }
    }
  }
  if ($index_comments) {
    $mode = variable_get('comment_default_mode_' . $node->type, COMMENT_MODE_THREADED);
    $comments_per_page = variable_get('comment_default_per_page_' . $node->type, 50);
    if ($node->comment && ($cids = comment_get_thread($node, $mode, $comments_per_page))) {
      $comments = comment_load_multiple($cids);
      comment_prepare_thread($comments);
      $build = comment_view_multiple($comments, $langcode);
      return drupal_render($build);
    }
  }
  return '';
}

/**
 * Implements hook_update_index().
 */
function comment_update_index() {

  // Store the maximum possible comments per thread (used for ranking by reply count)
  state()
    ->set('comment.node_comment_statistics_scale', 1.0 / max(1, db_query('SELECT MAX(comment_count) FROM {node_comment_statistics}')
    ->fetchField()));
}

/**
 * Implements hook_node_search_result().
 *
 * Formats a comment count string and returns it, for display with search
 * results.
 */
function comment_node_search_result(Node $node) {

  // Do not make a string if comments are hidden.
  if (user_access('access comments') && $node->comment != COMMENT_NODE_HIDDEN) {
    $comments = db_query('SELECT comment_count FROM {node_comment_statistics} WHERE nid = :nid', array(
      'nid' => $node->nid,
    ))
      ->fetchField();

    // Do not make a string if comments are closed and there are currently
    // zero comments.
    if ($node->comment != COMMENT_NODE_CLOSED || $comments > 0) {
      return array(
        'comment' => format_plural($comments, '1 comment', '@count comments'),
      );
    }
  }
}

/**
 * Implements hook_user_cancel().
 */
function comment_user_cancel($edit, $account, $method) {
  switch ($method) {
    case 'user_cancel_block_unpublish':
      $comments = entity_load_multiple_by_properties('comment', array(
        'uid' => $account->uid,
      ));
      foreach ($comments as $comment) {
        $comment->status = 0;
        comment_save($comment);
      }
      break;
    case 'user_cancel_reassign':
      $comments = entity_load_multiple_by_properties('comment', array(
        'uid' => $account->uid,
      ));
      foreach ($comments as $comment) {
        $comment->uid = 0;
        comment_save($comment);
      }
      break;
  }
}

/**
 * Implements hook_user_predelete().
 */
function comment_user_predelete($account) {
  $cids = db_query('SELECT c.cid FROM {comment} c WHERE uid = :uid', array(
    ':uid' => $account->uid,
  ))
    ->fetchCol();
  comment_delete_multiple($cids);
}

/**
 * Determines whether the current user has access to a particular comment.
 *
 * Authenticated users can edit their comments as long they have not been
 * replied to. This prevents people from changing or revising their statements
 * based on the replies to their posts.
 *
 * @param $op
 *   The operation that is to be performed on the comment. Only 'edit' is
 *   recognized now.
 * @param Drupal\comment\Comment $comment
 *   The comment object.
 *
 * @return
 *   TRUE if the current user has acces to the comment, FALSE otherwise.
 */
function comment_access($op, Comment $comment) {
  global $user;
  if ($op == 'edit') {
    return $user->uid && $user->uid == $comment->uid && $comment->status == COMMENT_PUBLISHED && user_access('edit own comments') || user_access('administer comments');
  }
}

/**
 * Accepts a submission of new or changed comment content.
 *
 * @param Drupal\comment\Comment $comment
 *   A comment object.
 */
function comment_save(Comment $comment) {
  $comment
    ->save();
}

/**
 * Deletes a comment and all its replies.
 *
 * @param $cid
 *   The ID of the comment to delete.
 */
function comment_delete($cid) {
  comment_delete_multiple(array(
    $cid,
  ));
}

/**
 * Deletes comments and all their replies.
 *
 * @param $cids
 *   The IDs of the comments to delete.
 *
 * @see hook_comment_predelete()
 * @see hook_comment_delete()
 */
function comment_delete_multiple($cids) {
  entity_delete_multiple('comment', $cids);
}

/**
 * Loads comment entities from the database.
 *
 * @param array $cids
 *   (optional) An array of entity IDs. If omitted, all entities are loaded.
 * @param bool $reset
 *   Whether to reset the internal static entity cache. Note that the static
 *   cache is disabled in comment_entity_info() by default.
 *
 * @return array
 *   An array of comment objects, indexed by comment ID.
 *
 * @see entity_load()
 * @see Drupal\Core\Entity\Query\QueryInterface
 */
function comment_load_multiple(array $cids = NULL, $reset = FALSE) {
  return entity_load_multiple('comment', $cids, $reset);
}

/**
 * Loads the entire comment by comment ID.
 *
 * @param int $cid
 *   The ID of the comment to be loaded.
 * @param bool $reset
 *   Whether to reset the internal static entity cache. Note that the static
 *   cache is disabled in comment_entity_info() by default.
 *
 * @return
 *   The comment object.
 */
function comment_load($cid, $reset = FALSE) {
  return entity_load('comment', $cid);
}

/**
 * Gets the number of new comments for the current user and the specified node.
 *
 * @param $nid
 *   Node ID to count comments for.
 * @param $timestamp
 *   Time to count from (defaults to time of last user access
 *   to node).
 *
 * @return
 *   The number of new comments or FALSE if the user is not logged in.
 */
function comment_num_new($nid, $timestamp = 0) {
  global $user;
  if ($user->uid && module_exists('history')) {

    // Retrieve the timestamp at which the current user last viewed this node.
    if (!$timestamp) {
      $timestamp = history_read($nid);
    }
    $timestamp = $timestamp > HISTORY_READ_LIMIT ? $timestamp : HISTORY_READ_LIMIT;

    // Use the timestamp to retrieve the number of new comments.
    return db_query('SELECT COUNT(cid) FROM {comment} WHERE nid = :nid AND created > :timestamp AND status = :status', array(
      ':nid' => $nid,
      ':timestamp' => $timestamp,
      ':status' => COMMENT_PUBLISHED,
    ))
      ->fetchField();
  }
  else {
    return FALSE;
  }
}

/**
 * Gets the display ordinal for a comment, starting from 0.
 *
 * Count the number of comments which appear before the comment we want to
 * display, taking into account display settings and threading.
 *
 * @param $cid
 *   The comment ID.
 * @param $node_type
 *   The node type of the comment's parent.
 *
 * @return
 *   The display ordinal for the comment.
 *
 * @see comment_get_display_page()
 */
function comment_get_display_ordinal($cid, $node_type) {

  // Count how many comments (c1) are before $cid (c2) in display order. This is
  // the 0-based display ordinal.
  $query = db_select('comment', 'c1');
  $query
    ->innerJoin('comment', 'c2', 'c2.nid = c1.nid');
  $query
    ->addExpression('COUNT(*)', 'count');
  $query
    ->condition('c2.cid', $cid);
  if (!user_access('administer comments')) {
    $query
      ->condition('c1.status', COMMENT_PUBLISHED);
  }
  $mode = variable_get('comment_default_mode_' . $node_type, COMMENT_MODE_THREADED);
  if ($mode == COMMENT_MODE_FLAT) {

    // For flat comments, cid is used for ordering comments due to
    // unpredicatable behavior with timestamp, so we make the same assumption
    // here.
    $query
      ->condition('c1.cid', $cid, '<');
  }
  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.
    // See CommentRenderController.
    $query
      ->where('SUBSTRING(c1.thread, 1, (LENGTH(c1.thread) -1)) < SUBSTRING(c2.thread, 1, (LENGTH(c2.thread) -1))');
  }
  return $query
    ->execute()
    ->fetchField();
}

/**
 * Returns the page number for a comment.
 *
 * Finds the correct page number for a comment taking into account display
 * and paging settings.
 *
 * @param $cid
 *   The comment ID.
 * @param $node_type
 *   The node type the comment is attached to.
 *
 * @return
 *   The page number.
 */
function comment_get_display_page($cid, $node_type) {
  $ordinal = comment_get_display_ordinal($cid, $node_type);
  $comments_per_page = variable_get('comment_default_per_page_' . $node_type, 50);
  return floor($ordinal / $comments_per_page);
}

/**
 * Page callback: Displays the comment editing form.
 *
 * @param Drupal\comment\Comment $comment
 *   The comment object representing the comment to be edited.
 *
 * @see comment_menu()
 */
function comment_edit_page(Comment $comment) {
  drupal_set_title(t('Edit comment %comment', array(
    '%comment' => $comment->subject,
  )), PASS_THROUGH);
  return entity_get_form($comment);
}

/**
 * Generates a comment preview.
 *
 * @param Drupal\comment\Comment $comment
 */
function comment_preview(Comment $comment) {
  global $user;
  $preview_build = array();
  if (!form_get_errors()) {
    $comment_body = field_get_items('comment', $comment, 'comment_body');
    $comment->format = $comment_body[0]['format'];

    // Attach the user and time information.
    if (!empty($comment->name)) {
      $account = user_load_by_name($comment->name);
    }
    elseif ($user->uid && empty($comment->is_anonymous)) {
      $account = $user;
    }
    if (!empty($account->uid)) {
      $comment->uid = $account->uid;
      $comment->name = check_plain($account->name);
      $comment->signature = $account->signature;
      $comment->signature_format = $account->signature_format;
    }
    elseif (empty($comment->name)) {
      $comment->name = config('user.settings')
        ->get('anonymous');
    }
    $comment->created = !empty($comment->created) ? $comment->created : REQUEST_TIME;
    $comment->changed = REQUEST_TIME;
    $comment->in_preview = TRUE;
    $comment_build = comment_view($comment);
    $comment_build['#weight'] = -100;
    $preview_build['comment_preview'] = $comment_build;
  }
  if ($comment->pid) {
    $build = array();
    $comment = comment_load($comment->pid);
    if ($comment && $comment->status == COMMENT_PUBLISHED) {
      $build = comment_view($comment);
    }
  }
  else {
    $build = node_view(node_load($comment->nid));
  }
  $preview_build['comment_output_below'] = $build;
  $preview_build['comment_output_below']['#weight'] = 100;
  return $preview_build;
}

/**
 * Implements hook_preprocess_HOOK() for block.tpl.php.
 */
function comment_preprocess_block(&$variables) {
  if ($variables['block']->module == 'comment') {
    $variables['attributes']['role'] = 'navigation';
  }
}

/**
 * Preprocesses variables for comment.tpl.php.
 *
 * @see comment.tpl.php
 */
function template_preprocess_comment(&$variables) {
  $comment = $variables['elements']['#comment'];
  $node = $variables['elements']['#node'];
  $variables['comment'] = $comment;
  $variables['node'] = $node;
  $variables['author'] = theme('username', array(
    'account' => $comment,
  ));
  $variables['created'] = format_date($comment->created);
  $variables['changed'] = format_date($comment->changed);
  $variables['new'] = !empty($comment->new) ? t('new') : '';
  if (theme_get_setting('toggle_comment_user_picture')) {

    // To change user picture settings (e.g., image style), edit the 'compact'
    // view mode on the User entity.
    $variables['user_picture'] = user_view($comment->account, 'compact');
  }
  else {
    $variables['user_picture'] = array();
  }
  $variables['signature'] = $comment->signature;
  $uri = $comment
    ->uri();
  $uri['options'] += array(
    'attributes' => array(
      'class' => 'permalink',
      'rel' => 'bookmark',
    ),
  );
  $variables['title'] = l($comment->subject, $uri['path'], $uri['options']);
  $variables['permalink'] = l(t('Permalink'), $uri['path'], $uri['options']);
  $variables['submitted'] = t('Submitted by !username on !datetime', array(
    '!username' => $variables['author'],
    '!datetime' => $variables['created'],
  ));
  if ($comment->pid > 0) {

    // Fetch and store the parent comment information for use in templates.
    $comment_parent = comment_load($comment->pid);
    $variables['parent_comment'] = $comment_parent;
    $variables['parent_author'] = theme('username', array(
      'account' => $comment_parent,
    ));
    $variables['parent_created'] = format_date($comment_parent->created);
    $variables['parent_changed'] = format_date($comment_parent->changed);
    $uri_parent = $comment_parent
      ->uri();
    $uri_parent['options'] += array(
      'attributes' => array(
        'class' => 'permalink',
        'rel' => 'bookmark',
      ),
    );
    $variables['parent_title'] = l($comment_parent->subject, $uri_parent['path'], $uri_parent['options']);
    $variables['parent_permalink'] = l(t('Parent permalink'), $uri_parent['path'], $uri_parent['options']);
    $variables['parent'] = t('In reply to !parent_title by !parent_username', array(
      '!parent_username' => $variables['parent_author'],
      '!parent_title' => $variables['parent_title'],
    ));
  }
  else {
    $variables['parent_comment'] = '';
    $variables['parent_author'] = '';
    $variables['parent_created'] = '';
    $variables['parent_changed'] = '';
    $variables['parent_title'] = '';
    $variables['parent_permalink'] = '';
    $variables['parent'] = '';
  }

  // Preprocess fields.
  field_attach_preprocess('comment', $comment, $variables['elements'], $variables);

  // Helpful $content variable for templates.
  foreach (element_children($variables['elements']) as $key) {
    $variables['content'][$key] = $variables['elements'][$key];
  }

  // Set status to a string representation of comment->status.
  if (isset($comment->in_preview)) {
    $variables['status'] = 'preview';
  }
  else {
    $variables['status'] = $comment->status == COMMENT_NOT_PUBLISHED ? 'unpublished' : 'published';
  }

  // Gather comment classes.
  // 'published' class is not needed, it is either 'preview' or 'unpublished'.
  if ($variables['status'] != 'published') {
    $variables['attributes']['class'][] = $variables['status'];
  }
  if ($variables['new']) {
    $variables['attributes']['class'][] = 'new';
  }
  if (!$comment->uid) {
    $variables['attributes']['class'][] = 'by-anonymous';
  }
  else {
    if ($comment->uid == $variables['node']->uid) {
      $variables['attributes']['class'][] = 'by-node-author';
    }
    if ($comment->uid == $variables['user']->uid) {
      $variables['attributes']['class'][] = 'by-viewer';
    }
  }
}

/**
 * Returns HTML for a "you can't post comments" notice.
 *
 * @param $variables
 *   An associative array containing:
 *   - node: The comment node.
 *
 * @ingroup themeable
 */
function theme_comment_post_forbidden($variables) {
  $node = $variables['node'];
  global $user;

  // Since this is expensive to compute, we cache it so that a page with many
  // comments only has to query the database once for all the links.
  $authenticated_post_comments =& drupal_static(__FUNCTION__, NULL);
  if (!$user->uid) {
    if (!isset($authenticated_post_comments)) {

      // We only output a link if we are certain that users will get permission
      // to post comments by logging in.
      $comment_roles = user_roles(TRUE, 'post comments');
      $authenticated_post_comments = isset($comment_roles[DRUPAL_AUTHENTICATED_RID]);
    }
    if ($authenticated_post_comments) {

      // We cannot use drupal_get_destination() because these links
      // sometimes appear on /node and taxonomy listing pages.
      if (variable_get('comment_form_location_' . $node->type, COMMENT_FORM_BELOW) == COMMENT_FORM_SEPARATE_PAGE) {
        $destination = array(
          'destination' => "comment/reply/{$node->nid}#comment-form",
        );
      }
      else {
        $destination = array(
          'destination' => "node/{$node->nid}#comment-form",
        );
      }
      if (config('user.settings')
        ->get('register') != USER_REGISTER_ADMINISTRATORS_ONLY) {

        // Users can register themselves.
        return t('<a href="@login">Log in</a> or <a href="@register">register</a> to post comments', array(
          '@login' => url('user/login', array(
            'query' => $destination,
          )),
          '@register' => url('user/register', array(
            'query' => $destination,
          )),
        ));
      }
      else {

        // Only admins can add new users, no public registration.
        return t('<a href="@login">Log in</a> to post comments', array(
          '@login' => url('user/login', array(
            'query' => $destination,
          )),
        ));
      }
    }
  }
}

/**
 * Preprocesses variables for comment-wrapper.tpl.php.
 *
 * @see comment-wrapper.tpl.php
 */
function template_preprocess_comment_wrapper(&$variables) {

  // Provide contextual information.
  $variables['node'] = $variables['content']['#node'];
  $variables['display_mode'] = variable_get('comment_default_mode_' . $variables['node']->type, COMMENT_MODE_THREADED);

  // The comment form is optional and may not exist.
  $variables['content'] += array(
    'comment_form' => array(),
  );
}

/**
 * Returns an array of viewing modes for comment listings.
 *
 * We can't use a global variable array because the locale system
 * is not initialized yet when the Comment module is loaded.
 */
function _comment_get_modes() {
  return array(
    COMMENT_MODE_FLAT => t('Flat list'),
    COMMENT_MODE_THREADED => t('Threaded list'),
  );
}

/**
 * Returns an array of "comments per page" values that users can select from.
 */
function _comment_per_page() {
  return drupal_map_assoc(array(
    10,
    30,
    50,
    70,
    90,
    150,
    200,
    250,
    300,
  ));
}

/**
 * Generates a sorting code.
 *
 * Consists of a leading character indicating length, followed by N digits
 * with a numerical value in base 36 (alphadecimal). These codes can be sorted
 * as strings without altering numerical order.
 *
 * It goes:
 * 00, 01, 02, ..., 0y, 0z,
 * 110, 111, ... , 1zy, 1zz,
 * 2100, 2101, ..., 2zzy, 2zzz,
 * 31000, 31001, ...
 */
function comment_int_to_alphadecimal($i = 0) {
  $num = base_convert((int) $i, 10, 36);
  $length = strlen($num);
  return chr($length + ord('0') - 1) . $num;
}

/**
 * Decodes a sorting code back to an integer.
 *
 * @see comment_int_to_alphadecimal()
 */
function comment_alphadecimal_to_int($c = '00') {
  return base_convert(substr($c, 1), 36, 10);
}

/**
 * Implements hook_action_info().
 */
function comment_action_info() {
  return array(
    'comment_publish_action' => array(
      'label' => t('Publish comment'),
      'type' => 'comment',
      'configurable' => FALSE,
      'behavior' => array(
        'changes_property',
      ),
      'triggers' => array(
        'comment_presave',
        'comment_insert',
        'comment_update',
      ),
    ),
    'comment_unpublish_action' => array(
      'label' => t('Unpublish comment'),
      'type' => 'comment',
      'configurable' => FALSE,
      'behavior' => array(
        'changes_property',
      ),
      'triggers' => array(
        'comment_presave',
        'comment_insert',
        'comment_update',
      ),
    ),
    'comment_unpublish_by_keyword_action' => array(
      'label' => t('Unpublish comment containing keyword(s)'),
      'type' => 'comment',
      'configurable' => TRUE,
      'behavior' => array(
        'changes_property',
      ),
      'triggers' => array(
        'comment_presave',
        'comment_insert',
        'comment_update',
      ),
    ),
    'comment_save_action' => array(
      'label' => t('Save comment'),
      'type' => 'comment',
      'configurable' => FALSE,
      'triggers' => array(
        'comment_insert',
        'comment_update',
      ),
    ),
  );
}

/**
 * Publishes a comment.
 *
 * @param Drupal\comment\Comment $comment
 *   (optional) A comment object to publish.
 * @param array $context
 *   Array with components:
 *   - 'cid': Comment ID. Required if $comment is not given.
 *
 * @ingroup actions
 */
function comment_publish_action(Comment $comment = NULL, $context = array()) {
  if (isset($comment->subject)) {
    $subject = $comment->subject;
    $comment->status = COMMENT_PUBLISHED;
  }
  else {
    $cid = $context['cid'];
    $subject = db_query('SELECT subject FROM {comment} WHERE cid = :cid', array(
      ':cid' => $cid,
    ))
      ->fetchField();
    db_update('comment')
      ->fields(array(
      'status' => COMMENT_PUBLISHED,
    ))
      ->condition('cid', $cid)
      ->execute();
  }
  watchdog('action', 'Published comment %subject.', array(
    '%subject' => $subject,
  ));
}

/**
 * Unpublishes a comment.
 *
 * @param Drupal\comment\Comment|null $comment
 *   (optional) A comment object to unpublish.
 * @param array $context
 *   Array with components:
 *   - 'cid': Comment ID. Required if $comment is not given.
 *
 * @ingroup actions
 */
function comment_unpublish_action(Comment $comment = NULL, $context = array()) {
  if (isset($comment->subject)) {
    $subject = $comment->subject;
    $comment->status = COMMENT_NOT_PUBLISHED;
  }
  else {
    $cid = $context['cid'];
    $subject = db_query('SELECT subject FROM {comment} WHERE cid = :cid', array(
      ':cid' => $cid,
    ))
      ->fetchField();
    db_update('comment')
      ->fields(array(
      'status' => COMMENT_NOT_PUBLISHED,
    ))
      ->condition('cid', $cid)
      ->execute();
  }
  watchdog('action', 'Unpublished comment %subject.', array(
    '%subject' => $subject,
  ));
}

/**
 * Unpublishes a comment if it contains certain keywords.
 *
 * @param Drupal\comment\Comment $comment
 *   Comment object to modify.
 * @param array $context
 *   Array with components:
 *   - 'keywords': Keywords to look for. If the comment contains at least one
 *     of the keywords, it is unpublished.
 *
 * @ingroup actions
 * @see comment_unpublish_by_keyword_action_form()
 * @see comment_unpublish_by_keyword_action_submit()
 */
function comment_unpublish_by_keyword_action(Comment $comment, $context) {
  foreach ($context['keywords'] as $keyword) {
    $text = drupal_render($comment);
    if (strpos($text, $keyword) !== FALSE) {
      $comment->status = COMMENT_NOT_PUBLISHED;
      watchdog('action', 'Unpublished comment %subject.', array(
        '%subject' => $comment->subject,
      ));
      break;
    }
  }
}

/**
 * Form constructor for the blacklisted keywords form.
 *
 * @ingroup forms
 * @see comment_unpublish_by_keyword_action()
 * @see comment_unpublish_by_keyword_action_submit()
 */
function comment_unpublish_by_keyword_action_form($context) {
  $form['keywords'] = array(
    '#title' => t('Keywords'),
    '#type' => 'textarea',
    '#description' => t('The comment will be unpublished if it contains any of the phrases above. Use a case-sensitive, comma-separated list of phrases. Example: funny, bungee jumping, "Company, Inc."'),
    '#default_value' => isset($context['keywords']) ? drupal_implode_tags($context['keywords']) : '',
  );
  return $form;
}

/**
 * Form submission handler for comment_unpublish_by_keyword_action_form().
 *
 * @see comment_unpublish_by_keyword_action()
 */
function comment_unpublish_by_keyword_action_submit($form, $form_state) {
  return array(
    'keywords' => drupal_explode_tags($form_state['values']['keywords']),
  );
}

/**
 * Saves a comment.
 *
 * @param Drupal\comment\Comment $comment
 *
 * @ingroup actions
 */
function comment_save_action(Comment $comment) {
  comment_save($comment);
  cache_invalidate_tags(array(
    'content' => TRUE,
  ));
  watchdog('action', 'Saved comment %title', array(
    '%title' => $comment->subject,
  ));
}

/**
 * Implements hook_ranking().
 */
function comment_ranking() {
  return array(
    'comments' => array(
      'title' => t('Number of comments'),
      'join' => array(
        'type' => 'LEFT',
        'table' => 'node_comment_statistics',
        'alias' => 'node_comment_statistics',
        'on' => 'node_comment_statistics.nid = i.sid',
      ),
      // Inverse law that maps the highest reply count on the site to 1 and 0 to 0.
      'score' => '2.0 - 2.0 / (1.0 + node_comment_statistics.comment_count * CAST(:scale AS DECIMAL))',
      'arguments' => array(
        ':scale' => state()
          ->get('comment.node_comment_statistics_scale') ?: 0,
      ),
    ),
  );
}

/**
 * Implements hook_rdf_mapping().
 */
function comment_rdf_mapping() {
  return array(
    array(
      'type' => 'comment',
      'bundle' => RDF_DEFAULT_BUNDLE,
      'mapping' => array(
        'rdftype' => array(
          'sioc:Post',
          'sioct:Comment',
        ),
        'title' => array(
          'predicates' => array(
            'dc:title',
          ),
        ),
        'created' => array(
          'predicates' => array(
            'dc:date',
            'dc:created',
          ),
          'datatype' => 'xsd:dateTime',
          'callback' => 'date_iso8601',
        ),
        'changed' => array(
          'predicates' => array(
            'dc:modified',
          ),
          'datatype' => 'xsd:dateTime',
          'callback' => 'date_iso8601',
        ),
        'comment_body' => array(
          'predicates' => array(
            'content:encoded',
          ),
        ),
        'pid' => array(
          'predicates' => array(
            'sioc:reply_of',
          ),
          'type' => 'rel',
        ),
        'uid' => array(
          'predicates' => array(
            'sioc:has_creator',
          ),
          'type' => 'rel',
        ),
        'name' => array(
          'predicates' => array(
            'foaf:name',
          ),
        ),
      ),
    ),
  );
}

/**
 * Implements hook_file_download_access().
 */
function comment_file_download_access($field, EntityInterface $entity, File $file) {
  if ($entity
    ->entityType() == 'comment') {
    if (user_access('access comments') && $entity->status == COMMENT_PUBLISHED || user_access('administer comments')) {
      $node = node_load($entity->nid);
      return node_access('view', $node);
    }
    return FALSE;
  }
}

/**
 * Implements hook_library_info().
 */
function comment_library_info() {
  $libraries['drupal.comment'] = array(
    'title' => 'Comment',
    'version' => VERSION,
    'js' => array(
      drupal_get_path('module', 'comment') . '/comment-node-form.js' => array(),
    ),
    'dependencies' => array(
      array(
        'system',
        'jquery',
      ),
      array(
        'system',
        'drupal',
      ),
      array(
        'system',
        'drupal.form',
      ),
    ),
  );
  return $libraries;
}

Functions

Namesort descending Description
comment_access Determines whether the current user has access to a particular comment.
comment_action_info Implements hook_action_info().
comment_add Returns a rendered form to comment the given node.
comment_alphadecimal_to_int Decodes a sorting code back to an integer.
comment_block_configure Implements hook_block_configure().
comment_block_info Implements hook_block_info().
comment_block_save Implements hook_block_save().
comment_block_view Implements hook_block_view().
comment_count_unpublished Returns a menu title which includes the number of unapproved comments.
comment_delete Deletes a comment and all its replies.
comment_delete_multiple Deletes comments and all their replies.
comment_edit_page Page callback: Displays the comment editing form.
comment_entity_info Implements hook_entity_info().
comment_field_extra_fields Implements hook_field_extra_fields().
comment_file_download_access Implements hook_file_download_access().
comment_form_node_form_alter Implements hook_form_BASE_FORM_ID_alter().
comment_form_node_type_form_alter Implements hook_form_FORM_ID_alter().
comment_get_display_ordinal Gets the display ordinal for a comment, starting from 0.
comment_get_display_page Returns the page number for a comment.
comment_get_recent Finds the most recent comments that are available to the current user.
comment_get_thread Retrieves comments for a thread.
comment_help Implements hook_help().
comment_int_to_alphadecimal Generates a sorting code.
comment_library_info Implements hook_library_info().
comment_links Adds reply, edit, delete, etc. links, depending on user permissions.
comment_load Loads the entire comment by comment ID.
comment_load_multiple Loads comment entities from the database.
comment_menu Implements hook_menu().
comment_menu_alter Implements hook_menu_alter().
comment_new_page_count Calculates the page number for the first new comment.
comment_node_insert Implements hook_node_insert().
comment_node_load Implements hook_node_load().
comment_node_page_additions Builds the comment-related elements for node detail pages.
comment_node_predelete Implements hook_node_predelete().
comment_node_prepare Implements hook_node_prepare().
comment_node_search_result Implements hook_node_search_result().
comment_node_type_delete Implements hook_node_type_delete().
comment_node_type_insert Implements hook_node_type_insert().
comment_node_type_load Loads the comment bundle name corresponding a given content type.
comment_node_type_update Implements hook_node_type_update().
comment_node_update_index Implements hook_node_update_index().
comment_node_view Implements hook_node_view().
comment_num_new Gets the number of new comments for the current user and the specified node.
comment_permalink Redirects comment links to the correct page depending on comment settings.
comment_permission Implements hook_permission().
comment_prepare_thread Calculates the indentation level of each comment in a comment thread.
comment_preprocess_block Implements hook_preprocess_HOOK() for block.tpl.php.
comment_preview Generates a comment preview.
comment_publish_action Publishes a comment.
comment_ranking Implements hook_ranking().
comment_rdf_mapping Implements hook_rdf_mapping().
comment_save Accepts a submission of new or changed comment content.
comment_save_action Saves a comment.
comment_theme Implements hook_theme().
comment_translation_configuration_element_submit Form submission handler for node_type_form().
comment_unpublish_action Unpublishes a comment.
comment_unpublish_by_keyword_action Unpublishes a comment if it contains certain keywords.
comment_unpublish_by_keyword_action_form Form constructor for the blacklisted keywords form.
comment_unpublish_by_keyword_action_submit Form submission handler for comment_unpublish_by_keyword_action_form().
comment_update_index Implements hook_update_index().
comment_uri Entity URI callback.
comment_user_cancel Implements hook_user_cancel().
comment_user_predelete Implements hook_user_predelete().
comment_view Generates an array for rendering a comment.
comment_view_multiple Constructs render array from an array of loaded comments.
template_preprocess_comment Preprocesses variables for comment.tpl.php.
template_preprocess_comment_wrapper Preprocesses variables for comment-wrapper.tpl.php.
theme_comment_block Returns HTML for a list of recent comments.
theme_comment_post_forbidden Returns HTML for a "you can't post comments" notice.
_comment_body_field_create Creates a comment_body field instance for a given node type.
_comment_get_modes Returns an array of viewing modes for comment listings.
_comment_per_page Returns an array of "comments per page" values that users can select from.

Constants

Namesort descending Description
COMMENT_ANONYMOUS_MAYNOT_CONTACT Anonymous posters cannot enter their contact information.
COMMENT_ANONYMOUS_MAY_CONTACT Anonymous posters may leave their contact information.
COMMENT_ANONYMOUS_MUST_CONTACT Anonymous posters are required to leave their contact information.
COMMENT_FORM_BELOW Comment form should be shown below post or list of comments.
COMMENT_FORM_SEPARATE_PAGE Comment form should be displayed on a separate page.
COMMENT_MODE_FLAT Comments are displayed in a flat list - expanded.
COMMENT_MODE_THREADED Comments are displayed as a threaded list - expanded.
COMMENT_NODE_CLOSED Comments for this node are closed.
COMMENT_NODE_HIDDEN Comments for this node are hidden.
COMMENT_NODE_OPEN Comments for this node are open.
COMMENT_NOT_PUBLISHED Comment is awaiting approval.
COMMENT_PUBLISHED Comment is published.