comment.module 59.7 KB
Newer Older
1
<?php
Dries's avatar
 
Dries committed
2

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

13
use Drupal\Core\Entity\EntityInterface;
14 15 16 17 18 19 20
use Drupal\Core\Entity\EntityChangedInterface;
use Drupal\comment\CommentInterface;
use Drupal\comment\Entity\Comment;
use Drupal\entity\Entity\EntityDisplay;
use Drupal\field\FieldInstanceInterface;
use Drupal\field\FieldInterface;
use Drupal\file\FileInterface;
21

22
/**
23
 * Comment is awaiting approval.
24
 */
25
const COMMENT_NOT_PUBLISHED = 0;
26 27

/**
28
 * Comment is published.
29
 */
30
const COMMENT_PUBLISHED = 1;
Dries's avatar
Dries committed
31

32 33 34
/**
 * Comments are displayed in a flat list - expanded.
 */
35
const COMMENT_MODE_FLAT = 0;
36 37 38 39

/**
 * Comments are displayed as a threaded list - expanded.
 */
40
const COMMENT_MODE_THREADED = 1;
Dries's avatar
Dries committed
41 42

/**
43
 * Anonymous posters cannot enter their contact information.
Dries's avatar
Dries committed
44
 */
45
const COMMENT_ANONYMOUS_MAYNOT_CONTACT = 0;
46 47 48 49

/**
 * Anonymous posters may leave their contact information.
 */
50
const COMMENT_ANONYMOUS_MAY_CONTACT = 1;
51 52

/**
53
 * Anonymous posters are required to leave their contact information.
54
 */
55
const COMMENT_ANONYMOUS_MUST_CONTACT = 2;
Dries's avatar
Dries committed
56 57

/**
58
 * Comment form should be displayed on a separate page.
Dries's avatar
Dries committed
59
 */
60
const COMMENT_FORM_SEPARATE_PAGE = 0;
61 62 63 64

/**
 * Comment form should be shown below post or list of comments.
 */
65
const COMMENT_FORM_BELOW = 1;
Dries's avatar
Dries committed
66 67

/**
68
 * Comments for this entity are hidden.
Dries's avatar
Dries committed
69
 */
70
const COMMENT_HIDDEN = 0;
71 72

/**
73
 * Comments for this entity are closed.
74
 */
75
const COMMENT_CLOSED = 1;
76 77

/**
78
 * Comments for this entity are open.
79
 */
80
const COMMENT_OPEN = 2;
81

82 83 84 85 86 87 88 89 90 91
/**
 * 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);
92

93
/**
94
 * Implements hook_help().
95
 */
96 97
function comment_help($path, $arg) {
  switch ($path) {
Dries's avatar
 
Dries committed
98
    case 'admin/help#comment':
99
      $output = '<h3>' . t('About') . '</h3>';
100
      $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>';
101 102 103
      $output .= '<h3>' . t('Uses') . '</h3>';
      $output .= '<dl>';
      $output .= '<dt>' . t('Default and custom settings') . '</dt>';
104
      $output .= '<dd>' . t("Comment functionality can be attached to any Drupal entity, eg. a content <a href='@content-type'>type</a> and the behavior can be customised to suit. Each entity can have its own default comment settings configured as: <em>Open</em> to allow new comments, <em>Hidden</em> to hide existing comments and prevent new comments, or <em>Closed</em> to view existing comments, but prevent new comments. These defaults will apply to all new content created (changes to the settings on existing content must be done manually). Other comment settings can also be customized per content type and entity, and can be overridden for any given item of content. When a comment has no replies, it remains editable by its author, as long as the author has a user account and is logged in.", array('@content-type' => url('admin/structure/types'))) . '</dd>';
105 106
      $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>';
107
      $output .= '</dl>';
108
      return $output;
109 110 111 112

    case 'admin/structure/comments':
      $output = '<p>' . t('This page provides a list of all comment forms on the site and allows you to manage the fields, form and display settings for each.') . '</p>';
      return $output;
113
  }
Dries's avatar
 
Dries committed
114 115
}

