NodeGrantDatabaseStorage.php 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. <?php
  2. namespace Drupal\node;
  3. use Drupal\Core\Access\AccessResult;
  4. use Drupal\Core\Database\Connection;
  5. use Drupal\Core\Database\Query\SelectInterface;
  6. use Drupal\Core\Database\Query\Condition;
  7. use Drupal\Core\Extension\ModuleHandlerInterface;
  8. use Drupal\Core\Language\LanguageManagerInterface;
  9. use Drupal\Core\Session\AccountInterface;
  10. /**
  11. * Defines a storage handler class that handles the node grants system.
  12. *
  13. * This is used to build node query access.
  14. *
  15. * @ingroup node_access
  16. */
  17. class NodeGrantDatabaseStorage implements NodeGrantDatabaseStorageInterface {
  18. /**
  19. * The database connection.
  20. *
  21. * @var \Drupal\Core\Database\Connection
  22. */
  23. protected $database;
  24. /**
  25. * The module handler.
  26. *
  27. * @var \Drupal\Core\Extension\ModuleHandlerInterface
  28. */
  29. protected $moduleHandler;
  30. /**
  31. * The language manager.
  32. *
  33. * @var \Drupal\Core\Language\LanguageManagerInterface
  34. */
  35. protected $languageManager;
  36. /**
  37. * Constructs a NodeGrantDatabaseStorage object.
  38. *
  39. * @param \Drupal\Core\Database\Connection $database
  40. * The database connection.
  41. * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
  42. * The module handler.
  43. * @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
  44. * The language manager.
  45. */
  46. public function __construct(Connection $database, ModuleHandlerInterface $module_handler, LanguageManagerInterface $language_manager) {
  47. $this->database = $database;
  48. $this->moduleHandler = $module_handler;
  49. $this->languageManager = $language_manager;
  50. }
  51. /**
  52. * {@inheritdoc}
  53. */
  54. public function access(NodeInterface $node, $operation, AccountInterface $account) {
  55. // Grants only support these operations.
  56. if (!in_array($operation, ['view', 'update', 'delete'])) {
  57. return AccessResult::neutral();
  58. }
  59. // If no module implements the hook or the node does not have an id there is
  60. // no point in querying the database for access grants.
  61. if (!$this->moduleHandler->getImplementations('node_grants') || !$node->id()) {
  62. // Return the equivalent of the default grant, defined by
  63. // self::writeDefault().
  64. if ($operation === 'view') {
  65. return AccessResult::allowedIf($node->isPublished())->addCacheableDependency($node);
  66. }
  67. else {
  68. return AccessResult::neutral();
  69. }
  70. }
  71. // Check the database for potential access grants.
  72. $query = $this->database->select('node_access');
  73. $query->addExpression('1');
  74. // Only interested for granting in the current operation.
  75. $query->condition('grant_' . $operation, 1, '>=');
  76. // Check for grants for this node and the correct langcode.
  77. $nids = $query->andConditionGroup()
  78. ->condition('nid', $node->id())
  79. ->condition('langcode', $node->language()->getId());
  80. // If the node is published, also take the default grant into account. The
  81. // default is saved with a node ID of 0.
  82. $status = $node->isPublished();
  83. if ($status) {
  84. $nids = $query->orConditionGroup()
  85. ->condition($nids)
  86. ->condition('nid', 0);
  87. }
  88. $query->condition($nids);
  89. $query->range(0, 1);
  90. $grants = static::buildGrantsQueryCondition(node_access_grants($operation, $account));
  91. if (count($grants) > 0) {
  92. $query->condition($grants);
  93. }
  94. // Only the 'view' node grant can currently be cached; the others currently
  95. // don't have any cacheability metadata. Hopefully, we can add that in the
  96. // future, which would allow this access check result to be cacheable in all
  97. // cases. For now, this must remain marked as uncacheable, even when it is
  98. // theoretically cacheable, because we don't have the necessary metadata to
  99. // know it for a fact.
  100. $set_cacheability = function (AccessResult $access_result) use ($operation) {
  101. $access_result->addCacheContexts(['user.node_grants:' . $operation]);
  102. if ($operation !== 'view') {
  103. $access_result->setCacheMaxAge(0);
  104. }
  105. return $access_result;
  106. };
  107. if ($query->execute()->fetchField()) {
  108. return $set_cacheability(AccessResult::allowed());
  109. }
  110. else {
  111. return $set_cacheability(AccessResult::neutral());
  112. }
  113. }
  114. /**
  115. * {@inheritdoc}
  116. */
  117. public function checkAll(AccountInterface $account) {
  118. $query = $this->database->select('node_access');
  119. $query->addExpression('COUNT(*)');
  120. $query
  121. ->condition('nid', 0)
  122. ->condition('grant_view', 1, '>=');
  123. $grants = static::buildGrantsQueryCondition(node_access_grants('view', $account));
  124. if (count($grants) > 0) {
  125. $query->condition($grants);
  126. }
  127. return $query->execute()->fetchField();
  128. }
  129. /**
  130. * {@inheritdoc}
  131. */
  132. public function alterQuery($query, array $tables, $op, AccountInterface $account, $base_table) {
  133. if (!$langcode = $query->getMetaData('langcode')) {
  134. $langcode = FALSE;
  135. }
  136. // Find all instances of the base table being joined -- could appear
  137. // more than once in the query, and could be aliased. Join each one to
  138. // the node_access table.
  139. $grants = node_access_grants($op, $account);
  140. foreach ($tables as $nalias => $tableinfo) {
  141. $table = $tableinfo['table'];
  142. if (!($table instanceof SelectInterface) && $table == $base_table) {
  143. // Set the subquery.
  144. $subquery = $this->database->select('node_access', 'na')
  145. ->fields('na', ['nid']);
  146. // If any grant exists for the specified user, then user has access to the
  147. // node for the specified operation.
  148. $grant_conditions = static::buildGrantsQueryCondition($grants);
  149. // Attach conditions to the subquery for nodes.
  150. if (count($grant_conditions->conditions())) {
  151. $subquery->condition($grant_conditions);
  152. }
  153. $subquery->condition('na.grant_' . $op, 1, '>=');
  154. // Add langcode-based filtering if this is a multilingual site.
  155. if (\Drupal::languageManager()->isMultilingual()) {
  156. // If no specific langcode to check for is given, use the grant entry
  157. // which is set as a fallback.
  158. // If a specific langcode is given, use the grant entry for it.
  159. if ($langcode === FALSE) {
  160. $subquery->condition('na.fallback', 1, '=');
  161. }
  162. else {
  163. $subquery->condition('na.langcode', $langcode, '=');
  164. }
  165. }
  166. $field = 'nid';
  167. // Now handle entities.
  168. $subquery->where("$nalias.$field = na.nid");
  169. $query->exists($subquery);
  170. }
  171. }
  172. }
  173. /**
  174. * {@inheritdoc}
  175. */
  176. public function write(NodeInterface $node, array $grants, $realm = NULL, $delete = TRUE) {
  177. if ($delete) {
  178. $query = $this->database->delete('node_access')->condition('nid', $node->id());
  179. if ($realm) {
  180. $query->condition('realm', [$realm, 'all'], 'IN');
  181. }
  182. $query->execute();
  183. }
  184. // Only perform work when node_access modules are active.
  185. if (!empty($grants) && count($this->moduleHandler->getImplementations('node_grants'))) {
  186. $query = $this->database->insert('node_access')->fields(['nid', 'langcode', 'fallback', 'realm', 'gid', 'grant_view', 'grant_update', 'grant_delete']);
  187. // If we have defined a granted langcode, use it. But if not, add a grant
  188. // for every language this node is translated to.
  189. $fallback_langcode = $node->getUntranslated()->language()->getId();
  190. foreach ($grants as $grant) {
  191. if ($realm && $realm != $grant['realm']) {
  192. continue;
  193. }
  194. if (isset($grant['langcode'])) {
  195. $grant_languages = [$grant['langcode'] => $this->languageManager->getLanguage($grant['langcode'])];
  196. }
  197. else {
  198. $grant_languages = $node->getTranslationLanguages(TRUE);
  199. }
  200. foreach ($grant_languages as $grant_langcode => $grant_language) {
  201. // Only write grants; denies are implicit.
  202. if ($grant['grant_view'] || $grant['grant_update'] || $grant['grant_delete']) {
  203. $grant['nid'] = $node->id();
  204. $grant['langcode'] = $grant_langcode;
  205. // The record with the original langcode is used as the fallback.
  206. if ($grant['langcode'] == $fallback_langcode) {
  207. $grant['fallback'] = 1;
  208. }
  209. else {
  210. $grant['fallback'] = 0;
  211. }
  212. $query->values($grant);
  213. }
  214. }
  215. }
  216. $query->execute();
  217. }
  218. }
  219. /**
  220. * {@inheritdoc}
  221. */
  222. public function delete() {
  223. $this->database->truncate('node_access')->execute();
  224. }
  225. /**
  226. * {@inheritdoc}
  227. */
  228. public function writeDefault() {
  229. $this->database->insert('node_access')
  230. ->fields([
  231. 'nid' => 0,
  232. 'realm' => 'all',
  233. 'gid' => 0,
  234. 'grant_view' => 1,
  235. 'grant_update' => 0,
  236. 'grant_delete' => 0,
  237. ])
  238. ->execute();
  239. }
  240. /**
  241. * {@inheritdoc}
  242. */
  243. public function count() {
  244. return $this->database->query('SELECT COUNT(*) FROM {node_access}')->fetchField();
  245. }
  246. /**
  247. * {@inheritdoc}
  248. */
  249. public function deleteNodeRecords(array $nids) {
  250. $this->database->delete('node_access')
  251. ->condition('nid', $nids, 'IN')
  252. ->execute();
  253. }
  254. /**
  255. * Creates a query condition from an array of node access grants.
  256. *
  257. * @param array $node_access_grants
  258. * An array of grants, as returned by node_access_grants().
  259. * @return \Drupal\Core\Database\Query\Condition
  260. * A condition object to be passed to $query->condition().
  261. *
  262. * @see node_access_grants()
  263. */
  264. protected static function buildGrantsQueryCondition(array $node_access_grants) {
  265. $grants = new Condition("OR");
  266. foreach ($node_access_grants as $realm => $gids) {
  267. if (!empty($gids)) {
  268. $and = new Condition('AND');
  269. $grants->condition($and
  270. ->condition('gid', $gids, 'IN')
  271. ->condition('realm', $realm)
  272. );
  273. }
  274. }
  275. return $grants;
  276. }
  277. }