<?php

/**
 * @file
 * Allows you to group users, content and other entities.
 */

use Drupal\Component\Utility\Html;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Config\Entity\ConfigEntityInterface;
use Drupal\Core\Database\Query\AlterableInterface;
use Drupal\Core\Database\Query\SelectInterface;
use Drupal\Core\Entity\EntityFormInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Element;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\group\Entity\GroupInterface;
use Drupal\group\Entity\GroupRelationshipInterface;
use Drupal\group\Entity\Storage\ConfigWrapperStorageInterface;
use Drupal\group\Entity\Storage\GroupRelationshipStorageInterface;
use Drupal\group\Entity\Storage\GroupRoleStorageInterface;
use Drupal\group\QueryAccess\EntityQueryAlter;
use Drupal\group\QueryAccess\GroupQueryAlter;
use Drupal\group\QueryAccess\GroupRelationshipQueryAlter;
use Drupal\views\Plugin\views\query\QueryPluginBase;
use Drupal\views\Plugin\views\query\Sql;
use Drupal\views\ViewExecutable;

/**
 * Implements hook_help().
 */
function group_help($route_name, RouteMatchInterface $route_match) {
  switch ($route_name) {
    case 'entity.group_type.content_plugins':
      return '<p>' . t('Entities that can be added to this group type.') . '</p>';
  }
}

/**
 * Implements hook_element_info_alter().
 */
function group_element_info_alter(array &$types) {
  // Attach our extra CSS for toolbar icons.
  if (isset($types['toolbar'])) {
    $types['toolbar']['#attached']['library'][] = 'group/toolbar';
  }
}

/**
 * Implements hook_entity_bundle_info().
 */
function group_entity_bundle_info() {
  $plugin_manager = _group_relation_type_manager();
  $installed_ids = array_unique(array_merge(...array_values($plugin_manager->getGroupTypePluginMap())));
  $installed_ids = array_combine($installed_ids, $installed_ids);

  $installed_config_entity_types = [];
  foreach (array_intersect_key($plugin_manager->getDefinitions(), $installed_ids) as $group_relation_type) {
    if ($group_relation_type->handlesConfigEntityType()) {
      $config_entity_type_id = $group_relation_type->getEntityTypeId();
      $installed_config_entity_types[$config_entity_type_id] = $config_entity_type_id;
    }
  }

  $config_entity_types = [];
  foreach (\Drupal::entityTypeManager()->getDefinitions() as $entity_type_id => $entity_type) {
    if ($entity_type->entityClassImplements(ConfigEntityInterface::class)) {
      $config_entity_types[$entity_type_id] = $entity_type->getLabel();
    }
  }

  $bundles = [];
  foreach (array_intersect_key($config_entity_types, $installed_config_entity_types) as $entity_type_id => $entity_type_label) {
    $bundles['group_config_wrapper'][$entity_type_id]['label'] = $entity_type_label;
  }

  return $bundles;
}

/**
 * Implements hook_config_translation_info_alter().
 */
function group_config_translation_info_alter(&$info) {
  $info['group_role']['class'] = 'Drupal\group\ConfigTranslation\GroupRoleMapper';
}

/**
 * Implements hook_field_widget_info_alter().
 */
function group_field_widget_info_alter(array &$info) {
  // Anything that supports entity reference fields should also work for ours.
  foreach ($info as $key => $widget_info) {
    if (in_array('entity_reference', $widget_info['field_types'], TRUE)) {
      $info[$key]['field_types'][] = 'group_relationship_target';
    }
  }
}

/**
 * Implements hook_field_formatter_info_alter().
 */
function group_field_formatter_info_alter(array &$info) {
  // Anything that supports entity reference fields should also work for ours.
  foreach ($info as $key => $formatter_info) {
    if (in_array('entity_reference', $formatter_info['field_types'], TRUE)) {
      $info[$key]['field_types'][] = 'group_relationship_target';
    }
  }
}

/**
 * Implements hook_theme().
 */
