<?php

/**
 * @file
 * Control access to site content based on the users and roles.
 */

use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\user\Entity\Role;
use Drupal\Core\Entity\EntityInterface;
use Drupal\node\NodeTypeInterface;
use Drupal\node\NodeInterface;

/**
 * Implements hook_help().
 */
function nodeaccess_help($route_name, RouteMatchInterface $route_match) {
  switch ($route_name) {
    case 'entity.node.grants':
      return t("You can set grants for individual users. Enter a name or a partial name in the box and click Search or press return. You must check the 'Keep?' checkbox if you want to keep the user for granting. Note that user grants are in addition to those coming from roles.");
  }
}

/**
 * Implements hook_node_access_records().
 */
function nodeaccess_node_access_records(NodeInterface $node) {
  $grants = [];
  $settings = \Drupal::configFactory()->get('nodeaccess.settings');
  $bundles_roles_grants = $settings->get('bundles_roles_grants');
  $bundle_roles_grants = $bundles_roles_grants[$node->bundle()] ?? [];

  // `nodeaccess_author` grant is loaded from `nodeaccess.settings`.
  if (isset($bundle_roles_grants['author'])) {
    // If the node's author is anonymous, ignore. Don't grant anonymous the
    // author access to avoid unexpected permission leaks.
    // @todo Add a test.
    if ($node->getOwner() && $node->getOwner()->isAuthenticated()) {
      $grants[] = [
        'realm' => 'nodeaccess_author',
        'gid' => $node->getOwnerId(),
      ] + $bundle_roles_grants['author'];
    }
    unset($bundle_roles_grants['author']);
  }

  $map_rid_gid = $settings->get('map_rid_gid');

  // Load grants from the `nodeaccess` table.
  $db = \Drupal::database();
  $entries = $db->select('nodeaccess', 'n')
    ->fields('n')
    ->condition('nid', $node->id())
    ->execute()
    ->fetchAll();

  // If grants found in the `nodeaccess` table, it means that this node has its
  // own grants granted via the Grants tab, no need to load grants from the
  // `nodeaccess.settings`.
  if (!empty($entries)) {
    foreach ($entries as $row) {
      $grant_languages = $node->getTranslationLanguages(TRUE);
      foreach ($grant_languages as $grant_language) {
        $translation = $node->getTranslation($grant_language->getId());
        $translation_published = $translation->isPublished() ? 1 : 0;
        $grants[] = [
          'realm' => $row->realm,
          'gid' => $row->gid,
          'grant_view' => $row->grant_view ? $translation_published : 0,
          'grant_update' => $row->grant_update,
          'grant_delete' => $row->grant_delete,
          'langcode' => $grant_language->getId(),
        ];
      }
    }
    return $grants;
  }

  // Or load grants from `nodeaccess.settings`.
  if (!empty($bundle_roles_grants)) {
    foreach ($bundle_roles_grants as $role_id => $grant_values) {
      // $grant_values holds values with key grant_view, grant_update and
      // grant_delete.
      $grant_languages = $node->getTranslationLanguages(TRUE);
      foreach ($grant_languages as $grant_language) {
        $translation = $node->getTranslation($grant_language->getId());
        $translation_published = $translation->isPublished() ? 1 : 0;
        $grants[] = [
          'realm' => 'nodeaccess_role',
          'gid' => $map_rid_gid[$role_id],
          'grant_view' => $grant_values['grant_view'] ? $translation_published : 0,
          'grant_update' => $grant_values['grant_update'],
          'grant_delete' => $grant_values['grant_delete'],
          'langcode' => $grant_language->getId(),
        ];
      }
    }
  }
  return $grants;
}

/**
 * Implements hook_node_grants().
 */
function nodeaccess_node_grants(AccountInterface $account, $op) {
  $config = \Drupal::configFactory()->get('nodeaccess.settings');
  $map_rid_gid = $config->get('map_rid_gid');
  $roles = $account->getRoles();
  $grant_ids = [];
  if (is_array($map_rid_gid)) {
    foreach ($roles as $role_id) {
      if (isset($map_rid_gid[$role_id])) {
        $grant_ids[] = $map_rid_gid[$role_id];
      }
    }
  }
  $user_id = $account->id();
  if ($account->isAnonymous()) {
    return [
      'nodeaccess_role' => $grant_ids,
      'nodeaccess_user' => [$user_id],
    ];
  }
  return [
    'nodeaccess_role' => $grant_ids,
    'nodeaccess_user' => [$user_id],
    'nodeaccess_author' => [$user_id],
  ];
}

