comment.module 32 KB

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