comment.module 63.4 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_block' => array(
177
      'variables' => array('number' => NULL),
178 179
    ),
    'comment_preview' => array(
180
      'variables' => array('comment' => NULL),
181 182
    ),
    'comment' => array(
183
      'template' => 'comment',
184
      'render element' => 'elements',
185 186
    ),
    'comment_post_forbidden' => array(
187
      'variables' => array('commented_entity' => NULL, 'field_name' => 'comment'),
188 189
    ),
    'comment_wrapper' => array(
190
      'template' => 'comment-wrapper',
191
      'render element' => 'content',
192 193 194 195
    ),
  );
}

Dries's avatar
 
Dries committed
196
/**
197
 * Implements hook_menu().
Dries's avatar
 
Dries committed
198
 */
199
function comment_menu() {
200 201 202 203 204 205 206 207 208
  $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',
  );
209
  $items['admin/content/comment'] = array(
210
    'title' => 'Comments',
211
    'description' => 'List and edit site comments and the comment approval queue.',
212
    'route_name' => 'comment.admin',
213
    'type' => MENU_LOCAL_TASK | MENU_NORMAL_ITEM,
214
  );
215
  // Tabs begin here.
216
  $items['admin/content/comment/new'] = array(
217
    'title' => 'Published comments',
218 219
    'type' => MENU_DEFAULT_LOCAL_TASK,
  );
220
  $items['admin/content/comment/approval'] = array(
221 222
    'title' => 'Unapproved comments',
    'title callback' => 'comment_count_unpublished',
223
    'route_name' => 'comment.admin_approval',
224 225
    'type' => MENU_LOCAL_TASK,
  );
226
  $items['comment/%comment'] = array(
227
    'title' => 'Comment permalink',
228
    'route_name' => 'comment.permalink',
229
  );
230
  $items['comment/%comment/view'] = array(
231 232 233
    'title' => 'View comment',
    'type' => MENU_DEFAULT_LOCAL_TASK,
  );
234 235
  // 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).
236 237 238
  $items['comment/%comment/edit'] = array(
    'title' => 'Edit',
    'type' => MENU_LOCAL_TASK,
239
    'route_name' => 'comment.edit_page',
240
  );
241
  $items['comment/%comment/approve'] = array(
242
    'title' => 'Approve',
243
    'weight' => 10,
244
    'route_name' => 'comment.approve',
245
  );
246
  $items['comment/%comment/delete'] = array(
247 248
    'title' => 'Delete',
    'type' => MENU_LOCAL_TASK,
249
    'route_name' => 'comment.confirm_delete',
250
    'weight' => 20,
251
  );
Dries's avatar
 
Dries committed
252 253 254 255

  return $items;
}

256 257 258 259
/**
 * Implements hook_menu_alter().
 */
function comment_menu_alter(&$items) {
260 261 262 263
  if (isset($items['admin/content'])) {
    // Add comments to the description for admin/content if any.
    $items['admin/content']['description'] = 'Administer content and comments.';
  }
264 265
}

266 267 268 269 270 271 272 273 274 275
/**
 * 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));
}

276
/**
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
 * Implements hook_ENTITY_TYPE_create() for 'field_instance'.
 */
function comment_field_instance_create(FieldInstanceInterface $instance) {
  if ($instance->getFieldType() == 'comment') {
    \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,
    ));
  }
293
}
294

295
/**
296
 * Implements hook_ENTITY_TYPE_update() for 'field_instance'.
297
 */
298 299 300
function comment_field_instance_update(FieldInstanceInterface $instance) {
  if ($instance->getFieldType() == 'comment') {
    \Drupal::entityManager()->getRenderController($instance->entity_type)->resetCache();
301 302
  }
}
303

304
/**
305
 * Implements hook_ENTITY_TYPE_delete() for 'field_entity'.
306
 */
307 308 309 310 311
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');
312 313 314
  }
}

315 316 317 318 319 320 321 322 323 324 325 326
/**
 * 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');
327
  }
328 329
}

Dries's avatar
 
Dries committed
330
/**
331
 * Implements hook_permission().
Dries's avatar
 
Dries committed
332
 */
