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

Dries's avatar
Dries committed
3 4
/**
 * @file
Dries's avatar
 
Dries committed
5
 * Enables users to comment on published content.
Dries's avatar
Dries committed
6
 *
7
 * 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\Comment;
15
use Drupal\comment\CommentManagerInterface;
16
use Drupal\comment\Entity\CommentType;
17
use Drupal\Core\Entity\FieldableEntityInterface;
18 19
use Drupal\comment\Plugin\Field\FieldType\CommentItemInterface;
use Drupal\Core\Entity\EntityInterface;
20
use Drupal\Core\Form\FormStateInterface;
21
use Drupal\Core\Routing\RouteMatchInterface;
22
use Drupal\Core\Entity\Entity\EntityViewDisplay;
23
use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
24
use Drupal\Core\Field\FieldDefinitionInterface;
25
use Drupal\Core\Render\Element;
26
use Drupal\Core\Url;
27
use Drupal\field\Entity\FieldStorageConfig;
28
use Drupal\field\FieldConfigInterface;
29
use Drupal\field\FieldStorageConfigInterface;
30
use Drupal\file\FileInterface;
31
use Drupal\user\EntityOwnerInterface;
32
use Drupal\node\NodeInterface;
33
use Drupal\user\RoleInterface;
34

Dries's avatar
Dries committed
35
/**
36
 * Anonymous posters cannot enter their contact information.
Dries's avatar
Dries committed
37
 */
38
const COMMENT_ANONYMOUS_MAYNOT_CONTACT = 0;
39 40 41 42

/**
 * Anonymous posters may leave their contact information.
 */
43
const COMMENT_ANONYMOUS_MAY_CONTACT = 1;
44 45

/**
46
 * Anonymous posters are required to leave their contact information.
47
 */
48
const COMMENT_ANONYMOUS_MUST_CONTACT = 2;
Dries's avatar
Dries committed
49

50 51 52 53 54 55 56
/**
 * 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.
 *
57
 * @todo Remove when https://www.drupal.org/node/1029708 lands.
58 59
 */
define('COMMENT_NEW_LIMIT', REQUEST_TIME - 30 * 24 * 60 * 60);
60

61
/**
62
 * Implements hook_help().
63
 */
64
function comment_help($route_name, RouteMatchInterface $route_match) {
65 66
  switch ($route_name) {
    case 'help.page.comment':
67
      $output = '<h3>' . t('About') . '</h3>';
68
      $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>.', array('!comment' => 'https://www.drupal.org/documentation/modules/comment')) . '</p>';
69 70
      $output .= '<h3>' . t('Uses') . '</h3>';
      $output .= '<dl>';
71 72 73 74
      $output .= '<dt>' . t('Enabling commenting') . '</dt>';
      $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>.', array('!content-type' => (\Drupal::moduleHandler()->moduleExists('node')) ? \Drupal::url('entity.node_type.collection') : '#', '!field' => \Drupal::url('help.page', array('name' => 'field')), '!field_ui' => (\Drupal::moduleHandler()->moduleExists('field_ui')) ? \Drupal::url('help.page', array('name' => 'field_ui')) : '#')) . '</dd>';
      $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>';
75
      $output .= '<dt>' . t('Overriding default settings') . '</dt>';
76
      $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>';
77 78
      $output .= '<dt>' . t('Approving and managing comments') . '</dt>';
      $output .= '<dd>' . t('Comments from users who have the <em>Skip comment approval</em> permission are published immediately. All other comments are placed in the <a href="!comment-approval">Unapproved comments</a> queue, until a user who has permission to <em>Administer comments 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.', array('!comment-approval' => \Drupal::url('comment.admin_approval'), '!admin-comment' => \Drupal::url('comment.admin'))) . '</dd>';
79
      $output .= '</dl>';
80
      return $output;
81

82
    case 'entity.comment_type.collection':
83
      $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>';
84
      return $output;
85
  }
Dries's avatar
 
Dries committed
86 87
}

88
/**
89
 * Entity URI callback.
90
 */