function group_theme() {
  return [
    'group' => [
      'render element' => 'elements',
    ],
    'group_relationship' => [
      'render element' => 'elements',
    ],
  ];
}

/**
 * Implements hook_theme_suggestions_HOOK().
 */
function group_theme_suggestions_group(array $variables) {
  $suggestions = [];

  $group = $variables['elements']['#group'];
  assert($group instanceof GroupInterface);

  $sanitized_view_mode = strtr($variables['elements']['#view_mode'], '.', '_');

  $suggestions[] = 'group__' . $sanitized_view_mode;
  $suggestions[] = 'group__' . $group->bundle();
  $suggestions[] = 'group__' . $group->bundle() . '__' . $sanitized_view_mode;
  $suggestions[] = 'group__' . $group->id();
  $suggestions[] = 'group__' . $group->id() . '__' . $sanitized_view_mode;

  return $suggestions;
}

/**
 * Implements hook_theme_suggestions_HOOK().
 */
function group_theme_suggestions_group_relationship(array $variables) {
  $suggestions = [];

  $group_relationship = $variables['elements']['#group_relationship'];
  assert($group_relationship instanceof GroupRelationshipInterface);

  $sanitized_view_mode = strtr($variables['elements']['#view_mode'], '.', '_');
  $sanitized_bundle = strtr($group_relationship->bundle(), '-', '_');

  $suggestions[] = 'group_relationship__' . $sanitized_view_mode;
  $suggestions[] = 'group_relationship__' . $sanitized_bundle;
  $suggestions[] = 'group_relationship__' . $sanitized_bundle . '__' . $sanitized_view_mode;
  $suggestions[] = 'group_relationship__' . $group_relationship->id();
  $suggestions[] = 'group_relationship__' . $group_relationship->id() . '__' . $sanitized_view_mode;

  return $suggestions;
}

/**
 * Prepares variables for the group template.
 *
 * Default template: group.html.twig.
 *
 * @param array $variables
 *   - elements: An array of elements to display in view mode.
 *   - group: The group object.
 *   - view_mode: View mode; e.g., 'full', 'teaser', etc.
 */
function template_preprocess_group(&$variables) {
  $group = $variables['elements']['#group'];
  assert($group instanceof GroupInterface);

  $variables['group'] = $group;
  $variables['view_mode'] = $variables['elements']['#view_mode'];
  $variables['label'] = $group->label();

  $variables['attributes']['class'][] = 'group';
  $variables['attributes']['class'][] = Html::cleanCssIdentifier('group--' . $variables['view_mode']);
  $variables['attributes']['class'][] = Html::cleanCssIdentifier('group--' . $variables['group']->bundle());

  // Set variables that depend on the group being saved.
  $variables['url'] = '';
  $variables['page'] = FALSE;

  if (!$group->isNew()) {
    $variables['url'] = $group->toUrl('canonical', ['language' => $group->language()]);

    // See if we are rendering the group at its canonical route.
    $route_match = \Drupal::routeMatch();
    if ($route_match->getRouteName() == 'entity.group.canonical') {
      $page_group = $route_match->getParameter('group');
    }
    $is_page = !empty($page_group) && $page_group->id() == $group->id();
    $variables['page'] = $variables['view_mode'] == 'full' && $is_page;
  }

  // Helpful $content variable for templates.
  $variables += ['content' => []];
  foreach (Element::children($variables['elements']) as $key) {
    $variables['content'][$key] = $variables['elements'][$key];
  }
}

/**
 * Prepares variables for the group relationship template.
 *
 * Default template: group-relationship.html.twig.
 *
 * @param array $variables
 *   - elements: An array of elements to display in view mode.
 *   - group_relationship: The group relationship object.
 *   - view_mode: View mode; e.g., 'full', 'teaser', etc.
 */
