You are here

function content_access_optimize_grants in Content Access 8

Same name and namespace in other branches
  1. 5 content_access.module \content_access_optimize_grants()
  2. 6 content_access.module \content_access_optimize_grants()
  3. 7 content_access.module \content_access_optimize_grants()

Removes grants that doesn't change anything.

@note The grants are compared with the normal access control settings.

1 call to content_access_optimize_grants()
content_access_node_access_records in ./content_access.module
Implements hook_node_access_records().

File

./content_access.module, line 570
Content access module file.

Code

function content_access_optimize_grants(&$grants, NodeInterface $node) {
  $rids = [
    'view' => [],
    'update' => [],
    'delete' => [],
  ];
  foreach ($grants as $key => $grant) {
    foreach ([
      'view',
      'update',
      'delete',
    ] as $op) {
      if (!empty($grant['grant_' . $op])) {
        $rids[$op][] = $grant['gid'];
      }
    }
  }

  // Detect if all are allowed to view.
  $anonymous_gid = content_access_get_role_gid(AccountInterface::ANONYMOUS_ROLE);
  $authenticated_gid = content_access_get_role_gid(AccountInterface::AUTHENTICATED_ROLE);
  $all = [
    $anonymous_gid,
    $authenticated_gid,
  ];
  if (empty(array_diff($all, $rids['view']))) {

    // Grant view access to all instead of single roles.
    $rids['view'] = [
      'all',
    ];
    $grants['all'] = [
      'realm' => 'all',
      'gid' => 0,
      'grant_view' => 1,
      'grant_update' => 0,
      'grant_delete' => 0,
      'priority' => content_access_get_settings('priority', $node
        ->getType()),
    ];
  }

  // If authenticated users are involved, remove unnecessary other roles.
  foreach ([
    'view',
    'update',
    'delete',
  ] as $op) {
    if (in_array($authenticated_gid, $rids[$op])) {
      $rids[$op] = in_array($anonymous_gid, $rids[$op]) ? [
        $anonymous_gid,
        $authenticated_gid,
      ] : [
        $authenticated_gid,
      ];
    }
  }

  // Now let's remove unnecessary grants, if any.
  foreach ($grants as $key => $grant) {
    if (!is_numeric($key)) {
      continue;
    }
    foreach ([
      'view',
      'update',
      'delete',
    ] as $op) {
      if ($grant['grant_' . $op] && in_array($grant['gid'], $rids[$op])) {

        // It is still here, so we cannot remove this grant.
        continue 2;
      }
    }

    // ok, remove it.
    unset($grants[$key]);
  }
}