91
function comment_uri(CommentInterface $comment) {
92
  return new Url(
93
    'entity.comment.canonical',
94
    array(
95 96
      'comment' => $comment->id(),
    ),
97
    array('fragment' => 'comment-' . $comment->id())
98
  );
99 100
}

101
/**
102
 * Implements hook_entity_extra_field_info().
103
 */
104
function comment_entity_extra_field_info() {
105
  $return = array();
106
  foreach (CommentType::loadMultiple() as $comment_type) {
107
    $return['comment'][$comment_type->id()] = array(
108 109 110 111 112
      'form' => array(
        'author' => array(
          'label' => t('Author'),
          'description' => t('Author textfield'),
          'weight' => -2,
113
        ),
114 115
      ),
    );
116 117 118 119 120 121
    $return['comment'][$comment_type->id()]['display']['links'] = array(
      'label' => t('Links'),
      'description' => t('Comment operation links'),
      'weight' => 100,
      'visible' => TRUE,
    );
122 123 124 125 126
  }

  return $return;
}

127
/**
128
 * Implements hook_theme().
129 130 131 132
 */
function comment_theme() {
  return array(
    'comment' => array(
133
      'render element' => 'elements',
134
    ),
135 136
    'field__comment' => array(
      'base hook' => 'field',
137 138 139 140
    ),
  );
}

141
/**
142
 * Implements hook_ENTITY_TYPE_create() for 'field_config'.
143
 */
144 145 146
function comment_field_config_create(FieldConfigInterface $field) {
  if ($field->getType() == 'comment' && !$field->isSyncing()) {
    // Assign default values for the field.
147 148 149
    $default_value = $field->getDefaultValueLiteral();
    $default_value += array(array());
    $default_value[0] += array(
150
      'status' => CommentItemInterface::OPEN,
151 152 153 154 155
      'cid' => 0,
      'last_comment_timestamp' => 0,
      'last_comment_name' => '',
      'last_comment_uid' => 0,
      'comment_count' => 0,
156
    );
157
    $field->setDefaultValue($default_value);
158
  }
159
}
160

161
/**
162
 * Implements hook_ENTITY_TYPE_update() for 'field_config'.
163
 */
164 165
function comment_field_config_update(FieldConfigInterface $field) {
  if ($field->getType() == 'comment') {
166 167 168
    // Comment field settings also affects the rendering of *comment* entities,
    // not only the *commented* entities.
    \Drupal::entityManager()->getViewBuilder('comment')->resetCache();
169 170
  }
}
171

172
/**
173
 * Implements hook_ENTITY_TYPE_insert() for 'field_storage_config'.
174
 */
175 176
function comment_field_storage_config_insert(FieldStorageConfigInterface $field_storage) {
  if ($field_storage->getType() == 'comment') {
177
    // Check that the target entity type uses an integer ID.
178
    $entity_type_id = $field_storage->getTargetEntityTypeId();
179 180 181
    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');
    }
182 183 184
  }
}

185
/**
186
 * Implements hook_ENTITY_TYPE_delete() for 'field_config'.
187
 */
188 189
function comment_field_config_delete(FieldConfigInterface $field) {
  if ($field->getType() == 'comment') {
190
    // Delete all comments that used by the entity bundle.
191
    $entity_query = \Drupal::entityQuery('comment');
192 193
    $entity_query->condition('entity_type', $field->getEntityTypeId());
    $entity_query->condition('field_name', $field->getName());
194 195
    $cids = $entity_query->execute();
    entity_delete_multiple('comment', $cids);
196
  }
197 198
}

Dries's avatar
 
Dries committed
199
/**
200
 * Implements hook_node_links_alter().
Dries's avatar
 
Dries committed
201
 */
202 203 204 205
function comment_node_links_alter(array &$node_links, NodeInterface $node, array &$context) {
  // 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.
206 207
  // @todo Make this configurable from the formatter. See
  //   https://www.drupal.org/node/1901110.
208

209 210
  $links = \Drupal::service('comment.link_builder')->buildCommentedEntityLinks($node, $context);
  $node_links += $links;
Dries's avatar
 
Dries committed
211 212
}