function template_preprocess_group_relationship(&$variables) {
  $group_relationship = $variables['elements']['#group_relationship'];
  assert($group_relationship instanceof GroupRelationshipInterface);

  $variables['group_relationship'] = $group_relationship;
  $variables['view_mode'] = $variables['elements']['#view_mode'];
  $variables['label'] = $group_relationship->label();
  $variables['url'] = $group_relationship->toUrl('canonical', ['language' => $group_relationship->language()]);

  $variables['attributes']['class'][] = 'group-content';
  $variables['attributes']['class'][] = Html::cleanCssIdentifier('group-content--' . $variables['view_mode']);

  // See if we are rendering the group at its canonical route.
  $route_match = \Drupal::routeMatch();
  if ($route_match->getRouteName() == 'entity.group_relationship.canonical') {
    $page_group_relationship = $route_match->getParameter('group_relationship');
  }
  $is_page = (!empty($page_group_relationship) ? $page_group_relationship->id() == $group_relationship->id() : FALSE);
  $variables['page'] = $variables['view_mode'] == 'full' && $is_page;

  // Helpful $content variable for templates.
  $variables += ['content' => []];
  foreach (Element::children($variables['elements']) as $key) {
    $variables['content'][$key] = $variables['elements'][$key];
  }
}

/**
 * Implements hook_rebuild().
 */
function group_rebuild() {
  _group_relation_type_manager()->installEnforced();
}

/**
 * Implements hook_modules_installed().
 */
function group_modules_installed($modules) {
  // Only create config objects while config import is not in progress.
  if (!\Drupal::isConfigSyncing()) {
    _group_relation_type_manager()->installEnforced();
  }
}

/**
 * Implements hook_form_FORM_ID_alter().
 */
function group_form_block_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if (isset($form['visibility']['group_type'])) {
    $form['visibility_tabs']['#attached']['library'][] = 'group/block';
    $form['visibility']['group_type']['#title'] = t('Group types');
    $form['visibility']['group_type']['negate']['#type'] = 'value';
    $form['visibility']['group_type']['negate']['#title_display'] = 'invisible';
    $form['visibility']['group_type']['negate']['#value'] = $form['visibility']['group_type']['negate']['#default_value'];
  }
}

/**
 * Implements hook_module_implements_alter().
 */
function group_module_implements_alter(&$implementations, $hook) {
  // Make sure our query alters happen at the very last moment.
  if (in_array($hook, ['query_entity_query_alter', 'views_query_alter'], TRUE)) {
    // Move hook to the end of the list.
    $group = $implementations['group'];
    unset($implementations['group']);
    $implementations['group'] = $group;
  }
}

/**
 * Implements hook_query_TAG_alter().
 */
function group_query_entity_query_alter(AlterableInterface $query) {
  if (!$query instanceof SelectInterface) {
    return;
  }

  $entity_type_id = $query->getMetaData('entity_type');
  if ($query->hasTag($entity_type_id . '_access')) {
    $entity_type_manager = \Drupal::entityTypeManager();
    $entity_type = $entity_type_manager->getDefinition($entity_type_id);

    // Add specific access checks based on the entity type. Please note that we
    // first check for the group and relationship entity types because we have
    // full control over those and can therefore optimize the query more. If the
    // query is for a different entity type, we fall back to the default query
    // alter.
    //
    // PLEASE KEEP IN MIND that this means that a plugin that allows you to nest
    // groups will have no query access added for nested groups whatsoever. This
    // is by design as those plugins should opt to use the permission calculator
    // system, as it's way faster and automatically included in GroupQueryAlter.
    switch ($entity_type_id) {
      case 'group':
        $class_name = GroupQueryAlter::class;
        break;

      case 'group_relationship':
        $class_name = GroupRelationshipQueryAlter::class;
        break;

      default:
        $class_name = EntityQueryAlter::class;
    }

    \Drupal::service('class_resolver')
      ->getInstanceFromDefinition($class_name)
      ->alter($query, $entity_type);
  }
}

/**
 * Implements hook_query_TAG_alter().
 */