333
function comment_permission() {
334
  return array(
335
    'administer comments' => array(
336
      'title' => t('Administer comments and comment settings'),
337 338
    ),
    'access comments' => array(
339
      'title' => t('View comments'),
340 341
    ),
    'post comments' => array(
342
      'title' => t('Post comments'),
343
    ),
344 345
    'skip comment approval' => array(
      'title' => t('Skip comment approval'),
346
    ),
347 348 349
    'edit own comments' => array(
      'title' => t('Edit own comments'),
    ),
350
  );
Dries's avatar
 
Dries committed
351 352
}

353
/**
354
 * Finds the most recent comments that are available to the current user.
355 356
 *
 * @param integer $number
357
 *   (optional) The maximum number of comments to find. Defaults to 10.
358
 *
359
 * @return
360 361
 *   An array of comment objects or an empty array if there are no recent
 *   comments visible to the current user.
362 363
 */
function comment_get_recent($number = 10) {
364
  $query = db_select('comment', 'c');
365
  $query->addMetaData('base_table', 'comment');
366 367 368 369 370 371
  $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');
372 373
    // @todo This should be actually filtering on the desired node status field
    //   language and just fall back to the default language.
374 375 376 377 378
    $query
      ->condition('n.status', NODE_PUBLISHED)
      ->condition('n.default_langcode', 1);
  }
  $comments = $query
379
    ->orderBy('c.created', 'DESC')
380 381 382
    // Additionally order by cid to ensure that comments with the same timestamp
    // are returned in the exact order posted.
    ->orderBy('c.cid', 'DESC')
383 384 385 386 387
    ->range(0, $number)
    ->execute()
    ->fetchAll();

  return $comments ? $comments : array();
388 389
}

390
/**
391
 * Calculates the page number for the first new comment.
392
 *
393
 * @param int $num_comments
394
 *   Number of comments.
395
 * @param int $new_replies
396
 *   Number of new replies.
397 398 399 400
 * @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.
401
 *
402 403
 * @return
 *   "page=X" if the page number is greater than zero; empty string otherwise.
404
 */
405 406 407 408
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');
409
  $pagenum = NULL;
410
  $flat = $mode == COMMENT_MODE_FLAT ? TRUE : FALSE;
411 412
  if ($num_comments <= $comments_per_page) {
    // Only one page of comments.
413
    $pageno = 0;
414
  }
415 416 417
  elseif ($flat) {
    // Flat comments.
    $count = $num_comments - $new_replies;
418
    $pageno = $count / $comments_per_page;
419
  }
420
  else {
421 422 423 424 425 426
    // 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'))
427 428 429
      ->condition('entity_id', $entity->id())
      ->condition('entity_type', $entity->entityType())
      ->condition('field_id', $entity->entityType() . '__' . $field_name)
430
      ->condition('status', COMMENT_PUBLISHED)
431 432
      ->orderBy('created', 'DESC')
      ->orderBy('cid', 'DESC')
433 434 435 436 437 438 439 440 441 442 443 444 445 446
      ->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.
447 448 449 450
    $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(
451
      ':status' => COMMENT_PUBLISHED,
452 453 454
      ':entity_id' => $entity->id(),
      ':field_id' => $entity->entityType() . '__' . $field_name,
      ':entity_type' => $entity->entityType(),
455
      ':thread' => $first_thread,
456
    ))->fetchField();
457

458
    $pageno = $count / $comments_per_page;
459
  }
460

461
  if ($pageno >= 1) {
462
    $pagenum = array('page' => intval($pageno));
463
  }
464

465 466 467
  return $pagenum;
}

468
/**
469
 * Returns HTML for a list of recent comments.
470 471 472
 *
 * @ingroup themeable
 */
473
function theme_comment_block($variables) {
474
  $items = array();
475
  $number = $variables['number'];
476
  foreach (comment_get_recent($number) as $comment) {
477
    $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>';
478
  }
479

480
  if ($items) {
481 482 483 484 485
    $item_list = array(
      '#theme' => 'item_list',
      '#items' => $items,
    );
    return drupal_render($item_list);
486
  }
487 488 489
  else {
    return t('No comments available.');
  }
490 491
}

Dries's avatar
 
Dries committed
492
/**
493
 * Implements hook_entity_view().
Dries's avatar
 
Dries committed
494
 */
495 496 497 498 499 500 501 502 503 504 505 506 507 508
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.
    if (!$entity->getPropertyDefinition($field_name)) {
      continue;
509
    }
