3 namespace Drupal\comment\Plugin\EntityReferenceSelection;
5 use Drupal\Core\Database\Query\SelectInterface;
6 use Drupal\Core\Entity\Plugin\EntityReferenceSelection\DefaultSelection;
7 use Drupal\comment\CommentInterface;
10 * Provides specific access control for the comment entity type.
12 * @EntityReferenceSelection(
13 * id = "default:comment",
14 * label = @Translation("Comment selection"),
15 * entity_types = {"comment"},
20 class CommentSelection extends DefaultSelection {
25 protected function buildEntityQuery($match = NULL, $match_operator = 'CONTAINS') {
26 $query = parent::buildEntityQuery($match, $match_operator);
28 // Adding the 'comment_access' tag is sadly insufficient for comments:
29 // core requires us to also know about the concept of 'published' and
31 if (!$this->currentUser->hasPermission('administer comments')) {
32 $query->condition('status', CommentInterface::PUBLISHED);
40 public function createNewEntity($entity_type_id, $bundle, $label, $uid) {
41 $comment = parent::createNewEntity($entity_type_id, $bundle, $label, $uid);
43 // In order to create a referenceable comment, it needs to published.
44 /** @var \Drupal\comment\CommentInterface $comment */
45 $comment->setPublished(TRUE);
53 public function validateReferenceableNewEntities(array $entities) {
54 $entities = parent::validateReferenceableNewEntities($entities);
55 // Mirror the conditions checked in buildEntityQuery().
56 if (!$this->currentUser->hasPermission('administer comments')) {
57 $entities = array_filter($entities, function ($comment) {
58 /** @var \Drupal\comment\CommentInterface $comment */
59 return $comment->isPublished();
68 public function entityQueryAlter(SelectInterface $query) {
69 $tables = $query->getTables();
70 $data_table = 'comment_field_data';
71 if (!isset($tables['comment_field_data']['alias'])) {
72 // If no conditions join against the comment data table, it should be
73 // joined manually to allow node access processing.
74 $query->innerJoin($data_table, NULL, "base_table.cid = $data_table.cid AND $data_table.default_langcode = 1");
77 // The Comment module doesn't implement any proper comment access,
78 // and as a consequence doesn't make sure that comments cannot be viewed
79 // when the user doesn't have access to the node.
80 $node_alias = $query->innerJoin('node_field_data', 'n', '%alias.nid = ' . $data_table . '.entity_id AND ' . $data_table . ".entity_type = 'node'");
81 // Pass the query to the node access control.
82 $this->reAlterQuery($query, 'node_access', $node_alias);
84 // Passing the query to node_query_node_access_alter() is sadly
85 // insufficient for nodes.
86 // @see SelectionEntityTypeNode::entityQueryAlter()
87 if (!$this->currentUser->hasPermission('bypass node access') && !count($this->moduleHandler->getImplementations('node_grants'))) {
88 $query->condition($node_alias . '.status', 1);