116 117 118 119 120
/**
 * Implements hook_entity_bundle_info().
 */
function comment_entity_bundle_info() {
  $bundles = array();
121 122 123 124 125 126 127 128 129
  foreach (\Drupal::service('comment.manager')->getAllFields() as $entity_type => $fields) {
    foreach ($fields as $field_name => $field_info) {
      $sample_bundle = reset($field_info['bundles']);
      // We cannot use field info API here because it will result in recursion.
      $config = \Drupal::config('field.instance.' . $entity_type .  '.' . $sample_bundle . '.' . $field_name);
      $bundles['comment'][$entity_type . '__' . $field_name] = array(
        'label' => $config->get('label'),
      );
    }
130
  }
131
  return $bundles;
132 133
}

134
/**
135
 * Entity URI callback.
136
 */
137
function comment_uri(Comment $comment) {
138
  return array(
139 140
    'path' => 'comment/' . $comment->id(),
    'options' => array('fragment' => 'comment-' . $comment->id()),
141
  );
142 143
}

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

  return $return;
}

171
/**
172
 * Implements hook_theme().
173 174 175 176
 */
function comment_theme() {
  return array(
    'comment_preview' => array(
177
      'variables' => array('comment' => NULL),
178 179
    ),
    'comment' => array(
180
      'template' => 'comment',
181
      'render element' => 'elements',
182 183
    ),
    'comment_post_forbidden' => array(
184
      'variables' => array('commented_entity' => NULL, 'field_name' => 'comment'),
185 186
    ),
    'comment_wrapper' => array(
187
      'template' => 'comment-wrapper',
188
      'render element' => 'content',
189 190 191 192
    ),
  );
}

Dries's avatar
 
Dries committed
193
/**
194
 * Implements hook_menu().
Dries's avatar
 
Dries committed
195
 */
196
function comment_menu() {
197 198 199 200 201 202 203 204 205
  $items['admin/structure/comments'] = array(
    'title' => 'Comment forms',
    'description' => 'Manage fields and displays settings for comment forms.',
    'route_name' => 'comment.bundle_list',
  );
  $items['admin/structure/comments/manage/%'] = array(
    'title' => 'Comment form',
    'route_name' => 'comment.bundle',
  );
206
  $items['admin/content/comment'] = array(
207
    'title' => 'Comments',
208
    'description' => 'List and edit site comments and the comment approval queue.',
209
    'route_name' => 'comment.admin',
210
  );
Dries's avatar
 
Dries committed
211 212 213 214

  return $items;
}

215 216 217 218
/**
 * Implements hook_menu_alter().
 */
function comment_menu_alter(&$items) {
219 220 221 222
  if (isset($items['admin/content'])) {
    // Add comments to the description for admin/content if any.
    $items['admin/content']['description'] = 'Administer content and comments.';
  }
223 224
}

225 226
/**
 * Returns a menu title which includes the number of unapproved comments.
227 228
 *
 * @todo Move to the comment manager and replace by a entity query?
229 230 231 232 233 234 235 236
 */
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));
}

237
/**
238 239 240
 * Implements hook_ENTITY_TYPE_create() for 'field_instance'.
 */
function comment_field_instance_create(FieldInstanceInterface $instance) {
241
  if ($instance->getFieldType() == 'comment' && !$instance->isSyncing()) {
242 243 244 245 246 247 248 249 250 251 252 253
    \Drupal::service('comment.manager')->addBodyField($instance->entity_type, $instance->getFieldName());
    \Drupal::cache()->delete('comment_entity_info');
    // Assign default values for the field instance.
    $instance->default_value = array(array(
      'status' => COMMENT_OPEN,
      'cid' => 0,
      'last_comment_timestamp' => 0,
      'last_comment_name' => '',
      'last_comment_uid' => 0,
      'comment_count' => 0,
    ));
  }
254
}
255

256
/**
257
 * Implements hook_ENTITY_TYPE_update() for 'field_instance'.
258
 */