function group_query_views_entity_query_alter(AlterableInterface $query) {
  if (!$query instanceof SelectInterface) {
    return;
  }

  $entity_type_id = $query->getMetaData('entity_type');
  $query->addTag($entity_type_id . '_access');
  group_query_entity_query_alter($query);
}

/**
 * Implements hook_views_query_alter().
 */
function group_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
  if (!$query instanceof Sql || !empty($query->options['disable_sql_rewrite'])) {
    return;
  }

  $table_info = $query->getEntityTableInfo();
  $base_table = reset($table_info);
  if (empty($base_table['entity_type']) || $base_table['relationship_id'] != 'none') {
    return;
  }

  // Add a custom tag so we don't trigger all other 'entity_query' tag alters.
  $entity_type_id = $base_table['entity_type'];
  $query->addTag('views_entity_query');

  // Build the Views query already so we can access the DB query.
  $query->build($view);
  $view->built = TRUE;

  // Add metadata to the DB query.
  $query = $view->build_info['query'];
  $count_query = $view->build_info['count_query'];
  $query->addMetaData('entity_type', $entity_type_id);
  $count_query->addMetaData('entity_type', $entity_type_id);
}

/**
 * Implements hook_entity_access().
 */
function group_entity_access(EntityInterface $entity, $operation, AccountInterface $account) {
  // Some modules, including the code in \Drupal\node\NodeForm::access() may
  // check for 'view', 'update' or 'delete' access on new entities, even though
  // that makes little sense. We need to account for it to avoid crashes because
  // we would otherwise query the DB with a non-existent node ID.
  if ($entity->isNew()) {
    return AccessResult::neutral();
  }

  $plugin_manager = _group_relation_type_manager();

  // Find all of the group relations that define access.
  $plugin_ids = $plugin_manager->getPluginIdsByEntityTypeAccess($entity->getEntityTypeId());
  if (empty($plugin_ids)) {
    return AccessResult::neutral();
  }

  // If any new relationship entity is added using any of the retrieved
  // plugins, it might change access.
  $plugin_cache_tags = [];
  foreach ($plugin_ids as $plugin_id) {
    $plugin_cache_tags[] = "group_relationship_list:plugin:$plugin_id";
  }
  $access = AccessResult::neutral()->addCacheTags($plugin_cache_tags);

  // If the entity is config, we need to find the wrapper for it.
  if ($entity instanceof ConfigEntityInterface) {
    $wrapper_storage = \Drupal::entityTypeManager()->getStorage('group_config_wrapper');
    assert($wrapper_storage instanceof ConfigWrapperStorageInterface);
    $entity_id = $wrapper_storage->wrapEntity($entity)->id();
  }
  else {
    $entity_id = $entity->id();
  }

  // Reduce the plugin IDs to those that are actually in use.
  $data_table = \Drupal::entityTypeManager()
    ->getDefinition('group_relationship')
    ->getDataTable();

  $plugin_ids_used = \Drupal::database()
    ->select($data_table, 'd')
    ->fields('d', ['plugin_id'])
    ->condition('entity_id', $entity_id)
    ->condition('plugin_id', $plugin_ids, 'IN')
    ->distinct(TRUE)
    ->execute()
    ->fetchCol();

  // Loop over the plugin handlers and add their access check to the result.
  foreach ($plugin_ids_used as $plugin_id) {
    $handler = $plugin_manager->getAccessControlHandler($plugin_id);
    $access = $access->orIf($handler->entityAccess($entity, $operation, $account, TRUE));

    // No need to continue if access is denied.
    if ($access->isForbidden()) {
      break;
    }
  }

  return $access;
}

/**
 * Implements hook_entity_delete().
 */
