comment.module 32 KB

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