259 260
function comment_field_instance_update(FieldInstanceInterface $instance) {
  if ($instance->getFieldType() == 'comment') {
261
    \Drupal::entityManager()->getViewBuilder($instance->entity_type)->resetCache();
262 263
  }
}
264

265
/**
266
 * Implements hook_ENTITY_TYPE_delete() for 'field_entity'.
267
 */
268 269 270 271 272
function comment_field_entity_delete(FieldInterface $field) {
  if ($field->getFieldType() == 'comment') {
    // Delete all fields and displays attached to the comment bundle.
    entity_invoke_bundle_hook('delete', 'comment', $field->getFieldName());
    \Drupal::cache()->delete('comment_entity_info');
273 274 275
  }
}

276 277 278 279 280 281 282 283 284 285 286 287
/**
 * Implements hook_ENTITY_TYPE_delete() for 'field_instance'.
 */
function comment_field_instance_delete(FieldInstanceInterface $instance) {
  if ($instance->getFieldType() == 'comment') {
    // Delete all comments that used by the entity bundle.
    $comments = db_query("SELECT cid FROM {comment} WHERE entity_type = :entity_type AND field_id = :field_id", array(
      ':entity_type' => $instance->entityType(),
      ':field_id' => $instance->entityType() . '__' . $instance->getFieldName(),
    ))->fetchCol();
    entity_delete_multiple('comment', $comments);
    \Drupal::cache()->delete('comment_entity_info');
288
  }
289 290
}

Dries's avatar
 
Dries committed
291
/**
292
 * Implements hook_permission().
Dries's avatar
 
Dries committed
293
 */
294
function comment_permission() {
295
  return array(
296
    'administer comments' => array(
297
      'title' => t('Administer comments and comment settings'),
298 299
    ),
    'access comments' => array(
300
      'title' => t('View comments'),
301 302
    ),
    'post comments' => array(
303
      'title' => t('Post comments'),
304
    ),
305 306
    'skip comment approval' => array(
      'title' => t('Skip comment approval'),
307
    ),
308 309 310
    'edit own comments' => array(
      'title' => t('Edit own comments'),
    ),
311
  );
Dries's avatar
 
Dries committed
312 313
}

314
/**
315
 * Finds the most recent comments that are available to the current user.
316 317
 *
 * @param integer $number
318
 *   (optional) The maximum number of comments to find. Defaults to 10.
319
 *
320
 * @return
321 322
 *   An array of comment objects or an empty array if there are no recent
 *   comments visible to the current user.
323 324
 */
function comment_get_recent($number = 10) {
325
  $query = db_select('comment', 'c');
326
  $query->addMetaData('base_table', 'comment');
327 328 329 330 331 332
  $query->fields('c')
    ->condition('c.status', COMMENT_PUBLISHED);
  if (\Drupal::moduleHandler()->moduleExists('node')) {
    // Special case to filter by published content.
    $query->innerJoin('node_field_data', 'n', "n.nid = c.entity_id AND c.entity_type = 'node'");
    $query->addTag('node_access');
333 334
    // @todo This should be actually filtering on the desired node status field
    //   language and just fall back to the default language.
335 336 337 338 339
    $query
      ->condition('n.status', NODE_PUBLISHED)
      ->condition('n.default_langcode', 1);
  }
  $comments = $query
340
    ->orderBy('c.created', 'DESC')
341 342 343
    // Additionally order by cid to ensure that comments with the same timestamp
    // are returned in the exact order posted.
    ->orderBy('c.cid', 'DESC')
344 345 346 347 348
    ->range(0, $number)
    ->execute()
    ->fetchAll();

  return $comments ? $comments : array();
349 350
}

351
/**
352
 * Calculates the page number for the first new comment.
353
 *
354
 * @param int $num_comments
355
 *   Number of comments.
356
 * @param int $new_replies
357
 *   Number of new replies.
358 359 360 361
 * @param \Drupal\Core\Entity\EntityInterface $entity
 *   The first new comment entity.
 * @param string $field_name
 *   The field name on the entity to which comments are attached to.
362
 *
363 364
 * @return
 *   "page=X" if the page number is greater than zero; empty string otherwise.
365
 */
