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

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

13
use Drupal\comment\CommentInterface;
14
use Drupal\comment\Entity\CommentType;
15
use Drupal\Core\Entity\FieldableEntityInterface;
16
use Drupal\comment\Plugin\Field\FieldType\CommentItemInterface;
17
use Drupal\Core\Entity\Entity\EntityViewMode;
18
use Drupal\Core\Entity\EntityInterface;
19
use Drupal\Core\Form\FormStateInterface;
20
use Drupal\Core\Routing\RouteMatchInterface;
21
use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
22
use Drupal\Core\Render\Element;
23
use Drupal\Core\Url;
24
use Drupal\field\FieldConfigInterface;
25
use Drupal\field\FieldStorageConfigInterface;
26
use Drupal\node\NodeInterface;
27
use Drupal\user\RoleInterface;
28

29
/**
30
 * Anonymous posters cannot enter their contact information.
31 32 33
 *
 * @deprecated in Drupal 8.3.x and will be removed before Drupal 9.0.0.
 *   Use \Drupal\comment\CommentInterface::ANONYMOUS_MAYNOT_CONTACT instead.
34 35
 *
 * @see https://www.drupal.org/node/2831620
36
 */
37
const COMMENT_ANONYMOUS_MAYNOT_CONTACT = 0;
38 39 40

/**
 * Anonymous posters may leave their contact information.
41 42 43
 *
 * @deprecated in Drupal 8.3.x and will be removed before Drupal 9.0.0.
 *   Use \Drupal\comment\CommentInterface::ANONYMOUS_MAY_CONTACT instead.
44 45
 *
 * @see https://www.drupal.org/node/2831620
46
 */
47
const COMMENT_ANONYMOUS_MAY_CONTACT = 1;
48 49

/**
50
 * Anonymous posters are required to leave their contact information.
51 52 53
 *
 * @deprecated in Drupal 8.3.x and will be removed before Drupal 9.0.0.
 *   Use \Drupal\comment\CommentInterface::ANONYMOUS_MUST_CONTACT instead.
54 55
 *
 * @see https://www.drupal.org/node/2831620
56
 */
57
const COMMENT_ANONYMOUS_MUST_CONTACT = 2;
58

59 60 61 62 63 64 65
/**
 * 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.
 *
66
 * @todo Remove when https://www.drupal.org/node/1029708 lands.
67 68
 */
define('COMMENT_NEW_LIMIT', REQUEST_TIME - 30 * 24 * 60 * 60);
69

70
/**
71
 * Implements hook_help().
72
 */
