annotate core/modules/comment/comment.module @ 19:fa3358dc1485 tip

Add ndrum files
author Chris Cannam
date Wed, 28 Aug 2019 13:14:47 +0100
parents af1871eacc83
children
rev   line source
Chris@0 1 <?php
Chris@0 2
Chris@0 3 /**
Chris@0 4 * @file
Chris@0 5 * Enables users to comment on published content.
Chris@0 6 *
Chris@0 7 * When installed, the Comment module creates a field that facilitates a
Chris@0 8 * discussion board for each Drupal entity to which a comment field is attached.
Chris@0 9 * Users can post comments to discuss a forum topic, story, collaborative
Chris@0 10 * book page, user etc.
Chris@0 11 */
Chris@0 12
Chris@0 13 use Drupal\comment\CommentInterface;
Chris@0 14 use Drupal\comment\Entity\CommentType;
Chris@0 15 use Drupal\Core\Entity\FieldableEntityInterface;
Chris@0 16 use Drupal\comment\Plugin\Field\FieldType\CommentItemInterface;
Chris@0 17 use Drupal\Core\Entity\Entity\EntityViewMode;
Chris@0 18 use Drupal\Core\Entity\EntityInterface;
Chris@0 19 use Drupal\Core\Form\FormStateInterface;
Chris@0 20 use Drupal\Core\Routing\RouteMatchInterface;
Chris@0 21 use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
Chris@0 22 use Drupal\Core\Render\Element;
Chris@0 23 use Drupal\Core\Url;
Chris@0 24 use Drupal\field\FieldConfigInterface;
Chris@0 25 use Drupal\field\FieldStorageConfigInterface;
Chris@0 26 use Drupal\node\NodeInterface;
Chris@0 27 use Drupal\user\RoleInterface;
Chris@17 28 use Drupal\user\UserInterface;
Chris@0 29
Chris@0 30 /**
Chris@0 31 * Anonymous posters cannot enter their contact information.
Chris@0 32 *
Chris@0 33 * @deprecated in Drupal 8.3.x and will be removed before Drupal 9.0.0.
Chris@0 34 * Use \Drupal\comment\CommentInterface::ANONYMOUS_MAYNOT_CONTACT instead.
Chris@0 35 *
Chris@0 36 * @see https://www.drupal.org/node/2831620
Chris@0 37 */
Chris@0 38 const COMMENT_ANONYMOUS_MAYNOT_CONTACT = 0;
Chris@0 39
Chris@0 40 /**
Chris@0 41 * Anonymous posters may leave their contact information.
Chris@0 42 *
Chris@0 43 * @deprecated in Drupal 8.3.x and will be removed before Drupal 9.0.0.
Chris@0 44 * Use \Drupal\comment\CommentInterface::ANONYMOUS_MAY_CONTACT instead.
Chris@0 45 *
Chris@0 46 * @see https://www.drupal.org/node/2831620
Chris@0 47 */
Chris@0 48 const COMMENT_ANONYMOUS_MAY_CONTACT = 1;
Chris@0 49
Chris@0 50 /**
Chris@0 51 * Anonymous posters are required to leave their contact information.
Chris@0 52 *
Chris@0 53 * @deprecated in Drupal 8.3.x and will be removed before Drupal 9.0.0.
Chris@0 54 * Use \Drupal\comment\CommentInterface::ANONYMOUS_MUST_CONTACT instead.
Chris@0 55 *
Chris@0 56 * @see https://www.drupal.org/node/2831620
Chris@0 57 */
Chris@0 58 const COMMENT_ANONYMOUS_MUST_CONTACT = 2;
Chris@0 59
Chris@0 60 /**
Chris@0 61 * The time cutoff for comments marked as read for entity types other node.
Chris@0 62 *
Chris@0 63 * Comments changed before this time are always marked as read.
Chris@0 64 * Comments changed after this time may be marked new, updated, or read,
Chris@0 65 * depending on their state for the current user. Defaults to 30 days ago.
Chris@0 66 *
Chris@0 67 * @todo Remove when https://www.drupal.org/node/1029708 lands.
Chris@0 68 */
Chris@0 69 define('COMMENT_NEW_LIMIT', REQUEST_TIME - 30 * 24 * 60 * 60);
Chris@0 70
Chris@0 71 /**
Chris@0 72 * Implements hook_help().
Chris@0 73 */
Chris@0 74 function comment_help($route_name, RouteMatchInterface $route_match) {
Chris@0 75 switch ($route_name) {
Chris@0 76 case 'help.page.comment':
Chris@0 77 $output = '<h3>' . t('About') . '</h3>';
Chris@0 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>';
Chris@0 79 $output .= '<h3>' . t('Uses') . '</h3>';
Chris@0 80 $output .= '<dl>';
Chris@0 81 $output .= '<dt>' . t('Enabling commenting') . '</dt>';
Chris@18 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')) ? Url::fromRoute('entity.node_type.collection')->toString() : '#', ':field' => Url::fromRoute('help.page', ['name' => 'field'])->toString(), ':field_ui' => (\Drupal::moduleHandler()->moduleExists('field_ui')) ? Url::fromRoute('help.page', ['name' => 'field_ui'])->toString() : '#']) . '</dd>';
Chris@0 83 $output .= '<dt>' . t('Configuring commenting settings') . '</dt>';
Chris@0 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>';
Chris@0 85 $output .= '<dt>' . t('Overriding default settings') . '</dt>';
Chris@0 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>';
Chris@0 87 $output .= '<dt>' . t('Adding comment types') . '</dt>';
Chris@18 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' => Url::fromRoute('entity.comment_type.collection')->toString()]) . '</dd>';
Chris@0 89 $output .= '<dt>' . t('Approving and managing comments') . '</dt>';
Chris@18 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' => Url::fromRoute('comment.admin_approval')->toString(), ':admin-comment' => Url::fromRoute('comment.admin')->toString()]) . '</dd>';
Chris@0 91 $output .= '</dl>';
Chris@0 92 return $output;
Chris@0 93
Chris@0 94 case 'entity.comment_type.collection':
Chris@0 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>';
Chris@0 96 return $output;
Chris@0 97 }
Chris@0 98 }
Chris@0 99
Chris@0 100 /**
Chris@0 101 * Entity URI callback.
Chris@0 102 */
Chris@0 103 function comment_uri(CommentInterface $comment) {
Chris@0 104 return new Url(
Chris@0 105 'entity.comment.canonical',
Chris@0 106 [
Chris@0 107 'comment' => $comment->id(),
Chris@0 108 ],
Chris@0 109 ['fragment' => 'comment-' . $comment->id()]
Chris@0 110 );
Chris@0 111 }
Chris@0 112
Chris@0 113 /**
Chris@0 114 * Implements hook_entity_extra_field_info().
Chris@0 115 */
Chris@0 116 function comment_entity_extra_field_info() {
Chris@0 117 $return = [];
Chris@0 118 foreach (CommentType::loadMultiple() as $comment_type) {
Chris@0 119 $return['comment'][$comment_type->id()] = [
Chris@0 120 'form' => [
Chris@0 121 'author' => [
Chris@0 122 'label' => t('Author'),
Chris@0 123 'description' => t('Author textfield'),
Chris@0 124 'weight' => -2,
Chris@0 125 ],
Chris@0 126 ],
Chris@0 127 ];
Chris@0 128 $return['comment'][$comment_type->id()]['display']['links'] = [
Chris@0 129 'label' => t('Links'),
Chris@0 130 'description' => t('Comment operation links'),
Chris@0 131 'weight' => 100,
Chris@0 132 'visible' => TRUE,
Chris@0 133 ];
Chris@0 134 }
Chris@0 135
Chris@0 136 return $return;
Chris@0 137 }
Chris@0 138
Chris@0 139 /**
Chris@0 140 * Implements hook_theme().
Chris@0 141 */
Chris@0 142 function comment_theme() {
Chris@0 143 return [
Chris@0 144 'comment' => [
Chris@0 145 'render element' => 'elements',
Chris@0 146 ],
Chris@0 147 'field__comment' => [
Chris@0 148 'base hook' => 'field',
Chris@0 149 ],
Chris@0 150 ];
Chris@0 151 }
Chris@0 152
Chris@0 153 /**
Chris@0 154 * Implements hook_ENTITY_TYPE_create() for 'field_config'.
Chris@0 155 */
Chris@0 156 function comment_field_config_create(FieldConfigInterface $field) {
Chris@0 157 if ($field->getType() == 'comment' && !$field->isSyncing()) {
Chris@0 158 // Assign default values for the field.
Chris@0 159 $default_value = $field->getDefaultValueLiteral();
Chris@0 160 $default_value += [[]];
Chris@0 161 $default_value[0] += [
Chris@0 162 'status' => CommentItemInterface::OPEN,
Chris@0 163 'cid' => 0,
Chris@0 164 'last_comment_timestamp' => 0,
Chris@0 165 'last_comment_name' => '',
Chris@0 166 'last_comment_uid' => 0,
Chris@0 167 'comment_count' => 0,
Chris@0 168 ];
Chris@0 169 $field->setDefaultValue($default_value);
Chris@0 170 }
Chris@0 171 }
Chris@0 172
Chris@0 173 /**
Chris@0 174 * Implements hook_ENTITY_TYPE_update() for 'field_config'.
Chris@0 175 */
Chris@0 176 function comment_field_config_update(FieldConfigInterface $field) {
Chris@0 177 if ($field->getType() == 'comment') {
Chris@0 178 // Comment field settings also affects the rendering of *comment* entities,
Chris@0 179 // not only the *commented* entities.
Chris@0 180 \Drupal::entityManager()->getViewBuilder('comment')->resetCache();
Chris@0 181 }
Chris@0 182 }
Chris@0 183
Chris@0 184 /**
Chris@0 185 * Implements hook_ENTITY_TYPE_insert() for 'field_storage_config'.
Chris@0 186 */
Chris@0 187 function comment_field_storage_config_insert(FieldStorageConfigInterface $field_storage) {
Chris@0 188 if ($field_storage->getType() == 'comment') {
Chris@0 189 // Check that the target entity type uses an integer ID.
Chris@0 190 $entity_type_id = $field_storage->getTargetEntityTypeId();
Chris@0 191 if (!_comment_entity_uses_integer_id($entity_type_id)) {
Chris@0 192 throw new \UnexpectedValueException('You cannot attach a comment field to an entity with a non-integer ID field');
Chris@0 193 }
Chris@0 194 }
Chris@0 195 }
Chris@0 196
Chris@0 197 /**
Chris@0 198 * Implements hook_ENTITY_TYPE_delete() for 'field_config'.
Chris@0 199 */
Chris@0 200 function comment_field_config_delete(FieldConfigInterface $field) {
Chris@0 201 if ($field->getType() == 'comment') {
Chris@0 202 // Delete all comments that used by the entity bundle.
Chris@0 203 $entity_query = \Drupal::entityQuery('comment');
Chris@0 204 $entity_query->condition('entity_type', $field->getEntityTypeId());
Chris@0 205 $entity_query->condition('field_name', $field->getName());
Chris@0 206 $cids = $entity_query->execute();
Chris@0 207 entity_delete_multiple('comment', $cids);
Chris@0 208 }
Chris@0 209 }
Chris@0 210
Chris@0 211 /**
Chris@0 212 * Implements hook_node_links_alter().
Chris@0 213 */
Chris@0 214 function comment_node_links_alter(array &$links, NodeInterface $node, array &$context) {
Chris@0 215 // Comment links are only added to node entity type for backwards
Chris@0 216 // compatibility. Should you require comment links for other entity types you
Chris@0 217 // can do so by implementing a new field formatter.
Chris@0 218 // @todo Make this configurable from the formatter. See
Chris@0 219 // https://www.drupal.org/node/1901110.
Chris@0 220
Chris@0 221 $comment_links = \Drupal::service('comment.link_builder')->buildCommentedEntityLinks($node, $context);
Chris@0 222 $links += $comment_links;
Chris@0 223 }
Chris@0 224
Chris@0 225 /**
Chris@0 226 * Implements hook_entity_view().
Chris@0 227 */
Chris@0 228 function comment_entity_view(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display, $view_mode) {
Chris@0 229 if ($entity instanceof FieldableEntityInterface && $view_mode == 'rss' && $display->getComponent('links')) {
Chris@0 230 /** @var \Drupal\comment\CommentManagerInterface $comment_manager */
Chris@0 231 $comment_manager = \Drupal::service('comment.manager');
Chris@0 232 $fields = $comment_manager->getFields($entity->getEntityTypeId());
Chris@0 233 foreach ($fields as $field_name => $detail) {
Chris@0 234 if ($entity->hasField($field_name) && $entity->get($field_name)->status != CommentItemInterface::HIDDEN) {
Chris@0 235 // Add a comments RSS element which is a URL to the comments of this
Chris@0 236 // entity.
Chris@0 237 $options = [
Chris@0 238 'fragment' => 'comments',
Chris@0 239 'absolute' => TRUE,
Chris@0 240 ];
Chris@0 241 $entity->rss_elements[] = [
Chris@0 242 'key' => 'comments',
Chris@18 243 'value' => $entity->toUrl('canonical', $options)->toString(),
Chris@0 244 ];
Chris@0 245 }
Chris@0 246 }
Chris@0 247 }
Chris@0 248 }
Chris@0 249
Chris@0 250 /**
Chris@0 251 * Implements hook_ENTITY_TYPE_view_alter() for node entities.
Chris@0 252 */
Chris@0 253 function comment_node_view_alter(array &$build, EntityInterface $node, EntityViewDisplayInterface $display) {
Chris@0 254 if (\Drupal::moduleHandler()->moduleExists('history')) {
Chris@0 255 $build['#attributes']['data-history-node-id'] = $node->id();
Chris@0 256 }
Chris@0 257 }
Chris@0 258
Chris@0 259 /**
Chris@0 260 * Generates an array for rendering a comment.
Chris@0 261 *
Chris@0 262 * @param \Drupal\comment\CommentInterface $comment
Chris@0 263 * The comment object.
Chris@0 264 * @param string $view_mode
Chris@0 265 * (optional) View mode; for instance, 'full', 'teaser', etc. Defaults to
Chris@0 266 * 'full'.
Chris@0 267 * @param string $langcode
Chris@0 268 * (optional) A language code to use for rendering. Defaults to the global
Chris@0 269 * content language of the current request.
Chris@0 270 *
Chris@0 271 * @return array
Chris@16 272 * An array as expected by \Drupal\Core\Render\RendererInterface::render().
Chris@0 273 *
Chris@0 274 * @deprecated in Drupal 8.x and will be removed before Drupal 9.0.
Chris@0 275 * Use \Drupal::entityManager()->getViewBuilder('comment')->view().
Chris@0 276 */
Chris@0 277 function comment_view(CommentInterface $comment, $view_mode = 'full', $langcode = NULL) {
Chris@0 278 return entity_view($comment, $view_mode, $langcode);
Chris@0 279 }
Chris@0 280
Chris@0 281 /**
Chris@0 282 * Constructs render array from an array of loaded comments.
Chris@0 283 *
Chris@0 284 * @param \Drupal\comment\CommentInterface[] $comments
Chris@0 285 * An array of comments as returned by entity_load_multiple().
Chris@0 286 * @param string $view_mode
Chris@0 287 * (optional) View mode; for instance, 'full', 'teaser', etc. Defaults to
Chris@0 288 * 'full'.
Chris@0 289 * @param string $langcode
Chris@0 290 * (optional) A string indicating the language field values are to be shown
Chris@0 291 * in. If no language is provided the current content language is used.
Chris@0 292 * Defaults to NULL.
Chris@0 293 *
Chris@0 294 * @return array
Chris@16 295 * An array in the format expected by
Chris@16 296 * \Drupal\Core\Render\RendererInterface::render().
Chris@0 297 *
Chris@0 298 * @deprecated in Drupal 8.x and will be removed before Drupal 9.0.
Chris@0 299 * Use \Drupal::entityManager()->getViewBuilder('comment')->viewMultiple().
Chris@0 300 *
Chris@16 301 * @see \Drupal\Core\Render\RendererInterface::render()
Chris@0 302 */
Chris@0 303 function comment_view_multiple($comments, $view_mode = 'full', $langcode = NULL) {
Chris@0 304 return entity_view_multiple($comments, $view_mode, $langcode);
Chris@0 305 }
Chris@0 306
Chris@0 307 /**
Chris@0 308 * Implements hook_form_FORM_ID_alter() for field_ui_field_storage_add_form.
Chris@0 309 */
Chris@0 310 function comment_form_field_ui_field_storage_add_form_alter(&$form, FormStateInterface $form_state) {
Chris@0 311 $route_match = \Drupal::routeMatch();
Chris@0 312 if ($form_state->get('entity_type_id') == 'comment' && $route_match->getParameter('commented_entity_type')) {
Chris@0 313 $form['#title'] = \Drupal::service('comment.manager')->getFieldUIPageTitle($route_match->getParameter('commented_entity_type'), $route_match->getParameter('field_name'));
Chris@0 314 }
Chris@0 315 if (!_comment_entity_uses_integer_id($form_state->get('entity_type_id'))) {
Chris@0 316 $optgroup = (string) t('General');
Chris@0 317 // You cannot use comment fields on entity types with non-integer IDs.
Chris@0 318 unset($form['add']['new_storage_type']['#options'][$optgroup]['comment']);
Chris@0 319 }
Chris@0 320 }
Chris@0 321
Chris@0 322 /**
Chris@0 323 * Implements hook_form_FORM_ID_alter().
Chris@0 324 */
Chris@0 325 function comment_form_field_ui_form_display_overview_form_alter(&$form, FormStateInterface $form_state) {
Chris@0 326 $route_match = \Drupal::routeMatch();
Chris@0 327 if ($form['#entity_type'] == 'comment' && $route_match->getParameter('commented_entity_type')) {
Chris@0 328 $form['#title'] = \Drupal::service('comment.manager')->getFieldUIPageTitle($route_match->getParameter('commented_entity_type'), $route_match->getParameter('field_name'));
Chris@0 329 }
Chris@0 330 }
Chris@0 331
Chris@0 332 /**
Chris@0 333 * Implements hook_form_FORM_ID_alter().
Chris@0 334 */
Chris@0 335 function comment_form_field_ui_display_overview_form_alter(&$form, FormStateInterface $form_state) {
Chris@0 336 $route_match = \Drupal::routeMatch();
Chris@0 337 if ($form['#entity_type'] == 'comment' && $route_match->getParameter('commented_entity_type')) {
Chris@0 338 $form['#title'] = \Drupal::service('comment.manager')->getFieldUIPageTitle($route_match->getParameter('commented_entity_type'), $route_match->getParameter('field_name'));
Chris@0 339 }
Chris@0 340 }
Chris@0 341
Chris@0 342 /**
Chris@0 343 * Implements hook_entity_storage_load().
Chris@0 344 *
Chris@0 345 * @see \Drupal\comment\Plugin\Field\FieldType\CommentItem::propertyDefinitions()
Chris@0 346 */
Chris@0 347 function comment_entity_storage_load($entities, $entity_type) {
Chris@0 348 // Comments can only be attached to content entities, so skip others.
Chris@0 349 if (!\Drupal::entityManager()->getDefinition($entity_type)->entityClassImplements(FieldableEntityInterface::class)) {
Chris@0 350 return;
Chris@0 351 }
Chris@0 352 if (!\Drupal::service('comment.manager')->getFields($entity_type)) {
Chris@0 353 // Do not query database when entity has no comment fields.
Chris@0 354 return;
Chris@0 355 }
Chris@0 356 // Load comment information from the database and update the entity's
Chris@0 357 // comment statistics properties, which are defined on each CommentItem field.
Chris@0 358 $result = \Drupal::service('comment.statistics')->read($entities, $entity_type);
Chris@0 359 foreach ($result as $record) {
Chris@0 360 // Skip fields that entity does not have.
Chris@0 361 if (!$entities[$record->entity_id]->hasField($record->field_name)) {
Chris@0 362 continue;
Chris@0 363 }
Chris@0 364 $comment_statistics = $entities[$record->entity_id]->get($record->field_name);
Chris@0 365 $comment_statistics->cid = $record->cid;
Chris@0 366 $comment_statistics->last_comment_timestamp = $record->last_comment_timestamp;
Chris@0 367 $comment_statistics->last_comment_name = $record->last_comment_name;
Chris@0 368 $comment_statistics->last_comment_uid = $record->last_comment_uid;
Chris@0 369 $comment_statistics->comment_count = $record->comment_count;
Chris@0 370 }
Chris@0 371 }
Chris@0 372
Chris@0 373 /**
Chris@0 374 * Implements hook_entity_insert().
Chris@0 375 */
Chris@0 376 function comment_entity_insert(EntityInterface $entity) {
Chris@0 377 // Allow bulk updates and inserts to temporarily disable the
Chris@0 378 // maintenance of the {comment_entity_statistics} table.
Chris@0 379 if (\Drupal::state()->get('comment.maintain_entity_statistics') &&
Chris@0 380 $fields = \Drupal::service('comment.manager')->getFields($entity->getEntityTypeId())) {
Chris@0 381 \Drupal::service('comment.statistics')->create($entity, $fields);
Chris@0 382 }
Chris@0 383 }
Chris@0 384
Chris@0 385 /**
Chris@0 386 * Implements hook_entity_predelete().
Chris@0 387 */
Chris@0 388 function comment_entity_predelete(EntityInterface $entity) {
Chris@0 389 // Entities can have non-numeric IDs, but {comment} and
Chris@0 390 // {comment_entity_statistics} tables have integer columns for entity ID, and
Chris@0 391 // PostgreSQL throws exceptions if you attempt query conditions with
Chris@0 392 // mismatched types. So, we need to verify that the ID is numeric (even for an
Chris@0 393 // entity type that has an integer ID, $entity->id() might be a string
Chris@0 394 // containing a number), and then cast it to an integer when querying.
Chris@0 395 if ($entity instanceof FieldableEntityInterface && is_numeric($entity->id())) {
Chris@0 396 $entity_query = \Drupal::entityQuery('comment');
Chris@0 397 $entity_query->condition('entity_id', (int) $entity->id());
Chris@0 398 $entity_query->condition('entity_type', $entity->getEntityTypeId());
Chris@0 399 $cids = $entity_query->execute();
Chris@0 400 entity_delete_multiple('comment', $cids);
Chris@0 401 \Drupal::service('comment.statistics')->delete($entity);
Chris@0 402 }
Chris@0 403 }
Chris@0 404
Chris@0 405 /**
Chris@0 406 * Determines if an entity type is using an integer-based ID definition.
Chris@0 407 *
Chris@0 408 * @param string $entity_type_id
Chris@0 409 * The ID the represents the entity type.
Chris@0 410 *
Chris@0 411 * @return bool
Chris@0 412 * Returns TRUE if the entity type has an integer-based ID definition and
Chris@0 413 * FALSE otherwise.
Chris@0 414 */
Chris@0 415 function _comment_entity_uses_integer_id($entity_type_id) {
Chris@0 416 $entity_type = \Drupal::entityManager()->getDefinition($entity_type_id);
Chris@0 417 $entity_type_id_key = $entity_type->getKey('id');
Chris@0 418 if ($entity_type_id_key === FALSE) {
Chris@0 419 return FALSE;
Chris@0 420 }
Chris@0 421 $field_definitions = \Drupal::entityManager()->getBaseFieldDefinitions($entity_type->id());
Chris@0 422 $entity_type_id_definition = $field_definitions[$entity_type_id_key];
Chris@0 423 return $entity_type_id_definition->getType() === 'integer';
Chris@0 424 }
Chris@0 425
Chris@0 426 /**
Chris@0 427 * Implements hook_node_update_index().
Chris@0 428 */
Chris@0 429 function comment_node_update_index(EntityInterface $node) {
Chris@0 430 $index_comments = &drupal_static(__FUNCTION__);
Chris@0 431
Chris@0 432 if ($index_comments === NULL) {
Chris@0 433 // Do not index in the following three cases:
Chris@0 434 // 1. 'Authenticated user' can search content but can't access comments.
Chris@0 435 // 2. 'Anonymous user' can search content but can't access comments.
Chris@0 436 // 3. Any role can search content but can't access comments and access
Chris@0 437 // comments is not granted by the 'authenticated user' role. In this case
Chris@0 438 // all users might have both permissions from various roles but it is also
Chris@0 439 // possible to set up a user to have only search content and so a user
Chris@0 440 // edit could change the security situation so it is not safe to index the
Chris@0 441 // comments.
Chris@0 442 $index_comments = TRUE;
Chris@0 443 $roles = \Drupal::entityManager()->getStorage('user_role')->loadMultiple();
Chris@0 444 $authenticated_can_access = $roles[RoleInterface::AUTHENTICATED_ID]->hasPermission('access comments');
Chris@0 445 foreach ($roles as $rid => $role) {
Chris@0 446 if ($role->hasPermission('search content') && !$role->hasPermission('access comments')) {
Chris@0 447 if ($rid == RoleInterface::AUTHENTICATED_ID || $rid == RoleInterface::ANONYMOUS_ID || !$authenticated_can_access) {
Chris@0 448 $index_comments = FALSE;
Chris@0 449 break;
Chris@0 450 }
Chris@0 451 }
Chris@0 452 }
Chris@0 453 }
Chris@0 454
Chris@0 455 $build = [];
Chris@0 456
Chris@0 457 if ($index_comments) {
Chris@0 458 foreach (\Drupal::service('comment.manager')->getFields('node') as $field_name => $info) {
Chris@0 459 // Skip fields that entity does not have.
Chris@0 460 if (!$node->hasField($field_name)) {
Chris@0 461 continue;
Chris@0 462 }
Chris@0 463 $field_definition = $node->getFieldDefinition($field_name);
Chris@0 464 $mode = $field_definition->getSetting('default_mode');
Chris@0 465 $comments_per_page = $field_definition->getSetting('per_page');
Chris@0 466 if ($node->get($field_name)->status) {
Chris@0 467 $comments = \Drupal::entityManager()->getStorage('comment')
Chris@0 468 ->loadThread($node, $field_name, $mode, $comments_per_page);
Chris@0 469 if ($comments) {
Chris@0 470 $build[] = \Drupal::entityManager()->getViewBuilder('comment')->viewMultiple($comments);
Chris@0 471 }
Chris@0 472 }
Chris@0 473 }
Chris@0 474 }
Chris@0 475 return \Drupal::service('renderer')->renderPlain($build);
Chris@0 476 }
Chris@0 477
Chris@0 478 /**
Chris@0 479 * Implements hook_cron().
Chris@0 480 */
Chris@0 481 function comment_cron() {
Chris@0 482 // Store the maximum possible comments per thread (used for node search
Chris@0 483 // ranking by reply count).
Chris@0 484 \Drupal::state()->set('comment.node_comment_statistics_scale', 1.0 / max(1, \Drupal::service('comment.statistics')->getMaximumCount('node')));
Chris@0 485 }
Chris@0 486
Chris@0 487 /**
Chris@0 488 * Implements hook_node_search_result().
Chris@0 489 *
Chris@0 490 * Formats a comment count string and returns it, for display with search
Chris@0 491 * results.
Chris@0 492 */
Chris@0 493 function comment_node_search_result(EntityInterface $node) {
Chris@0 494 $comment_fields = \Drupal::service('comment.manager')->getFields('node');
Chris@0 495 $comments = 0;
Chris@0 496 $open = FALSE;
Chris@0 497 foreach ($comment_fields as $field_name => $info) {
Chris@0 498 // Skip fields that entity does not have.
Chris@0 499 if (!$node->hasField($field_name)) {
Chris@0 500 continue;
Chris@0 501 }
Chris@0 502 // Do not make a string if comments are hidden.
Chris@0 503 $status = $node->get($field_name)->status;
Chris@0 504 if (\Drupal::currentUser()->hasPermission('access comments') && $status != CommentItemInterface::HIDDEN) {
Chris@0 505 if ($status == CommentItemInterface::OPEN) {
Chris@0 506 // At least one comment field is open.
Chris@0 507 $open = TRUE;
Chris@0 508 }
Chris@0 509 $comments += $node->get($field_name)->comment_count;
Chris@0 510 }
Chris@0 511 }
Chris@0 512 // Do not make a string if there are no comment fields, or no comments exist
Chris@0 513 // or all comment fields are hidden.
Chris@0 514 if ($comments > 0 || $open) {
Chris@0 515 return ['comment' => \Drupal::translation()->formatPlural($comments, '1 comment', '@count comments')];
Chris@0 516 }
Chris@0 517 }
Chris@0 518
Chris@0 519 /**
Chris@0 520 * Implements hook_user_cancel().
Chris@0 521 */
Chris@17 522 function comment_user_cancel($edit, UserInterface $account, $method) {
Chris@0 523 switch ($method) {
Chris@0 524 case 'user_cancel_block_unpublish':
Chris@0 525 $comments = entity_load_multiple_by_properties('comment', ['uid' => $account->id()]);
Chris@0 526 foreach ($comments as $comment) {
Chris@17 527 $comment->setUnpublished();
Chris@0 528 $comment->save();
Chris@0 529 }
Chris@0 530 break;
Chris@0 531
Chris@0 532 case 'user_cancel_reassign':
Chris@0 533 /** @var \Drupal\comment\CommentInterface[] $comments */
Chris@0 534 $comments = entity_load_multiple_by_properties('comment', ['uid' => $account->id()]);
Chris@0 535 foreach ($comments as $comment) {
Chris@0 536 $comment->setOwnerId(0);
Chris@0 537 $comment->setAuthorName(\Drupal::config('user.settings')->get('anonymous'));
Chris@0 538 $comment->save();
Chris@0 539 }
Chris@0 540 break;
Chris@0 541 }
Chris@0 542 }
Chris@0 543
Chris@0 544 /**
Chris@0 545 * Implements hook_ENTITY_TYPE_predelete() for user entities.
Chris@0 546 */
Chris@0 547 function comment_user_predelete($account) {
Chris@0 548 $entity_query = \Drupal::entityQuery('comment');
Chris@0 549 $entity_query->condition('uid', $account->id());
Chris@0 550 $cids = $entity_query->execute();
Chris@0 551 entity_delete_multiple('comment', $cids);
Chris@0 552 }
Chris@0 553
Chris@0 554 /**
Chris@0 555 * Generates a comment preview.
Chris@0 556 *
Chris@0 557 * @param \Drupal\comment\CommentInterface $comment
Chris@0 558 * The comment entity to preview.
Chris@0 559 * @param Drupal\Core\Form\FormStateInterface $form_state
Chris@0 560 * The current state of the form.
Chris@0 561 *
Chris@0 562 * @return array
Chris@16 563 * An array as expected by \Drupal\Core\Render\RendererInterface::render().
Chris@0 564 */
Chris@0 565 function comment_preview(CommentInterface $comment, FormStateInterface $form_state) {
Chris@0 566 $preview_build = [];
Chris@0 567 $entity = $comment->getCommentedEntity();
Chris@0 568
Chris@0 569 if (!$form_state->getErrors()) {
Chris@0 570 $comment->in_preview = TRUE;
Chris@0 571 $comment_build = \Drupal::entityTypeManager()->getViewBuilder('comment')->view($comment);
Chris@0 572 $comment_build['#weight'] = -100;
Chris@0 573
Chris@0 574 $preview_build['comment_preview'] = $comment_build;
Chris@0 575 }
Chris@0 576
Chris@0 577 if ($comment->hasParentComment()) {
Chris@0 578 $build = [];
Chris@0 579 $parent = $comment->getParentComment();
Chris@0 580 if ($parent && $parent->isPublished()) {
Chris@0 581 $build = \Drupal::entityTypeManager()->getViewBuilder('comment')->view($parent);
Chris@0 582 }
Chris@0 583 }
Chris@0 584 else {
Chris@0 585 // The comment field output includes rendering the parent entity of the
Chris@0 586 // thread to which the comment is a reply. The rendered entity output
Chris@0 587 // includes the comment reply form, which contains the comment preview and
Chris@0 588 // therefore the rendered parent entity. This results in an infinite loop of
Chris@0 589 // parent entity output rendering the comment form and the comment form
Chris@0 590 // rendering the parent entity. To prevent this infinite loop we temporarily
Chris@0 591 // set the value of the comment field on a clone of the entity to hidden
Chris@0 592 // before calling entity_view(). That way when the output of the commented
Chris@0 593 // entity is rendered, it excludes the comment field output.
Chris@0 594 $field_name = $comment->getFieldName();
Chris@0 595 $entity = clone $entity;
Chris@0 596 $entity->$field_name->status = CommentItemInterface::HIDDEN;
Chris@0 597 $build = entity_view($entity, 'full');
Chris@0 598 }
Chris@0 599
Chris@0 600 $preview_build['comment_output_below'] = $build;
Chris@0 601 $preview_build['comment_output_below']['#weight'] = 100;
Chris@0 602
Chris@0 603 return $preview_build;
Chris@0 604 }
Chris@0 605
Chris@0 606 /**
Chris@0 607 * Implements hook_preprocess_HOOK() for block templates.
Chris@0 608 */
Chris@0 609 function comment_preprocess_block(&$variables) {
Chris@0 610 if ($variables['configuration']['provider'] == 'comment') {
Chris@0 611 $variables['attributes']['role'] = 'navigation';
Chris@0 612 }
Chris@0 613 }
Chris@0 614
Chris@0 615 /**
Chris@0 616 * Prepares variables for comment templates.
Chris@0 617 *
Chris@0 618 * Default template: comment.html.twig.
Chris@0 619 *
Chris@0 620 * @param array $variables
Chris@0 621 * An associative array containing:
Chris@0 622 * - elements: An associative array containing the comment and entity objects.
Chris@0 623 * Array keys: #comment, #commented_entity.
Chris@0 624 */
Chris@0 625 function template_preprocess_comment(&$variables) {
Chris@18 626 /** @var \Drupal\Core\Datetime\DateFormatterInterface $date_formatter */
Chris@18 627 $date_formatter = \Drupal::service('date.formatter');
Chris@0 628 /** @var \Drupal\comment\CommentInterface $comment */
Chris@0 629 $comment = $variables['elements']['#comment'];
Chris@0 630 $commented_entity = $comment->getCommentedEntity();
Chris@0 631 $variables['comment'] = $comment;
Chris@0 632 $variables['commented_entity'] = $commented_entity;
Chris@0 633 $variables['threaded'] = $variables['elements']['#comment_threaded'];
Chris@0 634
Chris@0 635 $account = $comment->getOwner();
Chris@0 636 $username = [
Chris@0 637 '#theme' => 'username',
Chris@0 638 '#account' => $account,
Chris@0 639 ];
Chris@0 640 $variables['author'] = \Drupal::service('renderer')->render($username);
Chris@0 641 $variables['author_id'] = $comment->getOwnerId();
Chris@0 642 $variables['new_indicator_timestamp'] = $comment->getChangedTime();
Chris@18 643 $variables['created'] = $date_formatter->format($comment->getCreatedTime());
Chris@18 644 // Avoid calling DateFormatterInterface::format() twice on the same timestamp.
Chris@0 645 if ($comment->getChangedTime() == $comment->getCreatedTime()) {
Chris@0 646 $variables['changed'] = $variables['created'];
Chris@0 647 }
Chris@0 648 else {
Chris@18 649 $variables['changed'] = $date_formatter->format($comment->getChangedTime());
Chris@0 650 }
Chris@0 651
Chris@0 652 if (theme_get_setting('features.comment_user_picture')) {
Chris@0 653 // To change user picture settings (for instance, image style), edit the
Chris@0 654 // 'compact' view mode on the User entity.
Chris@0 655 $variables['user_picture'] = user_view($account, 'compact');
Chris@0 656 }
Chris@0 657 else {
Chris@0 658 $variables['user_picture'] = [];
Chris@0 659 }
Chris@0 660
Chris@0 661 if (isset($comment->in_preview)) {
Chris@0 662 $variables['title'] = \Drupal::l($comment->getSubject(), new Url('<front>'));
Chris@0 663 $variables['permalink'] = \Drupal::l(t('Permalink'), new Url('<front>'));
Chris@0 664 }
Chris@0 665 else {
Chris@0 666 $uri = $comment->permalink();
Chris@0 667 $attributes = $uri->getOption('attributes') ?: [];
Chris@0 668 $attributes += ['class' => ['permalink'], 'rel' => 'bookmark'];
Chris@0 669 $uri->setOption('attributes', $attributes);
Chris@0 670 $variables['title'] = \Drupal::l($comment->getSubject(), $uri);
Chris@0 671
Chris@0 672 $variables['permalink'] = \Drupal::l(t('Permalink'), $comment->permalink());
Chris@0 673 }
Chris@0 674
Chris@0 675 $variables['submitted'] = t('Submitted by @username on @datetime', ['@username' => $variables['author'], '@datetime' => $variables['created']]);
Chris@0 676
Chris@0 677 if ($comment->hasParentComment()) {
Chris@0 678 // Fetch and store the parent comment information for use in templates.
Chris@0 679 $comment_parent = $comment->getParentComment();
Chris@0 680 $account_parent = $comment_parent->getOwner();
Chris@0 681 $variables['parent_comment'] = $comment_parent;
Chris@0 682 $username = [
Chris@0 683 '#theme' => 'username',
Chris@0 684 '#account' => $account_parent,
Chris@0 685 ];
Chris@0 686 $variables['parent_author'] = \Drupal::service('renderer')->render($username);
Chris@18 687 $variables['parent_created'] = $date_formatter->format($comment_parent->getCreatedTime());
Chris@18 688 // Avoid calling DateFormatterInterface::format() twice on same timestamp.
Chris@0 689 if ($comment_parent->getChangedTime() == $comment_parent->getCreatedTime()) {
Chris@0 690 $variables['parent_changed'] = $variables['parent_created'];
Chris@0 691 }
Chris@0 692 else {
Chris@18 693 $variables['parent_changed'] = $date_formatter->format($comment_parent->getChangedTime());
Chris@0 694 }
Chris@0 695 $permalink_uri_parent = $comment_parent->permalink();
Chris@0 696 $attributes = $permalink_uri_parent->getOption('attributes') ?: [];
Chris@0 697 $attributes += ['class' => ['permalink'], 'rel' => 'bookmark'];
Chris@0 698 $permalink_uri_parent->setOption('attributes', $attributes);
Chris@0 699 $variables['parent_title'] = \Drupal::l($comment_parent->getSubject(), $permalink_uri_parent);
Chris@0 700 $variables['parent_permalink'] = \Drupal::l(t('Parent permalink'), $permalink_uri_parent);
Chris@0 701 $variables['parent'] = t('In reply to @parent_title by @parent_username',
Chris@0 702 ['@parent_username' => $variables['parent_author'], '@parent_title' => $variables['parent_title']]);
Chris@0 703 }
Chris@0 704 else {
Chris@0 705 $variables['parent_comment'] = '';
Chris@0 706 $variables['parent_author'] = '';
Chris@0 707 $variables['parent_created'] = '';
Chris@0 708 $variables['parent_changed'] = '';
Chris@0 709 $variables['parent_title'] = '';
Chris@0 710 $variables['parent_permalink'] = '';
Chris@0 711 $variables['parent'] = '';
Chris@0 712 }
Chris@0 713
Chris@0 714 // Helpful $content variable for templates.
Chris@0 715 foreach (Element::children($variables['elements']) as $key) {
Chris@0 716 $variables['content'][$key] = $variables['elements'][$key];
Chris@0 717 }
Chris@0 718
Chris@0 719 // Set status to a string representation of comment->status.
Chris@0 720 if (isset($comment->in_preview)) {
Chris@0 721 $variables['status'] = 'preview';
Chris@0 722 }
Chris@0 723 else {
Chris@0 724 $variables['status'] = $comment->isPublished() ? 'published' : 'unpublished';
Chris@0 725 }
Chris@0 726
Chris@0 727 // Add comment author user ID. Necessary for the comment-by-viewer library.
Chris@0 728 $variables['attributes']['data-comment-user-id'] = $comment->getOwnerId();
Chris@18 729 // Add anchor for each comment.
Chris@18 730 $variables['attributes']['id'] = 'comment-' . $comment->id();
Chris@0 731 }
Chris@0 732
Chris@0 733 /**
Chris@0 734 * Prepares variables for comment field templates.
Chris@0 735 *
Chris@0 736 * Default template: field--comment.html.twig.
Chris@0 737 *
Chris@0 738 * @param array $variables
Chris@0 739 * An associative array containing:
Chris@0 740 * - element: An associative array containing render arrays for the list of
Chris@0 741 * comments, and the comment form. Array keys: comments, comment_form.
Chris@0 742 *
Chris@0 743 * @todo Rename to template_preprocess_field__comment() once
Chris@0 744 * https://www.drupal.org/node/939462 is resolved.
Chris@0 745 */
Chris@0 746 function comment_preprocess_field(&$variables) {
Chris@0 747 $element = $variables['element'];
Chris@0 748 if ($element['#field_type'] == 'comment') {
Chris@0 749 // Provide contextual information.
Chris@0 750 $variables['comment_display_mode'] = $element[0]['#comment_display_mode'];
Chris@0 751 $variables['comment_type'] = $element[0]['#comment_type'];
Chris@0 752
Chris@0 753 // Append additional attributes (eg. RDFa) from the first field item.
Chris@0 754 $variables['attributes'] += $variables['items'][0]['attributes']->storage();
Chris@0 755
Chris@0 756 // Create separate variables for the comments and comment form.
Chris@0 757 $variables['comments'] = $element[0]['comments'];
Chris@0 758 $variables['comment_form'] = $element[0]['comment_form'];
Chris@0 759 }
Chris@0 760 }
Chris@0 761
Chris@0 762 /**
Chris@0 763 * Implements hook_ranking().
Chris@0 764 */
Chris@0 765 function comment_ranking() {
Chris@0 766 return \Drupal::service('comment.statistics')->getRankingInfo();
Chris@0 767 }
Chris@0 768
Chris@0 769 /**
Chris@0 770 * Implements hook_ENTITY_TYPE_presave() for entity_view_display entities.
Chris@0 771 */
Chris@0 772 function comment_entity_view_display_presave(EntityViewDisplayInterface $display) {
Chris@0 773 // Act only on comment view displays being disabled.
Chris@0 774 if ($display->isNew() || $display->getTargetEntityTypeId() !== 'comment' || $display->status()) {
Chris@0 775 return;
Chris@0 776 }
Chris@0 777 $storage = \Drupal::entityTypeManager()->getStorage('entity_view_display');
Chris@0 778 if (!$storage->loadUnchanged($display->getOriginalId())->status()) {
Chris@0 779 return;
Chris@0 780 }
Chris@0 781
Chris@0 782 // Disable the comment field formatter when the used view display is disabled.
Chris@0 783 foreach ($storage->loadMultiple() as $id => $view_display) {
Chris@0 784 $changed = FALSE;
Chris@0 785 /** @var \Drupal\Core\Entity\Display\EntityViewDisplayInterface $view_display */
Chris@0 786 foreach ($view_display->getComponents() as $field => $component) {
Chris@0 787 if (isset($component['type']) && ($component['type'] === 'comment_default')) {
Chris@0 788 if ($component['settings']['view_mode'] === $display->getMode()) {
Chris@0 789 $view_display->removeComponent($field);
Chris@0 790 /** @var \Drupal\Core\Entity\EntityViewModeInterface $mode */
Chris@0 791 $mode = EntityViewMode::load($display->getTargetEntityTypeId() . '.' . $display->getMode());
Chris@0 792 $arguments = [
Chris@0 793 '@id' => $view_display->id(),
Chris@0 794 '@name' => $field,
Chris@0 795 '@display' => $mode->label(),
Chris@0 796 '@mode' => $display->getMode(),
Chris@0 797 ];
Chris@0 798 \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);
Chris@0 799 $changed = TRUE;
Chris@0 800 }
Chris@0 801 }
Chris@0 802 }
Chris@0 803 if ($changed) {
Chris@0 804 $view_display->save();
Chris@0 805 }
Chris@0 806 }
Chris@0 807 }