213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
/**
 * Implements hook_entity_view().
 */
function comment_entity_view(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display, $view_mode, $langcode) {
  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.
        $options = array(
          'fragment' => 'comments',
          'absolute' => TRUE,
        );
        $entity->rss_elements[] = array(
          'key' => 'comments',
          'value' => $entity->url('canonical', $options),
        );
      }
    }
  }
}

238
/**
239
 * Implements hook_ENTITY_TYPE_view_alter() for node entities.
240
 */
241
function comment_node_view_alter(array &$build, EntityInterface $node, EntityViewDisplayInterface $display) {
242
  if (\Drupal::moduleHandler()->moduleExists('history')) {
243 244 245 246
    $build['#attributes']['data-history-node-id'] = $node->id();
  }
}

247
/**
248
 * Generates an array for rendering a comment.
249
 *
250
 * @param \Drupal\comment\CommentInterface $comment
251
 *   The comment object.
252
 * @param $view_mode
253
 *   (optional) View mode; e.g., 'full', 'teaser', etc. Defaults to 'full'.
254 255 256
 * @param $langcode
 *   (optional) A language code to use for rendering. Defaults to the global
 *   content language of the current request.
257
 *
258
 * @return array
259
 *   An array as expected by drupal_render().
260 261 262
 *
 * @deprecated in Drupal 8.x and will be removed before Drupal 9.0.
 *   Use \Drupal::entityManager()->getViewBuilder('comment')->view().
263
 */
264
function comment_view(CommentInterface $comment, $view_mode = 'full', $langcode = NULL) {
265
  return entity_view($comment, $view_mode, $langcode);
266 267 268
}

/**
269
 * Constructs render array from an array of loaded comments.
270 271
 *
 * @param $comments
272
 *   An array of comments as returned by entity_load_multiple().
273
 * @param $view_mode
274
 *   View mode; e.g., 'full', 'teaser', etc.
275
 * @param $langcode
276 277 278
 *   (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.
279
 *
280
 * @return array
281
 *   An array in the format expected by drupal_render().
282
 *
283 284 285
 * @deprecated in Drupal 8.x and will be removed before Drupal 9.0.
 *   Use \Drupal::entityManager()->getViewBuilder('comment')->viewMultiple().
 *
286
 * @see drupal_render()
287
 */
288 289
function comment_view_multiple($comments, $view_mode = 'full', $langcode = NULL) {
  return entity_view_multiple($comments, $view_mode, $langcode);
290 291
}

292
/**
293
 * Implements hook_form_FORM_ID_alter() for field_ui_field_storage_add_form.
294
 */
295
function comment_form_field_ui_field_storage_add_form_alter(&$form, FormStateInterface $form_state) {
296 297 298
  $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'));
299
  }
300
  if (!_comment_entity_uses_integer_id($form_state->get('entity_type_id'))) {
301 302 303
    // We cast the optgroup label to string as array keys must not be objects
    // and t() will return a TranslationWrapper once issue #2557113 lands.
    $optgroup = (string) t('General');
304
    // You cannot use comment fields on entity types with non-integer IDs.
305
    unset($form['add']['new_storage_type']['#options'][$optgroup]['comment']);
306
  }
307 308
}

309
/**
310
 * Implements hook_form_FORM_ID_alter().
311
 */
312
function comment_form_field_ui_form_display_overview_form_alter(&$form, FormStateInterface $form_state) {
313 314 315
  $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'));
316 317 318
  }
}

Dries's avatar
 
Dries committed
319
/**
320
 * Implements hook_form_FORM_ID_alter().
Dries's avatar
 
Dries committed
321
 */
322
function comment_form_field_ui_display_overview_form_alter(&$form, FormStateInterface $form_state) {
323 324 325
  $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'));
326
  }
327
}
328

329
/**
330
 * Implements hook_form_FORM_ID_alter() for 'field_storage_config_edit_form'.
331
 */
