comment.module 34 KB

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