366 367 368 369
function comment_new_page_count($num_comments, $new_replies, EntityInterface $entity, $field_name = 'comment') {
  $instance = \Drupal::service('field.info')->getInstance($entity->entityType(), $entity->bundle(), $field_name);
  $mode = $instance->getFieldSetting('default_mode');
  $comments_per_page = $instance->getFieldSetting('per_page');
370
  $pagenum = NULL;
371
  $flat = $mode == COMMENT_MODE_FLAT ? TRUE : FALSE;
372 373
  if ($num_comments <= $comments_per_page) {
    // Only one page of comments.
374
    $pageno = 0;
375
  }
376 377 378
  elseif ($flat) {
    // Flat comments.
    $count = $num_comments - $new_replies;
379
    $pageno = $count / $comments_per_page;
380
  }
381
  else {
382 383 384 385 386 387
    // 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'))
388 389 390
      ->condition('entity_id', $entity->id())
      ->condition('entity_type', $entity->entityType())
      ->condition('field_id', $entity->entityType() . '__' . $field_name)
391
      ->condition('status', COMMENT_PUBLISHED)
392 393
      ->orderBy('created', 'DESC')
      ->orderBy('cid', 'DESC')
394 395 396 397 398 399 400 401 402 403 404 405 406 407
      ->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.
408 409 410 411
    $count = db_query('SELECT COUNT(*) FROM {comment} WHERE entity_id = :entity_id
                      AND entity_type = :entity_type
                      AND field_id = :field_id
                      AND status = :status AND SUBSTRING(thread, 1, (LENGTH(thread) - 1)) < :thread', array(
412
      ':status' => COMMENT_PUBLISHED,
413 414 415
      ':entity_id' => $entity->id(),
      ':field_id' => $entity->entityType() . '__' . $field_name,
      ':entity_type' => $entity->entityType(),
416
      ':thread' => $first_thread,
417
    ))->fetchField();
418

419
    $pageno = $count / $comments_per_page;
420
  }
421

422
  if ($pageno >= 1) {
423
    $pagenum = array('page' => intval($pageno));
424
  }
425

426 427 428
  return $pagenum;
}

Dries's avatar
 
Dries committed
429
/**
430
 * Implements hook_entity_view().
Dries's avatar
 
Dries committed
431
 */
432 433 434 435 436 437 438 439 440 441 442 443
function comment_entity_view(EntityInterface $entity, EntityDisplay $display, $view_mode, $langcode) {
  if ($entity->entityType() != 'node') {
    // 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
    return;
  }
  $fields = \Drupal::service('comment.manager')->getFields('node');
  foreach ($fields as $field_name => $detail) {
    // Skip fields that entity does not have.
444
    if (!$entity->hasField($field_name)) {
445
      continue;
446
    }
447 448 449 450 451 452 453 454 455 456 457
    $links = array();
    $commenting_status = $entity->get($field_name)->status;
    if ($commenting_status) {
      $instance = \Drupal::service('field.info')->getInstance('node', $entity->bundle(), $field_name);
      // Entity have commenting open or close.
      $uri = $entity->uri();
      if ($view_mode == 'rss') {
        // Add a comments RSS element which is a URL to the comments of this node.
        if (!empty($uri['options'])) {
          $uri['options']['fragment'] = 'comments';
          $uri['options']['absolute'] = TRUE;
Dries's avatar
 
Dries committed
458
        }
459 460 461 462
        $entity->rss_elements[] = array(
          'key' => 'comments',
          'value' => url($uri['path'], $uri['options'])
        );
463
      }
464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489
      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($entity->get($field_name)->comment_count)) {
            $links['comment-comments'] = array(
              'title' => format_plural($entity->get($field_name)->comment_count, '1 comment', '@count comments'),
              'href' => $uri['path'],
              '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' => $entity->get($field_name)->last_comment_timestamp,
                  'data-history-node-field-name' => $field_name,
                ),
                'html' => TRUE,
              );
            }
490
          }
491
        }