function group_entity_delete(EntityInterface $entity) {
  $storage = \Drupal::entityTypeManager()->getStorage('group_relationship');
  assert($storage instanceof GroupRelationshipStorageInterface);

  // See if any relationships exist for the entity and delete them as well.
  if ($relationships = $storage->loadByEntity($entity)) {
    $storage->delete($relationships);
  }

  // Now that we've deleted all of the relationships, we can also see if the
  // entity was wrapped and delete the wrapper if necessary.
  if ($entity instanceof ConfigEntityInterface) {
    $storage = \Drupal::entityTypeManager()->getStorage('group_config_wrapper');
    assert($storage instanceof ConfigWrapperStorageInterface);

    if ($storage->supportsEntity($entity) && $wrapper = $storage->wrapEntity($entity, FALSE)) {
      $storage->delete([$wrapper]);
    }
  }
}

/**
 * Implements hook_entity_field_access().
 *
 * {@inheritdoc}
 *
 * @todo Move this to a form controller so we can hide the field if it has no
 *       options available to it?
 */
function group_entity_field_access($operation, FieldDefinitionInterface $field_definition, AccountInterface $account, ?FieldItemListInterface $items = NULL) {
  // Can't retrieve an entity from an empty item list.
  if (!isset($items)) {
    return AccessResult::neutral();
  }

  // We only care about the group_roles field when on a form.
  if ($field_definition->getName() != 'group_roles' || $operation !== 'edit') {
    return AccessResult::neutral();
  }

  // We only care if it is attached to a relationship type entity.
  if ($items->getEntity()->getEntityTypeId() != 'group_relationship') {
    return AccessResult::neutral();
  }

  $group_relationship = $items->getEntity();
  assert($group_relationship instanceof GroupRelationshipInterface);

  // We only care if the relationship entity is a group membership.
  if ($group_relationship->getPluginId() != 'group_membership') {
    return AccessResult::neutral();
  }

  // Now that we know we're dealing with a group_roles field on a group
  // membership form, we need to check whether the group membership belongs to a
  // group yet. If not, we can't check for access and should always hide it.
  if (!$group = $group_relationship->getGroup()) {
    return AccessResult::forbidden();
  }

  // Only group administrators should be able to change the membership roles.
  return AccessResult::forbiddenIf(!$group->hasPermission('administer members', $account));
}

/**
 * Implements hook_user_cancel_methods_alter().
 */
function group_user_cancel_methods_alter(&$methods) {
  $methods['user_cancel_block']['title'] = t('Disable the account and keep its content and groups.');
  $methods['user_cancel_block']['description'] .= ' ' . t('Groups that were created by you will still list you as the owner.');
  $methods['user_cancel_block_unpublish']['title'] .= ' ' . t('Does not affect groups.');
  $methods['user_cancel_block_unpublish']['description'] .= ' ' . t('Groups that were created by you will remain visible.');
  $methods['user_cancel_reassign']['title'] .= ' ' . t('Reassign its groups to the super administrator.');
  $methods['user_cancel_reassign']['description'] .= ' ' . t('All of your groups will be assigned to the super administrator.');
  $methods['user_cancel_delete']['title'] = t('Delete the account, its content and groups.');
  $methods['user_cancel_delete']['description'] .= ' ' . t('This includes groups that were created by you, including all of their content relationships!');
}

/**
 * Implements hook_user_cancel().
 */
function group_user_cancel($edit, $account, $method) {
  // Reassign all groups to the super user.
  if ($method == 'user_cancel_reassign') {
    $storage = \Drupal::entityTypeManager()->getStorage('group');
    $gids = $storage->getQuery()
      ->accessCheck(FALSE)
      ->condition('uid', $account->id())
      ->execute();

    // Run this as a batch if there are more than 10 groups.
    if (count($gids) > 10) {
      batch_set(['operations' => [['_group_mass_reassign_to_super_user', [$gids]]]]);
    }
    // Run it immediately if not.
    else {
      foreach ($storage->loadMultiple($gids) as $group) {
        assert($group instanceof GroupInterface);
        $group->set('uid', 1);
        $storage->save($group);
      }
    }
  }
}

/**
 * Implements callback_batch_operation().
 *
 * Mass reassigns ownership of groups to the super user.
 *
 * @param int[] $ids
 *   An array of group IDs.
 */
