5 * Enables users to comment on published content.
7 * When installed, the Comment module creates a field that facilitates a
8 * discussion board for each Drupal entity to which a comment field is attached.
9 * Users can post comments to discuss a forum topic, story, collaborative
10 * book page, user etc.
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;
24 use Drupal\field\FieldConfigInterface;
25 use Drupal\field\FieldStorageConfigInterface;
26 use Drupal\node\NodeInterface;
27 use Drupal\user\RoleInterface;
28 use Drupal\user\UserInterface;
31 * Anonymous posters cannot enter their contact information.
33 * @deprecated in Drupal 8.3.x and will be removed before Drupal 9.0.0.
34 * Use \Drupal\comment\CommentInterface::ANONYMOUS_MAYNOT_CONTACT instead.
36 * @see https://www.drupal.org/node/2831620
38 const COMMENT_ANONYMOUS_MAYNOT_CONTACT = 0;
41 * Anonymous posters may leave their contact information.
43 * @deprecated in Drupal 8.3.x and will be removed before Drupal 9.0.0.
44 * Use \Drupal\comment\CommentInterface::ANONYMOUS_MAY_CONTACT instead.
46 * @see https://www.drupal.org/node/2831620
48 const COMMENT_ANONYMOUS_MAY_CONTACT = 1;
51 * Anonymous posters are required to leave their contact information.
53 * @deprecated in Drupal 8.3.x and will be removed before Drupal 9.0.0.
54 * Use \Drupal\comment\CommentInterface::ANONYMOUS_MUST_CONTACT instead.
56 * @see https://www.drupal.org/node/2831620
58 const COMMENT_ANONYMOUS_MUST_CONTACT = 2;
61 * The time cutoff for comments marked as read for entity types other node.
63 * Comments changed before this time are always marked as read.
64 * Comments changed after this time may be marked new, updated, or read,
65 * depending on their state for the current user. Defaults to 30 days ago.
67 * @todo Remove when https://www.drupal.org/node/1029708 lands.
69 define('COMMENT_NEW_LIMIT', REQUEST_TIME - 30 * 24 * 60 * 60);
72 * Implements hook_help().
74 function comment_help($route_name, RouteMatchInterface $route_match) {
75 switch ($route_name) {
76 case 'help.page.comment':
77 $output = '<h3>' . t('About') . '</h3>';
78 $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>';
79 $output .= '<h3>' . t('Uses') . '</h3>';
81 $output .= '<dt>' . t('Enabling commenting') . '</dt>';
82 $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>';
83 $output .= '<dt>' . t('Configuring commenting settings') . '</dt>';
84 $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>';
85 $output .= '<dt>' . t('Overriding default settings') . '</dt>';
86 $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>';
87 $output .= '<dt>' . t('Adding comment types') . '</dt>';
88 $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>';
89 $output .= '<dt>' . t('Approving and managing comments') . '</dt>';
90 $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>';
94 case 'entity.comment_type.collection':
95 $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>';
101 * Entity URI callback.
103 function comment_uri(CommentInterface $comment) {
105 'entity.comment.canonical',
107 'comment' => $comment->id(),
109 ['fragment' => 'comment-' . $comment->id()]
114 * Implements hook_entity_extra_field_info().
116 function comment_entity_extra_field_info() {
118 foreach (CommentType::loadMultiple() as $comment_type) {
119 $return['comment'][$comment_type->id()] = [
122 'label' => t('Author'),
123 'description' => t('Author textfield'),
128 $return['comment'][$comment_type->id()]['display']['links'] = [
129 'label' => t('Links'),
130 'description' => t('Comment operation links'),
140 * Implements hook_theme().
142 function comment_theme() {
145 'render element' => 'elements',
147 'field__comment' => [
148 'base hook' => 'field',
154 * Implements hook_ENTITY_TYPE_create() for 'field_config'.
156 function comment_field_config_create(FieldConfigInterface $field) {
157 if ($field->getType() == 'comment' && !$field->isSyncing()) {
158 // Assign default values for the field.
159 $default_value = $field->getDefaultValueLiteral();
160 $default_value += [[]];
161 $default_value[0] += [
162 'status' => CommentItemInterface::OPEN,
164 'last_comment_timestamp' => 0,
165 'last_comment_name' => '',
166 'last_comment_uid' => 0,
167 'comment_count' => 0,
169 $field->setDefaultValue($default_value);
174 * Implements hook_ENTITY_TYPE_update() for 'field_config'.
176 function comment_field_config_update(FieldConfigInterface $field) {
177 if ($field->getType() == 'comment') {
178 // Comment field settings also affects the rendering of *comment* entities,
179 // not only the *commented* entities.
180 \Drupal::entityManager()->getViewBuilder('comment')->resetCache();
185 * Implements hook_ENTITY_TYPE_insert() for 'field_storage_config'.
187 function comment_field_storage_config_insert(FieldStorageConfigInterface $field_storage) {
188 if ($field_storage->getType() == 'comment') {
189 // Check that the target entity type uses an integer ID.
190 $entity_type_id = $field_storage->getTargetEntityTypeId();
191 if (!_comment_entity_uses_integer_id($entity_type_id)) {
192 throw new \UnexpectedValueException('You cannot attach a comment field to an entity with a non-integer ID field');
198 * Implements hook_ENTITY_TYPE_delete() for 'field_config'.
200 function comment_field_config_delete(FieldConfigInterface $field) {
201 if ($field->getType() == 'comment') {
202 // Delete all comments that used by the entity bundle.
203 $entity_query = \Drupal::entityQuery('comment');
204 $entity_query->condition('entity_type', $field->getEntityTypeId());
205 $entity_query->condition('field_name', $field->getName());
206 $cids = $entity_query->execute();
207 entity_delete_multiple('comment', $cids);
212 * Implements hook_node_links_alter().
214 function comment_node_links_alter(array &$links, NodeInterface $node, array &$context) {
215 // Comment links are only added to node entity type for backwards
216 // compatibility. Should you require comment links for other entity types you
217 // can do so by implementing a new field formatter.
218 // @todo Make this configurable from the formatter. See
219 // https://www.drupal.org/node/1901110.
221 $comment_links = \Drupal::service('comment.link_builder')->buildCommentedEntityLinks($node, $context);
222 $links += $comment_links;
226 * Implements hook_entity_view().
228 function comment_entity_view(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display, $view_mode) {
229 if ($entity instanceof FieldableEntityInterface && $view_mode == 'rss' && $display->getComponent('links')) {
230 /** @var \Drupal\comment\CommentManagerInterface $comment_manager */
231 $comment_manager = \Drupal::service('comment.manager');
232 $fields = $comment_manager->getFields($entity->getEntityTypeId());
233 foreach ($fields as $field_name => $detail) {
234 if ($entity->hasField($field_name) && $entity->get($field_name)->status != CommentItemInterface::HIDDEN) {
235 // Add a comments RSS element which is a URL to the comments of this
238 'fragment' => 'comments',
241 $entity->rss_elements[] = [
243 'value' => $entity->url('canonical', $options),
251 * Implements hook_ENTITY_TYPE_view_alter() for node entities.
253 function comment_node_view_alter(array &$build, EntityInterface $node, EntityViewDisplayInterface $display) {
254 if (\Drupal::moduleHandler()->moduleExists('history')) {
255 $build['#attributes']['data-history-node-id'] = $node->id();
260 * Generates an array for rendering a comment.
262 * @param \Drupal\comment\CommentInterface $comment
263 * The comment object.
264 * @param string $view_mode
265 * (optional) View mode; for instance, 'full', 'teaser', etc. Defaults to
267 * @param string $langcode
268 * (optional) A language code to use for rendering. Defaults to the global
269 * content language of the current request.
272 * An array as expected by \Drupal\Core\Render\RendererInterface::render().
274 * @deprecated in Drupal 8.x and will be removed before Drupal 9.0.
275 * Use \Drupal::entityManager()->getViewBuilder('comment')->view().
277 function comment_view(CommentInterface $comment, $view_mode = 'full', $langcode = NULL) {
278 return entity_view($comment, $view_mode, $langcode);
282 * Constructs render array from an array of loaded comments.
284 * @param \Drupal\comment\CommentInterface[] $comments
285 * An array of comments as returned by entity_load_multiple().
286 * @param string $view_mode
287 * (optional) View mode; for instance, 'full', 'teaser', etc. Defaults to
289 * @param string $langcode
290 * (optional) A string indicating the language field values are to be shown
291 * in. If no language is provided the current content language is used.
295 * An array in the format expected by
296 * \Drupal\Core\Render\RendererInterface::render().
298 * @deprecated in Drupal 8.x and will be removed before Drupal 9.0.
299 * Use \Drupal::entityManager()->getViewBuilder('comment')->viewMultiple().
301 * @see \Drupal\Core\Render\RendererInterface::render()
303 function comment_view_multiple($comments, $view_mode = 'full', $langcode = NULL) {
304 return entity_view_multiple($comments, $view_mode, $langcode);
308 * Implements hook_form_FORM_ID_alter() for field_ui_field_storage_add_form.
310 function comment_form_field_ui_field_storage_add_form_alter(&$form, FormStateInterface $form_state) {
311 $route_match = \Drupal::routeMatch();
312 if ($form_state->get('entity_type_id') == 'comment' && $route_match->getParameter('commented_entity_type')) {
313 $form['#title'] = \Drupal::service('comment.manager')->getFieldUIPageTitle($route_match->getParameter('commented_entity_type'), $route_match->getParameter('field_name'));
315 if (!_comment_entity_uses_integer_id($form_state->get('entity_type_id'))) {
316 $optgroup = (string) t('General');
317 // You cannot use comment fields on entity types with non-integer IDs.
318 unset($form['add']['new_storage_type']['#options'][$optgroup]['comment']);
323 * Implements hook_form_FORM_ID_alter().
325 function comment_form_field_ui_form_display_overview_form_alter(&$form, FormStateInterface $form_state) {
326 $route_match = \Drupal::routeMatch();
327 if ($form['#entity_type'] == 'comment' && $route_match->getParameter('commented_entity_type')) {
328 $form['#title'] = \Drupal::service('comment.manager')->getFieldUIPageTitle($route_match->getParameter('commented_entity_type'), $route_match->getParameter('field_name'));
333 * Implements hook_form_FORM_ID_alter().
335 function comment_form_field_ui_display_overview_form_alter(&$form, FormStateInterface $form_state) {
336 $route_match = \Drupal::routeMatch();
337 if ($form['#entity_type'] == 'comment' && $route_match->getParameter('commented_entity_type')) {
338 $form['#title'] = \Drupal::service('comment.manager')->getFieldUIPageTitle($route_match->getParameter('commented_entity_type'), $route_match->getParameter('field_name'));
343 * Implements hook_entity_storage_load().
345 * @see \Drupal\comment\Plugin\Field\FieldType\CommentItem::propertyDefinitions()
347 function comment_entity_storage_load($entities, $entity_type) {
348 // Comments can only be attached to content entities, so skip others.
349 if (!\Drupal::entityManager()->getDefinition($entity_type)->entityClassImplements(FieldableEntityInterface::class)) {
352 if (!\Drupal::service('comment.manager')->getFields($entity_type)) {
353 // Do not query database when entity has no comment fields.
356 // Load comment information from the database and update the entity's
357 // comment statistics properties, which are defined on each CommentItem field.
358 $result = \Drupal::service('comment.statistics')->read($entities, $entity_type);
359 foreach ($result as $record) {
360 // Skip fields that entity does not have.
361 if (!$entities[$record->entity_id]->hasField($record->field_name)) {
364 $comment_statistics = $entities[$record->entity_id]->get($record->field_name);
365 $comment_statistics->cid = $record->cid;
366 $comment_statistics->last_comment_timestamp = $record->last_comment_timestamp;
367 $comment_statistics->last_comment_name = $record->last_comment_name;
368 $comment_statistics->last_comment_uid = $record->last_comment_uid;
369 $comment_statistics->comment_count = $record->comment_count;
374 * Implements hook_entity_insert().
376 function comment_entity_insert(EntityInterface $entity) {
377 // Allow bulk updates and inserts to temporarily disable the
378 // maintenance of the {comment_entity_statistics} table.
379 if (\Drupal::state()->get('comment.maintain_entity_statistics') &&
380 $fields = \Drupal::service('comment.manager')->getFields($entity->getEntityTypeId())) {
381 \Drupal::service('comment.statistics')->create($entity, $fields);
386 * Implements hook_entity_predelete().
388 function comment_entity_predelete(EntityInterface $entity) {
389 // Entities can have non-numeric IDs, but {comment} and
390 // {comment_entity_statistics} tables have integer columns for entity ID, and
391 // PostgreSQL throws exceptions if you attempt query conditions with
392 // mismatched types. So, we need to verify that the ID is numeric (even for an
393 // entity type that has an integer ID, $entity->id() might be a string
394 // containing a number), and then cast it to an integer when querying.
395 if ($entity instanceof FieldableEntityInterface && is_numeric($entity->id())) {
396 $entity_query = \Drupal::entityQuery('comment');
397 $entity_query->condition('entity_id', (int) $entity->id());
398 $entity_query->condition('entity_type', $entity->getEntityTypeId());
399 $cids = $entity_query->execute();
400 entity_delete_multiple('comment', $cids);
401 \Drupal::service('comment.statistics')->delete($entity);
406 * Determines if an entity type is using an integer-based ID definition.
408 * @param string $entity_type_id
409 * The ID the represents the entity type.
412 * Returns TRUE if the entity type has an integer-based ID definition and
415 function _comment_entity_uses_integer_id($entity_type_id) {
416 $entity_type = \Drupal::entityManager()->getDefinition($entity_type_id);
417 $entity_type_id_key = $entity_type->getKey('id');
418 if ($entity_type_id_key === FALSE) {
421 $field_definitions = \Drupal::entityManager()->getBaseFieldDefinitions($entity_type->id());
422 $entity_type_id_definition = $field_definitions[$entity_type_id_key];
423 return $entity_type_id_definition->getType() === 'integer';
427 * Implements hook_node_update_index().
429 function comment_node_update_index(EntityInterface $node) {
430 $index_comments = &drupal_static(__FUNCTION__);
432 if ($index_comments === NULL) {
433 // Do not index in the following three cases:
434 // 1. 'Authenticated user' can search content but can't access comments.
435 // 2. 'Anonymous user' can search content but can't access comments.
436 // 3. Any role can search content but can't access comments and access
437 // comments is not granted by the 'authenticated user' role. In this case
438 // all users might have both permissions from various roles but it is also
439 // possible to set up a user to have only search content and so a user
440 // edit could change the security situation so it is not safe to index the
442 $index_comments = TRUE;
443 $roles = \Drupal::entityManager()->getStorage('user_role')->loadMultiple();
444 $authenticated_can_access = $roles[RoleInterface::AUTHENTICATED_ID]->hasPermission('access comments');
445 foreach ($roles as $rid => $role) {
446 if ($role->hasPermission('search content') && !$role->hasPermission('access comments')) {
447 if ($rid == RoleInterface::AUTHENTICATED_ID || $rid == RoleInterface::ANONYMOUS_ID || !$authenticated_can_access) {
448 $index_comments = FALSE;
457 if ($index_comments) {
458 foreach (\Drupal::service('comment.manager')->getFields('node') as $field_name => $info) {
459 // Skip fields that entity does not have.
460 if (!$node->hasField($field_name)) {
463 $field_definition = $node->getFieldDefinition($field_name);
464 $mode = $field_definition->getSetting('default_mode');
465 $comments_per_page = $field_definition->getSetting('per_page');
466 if ($node->get($field_name)->status) {
467 $comments = \Drupal::entityManager()->getStorage('comment')
468 ->loadThread($node, $field_name, $mode, $comments_per_page);
470 $build[] = \Drupal::entityManager()->getViewBuilder('comment')->viewMultiple($comments);
475 return \Drupal::service('renderer')->renderPlain($build);
479 * Implements hook_cron().
481 function comment_cron() {
482 // Store the maximum possible comments per thread (used for node search
483 // ranking by reply count).
484 \Drupal::state()->set('comment.node_comment_statistics_scale', 1.0 / max(1, \Drupal::service('comment.statistics')->getMaximumCount('node')));
488 * Implements hook_node_search_result().
490 * Formats a comment count string and returns it, for display with search
493 function comment_node_search_result(EntityInterface $node) {
494 $comment_fields = \Drupal::service('comment.manager')->getFields('node');
497 foreach ($comment_fields as $field_name => $info) {
498 // Skip fields that entity does not have.
499 if (!$node->hasField($field_name)) {
502 // Do not make a string if comments are hidden.
503 $status = $node->get($field_name)->status;
504 if (\Drupal::currentUser()->hasPermission('access comments') && $status != CommentItemInterface::HIDDEN) {
505 if ($status == CommentItemInterface::OPEN) {
506 // At least one comment field is open.
509 $comments += $node->get($field_name)->comment_count;
512 // Do not make a string if there are no comment fields, or no comments exist
513 // or all comment fields are hidden.
514 if ($comments > 0 || $open) {
515 return ['comment' => \Drupal::translation()->formatPlural($comments, '1 comment', '@count comments')];
520 * Implements hook_user_cancel().
522 function comment_user_cancel($edit, UserInterface $account, $method) {
524 case 'user_cancel_block_unpublish':
525 $comments = entity_load_multiple_by_properties('comment', ['uid' => $account->id()]);
526 foreach ($comments as $comment) {
527 $comment->setUnpublished();
532 case 'user_cancel_reassign':
533 /** @var \Drupal\comment\CommentInterface[] $comments */
534 $comments = entity_load_multiple_by_properties('comment', ['uid' => $account->id()]);
535 foreach ($comments as $comment) {
536 $comment->setOwnerId(0);
537 $comment->setAuthorName(\Drupal::config('user.settings')->get('anonymous'));
545 * Implements hook_ENTITY_TYPE_predelete() for user entities.
547 function comment_user_predelete($account) {
548 $entity_query = \Drupal::entityQuery('comment');
549 $entity_query->condition('uid', $account->id());
550 $cids = $entity_query->execute();
551 entity_delete_multiple('comment', $cids);
555 * Generates a comment preview.
557 * @param \Drupal\comment\CommentInterface $comment
558 * The comment entity to preview.
559 * @param Drupal\Core\Form\FormStateInterface $form_state
560 * The current state of the form.
563 * An array as expected by \Drupal\Core\Render\RendererInterface::render().
565 function comment_preview(CommentInterface $comment, FormStateInterface $form_state) {
567 $entity = $comment->getCommentedEntity();
569 if (!$form_state->getErrors()) {
570 $comment->in_preview = TRUE;
571 $comment_build = \Drupal::entityTypeManager()->getViewBuilder('comment')->view($comment);
572 $comment_build['#weight'] = -100;
574 $preview_build['comment_preview'] = $comment_build;
577 if ($comment->hasParentComment()) {
579 $parent = $comment->getParentComment();
580 if ($parent && $parent->isPublished()) {
581 $build = \Drupal::entityTypeManager()->getViewBuilder('comment')->view($parent);
585 // The comment field output includes rendering the parent entity of the
586 // thread to which the comment is a reply. The rendered entity output
587 // includes the comment reply form, which contains the comment preview and
588 // therefore the rendered parent entity. This results in an infinite loop of
589 // parent entity output rendering the comment form and the comment form
590 // rendering the parent entity. To prevent this infinite loop we temporarily
591 // set the value of the comment field on a clone of the entity to hidden
592 // before calling entity_view(). That way when the output of the commented
593 // entity is rendered, it excludes the comment field output.
594 $field_name = $comment->getFieldName();
595 $entity = clone $entity;
596 $entity->$field_name->status = CommentItemInterface::HIDDEN;
597 $build = entity_view($entity, 'full');
600 $preview_build['comment_output_below'] = $build;
601 $preview_build['comment_output_below']['#weight'] = 100;
603 return $preview_build;
607 * Implements hook_preprocess_HOOK() for block templates.
609 function comment_preprocess_block(&$variables) {
610 if ($variables['configuration']['provider'] == 'comment') {
611 $variables['attributes']['role'] = 'navigation';
616 * Prepares variables for comment templates.
618 * Default template: comment.html.twig.
620 * @param array $variables
621 * An associative array containing:
622 * - elements: An associative array containing the comment and entity objects.
623 * Array keys: #comment, #commented_entity.
625 function template_preprocess_comment(&$variables) {
626 /** @var \Drupal\comment\CommentInterface $comment */
627 $comment = $variables['elements']['#comment'];
628 $commented_entity = $comment->getCommentedEntity();
629 $variables['comment'] = $comment;
630 $variables['commented_entity'] = $commented_entity;
631 $variables['threaded'] = $variables['elements']['#comment_threaded'];
633 $account = $comment->getOwner();
635 '#theme' => 'username',
636 '#account' => $account,
638 $variables['author'] = \Drupal::service('renderer')->render($username);
639 $variables['author_id'] = $comment->getOwnerId();
640 $variables['new_indicator_timestamp'] = $comment->getChangedTime();
641 $variables['created'] = format_date($comment->getCreatedTime());
642 // Avoid calling format_date() twice on the same timestamp.
643 if ($comment->getChangedTime() == $comment->getCreatedTime()) {
644 $variables['changed'] = $variables['created'];
647 $variables['changed'] = format_date($comment->getChangedTime());
650 if (theme_get_setting('features.comment_user_picture')) {
651 // To change user picture settings (for instance, image style), edit the
652 // 'compact' view mode on the User entity.
653 $variables['user_picture'] = user_view($account, 'compact');
656 $variables['user_picture'] = [];
659 if (isset($comment->in_preview)) {
660 $variables['title'] = \Drupal::l($comment->getSubject(), new Url('<front>'));
661 $variables['permalink'] = \Drupal::l(t('Permalink'), new Url('<front>'));
664 $uri = $comment->permalink();
665 $attributes = $uri->getOption('attributes') ?: [];
666 $attributes += ['class' => ['permalink'], 'rel' => 'bookmark'];
667 $uri->setOption('attributes', $attributes);
668 $variables['title'] = \Drupal::l($comment->getSubject(), $uri);
670 $variables['permalink'] = \Drupal::l(t('Permalink'), $comment->permalink());
673 $variables['submitted'] = t('Submitted by @username on @datetime', ['@username' => $variables['author'], '@datetime' => $variables['created']]);
675 if ($comment->hasParentComment()) {
676 // Fetch and store the parent comment information for use in templates.
677 $comment_parent = $comment->getParentComment();
678 $account_parent = $comment_parent->getOwner();
679 $variables['parent_comment'] = $comment_parent;
681 '#theme' => 'username',
682 '#account' => $account_parent,
684 $variables['parent_author'] = \Drupal::service('renderer')->render($username);
685 $variables['parent_created'] = format_date($comment_parent->getCreatedTime());
686 // Avoid calling format_date() twice on the same timestamp.
687 if ($comment_parent->getChangedTime() == $comment_parent->getCreatedTime()) {
688 $variables['parent_changed'] = $variables['parent_created'];
691 $variables['parent_changed'] = format_date($comment_parent->getChangedTime());
693 $permalink_uri_parent = $comment_parent->permalink();
694 $attributes = $permalink_uri_parent->getOption('attributes') ?: [];
695 $attributes += ['class' => ['permalink'], 'rel' => 'bookmark'];
696 $permalink_uri_parent->setOption('attributes', $attributes);
697 $variables['parent_title'] = \Drupal::l($comment_parent->getSubject(), $permalink_uri_parent);
698 $variables['parent_permalink'] = \Drupal::l(t('Parent permalink'), $permalink_uri_parent);
699 $variables['parent'] = t('In reply to @parent_title by @parent_username',
700 ['@parent_username' => $variables['parent_author'], '@parent_title' => $variables['parent_title']]);
703 $variables['parent_comment'] = '';
704 $variables['parent_author'] = '';
705 $variables['parent_created'] = '';
706 $variables['parent_changed'] = '';
707 $variables['parent_title'] = '';
708 $variables['parent_permalink'] = '';
709 $variables['parent'] = '';
712 // Helpful $content variable for templates.
713 foreach (Element::children($variables['elements']) as $key) {
714 $variables['content'][$key] = $variables['elements'][$key];
717 // Set status to a string representation of comment->status.
718 if (isset($comment->in_preview)) {
719 $variables['status'] = 'preview';
722 $variables['status'] = $comment->isPublished() ? 'published' : 'unpublished';
725 // Add comment author user ID. Necessary for the comment-by-viewer library.
726 $variables['attributes']['data-comment-user-id'] = $comment->getOwnerId();
730 * Prepares variables for comment field templates.
732 * Default template: field--comment.html.twig.
734 * @param array $variables
735 * An associative array containing:
736 * - element: An associative array containing render arrays for the list of
737 * comments, and the comment form. Array keys: comments, comment_form.
739 * @todo Rename to template_preprocess_field__comment() once
740 * https://www.drupal.org/node/939462 is resolved.
742 function comment_preprocess_field(&$variables) {
743 $element = $variables['element'];
744 if ($element['#field_type'] == 'comment') {
745 // Provide contextual information.
746 $variables['comment_display_mode'] = $element[0]['#comment_display_mode'];
747 $variables['comment_type'] = $element[0]['#comment_type'];
749 // Append additional attributes (eg. RDFa) from the first field item.
750 $variables['attributes'] += $variables['items'][0]['attributes']->storage();
752 // Create separate variables for the comments and comment form.
753 $variables['comments'] = $element[0]['comments'];
754 $variables['comment_form'] = $element[0]['comment_form'];
759 * Implements hook_ranking().
761 function comment_ranking() {
762 return \Drupal::service('comment.statistics')->getRankingInfo();
766 * Implements hook_ENTITY_TYPE_presave() for entity_view_display entities.
768 function comment_entity_view_display_presave(EntityViewDisplayInterface $display) {
769 // Act only on comment view displays being disabled.
770 if ($display->isNew() || $display->getTargetEntityTypeId() !== 'comment' || $display->status()) {
773 $storage = \Drupal::entityTypeManager()->getStorage('entity_view_display');
774 if (!$storage->loadUnchanged($display->getOriginalId())->status()) {
778 // Disable the comment field formatter when the used view display is disabled.
779 foreach ($storage->loadMultiple() as $id => $view_display) {
781 /** @var \Drupal\Core\Entity\Display\EntityViewDisplayInterface $view_display */
782 foreach ($view_display->getComponents() as $field => $component) {
783 if (isset($component['type']) && ($component['type'] === 'comment_default')) {
784 if ($component['settings']['view_mode'] === $display->getMode()) {
785 $view_display->removeComponent($field);
786 /** @var \Drupal\Core\Entity\EntityViewModeInterface $mode */
787 $mode = EntityViewMode::load($display->getTargetEntityTypeId() . '.' . $display->getMode());
789 '@id' => $view_display->id(),
791 '@display' => $mode->label(),
792 '@mode' => $display->getMode(),
794 \Drupal::logger('system')->warning("View display '@id': Comment field formatter '@name' was disabled because it is using the comment view display '@display' (@mode) that was just disabled.", $arguments);
800 $view_display->save();