1. 8.3.x core/modules/comment/comment.module
  2. 8.0.x core/modules/comment/comment.module
  3. 8.1.x core/modules/comment/comment.module
  4. 8.2.x core/modules/comment/comment.module
  5. 8.4.x core/modules/comment/comment.module
  6. 4.6.x modules/comment.module
  7. 4.7.x modules/comment.module
  8. 5.x modules/comment/comment.module
  9. 6.x modules/comment/comment.module
  10. 7.x modules/comment/comment.module

Enables users to comment on published content.

When installed, the Comment module creates a field that facilitates a discussion board for each Drupal entity to which a comment field is attached. Users can post comments to discuss a forum topic, story, collaborative book page, user etc.

File

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

Functions

Namesort descending Description
comment_cron Implements hook_cron().
comment_entity_extra_field_info Implements hook_entity_extra_field_info().
comment_entity_insert Implements hook_entity_insert().
comment_entity_predelete Implements hook_entity_predelete().
comment_entity_storage_load Implements hook_entity_storage_load().
comment_entity_view Implements hook_entity_view().
comment_entity_view_display_presave Implements hook_ENTITY_TYPE_presave() for entity_view_display entities.
comment_field_config_create Implements hook_ENTITY_TYPE_create() for 'field_config'.
comment_field_config_delete Implements hook_ENTITY_TYPE_delete() for 'field_config'.
comment_field_config_update Implements hook_ENTITY_TYPE_update() for 'field_config'.
comment_field_storage_config_insert Implements hook_ENTITY_TYPE_insert() for 'field_storage_config'.
comment_form_field_storage_config_edit_form_alter Implements hook_form_FORM_ID_alter() for 'field_storage_config_edit_form'.
comment_form_field_ui_display_overview_form_alter Implements hook_form_FORM_ID_alter().
comment_form_field_ui_field_storage_add_form_alter Implements hook_form_FORM_ID_alter() for field_ui_field_storage_add_form.
comment_form_field_ui_form_display_overview_form_alter Implements hook_form_FORM_ID_alter().
comment_help Implements hook_help().
comment_node_links_alter Implements hook_node_links_alter().
comment_node_search_result Implements hook_node_search_result().
comment_node_update_index Implements hook_node_update_index().
comment_node_view_alter Implements hook_ENTITY_TYPE_view_alter() for node entities.
comment_preprocess_block Implements hook_preprocess_HOOK() for block templates.
comment_preprocess_field Prepares variables for comment field templates.
comment_preview Generates a comment preview.
comment_ranking Implements hook_ranking().
comment_theme Implements hook_theme().
comment_uri Entity URI callback.
comment_user_cancel Implements hook_user_cancel().
comment_user_predelete Implements hook_ENTITY_TYPE_predelete() for user entities.
comment_view Deprecated Generates an array for rendering a comment.
comment_view_multiple Deprecated Constructs render array from an array of loaded comments.
template_preprocess_comment Prepares variables for comment templates.
_comment_entity_uses_integer_id Determines if an entity type is using an integer-based ID definition.

Constants

Namesort descending Description
COMMENT_ANONYMOUS_MAYNOT_CONTACT Anonymous posters cannot enter their contact information.
COMMENT_ANONYMOUS_MAY_CONTACT Anonymous posters may leave their contact information.
COMMENT_ANONYMOUS_MUST_CONTACT Anonymous posters are required to leave their contact information.
COMMENT_NEW_LIMIT The time cutoff for comments marked as read for entity types other node.