5 use Drupal\Core\Access\AccessResult;
6 use Drupal\Core\Database\Connection;
7 use Drupal\Core\Database\Query\SelectInterface;
8 use Drupal\Core\Database\Query\Condition;
9 use Drupal\Core\Extension\ModuleHandlerInterface;
10 use Drupal\Core\Language\LanguageManagerInterface;
11 use Drupal\Core\Session\AccountInterface;
14 * Defines a storage handler class that handles the node grants system.
16 * This is used to build node query access.
18 * @ingroup node_access
20 class NodeGrantDatabaseStorage implements NodeGrantDatabaseStorageInterface {
23 * The database connection.
25 * @var \Drupal\Core\Database\Connection
32 * @var \Drupal\Core\Extension\ModuleHandlerInterface
34 protected $moduleHandler;
37 * The language manager.
39 * @var \Drupal\Core\Language\LanguageManagerInterface
41 protected $languageManager;
44 * Constructs a NodeGrantDatabaseStorage object.
46 * @param \Drupal\Core\Database\Connection $database
47 * The database connection.
48 * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
50 * @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
51 * The language manager.
53 public function __construct(Connection $database, ModuleHandlerInterface $module_handler, LanguageManagerInterface $language_manager) {
54 $this->database = $database;
55 $this->moduleHandler = $module_handler;
56 $this->languageManager = $language_manager;
62 public function access(NodeInterface $node, $operation, AccountInterface $account) {
63 // Grants only support these operations.
64 if (!in_array($operation, ['view', 'update', 'delete'])) {
65 return AccessResult::neutral();
68 // If no module implements the hook or the node does not have an id there is
69 // no point in querying the database for access grants.
70 if (!$this->moduleHandler->getImplementations('node_grants') || !$node->id()) {
71 // Return the equivalent of the default grant, defined by
72 // self::writeDefault().
73 if ($operation === 'view') {
74 return AccessResult::allowedIf($node->isPublished())->addCacheableDependency($node);
77 return AccessResult::neutral();
81 // Check the database for potential access grants.
82 $query = $this->database->select('node_access');
83 $query->addExpression('1');
84 // Only interested for granting in the current operation.
85 $query->condition('grant_' . $operation, 1, '>=');
86 // Check for grants for this node and the correct langcode.
87 $nids = $query->andConditionGroup()
88 ->condition('nid', $node->id())
89 ->condition('langcode', $node->language()->getId());
90 // If the node is published, also take the default grant into account. The
91 // default is saved with a node ID of 0.
92 $status = $node->isPublished();
94 $nids = $query->orConditionGroup()
96 ->condition('nid', 0);
98 $query->condition($nids);
101 $grants = static::buildGrantsQueryCondition(node_access_grants($operation, $account));
103 if (count($grants) > 0) {
104 $query->condition($grants);
107 // Only the 'view' node grant can currently be cached; the others currently
108 // don't have any cacheability metadata. Hopefully, we can add that in the
109 // future, which would allow this access check result to be cacheable in all
110 // cases. For now, this must remain marked as uncacheable, even when it is
111 // theoretically cacheable, because we don't have the necessary metadata to
112 // know it for a fact.
113 $set_cacheability = function (AccessResult $access_result) use ($operation) {
114 $access_result->addCacheContexts(['user.node_grants:' . $operation]);
115 if ($operation !== 'view') {
116 $access_result->setCacheMaxAge(0);
118 return $access_result;
121 if ($query->execute()->fetchField()) {
122 return $set_cacheability(AccessResult::allowed());
125 return $set_cacheability(AccessResult::neutral());
132 public function checkAll(AccountInterface $account) {
133 $query = $this->database->select('node_access');
134 $query->addExpression('COUNT(*)');
136 ->condition('nid', 0)
137 ->condition('grant_view', 1, '>=');
139 $grants = static::buildGrantsQueryCondition(node_access_grants('view', $account));
141 if (count($grants) > 0) {
142 $query->condition($grants);
144 return $query->execute()->fetchField();
150 public function alterQuery($query, array $tables, $op, AccountInterface $account, $base_table) {
151 if (!$langcode = $query->getMetaData('langcode')) {
155 // Find all instances of the base table being joined -- could appear
156 // more than once in the query, and could be aliased. Join each one to
157 // the node_access table.
158 $grants = node_access_grants($op, $account);
159 foreach ($tables as $nalias => $tableinfo) {
160 $table = $tableinfo['table'];
161 if (!($table instanceof SelectInterface) && $table == $base_table) {
163 $subquery = $this->database->select('node_access', 'na')
164 ->fields('na', ['nid']);
166 // If any grant exists for the specified user, then user has access to the
167 // node for the specified operation.
168 $grant_conditions = static::buildGrantsQueryCondition($grants);
170 // Attach conditions to the subquery for nodes.
171 if (count($grant_conditions->conditions())) {
172 $subquery->condition($grant_conditions);
174 $subquery->condition('na.grant_' . $op, 1, '>=');
176 // Add langcode-based filtering if this is a multilingual site.
177 if (\Drupal::languageManager()->isMultilingual()) {
178 // If no specific langcode to check for is given, use the grant entry
179 // which is set as a fallback.
180 // If a specific langcode is given, use the grant entry for it.
181 if ($langcode === FALSE) {
182 $subquery->condition('na.fallback', 1, '=');
185 $subquery->condition('na.langcode', $langcode, '=');
190 // Now handle entities.
191 $subquery->where("$nalias.$field = na.nid");
193 $query->exists($subquery);
201 public function write(NodeInterface $node, array $grants, $realm = NULL, $delete = TRUE) {
203 $query = $this->database->delete('node_access')->condition('nid', $node->id());
205 $query->condition('realm', [$realm, 'all'], 'IN');
209 // Only perform work when node_access modules are active.
210 if (!empty($grants) && count($this->moduleHandler->getImplementations('node_grants'))) {
211 $query = $this->database->insert('node_access')->fields(['nid', 'langcode', 'fallback', 'realm', 'gid', 'grant_view', 'grant_update', 'grant_delete']);
212 // If we have defined a granted langcode, use it. But if not, add a grant
213 // for every language this node is translated to.
214 $fallback_langcode = $node->getUntranslated()->language()->getId();
215 foreach ($grants as $grant) {
216 if ($realm && $realm != $grant['realm']) {
219 if (isset($grant['langcode'])) {
220 $grant_languages = [$grant['langcode'] => $this->languageManager->getLanguage($grant['langcode'])];
223 $grant_languages = $node->getTranslationLanguages(TRUE);
225 foreach ($grant_languages as $grant_langcode => $grant_language) {
226 // Only write grants; denies are implicit.
227 if ($grant['grant_view'] || $grant['grant_update'] || $grant['grant_delete']) {
228 $grant['nid'] = $node->id();
229 $grant['langcode'] = $grant_langcode;
230 // The record with the original langcode is used as the fallback.
231 if ($grant['langcode'] == $fallback_langcode) {
232 $grant['fallback'] = 1;
235 $grant['fallback'] = 0;
237 $query->values($grant);
248 public function delete() {
249 $this->database->truncate('node_access')->execute();
255 public function writeDefault() {
256 $this->database->insert('node_access')
271 public function count() {
272 return $this->database->query('SELECT COUNT(*) FROM {node_access}')->fetchField();
278 public function deleteNodeRecords(array $nids) {
279 $this->database->delete('node_access')
280 ->condition('nid', $nids, 'IN')
285 * Creates a query condition from an array of node access grants.
287 * @param array $node_access_grants
288 * An array of grants, as returned by node_access_grants().
289 * @return \Drupal\Core\Database\Query\Condition
290 * A condition object to be passed to $query->condition().
292 * @see node_access_grants()
294 protected static function buildGrantsQueryCondition(array $node_access_grants) {
295 $grants = new Condition("OR");
296 foreach ($node_access_grants as $realm => $gids) {
298 $and = new Condition('AND');
299 $grants->condition($and
300 ->condition('gid', $gids, 'IN')
301 ->condition('realm', $realm)