332 333
function comment_form_field_storage_config_edit_form_alter(&$form, FormStateInterface $form_state) {
  if ($form_state->getFormObject()->getEntity()->getType() == 'comment') {
334 335
    // We only support posting one comment at the time so it doesn't make sense
    // to let the site builder choose anything else.
336 337
    $form['cardinality_container']['cardinality']['#default_value'] = 1;
    $form['cardinality_container']['#access'] = FALSE;
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)->isSubclassOf('Drupal\Core\Entity\FieldableEntityInterface')) {
349 350
    return;
  }
351 352
  // @todo Investigate in https://www.drupal.org/node/2527866 why we need that.
  if (!\Drupal::hasService('comment.manager') || !\Drupal::service('comment.manager')->getFields($entity_type)) {
353 354 355
    // Do not query database when entity has no comment fields.
    return;
  }
356 357 358
  // 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);
359
  foreach ($result as $record) {
360
    // Skip fields that entity does not have.
361
    if (!$entities[$record->entity_id]->hasField($record->field_name)) {
362 363
      continue;
    }
364
    $comment_statistics = $entities[$record->entity_id]->get($record->field_name);
365 366 367 368 369
    $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;
370 371
  }
}
372

373
/**
374
 * Implements hook_entity_insert().
375
 */
376
function comment_entity_insert(EntityInterface $entity) {
377
  // Allow bulk updates and inserts to temporarily disable the
378 379
  // maintenance of the {comment_entity_statistics} table.
  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);
382
  }
383
}
384

385
/**
386
 * Implements hook_entity_predelete().
387
 */
388
function comment_entity_predelete(EntityInterface $entity) {
389 390 391 392 393 394
  // 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.
395
  if ($entity instanceof FieldableEntityInterface && is_numeric($entity->id())) {
396 397 398 399
    $entity_query = \Drupal::entityQuery('comment');
    $entity_query->condition('entity_id', (int) $entity->id());
    $entity_query->condition('entity_type', $entity->getEntityTypeId());
    $cids = $entity_query->execute();
400
    entity_delete_multiple('comment', $cids);
401
    \Drupal::service('comment.statistics')->delete($entity);
402
  }
403
}
404

405 406 407 408 409 410 411 412 413 414 415 416 417
/**
 * 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');
418 419 420
  if ($entity_type_id_key === FALSE) {
    return FALSE;
  }
421 422 423 424 425
  $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';
}

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

  if ($index_comments === NULL) {
433 434 435 436 437 438 439 440 441
    // 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.
442
    $index_comments = TRUE;
443
    $roles = \Drupal::entityManager()->getStorage('user_role')->loadMultiple();
444
    $authenticated_can_access = $roles[RoleInterface::AUTHENTICATED_ID]->hasPermission('access comments');
445 446
    foreach ($roles as $rid => $role) {
      if ($role->hasPermission('search content') && !$role->hasPermission('access comments')) {
447
        if ($rid == RoleInterface::AUTHENTICATED_ID || $rid == RoleInterface::ANONYMOUS_ID || !$authenticated_can_access) {
448 449 450
          $index_comments = FALSE;
          break;
        }
451 452 453 454
      }
    }
  }

455
  $build = array();
456

457
  if ($index_comments) {
458 459
    foreach (\Drupal::service('comment.manager')->getFields('node') as $field_name => $info) {
      // Skip fields that entity does not have.
460
      if (!$node->hasField($field_name)) {
461 462
        continue;
      }
463 464 465
      $field_definition = $node->getFieldDefinition($field_name);
      $mode = $field_definition->getSetting('default_mode');
      $comments_per_page = $field_definition->getSetting('per_page');
466 467 468 469 470 471
      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);
        }
472
      }
473
    }
474
  }
475
  return \Drupal::service('renderer')->renderPlain($build);
476
}
477

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

487
/**
488
 * Implements hook_node_search_result().
489 490 491
 *
 * Formats a comment count string and returns it, for display with search
 * results.
492
 */
