comment.module 31 KB

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