comment.module 33 KB

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