493
function comment_node_search_result(EntityInterface $node) {
494 495 496 497 498
  $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.
499
    if (!$node->hasField($field_name)) {
500 501 502 503
      continue;
    }
    // Do not make a string if comments are hidden.
    $status = $node->get($field_name)->status;
504 505
    if (\Drupal::currentUser()->hasPermission('access comments') && $status != CommentItemInterface::HIDDEN) {
      if ($status == CommentItemInterface::OPEN) {
506 507 508 509
        // At least one comment field is open.
        $open = TRUE;
      }
      $comments += $node->get($field_name)->comment_count;
510
    }
511
  }
512 513 514
  // 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) {
515
    return array('comment' => \Drupal::translation()->formatPlural($comments, '1 comment', '@count comments'));
516
  }
517
}
518

Dries's avatar
 
Dries committed
519
/**
520
 * Implements hook_user_cancel().
Dries's avatar
 
Dries committed
521
 */
522
function comment_user_cancel($edit, $account, $method) {
523 524
  switch ($method) {
    case 'user_cancel_block_unpublish':
525
      $comments = entity_load_multiple_by_properties('comment', array('uid' => $account->id()));
526
      foreach ($comments as $comment) {
527
        $comment->setPublished(CommentInterface::NOT_PUBLISHED);
528
        $comment->save();
529
      }
530 531 532
      break;

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

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

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

569
  if (!$form_state->getErrors()) {
570
    // Attach the user and time information.
571 572 573
    $author_name = $comment->getAuthorName();
    if (!empty($author_name)) {
      $account = user_load_by_name($author_name);
574
    }
575 576
    elseif (\Drupal::currentUser()->isAuthenticated() && empty($comment->is_anonymous)) {
      $account = \Drupal::currentUser();
577
    }
578

579
    if (!empty($account) && $account->isAuthenticated()) {
580
      $comment->setOwner($account);
581
      $comment->setAuthorName($account->getUsername());
582
    }
583 584
    elseif (empty($author_name)) {
      $comment->setAuthorName(\Drupal::config('user.settings')->get('anonymous'));
585
    }
586

587 588
    $created_time = !is_null($comment->getCreatedTime()) ? $comment->getCreatedTime() : REQUEST_TIME;
    $comment->setCreatedTime($created_time);
589
    $comment->changed->value = REQUEST_TIME;
590
    $comment->in_preview = TRUE;
591
    $comment_build = comment_view($comment);
592
    $comment_build['#weight'] = -100;
593

594
    $preview_build['comment_preview'] = $comment_build;
595
  }
596

597
  if ($comment->hasParentComment()) {
598
    $build = array();
599 600
    $parent = $comment->getParentComment();
    if ($parent && $parent->isPublished()) {
601
      $build = comment_view($parent);
602
    }
603 604
  }
  else {
605 606 607 608 609 610
    // 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
611
    // set the value of the comment field on a clone of the entity to hidden
612
    // before calling entity_view(). That way when the output of the commented
613
    // entity is rendered, it excludes the comment field output.
614
    $field_name = $comment->getFieldName();
615 616
    $entity = clone $entity;
    $entity->$field_name->status = CommentItemInterface::HIDDEN;
617
    $build = entity_view($entity, 'full');
618 619
  }

620 621
  $preview_build['comment_output_below'] = $build;
  $preview_build['comment_output_below']['#weight'] = 100;
622

623
  return $preview_build;
624 625
}

626
/**
627
 * Implements hook_preprocess_HOOK() for block templates.
628 629
 */
function comment_preprocess_block(&$variables) {
630
  if ($variables['configuration']['provider'] == 'comment') {
631
    $variables['attributes']['role'] = 'navigation';
632 633 634
  }
}

635
/**
636
 * Prepares variables for comment templates.
637
 *
638 639 640 641
 * Default template: comment.html.twig.
 *
 * @param array $variables
 *   An associative array containing:
642 643
 *   - elements: An associative array containing the comment and entity objects.
 *     Array keys: #comment, #commented_entity.
644 645
 */
function template_preprocess_comment(&$variables) {
646
  /** @var \Drupal\comment\CommentInterface $comment */
647
  $comment = $variables['elements']['#comment'];
648
  $commented_entity = $comment->getCommentedEntity();
649
  $variables['comment'] = $comment;
650
  $variables['commented_entity'] = $commented_entity;
651
  $variables['threaded'] = $variables['elements']['#comment_threaded'];
652

653
  $account = $comment->getOwner();
654 655 656 657 658
  $username = array(
    '#theme' => 'username',
    '#account' => $account,
  );
  $variables['author'] = drupal_render($username);
659
  $variables['author_id'] = $comment->getOwnerId();
660 661
  $variables['new_indicator_timestamp'] = $comment->getChangedTime();
  $variables['created'] = format_date($comment->getCreatedTime());
662
  // Avoid calling format_date() twice on the same timestamp.
663
  if ($comment->getChangedTime() == $comment->getCreatedTime()) {
664 665 666
    $variables['changed'] = $variables['created'];
  }
  else {
667
    $variables['changed'] = format_date($comment->getChangedTime());
668
  }
669

670
  if (theme_get_setting('features.comment_user_picture')) {
671 672
    // To change user picture settings (e.g., image style), edit the 'compact'
    // view mode on the User entity.
673
    $variables['user_picture'] = user_view($account, 'compact');
674 675 676 677
  }
  else {
    $variables['user_picture'] = array();
  }
678

679
  if (isset($comment->in_preview)) {
680 681
    $variables['title'] = \Drupal::l($comment->getSubject(), new Url('<front>'));
    $variables['permalink'] = \Drupal::l(t('Permalink'), new Url('<front>'));
682 683 684
  }
  else {
    $uri = $comment->urlInfo();
685 686 687
    $attributes = $uri->getOption('attributes') ?: array();
    $attributes += array('class' => array('permalink'), 'rel' => 'bookmark');
    $uri->setOption('attributes', $attributes);
688
    $variables['title'] = \Drupal::l($comment->getSubject(), $uri);
689

690
    $variables['permalink'] = \Drupal::l(t('Permalink'), $comment->permalink());
691
  }
692

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

695
  if ($comment->hasParentComment()) {
696
    // Fetch and store the parent comment information for use in templates.
697
    $comment_parent = $comment->getParentComment();
698
    $account_parent = $comment_parent->getOwner();
699
    $variables['parent_comment'] = $comment_parent;
700 701 702 703 704
    $username = array(
      '#theme' => 'username',
      '#account' => $account_parent,
    );
    $variables['parent_author'] = drupal_render($username);
705
    $variables['parent_created'] = format_date($comment_parent->getCreatedTime());
706
    // Avoid calling format_date() twice on the same timestamp.
707
    if ($comment_parent->getChangedTime() == $comment_parent->getCreatedTime()) {
708 709 710
      $variables['parent_changed'] = $variables['parent_created'];
    }
    else {
711
      $variables['parent_changed'] = format_date($comment_parent->getChangedTime());
712
    }
713
    $permalink_uri_parent = $comment_parent->permalink();
714 715 716
    $attributes = $permalink_uri_parent->getOption('attributes') ?: array();
    $attributes += array('class' => array('permalink'), 'rel' => 'bookmark');
    $permalink_uri_parent->setOption('attributes', $attributes);
717 718
    $variables['parent_title'] = \Drupal::l($comment_parent->getSubject(), $permalink_uri_parent);
    $variables['parent_permalink'] = \Drupal::l(t('Parent permalink'), $permalink_uri_parent);
719 720
    $variables['parent'] = t('In reply to @parent_title by @parent_username',
        array('@parent_username' => $variables['parent_author'], '@parent_title' => $variables['parent_title']));
721 722 723 724 725 726 727 728 729 730 731
  }
  else {
    $variables['parent_comment'] = '';
    $variables['parent_author'] = '';
    $variables['parent_created'] = '';
    $variables['parent_changed'] = '';
    $variables['parent_title'] = '';
    $variables['parent_permalink'] = '';
    $variables['parent'] = '';
  }

732
  // Helpful $content variable for templates.
733
  foreach (Element::children($variables['elements']) as $key) {