forked from Gizra/og
-
Notifications
You must be signed in to change notification settings - Fork 0
/
og.module
executable file
·430 lines (377 loc) · 15.1 KB
/
og.module
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
<?php
/**
* @file
* Enable users to create and manage groups with roles and permissions.
*/
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Config\Entity\ConfigEntityBundleBase;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\Core\Session\AccountInterface;
use Drupal\og\Entity\OgRole;
use Drupal\og\Og;
use Drupal\og\OgGroupAudienceHelperInterface;
use Drupal\og\OgMembershipInterface;
use Drupal\og\OgRoleInterface;
use Drupal\system\Entity\Action;
use Drupal\user\EntityOwnerInterface;
use Drupal\user\UserInterface;
/**
* Group default roles and permissions field.
*/
define('OG_DEFAULT_ACCESS_FIELD', 'og_roles_permissions');
/**
* Implements hook_entity_insert().
*
* Subscribe the group manager.
*/
function og_entity_insert(EntityInterface $entity) {
// Invalidate cache tags if new group content is created.
og_invalidate_group_content_cache_tags($entity);
if (!Og::isGroup($entity->getEntityTypeId(), $entity->bundle())) {
// Not a group entity.
return;
}
if (!$entity instanceof EntityOwnerInterface) {
return;
}
$owner = $entity->getOwner();
if (empty($owner) || $owner->isAnonymous()) {
// User is anonymous, se we cannot set a membership for them.
return;
}
// Other modules that implement hook_entity_insert() might already have
// created a membership ahead of us.
if (!Og::getMembership($entity, $entity->getOwner(), [
OgMembershipInterface::STATE_ACTIVE,
OgMembershipInterface::STATE_PENDING,
OgMembershipInterface::STATE_BLOCKED,
])) {
$membership = Og::createMembership($entity, $entity->getOwner());
$membership->save();
}
}
/**
* Implements hook_entity_update().
*/
function og_entity_update(EntityInterface $entity) {
// Invalidate cache tags if a group or group content entity is updated.
og_invalidate_group_content_cache_tags($entity);
}
/**
* Implements hook_entity_predelete().
*/
function og_entity_predelete(EntityInterface $entity) {
if (Og::isGroup($entity->getEntityTypeId(), $entity->bundle())) {
// Register orphaned group content for deletion, if this option has been
// enabled.
$config = \Drupal::config('og.settings');
if ($config->get('delete_orphans')) {
$plugin_id = $config->get('delete_orphans_plugin_id');
/** @var \Drupal\og\OgDeleteOrphansInterface $plugin */
$plugin = \Drupal::service('plugin.manager.og.delete_orphans')->createInstance($plugin_id, []);
$plugin->register($entity);
}
// @todo Delete user roles.
// @see https://github.com/amitaibu/og/issues/175
// og_delete_user_roles_by_group($entity_type, $entity);
}
// If a user is being deleted, also delete its memberships.
if ($entity instanceof UserInterface) {
/** @var \Drupal\og\MembershipManagerInterface $membership_manager */
$membership_manager = \Drupal::service('og.membership_manager');
foreach ($membership_manager->getMemberships($entity, []) as $membership) {
$membership->delete();
}
}
}
/**
* Implements hook_entity_delete().
*/
function og_entity_delete(EntityInterface $entity) {
// Invalidate cache tags after a group or group content entity is deleted.
og_invalidate_group_content_cache_tags($entity);
// Clear static caches after a group or group content entity is deleted.
if (Og::isGroup($entity->getEntityTypeId(), $entity->bundle()) || Og::isGroupContent($entity->getEntityTypeId(), $entity->bundle())) {
Og::invalidateCache();
}
// If a group content type is deleted, make sure to remove it from the list of
// groups.
if ($entity instanceof ConfigEntityBundleBase) {
$bundle = $entity->id();
$entity_type_id = \Drupal::entityTypeManager()->getDefinition($entity->getEntityTypeId())->getBundleOf();
if (Og::isGroup($entity_type_id, $bundle)) {
Og::groupTypeManager()->removeGroup($entity_type_id, $bundle);
}
}
}
/**
* Implements hook_entity_access().
*/
function og_entity_access(EntityInterface $entity, $operation, AccountInterface $account) {
// Grant access to view roles, so that they can be shown in listings.
if ($entity instanceof OgRoleInterface && $operation == 'view') {
return AccessResult::allowed();
}
// We only care about content entities that are groups or group content.
if (!$entity instanceof ContentEntityInterface) {
return AccessResult::neutral();
}
if ($operation == 'view') {
return AccessResult::neutral();
}
$entity_type_id = $entity->getEntityTypeId();
$bundle_id = $entity->bundle();
$is_group_content = Og::isGroupContent($entity_type_id, $bundle_id);
// If the entity is neither a group or group content, then we have no opinion.
if (!Og::isGroup($entity_type_id, $bundle_id) && !$is_group_content) {
return AccessResult::neutral();
}
// If the entity type is a group content type, but the entity is not
// associated with any groups, we have no opinion.
if ($is_group_content && \Drupal::service('og.membership_manager')->getGroupCount($entity) === 0) {
return AccessResult::neutral();
}
// If the user has permission to administer all groups, allow access.
if ($account->hasPermission('administer group')) {
return AccessResult::allowed();
}
/** @var \Drupal\Core\Access\AccessResult $access */
$access = \Drupal::service('og.access')->userAccessEntity($operation, $entity, $account);
if ($access->isAllowed()) {
return $access;
}
if ($entity_type_id == 'node') {
$node_access_strict = \Drupal::config('og.settings')->get('node_access_strict');
// Otherwise, ignore or deny based on whether strict node access is set.
return AccessResult::forbiddenIf($node_access_strict);
}
return AccessResult::forbidden();
}
/**
* Implements hook_entity_create_access().
*/
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();
}
$access_result = AccessResult::allowedIfHasPermission($account, 'administer group');
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_name => $field_definition) {
/** @var \Drupal\Core\Field\FieldDefinitionInterface $field_definition */
if (!\Drupal::service('og.group_audience_helper')->isGroupAudienceField($field_definition)) {
continue;
}
$handler = Og::getSelectionHandler($field_definition);
if ($handler->getReferenceableEntities()) {
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();
}
/**
* Implements hook_entity_bundle_field_info().
*
* Add a read only property to group entities as a group flag.
*/
function og_entity_bundle_field_info(EntityTypeInterface $entity_type, $bundle, array $base_field_definitions) {
if (!Og::isGroup($entity_type->id(), $bundle)) {
// Not a group type.
return NULL;
}
$fields = [];
$fields['og_group'] = BaseFieldDefinition::create('og_group')
->setLabel(t('OG Group'))
->setComputed(TRUE)
->setTranslatable(FALSE)
->setDefaultValue(TRUE)
->setReadOnly(TRUE);
return $fields;
}
/**
* Implements hook_entity_bundle_field_info_alter().
*
* Set the default field formatter of fields of type OG group.
*/
function og_entity_bundle_field_info_alter(&$fields, EntityTypeInterface $entity_type, $bundle) {
if (!isset($fields['og_group'])) {
// No OG group fields.
return;
}
$fields['og_group']->setDisplayOptions('view', [
'weight' => 0,
'type' => 'og_group_subscribe',
])->setDisplayConfigurable('view', TRUE);
}
/**
* Implements hook_field_formatter_info_alter().
*
* Allow OG audience fields to have entity reference formatters.
*/
function og_field_formatter_info_alter(array &$info) {
foreach (array_keys($info) as $key) {
if (!in_array('entity_reference', $info[$key]['field_types'])) {
// Not an entity reference formatter.
continue;
}
$info[$key]['field_types'][] = OgGroupAudienceHelperInterface::GROUP_REFERENCE;
}
}
/**
* Implements hook_field_widget_info_alter().
*/
function og_field_widget_info_alter(array &$info) {
$info['options_buttons']['field_types'][] = OgGroupAudienceHelperInterface::GROUP_REFERENCE;
}
/**
* Implements hook_entity_type_alter().
*
* Add link template to groups. We add it to all the entity types, and later on
* return the correct access, depending if the bundle is indeed a group and
* accessible. We do not filter here the entity type by groups, so whenever
* GroupTypeManagerInterface::addGroup is called, it's enough to mark route to
* be rebuilt via RouteBuilder::setRebuildNeeded.
*/
function og_entity_type_alter(array &$entity_types) {
/** @var \Drupal\Core\Entity\EntityTypeInterface $entity_type */
foreach ($entity_types as $entity_type_id => $entity_type) {
$entity_type->setLinkTemplate('og-admin-routes', "/group/$entity_type_id/{{$entity_type_id}}/admin");
}
}
/**
* Invalidates group content cache tags for the groups this entity belongs to.
*
* @param \Drupal\Core\Entity\EntityInterface $entity
* The group content entity that is being created, changed or deleted and is
* the direct cause for the need to invalidate cached group content.
*/
function og_invalidate_group_content_cache_tags(EntityInterface $entity) {
// If group content is created or updated, invalidate the group content cache
// tags for each of the groups this group content belongs to. This allows
// group listings to be cached effectively. Also invalidate the tags if the
// group itself changes. The cache tag format is
// 'og-group-content:{group entity type}:{group entity id}'.
$is_group_content = Og::isGroupContent($entity->getEntityTypeId(), $entity->bundle());
$group_is_updated = Og::isGroup($entity->getEntityTypeId(), $entity->bundle()) && !empty($entity->original);
if ($group_is_updated || $is_group_content) {
/** @var \Drupal\og\MembershipManagerInterface $membership_manager */
$membership_manager = \Drupal::service('og.membership_manager');
$tags = [];
// If the entity is a group content and we came here as an effect of an
// update, check if any of the OG audience fields have been changed. This
// means the group(s) of the entity changed and we should also invalidate
// the tags of the old group(s).
/** @var \Drupal\Core\Entity\FieldableEntityInterface $entity */
$original = !empty($entity->original) ? $entity->original : NULL;
if ($is_group_content && $original) {
/** @var \Drupal\og\OgGroupAudienceHelperInterface $group_audience_helper */
$group_audience_helper = \Drupal::service('og.group_audience_helper');
$audience_has_changed = FALSE;
/** @var \Drupal\Core\Entity\FieldableEntityInterface $original */
foreach ($group_audience_helper->getAllGroupAudienceFields($entity->getEntityTypeId(), $entity->bundle()) as $field) {
$field_name = $field->getName();
/** @var \Drupal\Core\Field\EntityReferenceFieldItemListInterface $original_field_item_list */
$original_field_item_list = $original->get($field_name);
if (!$entity->get($field_name)->equals($original_field_item_list)) {
foreach ($original_field_item_list->referencedEntities() as $old_group) {
$tags = Cache::mergeTags($tags, $old_group->getCacheTagsToInvalidate());
}
$audience_has_changed = TRUE;
}
}
if ($audience_has_changed) {
// If at least a group has changed, we clear the static cache of the
// membership manager which stores such relations. This is important
// when the membership manager was used previously in the same request.
$membership_manager->reset();
}
}
foreach ($membership_manager->getGroups($entity) as $group_entity_type_id => $groups) {
/** @var \Drupal\Core\Entity\ContentEntityInterface $group */
foreach ($groups as $group) {
$tags = Cache::mergeTags($tags, $group->getCacheTagsToInvalidate());
}
}
Cache::invalidateTags(Cache::buildTags('og-group-content', $tags));
}
}
/**
* Implements hook_ENTITY_TYPE_insert() for OgRole entities.
*/
function og_og_role_insert(OgRoleInterface $role) {
// Create actions to add or remove the role, except for the required default
// roles 'member' and 'non-member'. These cannot be added or removed.
if ($role->getRoleType() === OgRoleInterface::ROLE_TYPE_REQUIRED) {
return;
}
$add_id = 'og_membership_add_single_role_action.' . $role->getName();
if (!Action::load($add_id)) {
$action = Action::create([
'id' => $add_id,
'type' => 'og_membership',
'label' => t('Add the @label role to the selected members', ['@label' => $role->getName()]),
'configuration' => [
'role_name' => $role->getName(),
],
'plugin' => 'og_membership_add_single_role_action',
]);
$action->trustData()->save();
}
$remove_id = 'og_membership_remove_single_role_action.' . $role->getName();
if (!Action::load($remove_id)) {
$action = Action::create([
'id' => $remove_id,
'type' => 'og_membership',
'label' => t('Remove the @label role from the selected members', ['@label' => $role->getName()]),
'configuration' => [
'role_name' => $role->getName(),
],
'plugin' => 'og_membership_remove_single_role_action',
]);
$action->trustData()->save();
}
}
/**
* Implements hook_ENTITY_TYPE_delete() for OgRole entities.
*/
function og_og_role_delete(OgRoleInterface $role) {
$role_name = $role->getName();
/** @var \Drupal\system\ActionConfigEntityInterface[] $actions */
$actions = Action::loadMultiple([
'og_membership_add_single_role_action.' . $role_name,
'og_membership_remove_single_role_action.' . $role_name,
]);
// Only remove the actions when the role name is not used by any other roles.
foreach (OgRole::loadMultiple() as $role) {
if ($role->getName() === $role_name) {
return;
}
}
foreach ($actions as $action) {
$action->delete();
}
}