492 493 494 495
        // Provide a link to new comment form.
        if ($commenting_status == COMMENT_OPEN) {
          $comment_form_location = $instance->getFieldSetting('form_location');
          if (user_access('post comments')) {
496 497
            $links['comment-add'] = array(
              'title' => t('Add new comment'),
498 499
              'href' => $uri['path'],
              'attributes' => array('title' => t('Add a new comment to this page.')),
500 501 502
              'fragment' => 'comment-form',
            );
            if ($comment_form_location == COMMENT_FORM_SEPARATE_PAGE) {
503
              $links['comment-add']['href'] = 'comment/reply/'. $entity->entityType() . '/' . $entity->id() .'/' . $field_name;
504
            }
505
          }
506 507 508 509 510 511 512 513 514 515 516
          else {
            $comment_post_forbidden = array(
              '#theme' => 'comment_post_forbidden',
              '#commented_entity' => $entity,
              '#field_name' => $field_name,
            );
            $links['comment-forbidden'] = array(
              'title' => drupal_render($comment_post_forbidden),
              'html' => TRUE,
            );
          }
Dries's avatar
 
Dries committed
517
        }
518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551
      }
      elseif ($view_mode != 'search_index' && $view_mode != 'search_result') {
        // Entity in other view modes: add a "post comment" link if the user is
        // allowed to post comments and if this entity is allowing new comments.
        // But we don't want this link if we're building the entity for search
        // indexing or constructing a search result excerpt.
        if ($commenting_status == COMMENT_OPEN) {
          $comment_form_location = $instance->getFieldSetting('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($entity->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.')),
                'href' => $uri['path'],
                'fragment' => 'comment-form',
              );
              if ($comment_form_location == COMMENT_FORM_SEPARATE_PAGE) {
                $links['comment-add']['href'] = 'comment/reply/'. $entity->entityType() . '/' . $entity->id() .'/' . $field_name;
              }
            }
          }
          else {
            $comment_post_forbidden = array(
              '#theme' => 'comment_post_forbidden',
              '#commented_entity' => $entity,
              '#field_name' => $field_name,
            );
            $links['comment-forbidden'] = array(
              'title' => drupal_render($comment_post_forbidden),
              'html' => TRUE,
            );
          }
Dries's avatar
 
Dries committed
552 553 554
        }
      }
    }
Dries's avatar
Dries committed
555

556 557
    $entity->content['links']['comment__' . $field_name] = array(
      '#theme' => 'links__entity__comment__' . $field_name,
558 559 560
      '#links' => $links,
      '#attributes' => array('class' => array('links', 'inline')),
    );
561
    if ($view_mode == 'teaser' && \Drupal::moduleHandler()->moduleExists('history') && \Drupal::currentUser()->isAuthenticated()) {
562
      $entity->content['links']['#attached']['library'][] = array('comment', 'drupal.node-new-comments-link');
563
    }
564
  }
Dries's avatar
 
Dries committed
565 566
}

567 568 569 570
/**
 * Implements hook_node_view_alter().
 */
function comment_node_view_alter(&$build, EntityInterface $node, EntityDisplay $display) {
571
  if (\Drupal::moduleHandler()->moduleExists('history')) {
572 573 574 575
    $build['#attributes']['data-history-node-id'] = $node->id();
  }
}

576
/**
577
 * Returns a rendered form to comment the given entity.
578
 *
579 580 581 582
 * @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.
583 584 585
 * @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.
586 587 588 589
 *
 * @return array
 *   The renderable array for the comment addition form.
 */
590 591 592 593 594 595 596
function comment_add(EntityInterface $entity, $field_name = 'comment', $pid = NULL) {
  $values = array(
    'entity_type' => $entity->entityType(),
    'entity_id' => $entity->id(),
    'field_id' => $entity->entityType() . '__' . $field_name,
    'pid' => $pid,
  );
597
  $comment = entity_create('comment', $values);
598
  return \Drupal::entityManager()->getForm($comment);
599 600
}