510 511 512 513 514 515 516 517 518 519 520
    $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
521
        }
522 523 524 525
        $entity->rss_elements[] = array(
          'key' => 'comments',
          'value' => url($uri['path'], $uri['options'])
        );
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 552
      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,
              );
            }
553
          }
554
        }
555 556 557 558
        // Provide a link to new comment form.
        if ($commenting_status == COMMENT_OPEN) {
          $comment_form_location = $instance->getFieldSetting('form_location');
          if (user_access('post comments')) {
559 560
            $links['comment-add'] = array(
              'title' => t('Add new comment'),
561 562
              'href' => $uri['path'],
              'attributes' => array('title' => t('Add a new comment to this page.')),
563 564 565
              'fragment' => 'comment-form',
            );
            if ($comment_form_location == COMMENT_FORM_SEPARATE_PAGE) {
566
              $links['comment-add']['href'] = 'comment/reply/'. $entity->entityType() . '/' . $entity->id() .'/' . $field_name;
567
            }
568
          }
569 570 571 572 573 574 575 576 577 578 579
          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
580
        }
581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614
      }
      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
615 616 617
        }
      }
    }
Dries's avatar
Dries committed
618

619 620
    $entity->content['links']['comment__' . $field_name] = array(
      '#theme' => 'links__entity__comment__' . $field_name,
621 622 623
      '#links' => $links,
      '#attributes' => array('class' => array('links', 'inline')),
    );
624
    if ($view_mode == 'teaser' && \Drupal::moduleHandler()->moduleExists('history')) {
625
      $entity->content['links']['#attached']['library'][] = array('comment', 'drupal.node-new-comments-link');
626
    }
627
  }
Dries's avatar
 
Dries committed
628 629
}

630 631 632 633
/**
 * Implements hook_node_view_alter().
 */
function comment_node_view_alter(&$build, EntityInterface $node, EntityDisplay $display) {
634
  if (\Drupal::moduleHandler()->moduleExists('history')) {
635 636 637 638
    $build['#attributes']['data-history-node-id'] = $node->id();
  }
}

639
/**
640
 * Returns a rendered form to comment the given entity.
641
 *
642 643 644 645
 * @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.
646 647 648
 * @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.
649 650 651 652
 *
 * @return array
 *   The renderable array for the comment addition form.
 */
653 654 655 656 657 658 659
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,
  );
660
  $comment = entity_create('comment', $values);
661
  return \Drupal::entityManager()->getForm($comment);
662 663
}

664
/**
665
 * Retrieves comments for a thread.
666
 *
667 668 669 670 671
 * @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
672
 *   The comment display mode; COMMENT_MODE_FLAT or COMMENT_MODE_THREADED.
673
 * @param int $comments_per_page
674
 *   The amount of comments to display per page.
675
 *
676 677 678
 * @return
 *   An array of the IDs of the comment to be displayed.
 *
679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732
 * 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.
 */
733
function comment_get_thread(EntityInterface $entity, $field_name, $mode, $comments_per_page) {
734 735
  $query = db_select('comment', 'c')
    ->extend('Drupal\Core\Database\Query\PagerSelectExtender');
736 737
  $query->addField('c', 'cid');
  $query
738 739 740 741
    ->condition('c.entity_id', $entity->id())
    ->condition('c.entity_type', $entity->entityType())
    ->condition('c.field_id', $entity->entityType() . '__' . $field_name)
    ->addTag('entity_access')
742
    ->addTag('comment_filter')
743
    ->addMetaData('base_table', 'comment')
744 745
    ->addMetaData('entity', $entity)
    ->addMetaData('field_name', $field_name)
746 747 748 749 750
    ->limit($comments_per_page);

  $count_query = db_select('comment', 'c');
  $count_query->addExpression('COUNT(*)');
  $count_query
751 752 753 754
    ->condition('c.entity_id', $entity->id())
    ->condition('c.entity_type', $entity->entityType())
    ->condition('c.field_id', $entity->entityType() . '__' . $field_name)
    ->addTag('entity_access')
755
    ->addTag('comment_filter')
756
    ->addMetaData('base_table', 'comment')
757 758
    ->addMetaData('entity', $entity)
    ->addMetaData('field_name', $field_name);
759 760 761 762 763

  if (!user_access('administer comments')) {
    $query->condition('c.status', COMMENT_PUBLISHED);
    $count_query->condition('c.status', COMMENT_PUBLISHED);
  }
764
  if ($mode == COMMENT_MODE_FLAT) {
765 766 767 768 769 770
    $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.
771 772
    $query->addExpression('SUBSTRING(c.thread, 1, (LENGTH(c.thread) - 1))', 'torder');
    $query->orderBy('torder', 'ASC');
773 774 775
  }

  $query->setCountQuery($count_query);
776
  return $query->execute()->fetchCol();
777 778 779
}

