comment.module 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801
  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_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 drupal_render().
  273. *
  274. * @deprecated in Drupal 8.x and will be removed before Drupal 9.0.
  275. * Use \Drupal::entityManager()->getViewBuilder('comment')->viewMultiple().
  276. *
  277. * @see drupal_render()
  278. */
  279. function comment_view_multiple($comments, $view_mode = 'full', $langcode = NULL) {
  280. return entity_view_multiple($comments, $view_mode, $langcode);
  281. }
  282. /**
  283. * Implements hook_form_FORM_ID_alter() for field_ui_field_storage_add_form.
  284. */
  285. function comment_form_field_ui_field_storage_add_form_alter(&$form, FormStateInterface $form_state) {
  286. $route_match = \Drupal::routeMatch();
  287. if ($form_state->get('entity_type_id') == 'comment' && $route_match->getParameter('commented_entity_type')) {
  288. $form['#title'] = \Drupal::service('comment.manager')->getFieldUIPageTitle($route_match->getParameter('commented_entity_type'), $route_match->getParameter('field_name'));
  289. }
  290. if (!_comment_entity_uses_integer_id($form_state->get('entity_type_id'))) {
  291. $optgroup = (string) t('General');
  292. // You cannot use comment fields on entity types with non-integer IDs.
  293. unset($form['add']['new_storage_type']['#options'][$optgroup]['comment']);
  294. }
  295. }
  296. /**
  297. * Implements hook_form_FORM_ID_alter().
  298. */
  299. function comment_form_field_ui_form_display_overview_form_alter(&$form, FormStateInterface $form_state) {
  300. $route_match = \Drupal::routeMatch();
  301. if ($form['#entity_type'] == '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. }
  305. /**
  306. * Implements hook_form_FORM_ID_alter().
  307. */
  308. function comment_form_field_ui_display_overview_form_alter(&$form, FormStateInterface $form_state) {
  309. $route_match = \Drupal::routeMatch();
  310. if ($form['#entity_type'] == 'comment' && $route_match->getParameter('commented_entity_type')) {
  311. $form['#title'] = \Drupal::service('comment.manager')->getFieldUIPageTitle($route_match->getParameter('commented_entity_type'), $route_match->getParameter('field_name'));
  312. }
  313. }
  314. /**
  315. * Implements hook_entity_storage_load().
  316. *
  317. * @see \Drupal\comment\Plugin\Field\FieldType\CommentItem::propertyDefinitions()
  318. */
  319. function comment_entity_storage_load($entities, $entity_type) {
  320. // Comments can only be attached to content entities, so skip others.
  321. if (!\Drupal::entityManager()->getDefinition($entity_type)->entityClassImplements(FieldableEntityInterface::class)) {
  322. return;
  323. }
  324. if (!\Drupal::service('comment.manager')->getFields($entity_type)) {
  325. // Do not query database when entity has no comment fields.
  326. return;
  327. }
  328. // Load comment information from the database and update the entity's
  329. // comment statistics properties, which are defined on each CommentItem field.
  330. $result = \Drupal::service('comment.statistics')->read($entities, $entity_type);
  331. foreach ($result as $record) {
  332. // Skip fields that entity does not have.
  333. if (!$entities[$record->entity_id]->hasField($record->field_name)) {
  334. continue;
  335. }
  336. $comment_statistics = $entities[$record->entity_id]->get($record->field_name);
  337. $comment_statistics->cid = $record->cid;
  338. $comment_statistics->last_comment_timestamp = $record->last_comment_timestamp;
  339. $comment_statistics->last_comment_name = $record->last_comment_name;
  340. $comment_statistics->last_comment_uid = $record->last_comment_uid;
  341. $comment_statistics->comment_count = $record->comment_count;
  342. }
  343. }
  344. /**
  345. * Implements hook_entity_insert().
  346. */
  347. function comment_entity_insert(EntityInterface $entity) {
  348. // Allow bulk updates and inserts to temporarily disable the
  349. // maintenance of the {comment_entity_statistics} table.
  350. if (\Drupal::state()->get('comment.maintain_entity_statistics') &&
  351. $fields = \Drupal::service('comment.manager')->getFields($entity->getEntityTypeId())) {
  352. \Drupal::service('comment.statistics')->create($entity, $fields);
  353. }
  354. }
  355. /**
  356. * Implements hook_entity_predelete().
  357. */
  358. function comment_entity_predelete(EntityInterface $entity) {
  359. // Entities can have non-numeric IDs, but {comment} and
  360. // {comment_entity_statistics} tables have integer columns for entity ID, and
  361. // PostgreSQL throws exceptions if you attempt query conditions with
  362. // mismatched types. So, we need to verify that the ID is numeric (even for an
  363. // entity type that has an integer ID, $entity->id() might be a string
  364. // containing a number), and then cast it to an integer when querying.
  365. if ($entity instanceof FieldableEntityInterface && is_numeric($entity->id())) {
  366. $entity_query = \Drupal::entityQuery('comment');
  367. $entity_query->condition('entity_id', (int) $entity->id());
  368. $entity_query->condition('entity_type', $entity->getEntityTypeId());
  369. $cids = $entity_query->execute();
  370. entity_delete_multiple('comment', $cids);
  371. \Drupal::service('comment.statistics')->delete($entity);
  372. }
  373. }
  374. /**
  375. * Determines if an entity type is using an integer-based ID definition.
  376. *
  377. * @param string $entity_type_id
  378. * The ID the represents the entity type.
  379. *
  380. * @return bool
  381. * Returns TRUE if the entity type has an integer-based ID definition and
  382. * FALSE otherwise.
  383. */
  384. function _comment_entity_uses_integer_id($entity_type_id) {
  385. $entity_type = \Drupal::entityManager()->getDefinition($entity_type_id);
  386. $entity_type_id_key = $entity_type->getKey('id');
  387. if ($entity_type_id_key === FALSE) {
  388. return FALSE;
  389. }
  390. $field_definitions = \Drupal::entityManager()->getBaseFieldDefinitions($entity_type->id());
  391. $entity_type_id_definition = $field_definitions[$entity_type_id_key];
  392. return $entity_type_id_definition->getType() === 'integer';
  393. }
  394. /**
  395. * Implements hook_node_update_index().
  396. */
  397. function comment_node_update_index(EntityInterface $node) {
  398. $index_comments = &drupal_static(__FUNCTION__);
  399. if ($index_comments === NULL) {
  400. // Do not index in the following three cases:
  401. // 1. 'Authenticated user' can search content but can't access comments.
  402. // 2. 'Anonymous user' can search content but can't access comments.
  403. // 3. Any role can search content but can't access comments and access
  404. // comments is not granted by the 'authenticated user' role. In this case
  405. // all users might have both permissions from various roles but it is also
  406. // possible to set up a user to have only search content and so a user
  407. // edit could change the security situation so it is not safe to index the
  408. // comments.
  409. $index_comments = TRUE;
  410. $roles = \Drupal::entityManager()->getStorage('user_role')->loadMultiple();
  411. $authenticated_can_access = $roles[RoleInterface::AUTHENTICATED_ID]->hasPermission('access comments');
  412. foreach ($roles as $rid => $role) {
  413. if ($role->hasPermission('search content') && !$role->hasPermission('access comments')) {
  414. if ($rid == RoleInterface::AUTHENTICATED_ID || $rid == RoleInterface::ANONYMOUS_ID || !$authenticated_can_access) {
  415. $index_comments = FALSE;
  416. break;
  417. }
  418. }
  419. }
  420. }
  421. $build = [];
  422. if ($index_comments) {
  423. foreach (\Drupal::service('comment.manager')->getFields('node') as $field_name => $info) {
  424. // Skip fields that entity does not have.
  425. if (!$node->hasField($field_name)) {
  426. continue;
  427. }
  428. $field_definition = $node->getFieldDefinition($field_name);
  429. $mode = $field_definition->getSetting('default_mode');
  430. $comments_per_page = $field_definition->getSetting('per_page');
  431. if ($node->get($field_name)->status) {
  432. $comments = \Drupal::entityManager()->getStorage('comment')
  433. ->loadThread($node, $field_name, $mode, $comments_per_page);
  434. if ($comments) {
  435. $build[] = \Drupal::entityManager()->getViewBuilder('comment')->viewMultiple($comments);
  436. }
  437. }
  438. }
  439. }
  440. return \Drupal::service('renderer')->renderPlain($build);
  441. }
  442. /**
  443. * Implements hook_cron().
  444. */
  445. function comment_cron() {
  446. // Store the maximum possible comments per thread (used for node search
  447. // ranking by reply count).
  448. \Drupal::state()->set('comment.node_comment_statistics_scale', 1.0 / max(1, \Drupal::service('comment.statistics')->getMaximumCount('node')));
  449. }
  450. /**
  451. * Implements hook_node_search_result().
  452. *
  453. * Formats a comment count string and returns it, for display with search
  454. * results.
  455. */
  456. function comment_node_search_result(EntityInterface $node) {
  457. $comment_fields = \Drupal::service('comment.manager')->getFields('node');
  458. $comments = 0;
  459. $open = FALSE;
  460. foreach ($comment_fields as $field_name => $info) {
  461. // Skip fields that entity does not have.
  462. if (!$node->hasField($field_name)) {
  463. continue;
  464. }
  465. // Do not make a string if comments are hidden.
  466. $status = $node->get($field_name)->status;
  467. if (\Drupal::currentUser()->hasPermission('access comments') && $status != CommentItemInterface::HIDDEN) {
  468. if ($status == CommentItemInterface::OPEN) {
  469. // At least one comment field is open.
  470. $open = TRUE;
  471. }
  472. $comments += $node->get($field_name)->comment_count;
  473. }
  474. }
  475. // Do not make a string if there are no comment fields, or no comments exist
  476. // or all comment fields are hidden.
  477. if ($comments > 0 || $open) {
  478. return ['comment' => \Drupal::translation()->formatPlural($comments, '1 comment', '@count comments')];
  479. }
  480. }
  481. /**
  482. * Implements hook_user_cancel().
  483. */
  484. function comment_user_cancel($edit, $account, $method) {
  485. switch ($method) {
  486. case 'user_cancel_block_unpublish':
  487. $comments = entity_load_multiple_by_properties('comment', ['uid' => $account->id()]);
  488. foreach ($comments as $comment) {
  489. $comment->setPublished(CommentInterface::NOT_PUBLISHED);
  490. $comment->save();
  491. }
  492. break;
  493. case 'user_cancel_reassign':
  494. /** @var \Drupal\comment\CommentInterface[] $comments */
  495. $comments = entity_load_multiple_by_properties('comment', ['uid' => $account->id()]);
  496. foreach ($comments as $comment) {
  497. $comment->setOwnerId(0);
  498. $comment->setAuthorName(\Drupal::config('user.settings')->get('anonymous'));
  499. $comment->save();
  500. }
  501. break;
  502. }
  503. }
  504. /**
  505. * Implements hook_ENTITY_TYPE_predelete() for user entities.
  506. */
  507. function comment_user_predelete($account) {
  508. $entity_query = \Drupal::entityQuery('comment');
  509. $entity_query->condition('uid', $account->id());
  510. $cids = $entity_query->execute();
  511. entity_delete_multiple('comment', $cids);
  512. }
  513. /**
  514. * Generates a comment preview.
  515. *
  516. * @param \Drupal\comment\CommentInterface $comment
  517. * The comment entity to preview.
  518. * @param Drupal\Core\Form\FormStateInterface $form_state
  519. * The current state of the form.
  520. *
  521. * @return array
  522. * An array as expected by drupal_render().
  523. */
  524. function comment_preview(CommentInterface $comment, FormStateInterface $form_state) {
  525. $preview_build = [];
  526. $entity = $comment->getCommentedEntity();
  527. if (!$form_state->getErrors()) {
  528. $comment->in_preview = TRUE;
  529. $comment_build = \Drupal::entityTypeManager()->getViewBuilder('comment')->view($comment);
  530. $comment_build['#weight'] = -100;
  531. $preview_build['comment_preview'] = $comment_build;
  532. }
  533. if ($comment->hasParentComment()) {
  534. $build = [];
  535. $parent = $comment->getParentComment();
  536. if ($parent && $parent->isPublished()) {
  537. $build = \Drupal::entityTypeManager()->getViewBuilder('comment')->view($parent);
  538. }
  539. }
  540. else {
  541. // The comment field output includes rendering the parent entity of the
  542. // thread to which the comment is a reply. The rendered entity output
  543. // includes the comment reply form, which contains the comment preview and
  544. // therefore the rendered parent entity. This results in an infinite loop of
  545. // parent entity output rendering the comment form and the comment form
  546. // rendering the parent entity. To prevent this infinite loop we temporarily
  547. // set the value of the comment field on a clone of the entity to hidden
  548. // before calling entity_view(). That way when the output of the commented
  549. // entity is rendered, it excludes the comment field output.
  550. $field_name = $comment->getFieldName();
  551. $entity = clone $entity;
  552. $entity->$field_name->status = CommentItemInterface::HIDDEN;
  553. $build = entity_view($entity, 'full');
  554. }
  555. $preview_build['comment_output_below'] = $build;
  556. $preview_build['comment_output_below']['#weight'] = 100;
  557. return $preview_build;
  558. }
  559. /**
  560. * Implements hook_preprocess_HOOK() for block templates.
  561. */
  562. function comment_preprocess_block(&$variables) {
  563. if ($variables['configuration']['provider'] == 'comment') {
  564. $variables['attributes']['role'] = 'navigation';
  565. }
  566. }
  567. /**
  568. * Prepares variables for comment templates.
  569. *
  570. * Default template: comment.html.twig.
  571. *
  572. * @param array $variables
  573. * An associative array containing:
  574. * - elements: An associative array containing the comment and entity objects.
  575. * Array keys: #comment, #commented_entity.
  576. */
  577. function template_preprocess_comment(&$variables) {
  578. /** @var \Drupal\comment\CommentInterface $comment */
  579. $comment = $variables['elements']['#comment'];
  580. $commented_entity = $comment->getCommentedEntity();
  581. $variables['comment'] = $comment;
  582. $variables['commented_entity'] = $commented_entity;
  583. $variables['threaded'] = $variables['elements']['#comment_threaded'];
  584. $account = $comment->getOwner();
  585. $username = [
  586. '#theme' => 'username',
  587. '#account' => $account,
  588. ];
  589. $variables['author'] = \Drupal::service('renderer')->render($username);
  590. $variables['author_id'] = $comment->getOwnerId();
  591. $variables['new_indicator_timestamp'] = $comment->getChangedTime();
  592. $variables['created'] = format_date($comment->getCreatedTime());
  593. // Avoid calling format_date() twice on the same timestamp.
  594. if ($comment->getChangedTime() == $comment->getCreatedTime()) {
  595. $variables['changed'] = $variables['created'];
  596. }
  597. else {
  598. $variables['changed'] = format_date($comment->getChangedTime());
  599. }
  600. if (theme_get_setting('features.comment_user_picture')) {
  601. // To change user picture settings (for instance, image style), edit the
  602. // 'compact' view mode on the User entity.
  603. $variables['user_picture'] = user_view($account, 'compact');
  604. }
  605. else {
  606. $variables['user_picture'] = [];
  607. }
  608. if (isset($comment->in_preview)) {
  609. $variables['title'] = \Drupal::l($comment->getSubject(), new Url('<front>'));
  610. $variables['permalink'] = \Drupal::l(t('Permalink'), new Url('<front>'));
  611. }
  612. else {
  613. $uri = $comment->permalink();
  614. $attributes = $uri->getOption('attributes') ?: [];
  615. $attributes += ['class' => ['permalink'], 'rel' => 'bookmark'];
  616. $uri->setOption('attributes', $attributes);
  617. $variables['title'] = \Drupal::l($comment->getSubject(), $uri);
  618. $variables['permalink'] = \Drupal::l(t('Permalink'), $comment->permalink());
  619. }
  620. $variables['submitted'] = t('Submitted by @username on @datetime', ['@username' => $variables['author'], '@datetime' => $variables['created']]);
  621. if ($comment->hasParentComment()) {
  622. // Fetch and store the parent comment information for use in templates.
  623. $comment_parent = $comment->getParentComment();
  624. $account_parent = $comment_parent->getOwner();
  625. $variables['parent_comment'] = $comment_parent;
  626. $username = [
  627. '#theme' => 'username',
  628. '#account' => $account_parent,
  629. ];
  630. $variables['parent_author'] = \Drupal::service('renderer')->render($username);
  631. $variables['parent_created'] = format_date($comment_parent->getCreatedTime());
  632. // Avoid calling format_date() twice on the same timestamp.
  633. if ($comment_parent->getChangedTime() == $comment_parent->getCreatedTime()) {
  634. $variables['parent_changed'] = $variables['parent_created'];
  635. }
  636. else {
  637. $variables['parent_changed'] = format_date($comment_parent->getChangedTime());
  638. }
  639. $permalink_uri_parent = $comment_parent->permalink();
  640. $attributes = $permalink_uri_parent->getOption('attributes') ?: [];
  641. $attributes += ['class' => ['permalink'], 'rel' => 'bookmark'];
  642. $permalink_uri_parent->setOption('attributes', $attributes);
  643. $variables['parent_title'] = \Drupal::l($comment_parent->getSubject(), $permalink_uri_parent);
  644. $variables['parent_permalink'] = \Drupal::l(t('Parent permalink'), $permalink_uri_parent);
  645. $variables['parent'] = t('In reply to @parent_title by @parent_username',
  646. ['@parent_username' => $variables['parent_author'], '@parent_title' => $variables['parent_title']]);
  647. }
  648. else {
  649. $variables['parent_comment'] = '';
  650. $variables['parent_author'] = '';
  651. $variables['parent_created'] = '';
  652. $variables['parent_changed'] = '';
  653. $variables['parent_title'] = '';
  654. $variables['parent_permalink'] = '';
  655. $variables['parent'] = '';
  656. }
  657. // Helpful $content variable for templates.
  658. foreach (Element::children($variables['elements']) as $key) {
  659. $variables['content'][$key] = $variables['elements'][$key];
  660. }
  661. // Set status to a string representation of comment->status.
  662. if (isset($comment->in_preview)) {
  663. $variables['status'] = 'preview';
  664. }
  665. else {
  666. $variables['status'] = $comment->isPublished() ? 'published' : 'unpublished';
  667. }
  668. // Add comment author user ID. Necessary for the comment-by-viewer library.
  669. $variables['attributes']['data-comment-user-id'] = $comment->getOwnerId();
  670. }
  671. /**
  672. * Prepares variables for comment field templates.
  673. *
  674. * Default template: field--comment.html.twig.
  675. *
  676. * @param array $variables
  677. * An associative array containing:
  678. * - element: An associative array containing render arrays for the list of
  679. * comments, and the comment form. Array keys: comments, comment_form.
  680. *
  681. * @todo Rename to template_preprocess_field__comment() once
  682. * https://www.drupal.org/node/939462 is resolved.
  683. */
  684. function comment_preprocess_field(&$variables) {
  685. $element = $variables['element'];
  686. if ($element['#field_type'] == 'comment') {
  687. // Provide contextual information.
  688. $variables['comment_display_mode'] = $element[0]['#comment_display_mode'];
  689. $variables['comment_type'] = $element[0]['#comment_type'];
  690. // Append additional attributes (eg. RDFa) from the first field item.
  691. $variables['attributes'] += $variables['items'][0]['attributes']->storage();
  692. // Create separate variables for the comments and comment form.
  693. $variables['comments'] = $element[0]['comments'];
  694. $variables['comment_form'] = $element[0]['comment_form'];
  695. }
  696. }
  697. /**
  698. * Implements hook_ranking().
  699. */
  700. function comment_ranking() {
  701. return \Drupal::service('comment.statistics')->getRankingInfo();
  702. }
  703. /**
  704. * Implements hook_ENTITY_TYPE_presave() for entity_view_display entities.
  705. */
  706. function comment_entity_view_display_presave(EntityViewDisplayInterface $display) {
  707. // Act only on comment view displays being disabled.
  708. if ($display->isNew() || $display->getTargetEntityTypeId() !== 'comment' || $display->status()) {
  709. return;
  710. }
  711. $storage = \Drupal::entityTypeManager()->getStorage('entity_view_display');
  712. if (!$storage->loadUnchanged($display->getOriginalId())->status()) {
  713. return;
  714. }
  715. // Disable the comment field formatter when the used view display is disabled.
  716. foreach ($storage->loadMultiple() as $id => $view_display) {
  717. $changed = FALSE;
  718. /** @var \Drupal\Core\Entity\Display\EntityViewDisplayInterface $view_display */
  719. foreach ($view_display->getComponents() as $field => $component) {
  720. if (isset($component['type']) && ($component['type'] === 'comment_default')) {
  721. if ($component['settings']['view_mode'] === $display->getMode()) {
  722. $view_display->removeComponent($field);
  723. /** @var \Drupal\Core\Entity\EntityViewModeInterface $mode */
  724. $mode = EntityViewMode::load($display->getTargetEntityTypeId() . '.' . $display->getMode());
  725. $arguments = [
  726. '@id' => $view_display->id(),
  727. '@name' => $field,
  728. '@display' => $mode->label(),
  729. '@mode' => $display->getMode(),
  730. ];
  731. \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);
  732. $changed = TRUE;
  733. }
  734. }
  735. }
  736. if ($changed) {
  737. $view_display->save();
  738. }
  739. }
  740. }