601
/**
602
 * Retrieves comments for a thread.
603
 *
604 605 606 607 608
 * @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
609
 *   The comment display mode; COMMENT_MODE_FLAT or COMMENT_MODE_THREADED.
610
 * @param int $comments_per_page
611
 *   The amount of comments to display per page.
612
 *
613 614 615
 * @return
 *   An array of the IDs of the comment to be displayed.
 *
616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669
 * 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.
 */
670
function comment_get_thread(EntityInterface $entity, $field_name, $mode, $comments_per_page) {
671 672
  $query = db_select('comment', 'c')
    ->extend('Drupal\Core\Database\Query\PagerSelectExtender');
673 674
  $query->addField('c', 'cid');
  $query
675 676 677 678
    ->condition('c.entity_id', $entity->id())
    ->condition('c.entity_type', $entity->entityType())
    ->condition('c.field_id', $entity->entityType() . '__' . $field_name)
    ->addTag('entity_access')
679
    ->addTag('comment_filter')
680
    ->addMetaData('base_table', 'comment')
681 682
    ->addMetaData('entity', $entity)
    ->addMetaData('field_name', $field_name)
683 684 685 686 687
    ->limit($comments_per_page);

  $count_query = db_select('comment', 'c');
  $count_query->addExpression('COUNT(*)');
  $count_query
688 689 690 691
    ->condition('c.entity_id', $entity->id())
    ->condition('c.entity_type', $entity->entityType())
    ->condition('c.field_id', $entity->entityType() . '__' . $field_name)
    ->addTag('entity_access')
692
    ->addTag('comment_filter')
693
    ->addMetaData('base_table', 'comment')
694 695
    ->addMetaData('entity', $entity)
    ->addMetaData('field_name', $field_name);
696 697 698 699 700

  if (!user_access('administer comments')) {
    $query->condition('c.status', COMMENT_PUBLISHED);
    $count_query->condition('c.status', COMMENT_PUBLISHED);
  }
701
  if ($mode == COMMENT_MODE_FLAT) {
702 703 704 705 706 707
    $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.
708 709
    $query->addExpression('SUBSTRING(c.thread, 1, (LENGTH(c.thread) - 1))', 'torder');
    $query->orderBy('torder', 'ASC');
710 711 712
  }

  $query->setCountQuery($count_query);
713
  return $query->execute()->fetchCol();
714 715 716
}

/**
717 718 719 720 721
 * 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.
722 723
 *
 * @param array $comments
724
 *   An array of comment objects, keyed by comment ID.
725 726 727 728 729
 */
