This repository has been archived by the owner on Jul 8, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 28
/
openy_gated_content.module
592 lines (532 loc) · 20.6 KB
/
openy_gated_content.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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
<?php
/**
* @file
* The openy_gated_content module routines.
*/
use Drupal\Core\Entity\Entity\EntityViewDisplay;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
use Drupal\openy_gated_content\VyFavoriteItemsManager;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Drupal\openy_gated_content\SegmentContentAccessCheck;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\taxonomy\Entity\Vocabulary;
use Drupal\taxonomy\TermStorageInterface;
use Drupal\node\NodeInterface;
/**
* Implements hook_theme().
*/
function openy_gated_content_theme() {
return [
'paragraph__gated_content' => [
'base hook' => 'paragraph',
'variables' => [
'app_settings' => '',
'headline' => '',
],
],
'paragraph__gated_content_login' => [
'base hook' => 'paragraph',
'variables' => [
'auth_provider_id' => '',
'auth_configuration' => '',
],
],
];
}
/**
* Implements hook_preprocess_paragraph().
*/
function openy_gated_content_preprocess_paragraph(&$variables) {
if (!isset($variables['paragraph'])) {
return;
}
$paragraphs_list = ['gated_content', 'gated_content_login'];
if (!in_array($variables['paragraph']->getType(), $paragraphs_list)) {
return;
}
$variables['#cache']['tags'][] = 'config:openy_gated_content.settings';
$variables['#cache']['tags'][] = 'config:openy_gc_auth.settings';
$active_provider = \Drupal::config('openy_gc_auth.settings')->get('active_provider');
$identityProviderManager = \Drupal::service('plugin.manager.gc_identity_provider');
$plugin_definition = $identityProviderManager->getDefinition($active_provider, FALSE);
if (!$plugin_definition) {
return;
}
$plugin_instance = $identityProviderManager->createInstance($active_provider);
$app_config = \Drupal::config('openy_gated_content.settings')->getOriginal();
// Give ability for 3rd party modules to alter data for the js app.
\Drupal::moduleHandler()->alter('virtual_y_app_settings', $app_config);
$variables['app_settings'] = json_encode($app_config);
if ($variables['paragraph']->getType() === 'gated_content') {
$backgroundImage = '';
if ($mediaImage = $variables['paragraph']->field_prgf_image->entity) {
$display_options = EntityViewDisplay::collectRenderDisplay($variables['paragraph'], 'default')
->getComponent('field_prgf_image');
$image_style = \Drupal::service('entity_type.manager')->getStorage('image_style')
->load($display_options['settings']['image_style']);
$backgroundImage = $image_style->buildUrl($mediaImage->field_media_image->entity->uri->value);
}
if (empty($backgroundImage)) {
$file = 'base://' . \Drupal::service('extension.list.module')->getPath('openy_gated_content') . '/assets/img/paragraph-headline.png';
$backgroundImage = Url::fromUri($file)->setAbsolute()->toString();
}
$headline = [
'title' => $variables['paragraph']->field_prgf_title->value,
'description' => $variables['paragraph']->field_prgf_description->value,
'backgroundImage' => $backgroundImage,
];
if ($variables['paragraph']->field_prgf_link->title) {
$headline['linkText'] = $variables['paragraph']->field_prgf_link->title;
$headline['linkUrl'] = Url::fromUri($variables['paragraph']->field_prgf_link->uri)->toString();
}
$variables['headline'] = json_encode($headline);
}
$variables['#cache']['tags'][] = 'config:' . $plugin_instance->getConfigName();
}
/**
* Implements hook_preprocess_html().
*
* Set 'openy-gated-content' body class
* if gated_content paragraph is used on page.
*/
function openy_gated_content_preprocess_html(&$variables) {
$node = \Drupal::routeMatch()->getParameter('node');
if ($node instanceof NodeInterface) {
if ($node->hasField('field_content')) {
foreach ($node->field_content as $field_item) {
if ($field_item->entity->bundle() === 'gated_content') {
$variables['attributes']['class'][] = openy_gated_content_get_base_theme() . '-based';
$variables['attributes']['class'][] = 'openy-gated-content';
if (openy_gated_content_get_base_theme() === 'openy_rose') {
$variables['#attached']['library'][] = 'openy_gated_content/openy-rose-menu';
}
}
}
}
if ($node->hasField('field_bottom_content')) {
foreach ($node->field_bottom_content as $field_item) {
if ($field_item->entity->bundle() === 'gated_content') {
$variables['attributes']['class'][] = openy_gated_content_get_base_theme() . '-based';
$variables['attributes']['class'][] = 'openy-gated-content';
if (openy_gated_content_get_base_theme() === 'openy_rose') {
$variables['#attached']['library'][] = 'openy_gated_content/openy-rose-menu';
}
}
}
}
}
}
/**
* Return base theme name.
*/
function openy_gated_content_get_base_theme() {
$activeTheme = \Drupal::service('theme.manager')->getActiveTheme();
if ($extensions = $activeTheme->getBaseThemeExtensions()) {
$names = array_keys($extensions);
return end($names);
}
return $activeTheme->getName();
}
/**
* Implements hook_jsonapi_ENTITY_TYPE_filter_access().
*
* Without this hook there no access to filter by date in
* JSON API for eventinstance.
*
* @see https://www.drupal.org/project/jsonapi/issues/3037519
*/
function openy_gated_content_jsonapi_eventinstance_filter_access(EntityTypeInterface $entity_type, AccountInterface $account) {
return ([
JSONAPI_FILTER_AMONG_ALL => AccessResult::allowedIfHasPermission($account, 'view eventinstance entity'),
JSONAPI_FILTER_AMONG_PUBLISHED => AccessResult::allowedIfHasPermission($account, 'view eventinstance entity'),
JSONAPI_FILTER_AMONG_OWN => AccessResult::allowedIfHasPermission($account, 'view eventinstance entity'),
]);
}
/**
* Implements hook_jsonapi_ENTITY_TYPE_filter_access().
*
* Without this hook there no access to filter by parent category in
* JSON API for eventinstance.
*
* @see https://www.drupal.org/project/jsonapi/issues/3037519
*/
function openy_gated_content_jsonapi_eventseries_filter_access(EntityTypeInterface $entity_type, AccountInterface $account) {
return ([
JSONAPI_FILTER_AMONG_ALL => AccessResult::allowedIfHasPermission($account, 'view eventseries entity'),
JSONAPI_FILTER_AMONG_PUBLISHED => AccessResult::allowedIfHasPermission($account, 'view eventseries entity'),
JSONAPI_FILTER_AMONG_OWN => AccessResult::allowedIfHasPermission($account, 'view eventseries entity'),
]);
}
/**
* Implements hook_jsonapi_ENTITY_TYPE_filter_access().
*
* Without this hook there no access to filter by instructor in
* JSON API for eventinstance.
*
* @see https://www.drupal.org/project/jsonapi/issues/3037519
*/
function openy_gated_content_jsonapi_taxonomy_term_filter_access(EntityTypeInterface $entity_type, AccountInterface $account) {
return ([
JSONAPI_FILTER_AMONG_ALL => AccessResult::allowedIfHasPermission($account, 'access content'),
JSONAPI_FILTER_AMONG_PUBLISHED => AccessResult::allowedIfHasPermission($account, 'access content'),
JSONAPI_FILTER_AMONG_OWN => AccessResult::allowedIfHasPermission($account, 'access content'),
]);
}
/**
* Implements hook_form_alter().
*/
function openy_gated_content_form_alter(&$form, FormStateInterface $form_state, $form_id) {
$event_series_forms = [
'eventseries_live_stream_edit_form',
'eventseries_virtual_meeting_edit_form',
];
if (in_array($form_id, $event_series_forms)) {
// Disable rebuild form.
$form['#validate'][] = '_openy_gated_content_form_eventseries_live_stream_validate';
// We need to clear JSON API cache bin on submit.
$form['actions']['submit']['#submit'][] = '_openy_gated_content_form_eventseries_live_stream_submit';
}
$event_instance_forms = [
'eventinstance_live_stream_edit_form',
'eventinstance_virtual_meeting_edit_form',
];
if (in_array($form_id, $event_instance_forms)) {
// Collapse field_inheritance by default in event instance edit form.
$form['field_inheritance']['#open'] = FALSE;
}
if (!isset($form['field_vy_permission'])) {
return;
}
$gcConfig = \Drupal::config('openy_gated_content.settings')->getRawData();
$allowedForms = [];
if (!empty($gcConfig['permissions_entities'])) {
$permissionEnabledEntities = $gcConfig['permissions_entities'];
foreach ($permissionEnabledEntities as $entity_key => $bundle_list) {
foreach ($bundle_list as $bundle) {
$allowedForms[] = $entity_key . '_' . $bundle . '_form';
$allowedForms[] = $entity_key . '_' . $bundle . '_edit_form';
$allowedForms[] = $entity_key . '_' . $bundle . '_add_form';
// Adding _clone_form into allowedForms array.
$allowedForms[] = $entity_key . '_' . $bundle . '_clone_form';
}
}
}
$form['virtual_y_permissions'] = [
'#type' => 'details',
'#title' => t('Virtual Y Permissions'),
'#description' => t('Select user segments that available to see this content.'),
'#open' => FALSE,
'#group' => 'advanced',
'#weight' => 125,
];
$form['field_vy_permission']['#group'] = 'virtual_y_permissions';
if (!in_array($form_id, $allowedForms)) {
// Close access to permissions field for all entities except of enabled.
$form['virtual_y_permissions']['#access'] = FALSE;
$form['field_vy_permission']['#access'] = FALSE;
return;
}
}
/**
* Custom validation for eventseries_live_stream_edit_form.
*/
function _openy_gated_content_form_eventseries_live_stream_validate(&$form, FormStateInterface $form_state) {
// This will fix entity save, but disable confirmation step
// on date change.
$form_state->setRebuild(FALSE);
}
/**
* Custom submit handler for eventseries_live_stream_edit_form.
*/
function _openy_gated_content_form_eventseries_live_stream_submit(&$form, FormStateInterface $form_state) {
\Drupal::cache('jsonapi_normalizations')->deleteAll();
}
/**
* Implements hook_page_attachments().
*/
function openy_gated_content_page_attachments(array &$attachments) {
$attachments['#attached']['library'][] = 'openy_gated_content/admin_ui_styles';
$attachments['#attached']['library'][] = 'openy_gated_content/openy_gated_content_styles';
if (openy_gated_content_get_base_theme() === 'openy_lily') {
$attachments['#attached']['library'][] = 'openy_gated_content/openy_lily_styles';
}
if (openy_gated_content_get_base_theme() === 'openy_carnation') {
$attachments['#attached']['library'][] = 'openy_gated_content/openy_carnation_styles';
}
if (openy_gated_content_get_base_theme() === 'openy_rose') {
$attachments['#attached']['library'][] = 'openy_gated_content/openy_rose_styles';
}
}
/**
* Implements hook_form_FORM_ID_alter().
*/
function openy_gated_content_form_user_login_form_alter(&$form, FormStateInterface $form_state, $form_id) {
$form['#validate'][] = 'openy_gated_content_user_login_validation';
}
/**
* Implements hook_form_FORM_ID_alter().
*/
function openy_gated_content_form_user_pass_alter(&$form, FormStateInterface $form_state, $form_id) {
$form['#validate'][] = 'openy_gated_content_user_pass_validation';
}
/**
* Implements hook_form_FORM_ID_alter().
*/
function openy_gated_content_form_taxonomy_term_gc_category_form_alter(&$form, FormStateInterface $form_state) {
$form['#validate'][] = 'openy_gated_content_taxonomy_term_gc_category_validation';
}
/**
* Implements hook_form_FORM_ID_alter().
*/
function openy_gated_content_form_taxonomy_term_gc_duration_form_alter(&$form, FormStateInterface $form_state) {
$form['#validate'][] = 'openy_gated_content_taxonomy_term_gc_duration_validation';
}
/**
* Implements hook_form_FORM_ID_alter().
*/
function openy_gated_content_form_taxonomy_overview_terms_alter(&$form, FormStateInterface $form_state) {
$build_info = $form_state->getBuildInfo();
if (isset($build_info['args'][0]) && $build_info['args'][0] instanceof Vocabulary) {
/** @var Vocabulary $vocabulary */
$vocabulary = $build_info['args'][0];
if ($vocabulary->get('vid') === 'gc_category') {
$form['#validate'][] = 'openy_gated_content_taxonomy_gc_category_overview_terms_validation';
}
}
}
/**
* Checks if user has related to Virtual Y role.
*/
function openy_gated_content_user_login_validation(array &$form, FormStateInterface $form_state) {
if (!$form_state->get('uid')) {
return;
}
$account = \Drupal::entityTypeManager()->getStorage('user')->load($form_state->get('uid'));
if ($account) {
$roles = $account->getRoles();
$vy_roles = array_filter($roles, function ($role) {
return strpos($role, 'virtual_y_') !== FALSE || $role === 'virtual_y';
});
if (count($vy_roles) > 0 &&
count(array_diff($roles, array_merge([AccountInterface::AUTHENTICATED_ROLE], $vy_roles))) === 0
) {
\Drupal::messenger()->addError('Virtual YMCA members are not permitted to use this form. Please contact your branch for assistance or go back to the homepage to log in.');
throw new AccessDeniedHttpException();
}
}
}
/**
* Checks if user has related to Virtual Y role.
*/
function openy_gated_content_user_pass_validation(array &$form, FormStateInterface $form_state) {
$account = $form_state->getValue('account');
if ($account) {
$roles = $account->getRoles();
foreach ($roles as $role) {
if (strpos($role, 'virtual_y_') !== FALSE || $role == 'virtual_y') {
\Drupal::messenger()->addError('You\'re not allowed to reset password for user with Virtual Y role.');
throw new AccessDeniedHttpException();
}
}
}
}
/**
* Implements hook_mail().
*/
function openy_gated_content_mail($key, &$message, $params) {
switch ($key) {
case 'welcome_email':
$token = \Drupal::token();
$config = \Drupal::config('openy_gated_content.welcome_email_settings');
$message['from'] = \Drupal::config('system.site')->get('mail');
$message['subject'] = $token->replace($config->get('email_subject'), $params);
$message['body'][] = $token->replace($config->get('email_body'), $params);
break;
}
}
/**
* Make sure the terms do not have 2nd level of hierarchy.
*/
function openy_gated_content_taxonomy_term_gc_category_validation(array &$form, FormStateInterface $form_state) {
$parents = $form_state->getValue('parent');
$first_item = reset($parents);
// If current term references only <root> we can be sure the current term is
// going to have 1 level.
if (count($parents) == 1 && $first_item === 0) {
return;
}
/** @var TermStorageInterface $terms_storage */
$terms_storage = \Drupal::entityTypeManager()->getStorage('taxonomy_term');
foreach (array_keys($parents) as $parent_tid) {
// If the parents for the current term's parent are not empty, this means
// the current term is going to have 3rd level. We shouldn't allow it.
if (!empty($terms_storage->loadParents($parent_tid))) {
$form_state->setErrorByName('parent', "You are not allowed to have more than 2 levels of Categories terms. Please, adjust current term parent accordingly.");
break;
}
}
}
/**
* Do not allow duration ranges overlapping.
*/
function openy_gated_content_taxonomy_term_gc_duration_validation(array &$form, FormStateInterface $form_state) {
$taxonomy_storage = \Drupal::entityTypeManager()->getStorage('taxonomy_term');
$entity_id = 0;
/** @var EntityInterface $entity */
$entity = $form_state->getFormObject()->getEntity();
if (!$entity->isNew()) {
$entity_id = $entity->id();
}
// We have to make sure there are no overlapping duration terms. In order to
// do that, let's request all of the duration terms that satisfy the following
// criteria: "start-1" <= "end-2" && "start-2" <= "end-1".
// "start-1"
$min = $form_state->getValue('field_gc_duration_min', [['value' => '']]);
// "end-1"
$max = $form_state->getValue('field_gc_duration_max', [['value' => '']]);
$query = $taxonomy_storage->getQuery()
->condition('vid', 'gc_duration')
->range(0, 1)
// "start-2"
->condition('field_gc_duration_min', $max[0]['value'], '<=')
// "end-2"
->condition('field_gc_duration_max', $min[0]['value'], '>=');
// Exclude current duration term.
if ($entity_id !== 0) {
$query->condition('tid', $entity_id, '<>');
}
$intersection_term_id = $query->execute();
if (!empty($intersection_term_id)) {
$intersection_term_id = reset($intersection_term_id);
$intersection_term = $taxonomy_storage->load($intersection_term_id);
$form_state->setErrorByName('field_gc_duration_min', t(
'Given range intersects with the range of the Duration term @link. Please, make sure the newly created Duration range does not overlap existing duration ranges.',
[
'@link' => $intersection_term->toLink(NULL, 'edit-form')->toString(),
]
));
}
}
/**
* Make sure the terms do not have 2nd level of hierarchy.
*/
function openy_gated_content_taxonomy_gc_category_overview_terms_validation(array &$form, FormStateInterface $form_state) {
$terms = $form_state->getValue('terms');
foreach ($terms as $term_id => $term_info) {
if ($term_info['term']['depth'] > 1) {
$form_state->setErrorByName('terms', "You are not allowed to have more than 2 levels of categories. Please, adjust hierarchy accordingly.");
break;
}
}
}
/**
* Implements hook_entity_field_storage_info().
*/
function openy_gated_content_entity_field_storage_info(EntityTypeInterface $entity_type) {
$manageable_entity_types = [
'node',
'eventseries',
'eventinstance',
];
if (!in_array($entity_type->id(), $manageable_entity_types)) {
return [];
}
$fields = [];
$fields['field_vy_permission'] = BaseFieldDefinition::create('string')
->setLabel(t('Virtual Y Access Group'))
->setCardinality(1)
->setSetting('max_length', 255)
->setProvider('openy_gated_content')
->setName('field_vy_permission')
->setTargetEntityTypeId($entity_type->id())
->setRequired(FALSE)
->setRevisionable(FALSE)
->setTranslatable(FALSE)
->setDisplayConfigurable('view', FALSE)
->setDisplayConfigurable('form', TRUE)
->setDisplayOptions('form', [
'type' => 'virtual_y_roles_select',
'settings' => [
'size' => '255',
],
]);
if ($entity_type->id() !== 'eventinstance') {
$fields['field_vy_permission']->setDefaultValue('virtual_y,virtual_y_premium');
}
return $fields;
}
/**
* Implements hook_entity_bundle_field_info().
*/
function openy_gated_content_entity_bundle_field_info(EntityTypeInterface $entity_type, $bundle) {
$gc_config = \Drupal::config('openy_gated_content.settings')->getRawData();
if (!empty($gc_config['permissions_entities'])) {
$permissions_entities = $gc_config['permissions_entities'];
}
$entity_type_id = $entity_type->id();
if (!isset($permissions_entities[$entity_type_id])) {
return [];
}
$managed_bundles = $permissions_entities[$entity_type_id];
if (!in_array($bundle, $managed_bundles)) {
return [];
}
$fields = [];
$persistent_map = \Drupal::keyValue('entity.definitions.bundle_field_map');
foreach (openy_gated_content_entity_field_storage_info($entity_type) as $name => $definition) {
$fields[$name] = $definition;
$bundle_field_map = $persistent_map->get($entity_type_id);
if (!isset($bundle_field_map[$name])) {
// This field did not exist yet, initialize it with the type and empty
// bundle list.
$bundle_field_map[$name] = [
'type' => $definition->getType(),
'bundles' => [],
];
}
$bundle_field_map[$name]['bundles'][$bundle] = $bundle;
$persistent_map->set($entity_type_id, $bundle_field_map);
}
return $fields;
}
/**
* Implements hook_entity_access().
*/
function openy_gated_content_entity_access(EntityInterface $entity, $operation, AccountInterface $account) {
return \Drupal::service('class_resolver')
->getInstanceFromDefinition(SegmentContentAccessCheck::class)
->checkAccess($entity, $operation, $account);
}
/**
* Implements hook_entity_delete().
*/
function openy_gated_content_entity_delete(EntityInterface $entity) {
$vy_entity_types = [
'node' => [
'vy_blog_post',
'gc_video',
],
'eventinstance' => [
'live_stream',
'virtual_meeting',
],
'taxonomy_term' => [
'gc_category',
],
];
$is_vy_entity = FALSE;
foreach ($vy_entity_types as $entity_type => $bundles) {
$is_vy_entity |= $entity->getEntityTypeId() === $entity_type && in_array($entity->bundle(), $bundles);
}
if (!$is_vy_entity) {
return;
}
\Drupal::service('class_resolver')
->getInstanceFromDefinition(VyFavoriteItemsManager::class)
->deleteRelatedFavoriteItems($entity);
}