/**
780 781 782 783 784
 * 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.
785 786
 *
 * @param array $comments
787
 *   An array of comment objects, keyed by comment ID.
788 789 790 791 792
 */
function comment_prepare_thread(&$comments) {
  // A counter that helps track how indented we are.
  $divs = 0;

793
  foreach ($comments as $key => &$comment) {
794 795
    // The $divs element instructs #prefix whether to add an indent div or
    // close existing divs (a negative value).
796
    $comment->depth = count(explode('.', $comment->thread->value)) - 1;
797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813
    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;
}

/**
814
 * Generates an array for rendering a comment.
815
 *
816
 * @param \Drupal\comment\CommentInterface $comment
817
 *   The comment object.
818
 * @param $view_mode
819
 *   (optional) View mode, e.g. 'full', 'teaser'... Defaults to 'full'.
820 821 822
 * @param $langcode
 *   (optional) A language code to use for rendering. Defaults to the global
 *   content language of the current request.
823 824 825 826
 *
 * @return
 *   An array as expected by drupal_render().
 */
827
function comment_view(CommentInterface $comment, $view_mode = 'full', $langcode = NULL) {
828
  return entity_view($comment, $view_mode, $langcode);
829 830
}

831
/**
832
 * Adds reply, edit, delete, etc. links, depending on user permissions.
833
 *
834
 * @param \Drupal\comment\CommentInterface $comment
835
 *   The comment object.
836 837 838 839
 * @param \Drupal\Core\Entity\EntityInterface $entity
 *   The entity to which the comment is attached to.
 * @param string $field_name
 *   The field the comment is attached to.
840
 *
841 842 843
 * @return
 *   A structured array of links.
 */
844
function comment_links(CommentInterface $comment, EntityInterface $entity, $field_name) {
845
  $links = array();
846 847 848
  $status = $entity->get($field_name)->status;

  if ($status == COMMENT_OPEN) {
849
    if ($comment->access('delete')) {
850
      $links['comment-delete'] = array(
851
        'title' => t('delete'),
852
        'href' => "comment/{$comment->id()}/delete",
853 854 855
        'html' => TRUE,
      );
    }
856
    if ($comment->access('update')) {
857 858 859 860 861
      $links['comment-edit'] = array(
        'title' => t('edit'),
        'href' => "comment/{$comment->id()}/edit",
        'html' => TRUE,
      );
862 863
    }
    if ($comment->access('create')) {
864
      $links['comment-reply'] = array(
865
        'title' => t('reply'),
866
        'href' => "comment/reply/{$comment->entity_type->value}/{$comment->entity_id->value}/$field_name/{$comment->id()}",
867 868 869
        'html' => TRUE,
      );
    }
870 871 872 873 874 875 876 877 878
    if ($comment->status->value == COMMENT_NOT_PUBLISHED && $comment->access('approve')) {
      $links['comment-approve'] = array(
        'title' => t('approve'),
        'href' => "comment/{$comment->id()}/approve",
        'html' => TRUE,
        'query' => array('token' => drupal_get_token("comment/{$comment->id()}/approve")),
      );
    }
    if (empty($links)) {
879 880
      $comment_post_forbidden = array(
        '#theme' => 'comment_post_forbidden',
881 882
        '#commented_entity' => $entity,
        '#field_name' => $field_name,
883 884
      );
      $links['comment-forbidden']['title'] = drupal_render($comment_post_forbidden);
885
      $links['comment-forbidden']['html'] = TRUE;
886 887
    }
  }
888 889

  // Add translations link for translation-enabled comment bundles.
890
  if (module_exists('content_translation') && content_translation_translate_access($comment)) {