function comment_prepare_thread(&$comments) {
  // A counter that helps track how indented we are.
  $divs = 0;

730
  foreach ($comments as $key => &$comment) {
731 732
    // The $divs element instructs #prefix whether to add an indent div or
    // close existing divs (a negative value).
733
    $comment->depth = count(explode('.', $comment->thread->value)) - 1;
734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750
    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;
}

/**
751
 * Generates an array for rendering a comment.
752
 *
753
 * @param \Drupal\comment\CommentInterface $comment
754
 *   The comment object.
755
 * @param $view_mode
756
 *   (optional) View mode, e.g. 'full', 'teaser'... Defaults to 'full'.
757 758 759
 * @param $langcode
 *   (optional) A language code to use for rendering. Defaults to the global
 *   content language of the current request.
760 761 762 763
 *
 * @return
 *   An array as expected by drupal_render().
 */
764
function comment_view(CommentInterface $comment, $view_mode = 'full', $langcode = NULL) {
765
  return entity_view($comment, $view_mode, $langcode);
766 767 768
}

/**
769
 * Constructs render array from an array of loaded comments.
770 771
 *
 * @param $comments
772
 *   An array of comments as returned by entity_load_multiple().
773 774
 * @param $view_mode
 *   View mode, e.g. 'full', 'teaser'...
775
 * @param $langcode
776 777 778
 *   (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.
779
 *
780 781
 * @return
 *   An array in the format expected by drupal_render().
782 783
 *
 * @see drupal_render()
784
 */
785 786
function comment_view_multiple($comments, $view_mode = 'full', $langcode = NULL) {
  return entity_view_multiple($comments, $view_mode, $langcode);
787 788
}

789
/**
790
 * Implements hook_form_FORM_ID_alter().
791
 */
792
function comment_form_field_ui_field_instance_edit_form_alter(&$form, $form_state) {
793
  if ($form['#field']->getFieldType() == 'comment') {
794 795
    // Collect translation settings.
    if (\Drupal::moduleHandler()->moduleExists('content_translation')) {
796 797
      array_unshift($form['#submit'], 'comment_translation_configuration_element_submit');
    }
798 799 800

    // Hide required checkbox.
    $form['instance']['required']['#access'] = FALSE;
801
  }
802 803
}

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

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

Dries's avatar
 
Dries committed
824
/**
825
 * Implements hook_form_FORM_ID_alter().
Dries's avatar
 
Dries committed
826
 */
827 828
function comment_form_field_ui_display_overview_form_alter(&$form, $form_state) {
  if ($form['#entity_type'] == 'comment') {
829 830
    $request = \Drupal::request();
    $form['#title'] = \Drupal::service('comment.manager')->getFieldUIPageTitle($request->attributes->get('commented_entity_type'), $request->attributes->get('field_name'));
831
  }
832
}
833

834 835 836 837
/**
 * Implements hook_form_FORM_ID_alter().
 */
function comment_form_field_ui_field_edit_form_alter(&$form, $form_state) {
838
  if ($form['#field']->getFieldType() == 'comment') {
839 840 841 842
    // 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'] = drupal_map_assoc(array(1));
    $form['field']['cardinality_container']['#access'] = FALSE;
843 844
  }
}
845

846
/**
847 848 849 850 851 852 853 854 855 856 857 858 859 860 861
 * Form submission handler for field_ui_field_edit_form().
 *
 * This handles the comment translation settings added by
 * _comment_field_instance_settings_form_process().
 *
 * @see _comment_field_instance_settings_form_process()
 */
function comment_translation_configuration_element_submit($form, &$form_state) {
  // The comment translation settings form element is embedded into the instance
  // settings form. Hence we need to provide to the regular submit handler a
  // manipulated form state to make it process comment settings instead of the
  // host entity.
  $key = 'language_configuration';
  $comment_form_state = array(
    'content_translation' => array('key' => $key),
862
    'language' => array($key => array('entity_type' => 'comment', 'bundle' => $form['#field']->name)),
863 864 865 866 867 868 869 870
    'values' => array($key => array('content_translation' => $form_state['values']['content_translation'])),
  );
  content_translation_language_configuration_element_submit($form, $comment_form_state);
}

/**
 * Implements hook_entity_load().
 *
871
 * @see \Drupal\comment\Plugin\Field\FieldType\CommentItem::getPropertyDefinitions()
872
 */
873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893
function comment_entity_load($entities, $entity_type) {
  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 = db_select('comment_entity_statistics', 'ces')
    ->fields('ces')
    ->condition('ces.entity_id', array_keys($entities))
    ->condition('ces.entity_type', $entity_type)
    ->execute();
  foreach ($result as $record) {
    $parts = explode('__', $record->field_id, 2);
    list(, $field_name) = $parts;
    $comment_statistics = $entities[$record->entity_id]->get($field_name);
    $comment_statistics->cid = $record->cid;
    $comment_statistics->last_comment_timestamp = $record->last_comment_timestamp;
    $comment_statistics->last_comment_name = $record->last_comment_name;
    $comment_statistics->last_comment_uid = $record->last_comment_uid;
    $comment_statistics->comment_count = $record->comment_count;
894 895
  }
}
896

897
/**
898
 * Implements hook_entity_insert().
899
 */
900
function comment_entity_insert(EntityInterface $entity) {
901
  // Allow bulk updates and inserts to temporarily disable the
902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917
  // maintenance of the {comment_entity_statistics} table.
  if (\Drupal::state()->get('comment.maintain_entity_statistics') &&
    $fields = \Drupal::service('comment.manager')->getFields($entity->entityType())) {
    $query = db_insert('comment_entity_statistics')
     ->fields(array(
      'entity_id',
      'en