You are here

function abt_node_access_records in Access By Term 7

Implements hook_node_access_records().

Writes to node_access table every time a node gets added / updated. Here we check for reference fields and can see if user has updated/created any access fields - and then we act on that.

File

./abt.module, line 107
abt.module Module for controling access by using user->term<-node relationship.

Code

function abt_node_access_records($node) {
  $grants = array();
  $access_map = field_read_fields(array(
    'module' => 'taxonomy',
  ));
  foreach ($access_map as $field_name => $realm) {
    if (!property_exists($node, $field_name) || !array_key_exists('abt_map', $realm['settings'])) {
      continue;
    }
    $abtmap = $realm['settings']['abt_map'];
    $field_data = field_get_items('node', $node, $field_name);
    if (empty($field_data)) {
      $grants[] = AbtUtils::grantConstruct($node->nid, 'abt_' . $realm['field_name'], 0, $abtmap['ctrl_view_access'] == ABT_CONTROL_DEFAULT_ALLOW ? 1 : 0, $abtmap['ctrl_update_access'] == ABT_CONTROL_DEFAULT_ALLOW ? 1 : 0, $abtmap['ctrl_delete_access'] == ABT_CONTROL_DEFAULT_ALLOW ? 1 : 0);
    }
    else {
      $used_tids = array();
      for ($i = 0; $i < count($field_data); $i++) {

        // node_access table does not allow duplicate nid-gid-realm combo (in our case it's nid-tid-fieldname).
        // Duplicate terms will probably never happen in normal usage but devel-generate module does this
        // when field cardinality is greater then 1 (there is a debate on wheather this is a bug or not).
        // Anyway, we adress it here and prevent duplicate terms trigger writing to the node_access table.
        if (isset($field_data[$i]['tid'])) {
          if (!in_array($field_data[$i]['tid'], $used_tids)) {
            $used_tids[] = $field_data[$i]['tid'];
            if (isset($realm['settings']['abt_map'])) {
              $grants[] = AbtUtils::grantConstruct($node->nid, 'abt_' . $field_name, $field_data[$i]['tid'], $abtmap['ctrl_view_access'] == ABT_CONTROL_DEFAULT_RESTRICT || $abtmap['ctrl_view_access'] == ABT_CONTROL_DEFAULT_ALLOW ? 1 : 0, $abtmap['ctrl_update_access'] == ABT_CONTROL_DEFAULT_RESTRICT || $abtmap['ctrl_update_access'] == ABT_CONTROL_DEFAULT_ALLOW ? 1 : 0, $abtmap['ctrl_delete_access'] == ABT_CONTROL_DEFAULT_RESTRICT || $abtmap['ctrl_delete_access'] == ABT_CONTROL_DEFAULT_ALLOW ? 1 : 0);
            }
          }
        }
      }
    }
  }
  return $grants;
}