73
function comment_help($route_name, RouteMatchInterface $route_match) {
74 75
  switch ($route_name) {
    case 'help.page.comment':
76
      $output = '<h3>' . t('About') . '</h3>';
77
      $output .= '<p>' . t('The Comment module allows users to comment on site content, set commenting defaults and permissions, and moderate comments. For more information, see the <a href=":comment">online documentation for the Comment module</a>.', [':comment' => 'https://www.drupal.org/documentation/modules/comment']) . '</p>';
78 79
      $output .= '<h3>' . t('Uses') . '</h3>';
      $output .= '<dl>';
80
      $output .= '<dt>' . t('Enabling commenting') . '</dt>';
81
      $output .= '<dd>' . t('Comment functionality can be enabled for any entity sub-type (for example, a <a href=":content-type">content type</a>) by adding a <em>Comments</em> field on its <em>Manage fields page</em>. Adding or removing commenting for an entity through the user interface requires the <a href=":field_ui">Field UI</a> module to be enabled, even though the commenting functionality works without it. For more information on fields and entities, see the <a href=":field">Field module help page</a>.', [':content-type' => (\Drupal::moduleHandler()->moduleExists('node')) ? \Drupal::url('entity.node_type.collection') : '#', ':field' => \Drupal::url('help.page', ['name' => 'field']), ':field_ui' => (\Drupal::moduleHandler()->moduleExists('field_ui')) ? \Drupal::url('help.page', ['name' => 'field_ui']) : '#']) . '</dd>';
82 83
      $output .= '<dt>' . t('Configuring commenting settings') . '</dt>';
      $output .= '<dd>' . t('Commenting settings can be configured by editing the <em>Comments</em> field on the <em>Manage fields page</em> of an entity type if the <em>Field UI module</em> is enabled. Configuration includes the label of the comments field, the number of comments to be displayed, and whether they are shown in threaded list. Commenting can be be configured as: <em>Open</em> to allow new comments, <em>Closed</em> to view existing comments, but prevent new comments, or <em>Hidden</em> to hide existing comments and prevent new comments. Changing this configuration for an entity type will not change existing entity items.') . '</dd>';
84
      $output .= '<dt>' . t('Overriding default settings') . '</dt>';
85
      $output .= '<dd>' . t('Users with the appropriate permissions can override the default commenting settings of an entity type when they create an item of that type.') . '</dd>';
86
      $output .= '<dt>' . t('Adding comment types') . '</dt>';
87
      $output .= '<dd>' . t('Additional <em>comment types</em> can be created per entity sub-type and added on the <a href=":field">Comment types page</a>. If there are multiple comment types available you can select the appropriate one after adding a <em>Comments field</em>.', [':field' => \Drupal::url('entity.comment_type.collection')]) . '</dd>';
88
      $output .= '<dt>' . t('Approving and managing comments') . '</dt>';
89
      $output .= '<dd>' . t('Comments from users who have the <em>Skip comment approval</em> permission are published immediately. All other comments are placed in the <a href=":comment-approval">Unapproved comments</a> queue, until a user who has permission to <em>Administer comments and comment settings</em> publishes or deletes them. Published comments can be bulk managed on the <a href=":admin-comment">Published comments</a> administration page. When a comment has no replies, it remains editable by its author, as long as the author has <em>Edit own comments</em> permission.', [':comment-approval' => \Drupal::url('comment.admin_approval'), ':admin-comment' => \Drupal::url('comment.admin')]) . '</dd>';
90
      $output .= '</dl>';
91
      return $output;
92

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

99
/**
100
 * Entity URI callback.
101
 */
102
function comment_uri(CommentInterface $comment) {
103
  return new Url(
104
    'entity.comment.canonical',
105
    [
106
      'comment' => $comment->id(),
107 108
    ],
    ['fragment' => 'comment-' . $comment->id()]
109
  );
110 111
}

112
/**
113
 * Implements hook_entity_extra_field_info().
114
 */
115
function comment_entity_extra_field_info() {
116
  $return = [];
117
  foreach (CommentType::loadMultiple() as $comment_type) {
118 119 120
    $return['comment'][$comment_type->id()] = [
      'form' => [
        'author' => [
121 122 123
          'label' => t('Author'),
          'description' => t('Author textfield'),
          'weight' => -2,
124 125 126 127
        ],
      ],
    ];
    $return['comment'][$comment_type->id()]['display']['links'] = [
128 129 130 131
      'label' => t('Links'),
      'description' => t('Comment operation links'),
      'weight' => 100,
      'visible' => TRUE,
132
    ];
133 134 135 136 137
  }

  return $return;
}

138
/**
139
 * Implements hook_theme().
140 141
 */
function comment_theme() {
142 143
  return [
    'comment' => [
144
      'render element' => 'elements',
145 146
    ],
    'field__comment' => [
147
      'base hook' => 'field',
148 149
    ],
  ];
150 151
}

152
/**
153
 * Implements hook_ENTITY_TYPE_create() for 'field_config'.
154
 */
155 156 157
function comment_field_config_create(FieldConfigInterface $field) {
  if ($field->getType() == 'comment' && !$field->isSyncing()) {
    // Assign default values for the field.
158
    $default_value = $field->getDefaultValueLiteral();
159 160
    $default_value += [[]];
    $default_value[0] += [
161
      'status' => CommentItemInterface::OPEN,
162 163 164 165 166
      'cid' => 0,
      'last_comment_timestamp' => 0,
      'last_comment_name' => '',
      'last_comment_uid' => 0,
      'comment_count' => 0,
167
    ];
168
    $field->setDefaultValue($default_value);
169
  }
170
}
171

172
/**
173
 * Implements hook_ENTITY_TYPE_update() for 'field_config'.
174
 */
175 176
function comment_field_config_update(FieldConfigInterface $field) {
  if ($field->getType() == 'comment') {
177 178 179
    // Comment field settings also affects the rendering of *comment* entities,
    // not only the *commented* entities.
    \Drupal::entityManager()->getViewBuilder('comment')->resetCache();
180 181
  }
}
182

183
/**
184
 * Implements hook_ENTITY_TYPE_insert() for 'field_storage_config'.
185
 */
186 187
function comment_field_storage_config_insert(FieldStorageConfigInterface $field_storage) {
  if ($field_storage->getType() == 'comment') {
188
    // Check that the target entity type uses an integer ID.
189
    $entity_type_id = $field_storage->getTargetEntityTypeId();
190 191 192
    if (!_comment_entity_uses_integer_id($entity_type_id)) {
      throw new \UnexpectedValueException('You cannot attach a comment field to an entity with a non-integer ID field');
    }
193 194 195
  }
}

196
/**
197
 * Implements hook_ENTITY_TYPE_delete() for 'field_config'.
198
 */
199 200
function comment_field_config_delete(FieldConfigInterface $field) {
  if ($field->getType() == 'comment') {
201
    // Delete all comments that used by the entity bundle.
202
    $entity_query = \Drupal::entityQuery('comment');
203 204
    $entity_query->condition('entity_type', $field->getEntityTypeId());
    $entity_query->condition('field_name', $field->getName());
205 206
    $cids = $entity_query->execute();
    entity_delete_multiple('comment', $cids);
207
  }
208 209
}

210
/**
211
 * Implements hook_node_links_alter().
212
 */
213
function comment_node_links_alter(array &$links, NodeInterface $node, array &$context) {
214 215 216
  // 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.
217 218
  // @todo Make this configurable from the formatter. See
  //   https://www.drupal.org/node/1901110.
219

220 221
  $comment_links = \Drupal::service('comment.link_builder')->buildCommentedEntityLinks($node, $context);
  $links += $comment_links;
222 223
}

224 225 226
/**
 * Implements hook_entity_view().
 */
227
function comment_entity_view(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display, $view_mode) {
228 229 230 231 232 233 234 235
  if ($entity instanceof FieldableEntityInterface && $view_mode == 'rss' && $display->getComponent('links')) {
    /** @var \Drupal\comment\CommentManagerInterface $comment_manager */
    $comment_manager = \Drupal::service('comment.manager');
    $fields = $comment_manager->getFields($entity->getEntityTypeId());
    foreach ($fields as $field_name => $detail) {
      if ($entity->hasField($field_name) && $entity->get($field_name)->status != CommentItemInterface::HIDDEN) {
        // Add a comments RSS element which is a URL to the comments of this
        // entity.
236
        $options = [
237 238
          'fragment' => 'comments',
          'absolute' => TRUE,
239 240
        ];
        $entity->rss_elements[] = [
241 242
          'key' => 'comments',
          'value' => $entity->url('canonical', $options),
243
        ];
244 245 246 247 248
      }
    }
  }
}

249
/**
250
 * Implements hook_ENTITY_TYPE_view_alter() for node entities.
251
 */
252
function comment_node_view_alter(array &$build, EntityInterface $node, EntityViewDisplayInterface $display) {
253
  if (\Drupal::moduleHandler()->moduleExists('history')) {
254 255 256 257
    $build['#attributes']['data-history-node-id'] = $node->id();
  }
}

258
/**
259
 * Generates an array for rendering a comment.
260
 *
261
 * @param \Drupal\comment\CommentInterface $comment
262
 *   The comment object.
263
 * @param string $view_mode
264 265
 *   (optional) View mode; for instance, 'full', 'teaser', etc. Defaults to
 *   'full'.
266
 * @param string $langcode
267 268
 *   (optional) A language code to use for rendering. Defaults to the global
 *   content language of the current request.
269
 *
270
 * @return array
271
 *   An array as expected by \Drupal\Core\Render\RendererInterface::render().
272 273 274
 *
 * @deprecated in Drupal 8.x and will be removed before Drupal 9.0.
 *   Use \Drupal::entityManager()->getViewBuilder('comment')->view().
275
 */
276
function comment_view(CommentInterface $comment, $view_mode = 'full', $langcode = NULL) {
277
  return entity_view($comment, $view_mode, $langcode);
278 279 280
}

/**
281
 * Constructs render array from an array of loaded comments.
282
 *
283
 * @param \Drupal\comment\CommentInterface[] $comments
284
 *   An array of comments as returned by entity_load_multiple().
285
 * @param string $view_mode
286 287
 *   (optional) View mode; for instance, 'full', 'teaser', etc. Defaults to
 *   'full'.
288
 * @param string $langcode
289 290 291
 *   (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.
292
 *
293
 * @return array
294 295
 *   An array in the format expected by
 *   \Drupal\Core\Render\RendererInterface::render().
296
 *
297 298 299
 * @deprecated in Drupal 8.x and will be removed before Drupal 9.0.
 *   Use \Drupal::entityManager()->getViewBuilder('comment')->viewMultiple().
 *
300
 * @see \Drupal\Core\Render\RendererInterface::render()
301
 */
302 303
function comment_view_multiple($comments, $view_mode = 'full', $langcode = NULL) {
  return entity_view_multiple($comments, $view_mode, $langcode);
304 305
}

306
/**
307
 * Implements hook_form_FORM_ID_alter() for field_ui_field_storage_add_form.
308
 */
309
function comment_form_field_ui_field_storage_add_form_alter(&$form, FormStateInterface $form_state) {
310 311 312
  $route_match = \Drupal::routeMatch();
  if ($form_state->get('entity_type_id') == 'comment' && $route_match->getParameter('commented_entity_type')) {
    $form['#title'] = \Drupal::service('comment.manager')->getFieldUIPageTitle($route_match->getParameter('commented_entity_type'), $route_match->getParameter('field_name'));
313
  }
314
  if (!_comment_entity_uses_integer_id($form_state->get('entity_type_id'))) {
315
    $optgroup = (string) t('General');
316
    // You cannot use comment fields on entity types with non-integer IDs.
317
    unset($form['add']['new_storage_type']['#options'][$optgroup]['comment']);
318
  }
319 320
}

321
/**
322
 * Implements hook_form_FORM_ID_alter().
323
 */
324
function comment_form_field_ui_form_display_overview_form_alter(&$form, FormStateInterface $form_state) {
325 326 327
  $route_match = \Drupal::routeMatch();
  if ($form['#entity_type'] == 'comment' && $route_match->getParameter('commented_entity_type')) {
    $form['#title'] = \Drupal::service('comment.manager')->getFieldUIPageTitle($route_match->getParameter('commented_entity_type'), $route_match->getParameter('field_name'));
328 329 330
  }
}

331
/**
332
 * Implements hook_form_FORM_ID_alter().
333
 */
334
function comment_form_field_ui_display_overview_form_alter(&$form, FormStateInterface $form_state) {
335 336 337
  $route_match = \Drupal::routeMatch();
  if ($form['#entity_type'] == 'comment' && $route_match->getParameter('commented_entity_type')) {
    $form['#title'] = \Drupal::service('comment.manager')->getFieldUIPageTitle($route_match->getParameter('commented_entity_type'), $route_match->getParameter('field_name'));
338
  }
339
}
340

341
/**
342
 * Implements hook_entity_storage_load().
343
 *
344
 * @see \Drupal\comment\Plugin\Field\FieldType\CommentItem::propertyDefinitions()
345
 */
346
function comment_entity_storage_load($entities, $entity_type) {
347
  // Comments can only be attached to content entities, so skip others.
348
  if (!\Drupal::entityManager()->getDefinition($entity_type)->entityClassImplements(FieldableEntityInterface::class)) {
349 350
    return;
  }
351
  if (!\Drupal::service('comment.manager')->getFields($entity_type)) {
352 353 354
    // Do not query database when entity has no comment fields.
    return;
  }
355 356 357
  // Load comment information from the database and update the entity's
  // comment statistics properties, which are defined on each CommentItem field.
  $result = \Drupal::service('comment.statistics')->read($entities, $entity_type);
358
  foreach ($result as $record) {
359
    // Skip fields that entity does not have.
360
    if (!$entities[$record->entity_id]->hasField($record->field_name)) {
361 362
      continue;
    }
363
    $comment_statistics = $entities[$record->entity_id]->get($record->field_name);
364 365 366 367 368
    $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;
369 370
  }
}
371

372
/**
373
 * Implements hook_entity_insert().
374
 */
375
function comment_entity_insert(EntityInterface $entity) {
376
  // Allow bulk updates and inserts to temporarily disable the
377 378
  // maintenance of the {comment_entity_statistics} table.
  if (\Drupal::state()->get('comment.maintain_entity_statistics') &&
379
    $fields = \Drupal::service('comment.manager')->getFields($entity->getEntityTypeId())) {
380
    \Drupal::service('comment.statistics')->create($entity, $fields);
381
  }
382
}
383

384
/**
385
 * Implements hook_entity_predelete().
386
 */
387
function comment_entity_predelete(EntityInterface $entity) {
388 389 390 391 392 393
  // Entities can have non-numeric IDs, but {comment} and
  // {comment_entity_statistics} tables have integer columns for entity ID, and
  // PostgreSQL throws exceptions if you attempt query conditions with
  // mismatched types. So, we need to verify that the ID is numeric (even for an
  // entity type that has an integer ID, $entity->id() might be a string
  // containing a number), and then cast it to an integer when querying.
394
  if ($entity instanceof FieldableEntityInterface && is_numeric($entity->id())) {
395 396 397 398
    $entity_query = \Drupal::entityQuery('comment');
    $entity_query->condition('entity_id', (int) $entity->id());
    $entity_query->condition('entity_type', $entity->getEntityTypeId());
    $cids = $entity_query->execute();
399
    entity_delete_multiple('comment', $cids);
400
    \Drupal::service('comment.statistics')->delete($entity);
401
  }
402
}
403

404 405 406 407 408 409 410 411 412 413 414 415 416
/**
 * Determines if an entity type is using an integer-based ID definition.
 *
 * @param string $entity_type_id
 *   The ID the represents the entity type.
 *
 * @return bool
 *   Returns TRUE if the entity type has an integer-based ID definition and
 *   FALSE otherwise.
 */
function _comment_entity_uses_integer_id($entity_type_id) {
  $entity_type = \Drupal::entityManager()->getDefinition($entity_type_id);
  $entity_type_id_key = $entity_type->getKey('id');
417 418 419
  if ($entity_type_id_key === FALSE) {
    return FALSE;
  }
420 421 422 423 424
  $field_definitions = \Drupal::entityManager()->getBaseFieldDefinitions($entity_type->id());
  $entity_type_id_definition = $field_definitions[$entity_type_id_key];
  return $entity_type_id_definition->getType() === 'integer';
}

425
/**
426
 * Implements hook_node_update_index().
427
 */
428
function comment_node_update_index(EntityInterface $node) {
429 430 431
  $index_comments = &drupal_static(__FUNCTION__);

  if ($index_comments === NULL) {
432 433 434 435 436 437 438 439 440
    // Do not index in the following three cases:
    // 1. 'Authenticated user' can search content but can't access comments.
    // 2. 'Anonymous user' can search content but can't access comments.
    // 3. Any role can search content but can't access comments and access
    // comments is not granted by the 'authenticated user' role. In this case
    // all users might have both permissions from various roles but it is also
    // possible to set up a user to have only search content and so a user
    // edit could change the security situation so it is not safe to index the
    // comments.
441
    $index_comments = TRUE;
442
    $roles = \Drupal::entityManager()->getStorage('user_role')->loadMultiple();
443
    $authenticated_can_access = $roles[RoleInterface::AUTHENTICATED_ID]->hasPermission('access comments');
444 445
    foreach ($roles as $rid => $role) {
      if ($role->hasPermission('search content') && !$role->hasPermission('access comments')) {
446
        if ($rid == RoleInterface::AUTHENTICATED_ID || $rid == RoleInterface::ANONYMOUS_ID || !$authenticated_can_access) {
447 448 449
          $index_comments = FALSE;
          break;
        }
450 451 452 453
      }
    }
  }

454
  $build = [];
455

456
  if ($index_comments) {
457 458
    foreach (\Drupal::service('comment.manager')->getFields('node') as $field_name => $info) {
      // Skip fields that entity does not have.
459
      if (!$node->hasField($field_name)) {
460 461
        continue;
      }
462 463 464
      $field_definition = $node->getFieldDefinition($field_name);
      $mode = $field_definition->getSetting('default_mode');
      $comments_per_page = $field_definition->getSetting('per_page');
465 466 467 468 469 470
      if ($node->get($field_name)->status) {
        $comments = \Drupal::entityManager()->getStorage('comment')
          ->loadThread($node, $field_name, $mode, $comments_per_page);
        if ($comments) {
          $build[] = \Drupal::entityManager()->getViewBuilder('comment')->viewMultiple($comments);
        }
471
      }
472
    }
473
  }
474
  return \Drupal::service('renderer')->renderPlain($build);
475
}
476

477
/**
478
 * Implements hook_cron().
479
 */
480 481 482
function comment_cron() {
  // Store the maximum possible comments per thread (used for node search
  // ranking by reply count).
483
  \Drupal::state()->set('comment.node_comment_statistics_scale', 1.0 / max(1, \Drupal::service('comment.statistics')->getMaximumCount('node')));
484 485
}

486
/**
487
 * Implements hook_node_search_result().
488 489 490
 *
 * Formats a comment count string and returns it, for display with search
 * results.
491
 */
492
function comment_node_search_result(EntityInterface $node) {
493 494 495 496 497
  $comment_fields = \Drupal::service('comment.manager')->getFields('node');
  $comments = 0;
  $open = FALSE;
  foreach ($comment_fields as $field_name => $info) {
    // Skip fields that entity does not have.
498
    if (!$node->hasField($field_name)) {
499 500 501 502
      continue;
    }
    // Do not make a string if comments are hidden.
    $status = $node->get($field_name)->status;
503 504
    if (\Drupal::currentUser()->hasPermission('access comments') && $status != CommentItemInterface::HIDDEN) {
      if ($status == CommentItemInterface::OPEN) {
505 506 507 508
        // At least one comment field is open.
        $open = TRUE;
      }
      $comments += $node->get($field_name)->comment_count;
509
    }
510
  }
511 512 513
  // Do not make a string if there are no comment fields, or no comments exist
  // or all comment fields are hidden.
  if ($comments > 0 || $open) {
514
    return ['comment' => \Drupal::translation()->formatPlural($comments, '1 comment', '@count comments')];
515
  }
516
}
517

518
/**
519
 * Implements hook_user_cancel().
520
 */
521
function comment_user_cancel($edit, $account, $method) {
522 523
  switch ($method) {
    case 'user_cancel_block_unpublish':
524
      $comments = entity_load_multiple_by_properties('comment', ['uid' => $account->id()]);
525
      foreach ($comments as $comment) {
526
        $comment->setUnpublished();
527
        $comment->save();
528
      }
529 530 531
      break;

    case 'user_cancel_reassign':
532
      /** @var \Drupal\comment\CommentInterface[] $comments */
533
      $comments = entity_load_multiple_by_properties('comment', ['uid' => $account->id()]);
534
      foreach ($comments as $comment) {
535
        $comment->setOwnerId(0);
536
        $comment->setAuthorName(\Drupal::config('user.settings')->get('anonymous'));
537
        $comment->save();
538
      }
539 540
      break;
  }
541 542
}

543
/**
544
 * Implements hook_ENTITY_TYPE_predelete() for user entities.
545
 */
546
function comment_user_predelete($account) {
547 548 549
  $entity_query = \Drupal::entityQuery('comment');
  $entity_query->condition('uid', $account->id());
  $cids = $entity_query->execute();
550
  entity_delete_multiple('comment', $cids);
551 552
}

553
/**
554 555
 * Generates a comment preview.
 *
556
 * @param \Drupal\comment\CommentInterface $comment
557
 *   The comment entity to preview.
558 559
 * @param Drupal\Core\Form\FormStateInterface $form_state
 *   The current state of the form.
560 561
 *
 * @return array
562
 *   An array as expected by \Drupal\Core\Render\RendererInterface::render().
563
 */
564
function comment_preview(CommentInterface $comment, FormStateInterface $form_state) {
565
  $preview_build = [];
566
  $entity = $comment->getCommentedEntity();
567

568
  if (!$form_state->getErrors()) {
569
    $comment->in_preview = TRUE;
570
    $comment_build = \Drupal::entityTypeManager()->getViewBuilder('comment')->view($comment);
571
    $comment_build['#weight'] = -100;
572

573
    $preview_build['comment_preview'] = $comment_build;
574
  }
575

576
  if ($comment->hasParentComment()) {
577
    $build = [];
578 579
    $parent = $comment->getParentComment();
    if ($parent && $parent->isPublished()) {
580
      $build = \Drupal::entityTypeManager()->getViewBuilder('comment')->view($parent);
581
    }
582 583
  }
  else {
584 585 586 587 588 589
    // The comment field output includes rendering the parent entity of the
    // thread to which the comment is a reply. The rendered entity output
    // includes the comment reply form, which contains the comment preview and
    // therefore the rendered parent entity. This results in an infinite loop of
    // parent entity output rendering the comment form and the comment form
    // rendering the parent entity. To prevent this infinite loop we temporarily
590
    // set the value of the comment field on a clone of the entity to hidden
591
    // before calling entity_view(). That way when the output of the commented
592
    // entity is rendered, it excludes the comment field output.
593
    $field_name = $comment->getFieldName();
594 595
    $entity = clone $entity;
    $entity->$field_name->status = CommentItemInterface::HIDDEN;
596
    $build = entity_view($entity, 'full');
597 598
  }

599 600
  $preview_build['comment_output_below'] = $build;
  $preview_build['comment_output_below']['#weight'] = 100;
601

602
  return $preview_build;
603 604
}

605
/**
606
 * Implements hook_preprocess_HOOK() for block templates.
607 608
 */
function comment_preprocess_block(&$variables) {
609
  if ($variables['configuration']['provider'] == 'comment') {
610
    $variables['attributes']['role'] = 'navigation';
611 612 613
  }
}

614
/**
615
 * Prepares variables for comment templates.
616
 *
617 618 619 620
 * Default template: comment.html.twig.
 *
 * @param array $variables
 *   An associative array containing:
621 622
 *   - elements: An associative array containing the comment and entity objects.
 *     Array keys: #comment, #commented_entity.
623 624
 */
function template_preprocess_comment(&$variables) {
625
  /** @var \Drupal\comment\CommentInterface $comment */
626
  $comment = $variables['elements']['#comment'];
627
  $commented_entity = $comment->getCommentedEntity();
628
  $variables['comment'] = $comment;
629
  $variables['commented_entity'] = $commented_entity;
630
  $variables['threaded'] = $variables['elements']['#comment_threaded'];
631

632
  $account = $comment->getOwner();
633
  $username = [
634 635
    '#theme' => 'username',
    '#account' => $account,
636
  ];
637
  $variables['author'] = \Drupal::service('renderer')->render($username);
638
  $variables['author_id'] = $comment->getOwnerId();
639 640
  $variables['new_indicator_timestamp'] = $comment->getChangedTime();
  $variables['created'] = format_date($comment->getCreatedTime());
641
  // Avoid calling format_date() twice on the same timestamp.
642
  if ($comment->getChangedTime() == $comment->getCreatedTime()) {
643 644 645
    $variables['changed'] = $variables['created'];
  }
  else {
646
    $variables['changed'] = format_date($comment->getChangedTime());
647
  }
648

649
  if (theme_get_setting('features.comment_user_picture')) {
650 651
    // To change user picture settings (for instance, image style), edit the
    // 'compact' view mode on the User entity.
652
    $variables['user_picture'] = user_view($account, 'compact');
653 654
  }
  else {
655
    $variables['user_picture'] = [];
656
  }
657

658
  if (isset($comment->in_preview)) {
659 660
    $variables['title'] = \Drupal::l($comment->getSubject(), new Url('<front>'));
    $variables['permalink'] = \Drupal::l(t('Permalink'), new Url('<front>'));
661 662
  }
  else {
663
    $uri = $comment->permalink();
664 665
    $attributes = $uri->getOption('attributes') ?: [];
    $attributes += ['class' => ['permalink'], 'rel' => 'bookmark'];
666
    $uri->setOption('attributes', $attributes);
667
    $variables['title'] = \Drupal::l($comment->getSubject(), $uri);
668

669
    $variables['permalink'] = \Drupal::l(t('Permalink'), $comment->permalink());
670
  }
671

672
  $variables['submitted'] = t('Submitted by @username on @datetime', ['@username' => $variables['author'], '@datetime' => $variables['created']]);
673

674
  if ($comment->hasParentComment()) {
675
    // Fetch and store the parent comment information for use in templates.
676
    $comment_parent = $comment->getParentComment();
677
    $account_parent = $comment_parent->getOwner();
678
    $variables['parent_comment'] = $comment_parent;
679
    $username = [
680 681
      '#theme' => 'username',
      '#account' => $account_parent,
682
    ];
683
    $variables['parent_author'] = \Drupal::service('renderer')->render($username);
684
    $variables['parent_created'] = format_date($comment_parent->getCreatedTime());
685
    // Avoid calling format_date() twice on the same timestamp.
686
    if ($comment_parent->getChangedTime() == $comment_parent->getCreatedTime()) {
687 688 689
      $variables['parent_changed'] = $variables['parent_created'];
    }
    else {
690
      $variables['parent_changed'] = format_date($comment_parent->getChangedTime());
691
    }
692
    $permalink_uri_parent = $comment_parent->permalink();
693 694
    $attributes = $permalink_uri_parent->getOption('attributes') ?: [];
    $attributes += ['class' => ['permalink'], 'rel' => 'bookmark'];
695
    $permalink_uri_parent->setOption('attributes', $attributes);
696 697
    $variables['parent_title'] = \Drupal::l($comment_parent->getSubject(), $permalink_uri_parent);
    $variables['parent_permalink'] = \Drupal::l(t('Parent permalink'), $permalink_uri_parent);
698
    $variables['parent'] = t('In reply to @parent_title by @parent_username',
699
        ['@parent_username' => $variables['parent_author'], '@parent_title' => $variables['parent_title']]);
700 701 702 703 704 705 706 707 708 709 710
  }
  else {
    $variables['parent_comment'] = '';
    $variables['parent_author'] = '';
    $variables['parent_created'] = '';
    $variables['parent_changed'] = '';
    $variables['parent_title'] = '';
    $variables['parent_permalink'] = '';
    $variables['parent'] = '';
  }

711
  // Helpful $content variable for templates.
712
  foreach (Element::children($variables['elements']) as $key) {
713 714
    $variables['content'][$key] = $variables['elements'][$key];
  }
715

716
  // Set status to a string representation of comment->status.
717
  if (isset($comment->in_preview)) {
718
    $variables['status'] = 'preview';
719 720
  }
  else {
721
    $variables['status'] = $comment->isPublished() ? 'published' : 'unpublished';
722
  }
723

724
  // Add comment author user ID. Necessary for the comment-by-viewer library.
725
  $variables['attributes']['data-comment-user-id'] = $comment->getOwnerId();
726 727
}

728
/**
729
 * Prepares variables for comment field templates.
730
 *
731
 * Default template: field--comment.html.twig.
732
 *
733 734
 * @param array $variables
 *   An associative array containing:
735
 *   - element: An associative array containing render arrays for the list of
736
 *     comments, and the comment form. Array keys: comments, comment_form.