-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcsis_helpers.module
executable file
·807 lines (715 loc) · 31.4 KB
/
csis_helpers.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
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
<?php
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\CloseModalDialogCommand;
use Drupal\Core\Ajax\RedirectCommand;
use Drupal\group\Entity\Group;
use Drupal\group\Entity\GroupContent;
use Drupal\node\Entity\Node;
use Drupal\taxonomy\Entity\Term;
use Drupal\paragraphs\Entity\Paragraph;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\field\Entity\FieldStorageConfig;
/**
* Disable in production!
*/
$DEBUG = true;
/**
* Poor man's debugger
* See https://stackify.com/how-to-log-to-console-in-php/
*/
function console_log($output, $with_script_tags = true)
{
$js_code = "console.debug(" . json_encode($output, JSON_HEX_TAG) . ");";
if ($with_script_tags) {
$js_code = '<script>' . $js_code . '</script>';
}
echo $js_code;
}
/**
* Implements hook_theme().
*/
function csis_helpers_theme($existing, $type, $theme, $path)
{
return array(
"emikat_results" => array(
"variables" => array("items" => array(), "title" => "", "warningCount" => "", "calcStarted" => "")
),
"emikat_trigger" => array(
"variables" => array("title" => "", "result" => "")
)
);
}
/**
* FIXME: This method is invoked for each entity on the page and thus overwrites all other entity Infos
*/
function csis_helpers_node_view(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display, $view_mode)
{
$type = $entity->bundle();
if ($type == ("gl_step" || "data_package" || "data_package_metadata") && $view_mode != "compact") {
$entityInfo = csis_helpers_node_entity_info($entity);
$build['#attached']['library'][] = 'csis_helpers/entityinfo_helpers';
$build['#attached']['library'][] = 'csis_helpers/include_in_report';
$build['#attached']['library'][] = 'csis_helpers/html2canvas';
$build['#attached']['library'][] = 'csis_helpers/seamless';
$build['#attached']['library'][] = 'csis_helpers/update_step_relations';
$build['#attached']['library'][] = 'csis_helpers/iframe_connector';
switch ($type) {
case 'gl_step':
$build['#attached']['drupalSettings']['csisHelpers']['studyInfo'] = $entityInfo;
// DEPRECATED: use studyInfo/datapackageInfo/resourceInfo instead!
$entityInfo['Warning'] = 'DEPRECATED! Use studyInfo instead';
$build['#attached']['drupalSettings']['csisHelpers']['entityinfo'] = $entityInfo;
$build['#attached']['library'][] = 'csis_helpers/permission_control';
//$build['#attached']['library'][] = 'csis_helpers/pull_emikat_status'; // is it needed in the GL-steps as well or just in the Study group?
break;
case 'data_package':
$build['#attached']['drupalSettings']['csisHelpers']['datapackageInfo'] = $entityInfo;
break;
case 'data_package_metadata':
$build['#attached']['drupalSettings']['csisHelpers']['resourceInfo'] = $entityInfo;
break;
//default:$build['#attached']['drupalSettings']['csisHelpers']['studyInfo'] = $entityInfo;
}
} else {
//console_log('entity type ' . $type . ' not supported');
}
}
function csis_helpers_group_view(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display, $view_mode)
{
// DEPRECATED: use studyInfo/datapackageInfo/resourceInfo instead!
$build['#attached']['drupalSettings']['csisHelpers']['entityinfo'] = csis_helpers_group_entity_info($entity);
$build['#attached']['library'][] = 'csis_helpers/entityinfo_helpers';
$build['#attached']['library'][] = 'csis_helpers/permission_control';
$build['#attached']['library'][] = 'csis_helpers/pull_emikat_status';
$build['#attached']['drupalSettings']['csisHelpers']['studyInfo'] = csis_helpers_group_entity_info($entity);
// if ($view_mode == "full" || $view_mode == "introduction") {
// // when group is called in 'full' or 'introduction' view (= default forwarding after Study is created)
// // check the TM trigger queue for possible new TM Studies which need to be sent over to the TM
// $queue = \Drupal::service('queue')->get('tm_trigger_queue');
// while ($item = $queue->claimItem()) {
// $studyID = $item->data->gid;
// $study = Group::load($studyID);
// /** @var \Drupal\csis_helpers\Utils\TMHelperFunctions $tmService */
// $tmService = \Drupal::service('csis_helpers.tm_helper_functions');
// $result = $tmService->triggerTM($study);
// $queue->deleteItem($item);
// }
// }
}
function csis_helpers_form_node_form_alter(&$form, $form_state, $form_id)
{
//attach node-id and if group node group-id to drupalSettings
$entity = $form_state->GetFormObject()->getEntity();
if ($entity->id()) {
$form['#attached']['drupalSettings']['csisHelpers']['entityinfo'] = csis_helpers_node_entity_info($entity);
}
if ($entity->bundle() == "gl_step" && $form_id != "node_gl_step_form") {
// deny access if user is not admin, or if auth_user is not member of group or form id is not "node_gl_step_introduction_form"
$user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
$relations = GroupContent::loadByEntity($entity);
$userAccount = \Drupal::currentUser();
if (!($user->hasRole("administrator") || $user->hasRole("editor"))) {
foreach ($relations as $relation) {
if (!$relation->getGroup()->getMember($userAccount) || $form_id != "node_gl_step_introduction_form") {
$form['#access'] = FALSE;
$form['#markup'] = t('Access Denied.');
$form['#cache'] = [
'contexts' => [],
'max-age' => 0,
];
}
}
}
}
if ($entity->bundle() == "gl_step" && $form_id != "node_gl_step_edit_form") {
$form['actions']['delete']['#access'] = false;
}
// prevent page-reload /redirect for the edit-form of Report images (unless user is on the summary page)
if ($form_id == "node_report_image_edit_form" && \Drupal::request()->query->has('destination')) {
$pathComponents = explode("/", \Drupal::request()->query->get('destination'));
$lastPathComponent = end($pathComponents);
if ($lastPathComponent != "summary") {
$form['actions']['submit']['#submit'][] = '_csis_helpers_ajax_submit';
$form['actions']['submit']['#attributes']['class'][] = 'use-ajax-submit';
}
}
}
function csis_helpers_form_group_form_alter(&$form, $form_state, $form_id)
{
//attach group node grout-id to drupalSettings
$entity = $form_state->GetFormObject()->getEntity();
if ($entity->id()) {
$form['#attached']['drupalSettings']['csisHelpers']['entityinfo'] = csis_helpers_group_entity_info($entity);
$form['#attached']['library'][] = 'csis_helpers/entityinfo_helpers';
}
// hide Delete-button for Studies everywhere except for the default Edit-form
if ($entity->bundle() == "study" && $form['form_id']['#value'] != "group_study_edit_form") {
$form['actions']['delete']['#access'] = false;
}
// on Study Trigger-form submit trigger calculations in external application
if ($entity->bundle() == "study" && $form['form_id']['#value'] == "group_study_trigger_form") {
$studyType = Term::load($entity->get('field_study_type')->target_id);
$calcMethods = $studyType->get('field_study_calculation')->referencedEntities();
foreach ($calcMethods as $calcMethod) {
$calcMethodID = $calcMethod->get("field_calculation_method_id")->value;
if (stripos($calcMethodID, "emikat") !== false) {
$statusCode = $entity->get('field_calculation_status')->value;
if ($statusCode == 0 || $statusCode == 2) {
$form['text']['#markup'] = t('Study not yet ready for calculations or previous calculations have not yet finished.');
$form['actions']['submit']['#value'] = t('Cancel');
} else {
foreach (array_keys($form['actions']) as $action) {
if ($action != 'preview' && isset($form['actions'][$action]['#type']) && $form['actions'][$action]['#type'] === 'submit') {
$form['text']['#markup'] = t(
'Your Study now contains all required information. If you wish, you can now trigger the calculation.
Depending on the current workload and the Study parameters, calculation results may take a couple
of minutes or hours.'
);
$form['actions']['submit']['#value'] = t('Trigger calculations');
$form['actions'][$action]['#submit'][] = 'csis_helpers_emikat_trigger_form_submit';
}
}
}
}
}
}
}
/**
* This function triggers the Study calculations in external services (e.g. Emikat).
*
* @param [type] $form
* @param FormStateInterface $form_state
* @return void
*/
function csis_helpers_emikat_trigger_form_submit($form, FormStateInterface $form_state)
{
// trigger external apps (Emikat, TM) only based on fitting Study type and on live website
if (\Drupal::request()->getSchemeAndHttpHost() == "https://csis.myclimateservice.eu") {
$entity = $form_state->GetFormObject()->getEntity();
/** @var \Drupal\csis_helpers\Utils\EmikatHelperFunctions $emikatService */
$emikatService = \Drupal::service('csis_helpers.emikat_helper_functions');
$result = $emikatService->triggerEmikat($entity);
//print result message to admins and developers directly to FE
$user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
if ($user->hasRole('administrator') || $user->hasRole('developer')) {
\Drupal::messenger()->addMessage($result['message'], $result['type']);
}
} else {
\Drupal::logger('csis_helpers')->notice(
"Emikat Study calculations cannot be triggered on local or development instances of CSIS."
);
return false;
}
}
/**
* Implements hook_block_access().
* Hide the "Study details" block unless it's an Emikat-relevant Study.
* In the future we might add more such Study checklists, but since each external
* system will require different data, each Checklist must be created as a seperate
* block and hidden for all other non-relevant Studies
*/
function csis_helpers_block_access(\Drupal\block\Entity\Block $block, $operation, \Drupal\Core\Session\AccountInterface $account)
{
// this Checklist block is only for Emikat-relevant Studies, other Studies should not show this block
if ($operation == 'view' && $block->getPluginId() == 'views_block:study_group_overview-study_status_block') {
// load the Study group and check the calculation method based on the Study type
$group = \Drupal::routeMatch()->getParameter('group');
if ($group && $group->bundle() == "study") {
$studyType = Term::load($group->get('field_study_type')->target_id);
$calcMethods = $studyType->get('field_study_calculation')->referencedEntities();
foreach ($calcMethods as $calcMethod) {
$calcMethodID = $calcMethod->get("field_calculation_method_id")->value;
// if the calculation method contains "emikat", the block can be displayed
if (stripos($calcMethodID, "emikat") !== false) {
return AccessResult::neutral();
}
}
// hide this block, since the Study is not calculated in Emikat
return AccessResult::forbidden();
}
}
// default access result
return AccessResult::neutral();
}
/**
* implementation of hook_form_alter() for Datapackage selection form in Study
* "group_study_introduction_form"
*/
function csis_helpers_form_group_study_data_form_alter(&$form, $form_state, $form_id)
{
// adds a preview of the selected data package
$form['#attached']['library'][] = 'csis_helpers/dp_selector_helpers';
$entity = $form_state->GetFormObject()->getEntity();
// load term with Study type to get the calculation methods
$studyType = Term::load($entity->get('field_study_type')->target_id);
$calcMethod = $studyType->get('field_study_calculation')->target_id;
// load available select options in form and loop through them
$dp_options = $form["field_data_package"]["widget"]["#options"];
foreach ($dp_options as $key => $dp_option) {
// skip the default "none" or "all" options
if (!is_numeric($key)) {
continue;
}
// load data package from select option and check its allowed calculation methods
$dp = Node::load($key);
$dpCalcMethods = $dp->get("field_calculation_methods")->getString();
// remove data package from select options if unpublished or if Study calculation method not supported
if (!$dp->isPublished() || strpos($dpCalcMethods, $calcMethod) === false) {
unset($form["field_data_package"]["widget"]["#options"][$key]);
}
}
}
function csis_helpers_preprocess_views_view(&$variables)
{
$view = $variables['view'];
//\Drupal::logger('csis helpers')->notice($view->id());
if ($view->id() == 'data_packages' && $view->current_display == 'browser') {
$variables['#attached']['library'][] = 'csis_helpers/entitybrowser_helpers';
$variables['#attached']['library'][] = 'csis_helpers/entitybrowser_reorder';
}
$variables['#attached']['library'][] = 'csis_helpers/stepdata_helpers';
$variables['#attached']['library'][] = 'bootstrap/drupal.vertical-tabs';
$variables['#attached']['library'][] = 'csis_helpers/progress_indicator';
}
function csis_js_alter(&$javascript, \Drupal\Core\Asset\AttachedAssetsInterface $assets)
{
// kint($javascript);
}
/**
* Extract information from **node** entity.
*
* Attention: data_package_metadata is the machine name of Data Package **Resource**!
*
* @param \Drupal\Core\Entity\EntityInterface $entity
* @return Drupal\node\Entity\Node[]
*/
function csis_helpers_node_entity_info(\Drupal\Core\Entity\EntityInterface $entity)
{
// check if current user has assigned other role than "authenticated", if not -> no write/edit rights
$userAccount = \Drupal::currentUser();
// getRoles(TRUE) only returns roles other than "anonymous" and "authenticated"
$has_user_special_roles = !empty($userAccount->getRoles(true));
$nodeEntityInfo = array(
'id' => $entity->id(),
'uuid' => $entity->uuid(),
//'title' => $entity->get('title')->value, // inconsistency: no title field ins study group! title? label? name?
//'name' => $entity->get('field_name')->value, // inconsistency: no name field in resource, name field in data package used for 'ckan_id'
'write_permissions' => ($has_user_special_roles ? 1 : 0),
);
$type = $entity->bundle();
switch ($type) {
case 'gl_step':
return array_merge($nodeEntityInfo, csis_helpers_node_entity_info_study($entity));
break;
case 'data_package':
return array_merge($nodeEntityInfo, csis_helpers_node_entity_info_datapackage($entity));
break;
case 'data_package_metadata':
return array_merge($nodeEntityInfo, csis_helpers_node_entity_info_resource($entity));
break;
//default:return array_merge($nodeEntityInfo, csis_helpers_node_entity_info_study($entity));
}
return $nodeEntityInfo;
}
/**
* Extract information from **Data Package** entity.
*
* @param \Drupal\Core\Entity\EntityInterface $entity
* @return Drupal\node\Entity\Node[]
*/
function csis_helpers_node_entity_info_datapackage(\Drupal\Core\Entity\EntityInterface $entity)
{
//console_log('creating entity info for data package ' . $entity->get('title')->value);
$datapackageEntityInfo = array(
'name' => $entity->get('title')->value
);
$spatialExtent = extractSpatialExtent($entity);
if ($spatialExtent != null) {
return array_merge($datapackageEntityInfo, $spatialExtent);
}
return $datapackageEntityInfo;
}
/**
* Extract information from DATA PACKAGES' RESOURCE entity.
*
* @param \Drupal\Core\Entity\EntityInterface $entity
* @return Drupal\node\Entity\Node[]
*/
function csis_helpers_node_entity_info_resource(\Drupal\Core\Entity\EntityInterface $entity)
{
//console_log('creating entity info for resource ' . $entity->get('title')->value);
$resourcEntityInfo = array(
'name' => $entity->get('title')->value
);
$spatialExtent = extractSpatialExtent($entity);
if ($spatialExtent != null) {
return array_merge($resourcEntityInfo, $spatialExtent);
}
return $resourcEntityInfo;
}
/**
* Extract information from STUDY's GL_STEP **node** entity.
*
* @param \Drupal\Core\Entity\EntityInterface $entity
* @return Drupal\node\Entity\Node[]
*/
function csis_helpers_node_entity_info_study(\Drupal\Core\Entity\EntityInterface $entity)
{
return \Drupal::service('csis_helpers.study_info_generator')->generateStudyInfoNode($entity);
}
/**
* sets for each Study group the $entityInfo variable
* Extract information from STUDY **GROUP** entity.
*
* @param \Drupal\Core\Entity\EntityInterface $entity
* @return Drupal\node\Entity\Node[]
*/
function csis_helpers_group_entity_info(\Drupal\Core\Entity\EntityInterface $entity)
{
// specify GroupType explicitly, since some fields might be unique to certain GroupTypes only
if ($entity->getGroupType()->id() == "study") {
return \Drupal::service('csis_helpers.study_info_generator')->generateStudyInfoGroup($entity);
}
}
/**
* Implements hook_entity_presave().
* This is the automated Study calculation trigger. Currently used only for the TM.
* For Emikat we just update whether or not a Study (re)calculation can be triggered
* by the Study owner
*
* @param \Drupal\Core\Entity\EntityInterface $entity
* @return Drupal\node\Entity\Node[]
*/
function csis_helpers_entity_presave(\Drupal\Core\Entity\EntityInterface $entity)
{
if ($entity->bundle() == "study") {
// load term with Study type to get the calculation methods
$studyType = Term::load($entity->get('field_study_type')->target_id);
$calcMethods = $studyType->get('field_study_calculation')->referencedEntities();
// check if study is saved for the first time
if ($entity->isNew()) {
// if Studytype IDs match, it's a TM Study and we need to change the default Study area map
if ($studyType->get('field_study_type_id')->value == "study-type:screening-transport") {
$studyAreaTMmap = \Drupal::service('entity.repository')->loadEntityByUuid('node', 'eb6c7a73-de1a-43b9-9de3-cab5b9cdb55d');
if ($studyAreaTMmap) {
$entity->set('field_study_area_map', $studyAreaTMmap->id());
}
else {
\Drupal::logger('csis helpers')->error("Couldn't set default Studyarea Map for new TM Study. UUID not found");
}
}
}
// trigger external apps (Emikat, TM) only based on fitting Study type and on live website
if (\Drupal::request()->getSchemeAndHttpHost() == "https://csis.myclimateservice.eu") {
foreach ($calcMethods as $calcMethod) {
$calcMethodID = $calcMethod->get("field_calculation_method_id")->value;
if (stripos($calcMethodID, "meteogrid") !== false) {
//TM is used for calculation, so it is relevant
/** @var \Drupal\csis_helpers\Utils\TMHelperFunctions $tmService */
$tmService = \Drupal::service('csis_helpers.tm_helper_functions');
$result = $tmService->triggerTM($entity);
//print result message to admins and developers directly to FE
$user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
if ($user->hasRole('administrator') || $user->hasRole('developer')) {
\Drupal::messenger()->addMessage($result['message'], $result['type']);
}
break;
}
else if (stripos($calcMethodID, "emikat") !== false) {
/** @var \Drupal\csis_helpers\Utils\EmikatHelperFunctions $emikatService */
$emikatService = \Drupal::service('csis_helpers.emikat_helper_functions');
$statusCode = $emikatService->checkStudyChanges($entity);
break;
}
}
} else {
\Drupal::logger('csis_helpers')->notice(
"External (Study) calculations cannot be triggered on local or development instances of CSIS."
);
return false;
}
}
}
// /**
// * Implements hook_ENTITY_TYPE_insert() for Group type. Currently needed to add
// * new TM relevant Studies to the TM_trigger_queue, which is processed after the
// * Study ID is available (which is needed in the TM as a reference to the Study
// * in the CSIS).
// *
// * @param \Drupal\Core\Entity\EntityInterface $entity
// *
// */
// function csis_helpers_group_insert(\Drupal\Core\Entity\EntityInterface $entity)
// {
// if ($entity->bundle() == "study") {
// // load term with Study type to get the calculation methods
// $studyType = Term::load($entity->get('field_study_type')->target_id);
// $calcMethods = $studyType->get('field_study_calculation')->referencedEntities();
// // process Studies only based on fitting Study type and on live website
// if (\Drupal::request()->getSchemeAndHttpHost() == "https://csis.myclimateservice.eu") {
// foreach ($calcMethods as $calcMethod) {
// $calcMethodID = $calcMethod->get("field_calculation_method_id")->value;
// if (stripos($calcMethodID, "meteogrid") !== false) {
// // TM is used for calculation, so it is relevant
// // instead of triggering directly, add study to the TM trigger queue
// /** @var QueueFactory $queue_factory */
// $queue_factory = \Drupal::service('queue');
// /** @var QueueInterface $queue */
// $queue = $queue_factory->get('tm_trigger_queue');
// $item = new \stdClass();
// $item->gid = $entity->id();
// $queue->createItem($item);
// break;
// }
// }
// }
// }
// }
/**
* @param $node \Drupal\node\Entity\Node
*/
function csis_helpers_node_insert(\Drupal\node\Entity\Node $node)
{
// if a Report image is created -> add it as a group content depending on the referenced GL-step
if ($node->bundle() == 'report_image' && !$node->get('field_source_step')->isEmpty()) {
// get GL-step (which is already part of the Group)
$source_step_id = $node->get("field_source_step")->first()->getValue()['target_id'];
$gl_node = Node::load($source_step_id);
$plugin_id = 'group_node:' . $node->bundle();
// if GL-step exists -> load the corresponding group content and retrieve the group id
if ($gl_node) {
$group_id = -1;
$group_contents = GroupContent::loadByEntity($gl_node);
foreach ($group_contents as $group_content) {
$group_id = $group_content->getGroup()->id();
}
$group = Group::load($group_id);
// if group exists -> add report image as group content to that group
if ($group) {
$group->addContent($node, $plugin_id);
}
}
}
}
/**
* Implements hook_jsonapi_entity_filter_access() for 'study' group.
* This is necessary to fix this issue: https://www.drupal.org/project/jsonapi/issues/3037519
*/
function csis_helpers_jsonapi_entity_filter_access(\Drupal\Core\Entity\EntityTypeInterface $entity_type, \Drupal\Core\Session\AccountInterface $account)
{
return ([
JSONAPI_FILTER_AMONG_ALL => AccessResult::allowed(),
]);
}
/**
* Close the Modal and prevent redirect or page reload.
*
* @param array $form
* The form that will be altered.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* FormState Object.
*/
function _csis_helpers_ajax_submit(array $form, FormStateInterface &$form_state)
{
$response = new AjaxResponse();
$response->addCommand(new CloseModalDialogCommand());
$form_state->setResponse($response);
}
/**
* @param \Drupal\Core\Entity\EntityInterface $entity
* @return Array
*/
function extractSpatialExtent($entity)
{
$spatial_extents = $entity->get('field_spatial_extent')->referencedEntities(); // referencedEntities() returns an array of entities
if (
!empty($spatial_extents) && is_array($spatial_extents) && sizeof($spatial_extents) > 0
&& $spatial_extents[0] != null && $spatial_extents[0]->get('field_bounding_box') != null
) {
//console_log($spatial_extents[0]->get('field_bounding_box')->value);
$spatialExtent = array('spatial_extent' => $spatial_extents[0]->get('field_bounding_box')->value);
// @deprecated See https://github.com/clarity-h2020/map-component/issues/53
/*$spatialExtent = array(
'minx' => $spatial_extents[0]->get('field_xmin')->value,
'miny' => $spatial_extents[0]->get('field_ymin')->value,
'maxx' => $spatial_extents[0]->get('field_xmax')->value,
'maxy' => $spatial_extents[0]->get('field_ymax')->value,
);*/
return $spatialExtent;
} else {
return null;
}
}
// /**
// * Implements hook_cron().
// * Instead of running these tests via CRON, use the StudyCalculationController methods
// * to trigger these tests via external CI testing services
// */
// function csis_helpers_cron()
// {
// $interval = 60 * 60 * 24; // Approx one day
// $last_run = \Drupal::state()->get('csis_helpers.emikat_last_run', 0);
// $item = new \stdClass(); // create a dummy object for the queue/service
// $item->gid = 60; // The ID of our special Study group reserved for tests
// // either run a new calculation every 24 hours or check if there are currently results available
// if ((REQUEST_TIME - $last_run) >= $interval) {
// \Drupal::service('csis_helpers.testing')->sendTestStudy($item);
// \Drupal::state()->set('csis_helpers.emikat_last_run', REQUEST_TIME);
// }
// else {
// \Drupal::service('csis_helpers.testing')->checkTestResults($item);
// }
// }
/**
* Generates list with allowed options for this field based on the linked ParagraphType "Study presets" for the "Study" Group
* this function needs to be added to the configuration of the Field Storage for the given field under
* settings:
* allowed_values_function: NAME_OF_THE_FUNCTION
*
* @param FieldStorageConfig $definition
* @param ContentEntityInterface $entity
* @param [type] $cacheable
* @return allowed options
*/
function csis_helpers_allowed_values_function(FieldStorageConfig $definition, ContentEntityInterface $entity = NULL, $cacheable)
{
$options = [];
// check allowed values for the "active scenario" field based on defined scenarios in that Study
if ($definition->id() == "group.field_active_scenario") {
if (!$entity->get('field_study_presets')->isEmpty()) {
foreach ($entity->get('field_study_presets') as $paraReference) {
$paragraph = Paragraph::load($paraReference->target_id);
if ($paragraph && $paragraph->getType() == "variable_set") {
$options[$paraReference->target_id] = $paragraph->get('field_label')->value;
}
}
}
}
return $options;
}
/**
* Implements hook_ds_pre_render_alter().
*/
function csis_helpers_ds_pre_render_alter(array &$layout_render_array, array $context, array &$vars)
{
// for Introduction, Summary and PDF tab of GL-step show custom description instead of default EU-GL taxonomy term
// if one was set in the used Study type template
if ($context['entity']->bundle() == 'gl_step') {
if ($context['view_mode'] == 'introduction') {
if (isset($vars['content']['ds_content']['group_prototype']['field_step_description']['#theme'])) {
unset($vars['content']['ds_content']['group_prototype']['field_field_eu_gl_methodology']);
}
}
elseif ($context['view_mode'] == 'summary') {
if (isset($vars['content']['left']['group_overview']['field_step_description']['#theme'])) {
unset($vars['content']['left']['group_overview']['field_field_eu_gl_methodology']);
}
}
elseif ($context['view_mode'] == 'pdf') {
if (isset($vars['content']['ds_content']['group_introduction']['field_step_description']['#theme'])) {
unset($vars['content']['ds_content']['group_introduction']['field_field_eu_gl_methodology']);
}
}
}
// hide "trigger calculation" button if Study is not relevant for Emikat (based on Calculation method in Study type)
// not necessary as long as the calculation button will only be shown in the Checklist sidebar (since sidebar
// is already shown/hidden based on Study Type)
// else if ($context['entity']->bundle() == 'study') {
// if ($context['view_mode'] == 'summary') {
// $emikatRelevant = false;
// $studyType = Term::load($context['entity']->get('field_study_type')->target_id);
// $calcMethods = $studyType->get('field_study_calculation')->referencedEntities();
// foreach ($calcMethods as $calcMethod) {
// $calcMethodID = $calcMethod->get("field_calculation_method_id")->value;
// if (stripos($calcMethodID, "emikat") !== false) {
// $emikatRelevant = true;
// break;
// }
// }
// if (!$emikatRelevant) {
// unset($vars['content']['header']['dynamic_token_field:group-trigger_calculation']);
// }
// }
// }
}
/**
* Implements hook_group_access().
*
* Limits access to Studies:
* - anonymous users may only view allowed Studies (mainly DCs)
* - registered users may only view published Studies and Studies that they are a member of
*/
function csis_helpers_group_access(\Drupal\Core\Entity\EntityInterface $entity, $operation, \Drupal\Core\Session\AccountInterface $account)
{
if ($operation == 'view' && $entity->bundle() == "study") {
$config = \Drupal::config('csis_helpers.default');
$allowedStudies = $config->get('allowed_studies');
// if user is anonymous limit access only to allowed Studies
if ($account->isAnonymous()) {
// if study ID is not in allowed list, than anonymous users should not be able to view it
if (!in_array($entity->id(), $allowedStudies)) {
return AccessResult::forbidden();
}
} else {
// deny access to unpublished Studies, unless user is a member or an admin
// also add bypass to all REST users, who need to access Study detail via REST
$user = \Drupal\user\Entity\User::load($account->id());
if (!($user->hasRole("administrator") || $user->hasRole("rest") || $entity->getMember($account))) {
if (!$entity->get('field_publish')->value) {
return AccessResult::forbidden();
}
}
}
}
return AccessResult::neutral();
}
/**
* Implements hook_views_post_execute().
*
* Limits access for anonymous users to only allowed Studies (mainly DCs)
* This hook blocks anonymous users from accessing GL-steps of restricted studies
*/
function csis_helpers_views_post_execute(\Drupal\views\ViewExecutable $view)
{
if ($view->id() == "view_mode_for_gl_step") {
$result = $view->result;
$account = $view->getUser();
$user = \Drupal::entityTypeManager()->getStorage('user')->load($account->id());
if ($account->isAnonymous() && $result && $result[0]->nid) {
$glStep = Node::load(intval($result[0]->nid));
$relations = GroupContent::loadByEntity($glStep);
// we can skip loop after first iteration, since a GL-Step can have only one group
foreach ($relations as $relation) {
$groupid = $relation->getGroup()->id();
$config = \Drupal::config('csis_helpers.default');
$allowedStudies = $config->get('allowed_studies');
// if study ID is not in allowed list, than anonymous users should not be able to view it
if (!in_array($groupid, $allowedStudies)) {
$view->result = [];
}
break;
}
}
}
// hide published Studies that cannot be accessed by anonymous users
else if ($view->id() == "study_group_overview") {
$results = $view->result;
$filter_results = [];
$account = $view->getUser();
if ($account->isAnonymous()) {
foreach ($results as $key => $value) {
$config = \Drupal::config('csis_helpers.default');
$allowedStudies = $config->get('allowed_studies');
// if study ID is in allowed list, keep it in the View results
if (in_array($value->id, $allowedStudies)) {
$filter_results[$key] = $value;
}
}
$view->result = $filter_results;
}
}
}