You are here

function abt_node_grants in Access By Term 7

Implements hook_node_grants().

Every time a node (or a part of a node) is subject to viewing/updating/deleting this hook is called and we can evaluate the user access and his operations.

File

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

Code

function abt_node_grants($account, $op) {
  $grants = array();
  $usr = user_load($account->uid);
  $access_map = field_read_fields(array(
    'module' => 'taxonomy',
  ));
  $cop = 'ctrl_' . $op . '_access';
  foreach ($access_map as $field_name => $r) {
    if (!(array_key_exists('abt_map', $r['settings']) && array_key_exists($cop, $r['settings']['abt_map']))) {
      continue;
    }
    if (is_object($usr) && property_exists($usr, $field_name) === TRUE) {

      // Current realm is applicable on this user.
      // Get the tids from users field (realm).
      $terms = field_get_items('user', $usr, $field_name);

      /* Get the children of terms and assign them all to the current realm. */
      $grants['abt_' . $field_name] = AbtUtils::taxonomyGetChildrenAll($terms);
    }

    // Check for Profile 2 module
    if (module_exists('profile2')) {

      // Get a list of profile names with current $r field.
      $profile_names = db_select('field_config_instance', 'fci')
        ->fields('fci', array(
        'bundle',
      ))
        ->condition('field_name', $r['field_name'])
        ->execute();
      while ($pname = $profile_names
        ->fetchAssoc()) {

        // Check if user has profile with $r field and get pid if true.
        $pids = db_select('profile', 'p')
          ->fields('p', array(
          'pid',
        ))
          ->condition('type', $pname['bundle'])
          ->condition('uid', $usr->uid)
          ->execute();
        while ($pid = $pids
          ->fetchAssoc()) {

          // Load Profile by pid.
          $profile = profile2_load($pid['pid']);
          if (property_exists($profile, $r['field_name']) === TRUE) {
            $terms = field_get_items('profile2', $profile, $r['field_name']);

            /* Get the children of terms and assign them all to the current realm. */
            $grants['abt_' . $r['field_name']] = AbtUtils::taxonomyGetChildrenAll($terms);
          }
        }
      }
    }

    // Make sure that user has the bare minimum in order to see unrestricted nodes
    $grants['abt_' . $r['field_name']][] = 0;
  }
  return $grants;
}