/**
 * Implements hook_ENTITY_TYPE_insert().
 */
function nodeaccess_node_type_insert(NodeTypeInterface $node_type) {
  // Update `grants_tab_availability` and `bundles_roles_grants` in
  // `nodeaccess.settings` to add this bundle related settings.
  $bundle = $node_type->id();
  $nodeaccess_settings = \Drupal::configFactory()->getEditable('nodeaccess.settings');

  $bundle_roles_grants = [];
  foreach (Role::loadMultiple() as $role_id => $role) {
    $bundle_roles_grants[$role_id] = [
      'grant_view' => 0,
      'grant_update' => 0,
      'grant_delete' => 0,
    ];
  }
  $bundle_roles_grants['author'] = [
    'grant_view' => 0,
    'grant_update' => 0,
    'grant_delete' => 0,
  ];
  $grants_tab_availability = $nodeaccess_settings->get('grants_tab_availability');
  $grants_tab_availability[$bundle] = FALSE;
  $bundles_roles_grants = $nodeaccess_settings->get('bundles_roles_grants');
  $bundles_roles_grants[$bundle] = $bundle_roles_grants;
  $nodeaccess_settings
    ->set('grants_tab_availability', $grants_tab_availability)
    ->set('bundles_roles_grants', $bundles_roles_grants)
    ->save();
  // @todo display a message or something to promote end users to update
  //   `nodeaccess.settings`.
  node_access_needs_rebuild(TRUE);
}

/**
 * Implements hook_ENTITY_TYPE_delete().
 */
function nodeaccess_node_type_delete(NodeTypeInterface $node_type) {
  // Update `grants_tab_availability` and `bundles_roles_grants` in
  // `nodeaccess.settings` to remove this bundle related settings.
  $bundle = $node_type->id();
  $nodeaccess_settings = \Drupal::configFactory()->getEditable('nodeaccess.settings');
  $grants_tab_availability = $nodeaccess_settings->get('grants_tab_availability');
  $bundles_roles_grants = $nodeaccess_settings->get('bundles_roles_grants');
  unset($grants_tab_availability[$bundle]);
  unset($bundles_roles_grants[$bundle]);
  $nodeaccess_settings
    ->set('grants_tab_availability', $grants_tab_availability)
    ->set('bundles_roles_grants', $bundles_roles_grants)
    ->save();
}

/**
 * Implements hook_ENTITY_TYPE_delete().
 */
function nodeaccess_node_delete(EntityInterface $node) {
  // Remove related records from the `nodeaccess` table .
  \Drupal::database()->delete('nodeaccess')
    ->condition('nid', $node->id())
    ->execute();
}

/**
 * Implements hook_ENTITY_TYPE_insert().
 */
function nodeaccess_user_role_insert(EntityInterface $entity) {
  /** @var \Drupal\user\RoleInterface $entity */
  /** @var \Drupal\nodeaccess\NodeAccessHelper $nodeaccess_helper */
  $nodeaccess_helper = \Drupal::service('nodeaccess.helper');
  $nodeaccess_helper->addRoleRelatedSettings($entity);
}

/**
 * Implements hook_ENTITY_TYPE_update().
 */
function nodeaccess_user_role_update(EntityInterface $entity) {
  /** @var \Drupal\user\RoleInterface $entity */
  /** @var \Drupal\nodeaccess\NodeAccessHelper $nodeaccess_helper */
  $nodeaccess_helper = \Drupal::service('nodeaccess.helper');
  $nodeaccess_helper->updateRoleRelatedSettings($entity);
}

/**
 * Implements hook_ENTITY_TYPE_delete().
 */
function nodeaccess_user_role_delete(EntityInterface $entity) {
  /** @var \Drupal\user\RoleInterface $entity */
  /** @var \Drupal\nodeaccess\NodeAccessHelper $nodeaccess_helper */
  $nodeaccess_helper = \Drupal::service('nodeaccess.helper');
  $nodeaccess_helper->deleteRoleRelatedSettings($entity);
  // Rebuild permissions after deleting role-related settings.
  \Drupal::service('router.builder')->rebuild();
}
