You are here

rac_na.module in Role Access Control 8

Module providing role base access for nodes.

File

contrib/rac_na/rac_na.module
View source
<?php

/**
 * @file
 * Module providing role base access for nodes.
 */
use Drupal\node\NodeInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_node_access_records().
 */
function rac_na_node_access_records(NodeInterface $node) {
  $nodeRoles = _rac_get_entity_reference_roles($node);
  if (count($nodeRoles)) {

    // If we're here, the node has roles associated with it which restrict
    // access to the node.
    $grants = [];
    $roles = user_roles();
    foreach ($nodeRoles as $role) {
      $grant = [
        'realm' => "rac_" . $roles[$role]
          ->id(),
        'gid' => 1,
        'grant_view' => 1,
        'grant_update' => 0,
        'grant_delete' => 0,
        'priority' => 0,
      ];
      $grant2 = [
        'realm' => "rac_" . $roles[$role]
          ->id(),
        'gid' => 2,
        'grant_view' => 1,
        'grant_update' => 1,
        'grant_delete' => 0,
        'priority' => 0,
      ];
      if ($node
        ->isPublished()) {
        $grants[] = $grant;
        $grants[] = $grant2;
      }
      else {
        if (_rac_update_unpublished()) {
          $grants[] = $grant2;
        }
      }
    }
    return $grants;
  }
}

/**
 * Implements hook_node_grants().
 *
 * Returns any grants which may give the user permission to perform the
 * requested op.
 */
function rac_na_node_grants(AccountInterface $account, $op) {
  $grants = [];
  $access = $op === 'view' ? 1 : 2;
  $userRoles = _rac_get_account_roles($op, $account);
  foreach ($userRoles as $role) {
    $grants["rac_" . $role
      ->id()][] = $access;
  }
  if ($access === 1) {

    /*
     * For view access, check if the user has edit access. This is required if
     * the content is unpublishes, since the view grant records will not be
     * stored, but update grants view.
     */
    $update_grants = rac_na_node_grants($account, "update");
    if ($update_grants) {
      $grants = array_merge_recursive($grants, $update_grants);
    }
  }
  if (count($grants)) {
    return $grants;
  }
}

/**
 * Implements hook_form_FORM_ID_alter().
 *
 * Alter node forms for entities managed by RAC, and restrict values on fields.
 */
function rac_na_form_node_form_alter(&$form, FormStateInterface &$form_state, $form_id) {
  $formObj = $form_state
    ->getFormObject();
  $node = $formObj
    ->getEntity();

  // Get entity fields and form data.
  $fields = _rac_get_entity_reference_role_fields($node
    ->getEntityType(), $node
    ->bundle());
  if (!empty($fields)) {

    // Hide values for any role reference fields on this node.
    foreach ($fields as $field) {
      if (isset($form[$field])) {

        // Restrict element Values.
        $element =& $form[$field];
        _rac_restrict_field_values($field, $element);
      }
    }
  }
}