You are here

function og_entity_create_access in Organic groups 8

Implements hook_entity_create_access().

File

./og.module, line 178

Code

function og_entity_create_access(AccountInterface $account, array $context, $bundle) {
  $entity_type_id = $context['entity_type_id'];
  if (!Og::isGroupContent($entity_type_id, $bundle)) {

    // Not a group content.
    return AccessResult::neutral();
  }

  // A user with the global permission to administer all groups has full access.
  $access_result = AccessResult::allowedIfHasPermission($account, 'administer organic groups');
  if ($access_result
    ->isAllowed()) {
    return $access_result;
  }
  $node_access_strict = \Drupal::config('og.settings')
    ->get('node_access_strict');
  if ($entity_type_id == 'node' && !$node_access_strict && $account
    ->hasPermission("create {$bundle} content")) {

    // The user has the core permission and strict node access is not set.
    return AccessResult::neutral();
  }

  // We can't check if user has create permissions, as there is no group
  // context. However, we can check if there are any groups the user will be
  // able to select, and if not, we don't allow access but if there are,
  // AccessResult::neutral() will be returned in order to not override other
  // access results.
  // @see \Drupal\og\Plugin\EntityReferenceSelection\OgSelection::buildEntityQuery()
  $required = FALSE;
  $field_definitions = \Drupal::service('entity_field.manager')
    ->getFieldDefinitions($entity_type_id, $bundle);
  foreach ($field_definitions as $field_definition) {

    /** @var \Drupal\Core\Field\FieldDefinitionInterface $field_definition */
    if (!\Drupal::service('og.group_audience_helper')
      ->isGroupAudienceField($field_definition)) {
      continue;
    }
    $options = [
      'target_type' => $field_definition
        ->getFieldStorageDefinition()
        ->getSetting('target_type'),
      'handler' => $field_definition
        ->getSetting('handler'),
      'field_mode' => 'admin',
    ];

    /** @var \Drupal\Core\Entity\EntityReferenceSelection\SelectionPluginManager $handler */
    $handler = \Drupal::service('plugin.manager.entity_reference_selection');
    if ($handler
      ->getInstance($options)) {
      return AccessResult::neutral();
    }

    // Allow users to create content outside of groups, if none of the
    // audience fields is required.
    $required = $field_definition
      ->isRequired();
  }

  // Otherwise, ignore or deny based on whether strict entity access is set.
  return $required ? AccessResult::forbiddenIf($node_access_strict) : AccessResult::neutral();
}