function _group_mass_reassign_to_super_user(array $ids, &$context) {
  if (!isset($context['sandbox']['progress'])) {
    $context['sandbox']['progress'] = 0;
    $context['sandbox']['max'] = count($ids);
    $context['sandbox']['ids'] = $ids;
  }

  // Try to update 10 groups at a time.
  $ids = array_slice($context['sandbox']['ids'], $context['sandbox']['progress'], 10);

  $storage = \Drupal::entityTypeManager()->getStorage('group');
  foreach ($storage->loadMultiple($ids) as $group) {
    assert($group instanceof GroupInterface);
    $group->set('uid', 1);
    $storage->save($group);
    $context['sandbox']['progress']++;
  }

  if ($context['sandbox']['progress'] != $context['sandbox']['max']) {
    $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];
  }
}

/**
 * Implements hook_ENTITY_TYPE_update().
 */
function group_user_update(AccountInterface $account) {
  // If a user's roles change, we need to reset their group roles cache.
  $new = array_unique($account->getRoles());
  $old = array_unique($account->original->getRoles());
  sort($new);
  sort($old);

  if ($new != $old) {
    $storage = \Drupal::entityTypeManager()->getStorage('group_role');
    assert($storage instanceof GroupRoleStorageInterface);
    $storage->resetUserGroupRoleCache($account);
  }
}

/**
 * Implements hook_ENTITY_TYPE_delete().
 */
function group_user_delete(EntityInterface $account) {
  // If a user is deleted, we delete all of their groups too.
  $storage = \Drupal::entityTypeManager()->getStorage('group');
  if ($groups = $storage->loadByProperties(['uid' => $account->id()])) {
    $storage->delete($groups);
  }
}

/**
 * Implements hook_form_alter().
 */
function group_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  // GroupRelationshipController::createForm() tends to load entity forms for
  // adding entities to a group. We need to add or alter the submit handlers of
  // those forms for the process to work properly.
  if ($form_state->has('group_wizard') && $form_state->get('group_wizard_id') == 'group_entity') {
    if ($wizard = $form_state->get('group_wizard')) {
      $store = \Drupal::service('tempstore.private')->get($form_state->get('group_wizard_id'));
      $store_id = $form_state->get('store_id');

      // Bail out if we are on step 2 of the wizard. We only want to alter the
      // submit handlers for the first step or if we are not in a wizard.
      if ($store->get("$store_id:step") === 2) {
        return;
      }
    }

    $actions = $form['actions'] ?? [];
    foreach (Element::children($actions) as $name) {
      // Remove preview button as it redirects back to the wrong form.
      if ($name == 'preview') {
        unset($form['actions'][$name]);
        continue;
      }

      // Skip buttons without submit handlers.
      if (empty($form['actions'][$name]['#submit'])) {
        continue;
      }

      // Skip buttons that do not properly build and save an entity.
      $submit = $form['actions'][$name]['#submit'];
      if (!in_array('::submitForm', $submit) || !in_array('::save', $submit)) {
        continue;
      }

      // If we are using the wizard, we need to substitute the entity save
      // handler in order to add the entity to the private temp store.
      if ($wizard) {
        foreach ($submit as $key => $handler) {
          if ($handler == '::save') {
            $form['actions'][$name]['#submit'][$key] = 'group_relationship_wizard_store';
          }
        }
      }
      // Otherwise, we can simply add our submit handler and be done with it.
      else {
        $form['actions'][$name]['#submit'][] = 'group_relationship_entity_submit';
      }
    }

    // If we are using the wizard, we also add a cancel button to step 1.
    if ($wizard) {
      $form['actions']['cancel'] = [
        '#type' => 'submit',
        '#value' => t('Cancel'),
        '#submit' => ['group_relationship_wizard_cancel'],
        '#limit_validation_errors' => [],
      ];
    }
  }
}

/**
 * Stores a content entity from the wizard step 1 in the temp store.
 *
 * @see group_form_alter()
 * @see \Drupal\group\Entity\Controller\GroupRelationshipController::createForm()
 */
function group_relationship_wizard_store($form, FormStateInterface $form_state) {
  $form_object = $form_state->getFormObject();
  assert($form_object instanceof EntityFormInterface);

  // Store the unsaved entity in the temp store.
  $store = \Drupal::service('tempstore.private')->get($form_state->get('group_wizard_id'));
  $store_id = $form_state->get('store_id');
  $store->set("$store_id:entity", $form_object->getEntity());
  $store->set("$store_id:step", 2);

  // Disable any URL-based redirect until the final step.
  $request = \Drupal::service('request_stack')->getCurrentRequest();
  $form_state->setRedirect('<current>', [], ['query' => $request->query->all()]);
  $request->query->remove('destination');
}

/**
 * Cancels the wizard for relationship creation.
 *
 * @see group_form_alter()
 * @see \Drupal\group\Entity\Controller\GroupRelationshipController::createForm()
 */
function group_relationship_wizard_cancel($form, FormStateInterface $form_state) {
  $store = \Drupal::service('tempstore.private')->get($form_state->get('group_wizard_id'));
  $store_id = $form_state->get('store_id');
  $store->delete("$store_id:entity");
  $store->delete("$store_id:step");

  $group = $form_state->get('group');
  assert($group instanceof GroupInterface);

  // Redirect to the group page if no destination was set in the URL.
  $form_state->setRedirect('entity.group.canonical', ['group' => $group->id()]);
}

/**
 * Adds a newly saved entity to a group.
 *
 * @see group_form_alter()
 * @see \Drupal\group\Entity\Controller\GroupRelationshipController::createForm()
 */
function group_relationship_entity_submit($form, FormStateInterface $form_state) {
  $form_object = $form_state->getFormObject();
  assert($form_object instanceof EntityFormInterface);
  $entity = $form_object->getEntity();

  $group = $form_state->get('group');
  assert($group instanceof GroupInterface);
  $group->addRelationship($entity, $form_state->get('group_relation'));

  // This submit handler is only called when creating new content within a group
  // without using the 2-step wizard. We can therefore safely assume the user
  // wants to see the entity itself and not the relationship. This only applies
  // if there was no "destination" query argument.
  if ($entity->access('view')) {
    $form_state->setRedirectUrl($entity->toUrl());
  }
  elseif ($group->access('view')) {
    $form_state->setRedirectUrl($group->toUrl());
  }
  else {
    $form_state->setRedirect('<front>');
  }
}

/**
 * @defgroup group_access Group access rights
 * @{
 * The group access system determines who can do what in which groups.
 *
 * Each group type can specify an unlimited amount of group roles. Just like
 * user roles in the global scope, a group role can be assigned specific
 * permissions. Users who are then given such group roles will be able to
 * perform any action their permissions allow them.
 *
 * There are three categories of users who are eligible to receive group roles:
 * - Anonymous: These users do not have a site account and will only receive the
 *   'anonymous' group role, which typically grants them a very limited set of
 *   permissions.
 * - Outsider: These users have a site account, but are not yet a member of the
 *   group in question. They will only receive the 'outsider' group role. This
 *   role is usually more permissive than 'anonymous'.
 * - Member: These users have a site account and are part of the group. They
 *   will automatically receive the 'member' role but can be assigned any other
 *   user defined group role. Common examples are: Editor, Admin, etc.
 *
 * Please keep in mind that the 'anonymous', 'outsider' and 'member' role will
 * always be assigned because they're assumed roles based on the user's account
 * status.
 */

// Nothing to see here yet, our own access hook implementations will go here.

/**
 * @} End of "defgroup group_access".
 */

/**
 * Gets the group relation type manager.
 *
 * @return \Drupal\group\Plugin\Group\Relation\GroupRelationTypeManagerInterface
 *   The group relation type manager.
 *
 * @internal Try to properly inject the service when possible.
 */
function _group_relation_type_manager() {
  return \Drupal::service('group_relation_type.manager');
}
