-
Notifications
You must be signed in to change notification settings - Fork 0
/
ldbase_handlers.module
489 lines (452 loc) · 19 KB
/
ldbase_handlers.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
<?php
use Drupal\Core\Form\FormStateInterface;
use Drupal\node\Entity\Node;
use Drupal\Core\Render\Element\PasswordConfirm;
use Drupal\Core\Url;
/**
* Implements hook_webform_element_alter().
*
* @param array $element
* @param FormStateInterface $form_state
* @param array $context
*/
function ldbase_handlers_webform_element_alter(array &$element, FormStateInterface $form_state, array $context) {
if (isset($element['#webform_id'])) {
// change validation for these fields to Person auto-created stub records
$author_webform_ids = array(
'create_update_dataset--contributors',
'create_update_document--authors',
'create_update_codebook--authors',
'create_update_project--related_persons',
'create_update_code--authors'
);
// change validation for these fields to Organization auto-created stub records
$organization_webform_ids = array(
'create_update_project--related_organizations',
'create_update_dataset--host_organizations',
'create_update_person--related_organizations'
);
$modify_validations = array_merge($author_webform_ids, $organization_webform_ids);
if (in_array($element['#webform_id'], $modify_validations)) {
$use_validation = array(
'Drupal\Core\Entity\Element\EntityAutocomplete',
'validateEntityAutocomplete',
);
// clear validation and add core validation back
$element['#element']['#element_validate'] = array();
array_push($element['#element']['#element_validate'], $use_validation);
}
// Select2 validation - remove default validation so we can add taxonomy terms
$select2_fields = array(
'create_update_project--project_type',
'create_update_project--schooling',
'create_update_project--curricula',
'create_update_project--time_method',
'create_update_dataset--constructs',
'create_update_dataset--data_collection_locations',
'create_update_dataset--assessment_name',
'create_update_dataset--special_populations',
'create_update_dataset--variable_types_in_dataset'
);
if (in_array($element['#webform_id'], $select2_fields)) {
$use_validation = array('validateMultipleOptions');
unset($element['#element_validate'][0]);
$element['#element_validate'][] = $use_validation;
$element['#validated'] = TRUE;
}
}
}
/**
* Implements hook_webform_submission_form_alter().
*
* Add 'Cancel' button to update password form.
*/
function ldbase_handlers_webform_submission_form_alter(array &$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
if ($form['#webform_id'] === 'update_password') {
$cancel_route = 'entity.user.canonical';
$route_parameters = ['user' => \Drupal::currentUser()->id()];
$url = Url::fromRoute($cancel_route, $route_parameters);
$form['actions']['cancel'] = [
'#type' => 'link',
'#title' => t('Cancel'),
'#attributes' => ['class' => ['button']],
'#url' => $url,
'#cache' => [
'contexts' => [
'url.path',
],
],
'#weight' => 10,
];
}
}
/**
* Implements hook_ENTITY_TYPE_presave().
*/
function ldbase_handlers_node_presave(\Drupal\Node\NodeInterface $node) {
// trim title field
$trimmed_title = trim($node->get('title')->value);
$node->setTitle($trimmed_title);
}
/**
* Implements hook_ENTITY_TYPE_insert().
*/
function ldbase_handlers_node_insert(\Drupal\Node\NodeInterface $node) {
//message users added as contributors
$contributor_content = ['project','dataset','document','code'];
if (in_array($node->getType(), $contributor_content)) {
if (!empty($node->original)) {
$original = $node->original->toArray();
$original_persons = array_map('getTargetReferences', $original['field_related_persons']);
}
else {
$original = [];
$original_persons = [];
}
$submitted = $node->toArray();
$submitted_persons = array_map('getTargetReferences', $submitted['field_related_persons']);
$added_contributors = array_diff($submitted_persons, $original_persons);
$current_user_id = \Drupal::currentUser()->id();
foreach ($added_contributors as $key => $reference) {
$person = Node::load($reference);
$added_user_id = $person->field_drupal_account_id->target_id;
if (!empty($added_user_id) && $added_user_id <> $current_user_id) {
// send a message to the added user
\Drupal::service('ldbase_handlers.message_service')->contributorAddedMessage($added_user_id, $node);
}
}
}
}
function getTargetReferences(array $value) {
return $value['target_id'];
}
/**
* Implements hook_webform_options_WEBFORM_OPTIONS_ID_alter()
* Creates year options
*
* @param array $options
* @param array $element
*/
function ldbase_handlers_webform_options_years_alter(array &$options, array &$element) {
// load cached options if avaliable
if ($cache = \Drupal::cache()->get('years')) {
$options = $cache->data;
return;
}
$this_year = date("Y");
for ($x = $this_year + 10; $x >= $this_year - 50; $x--) {
$options[$x] = $x;
}
// cache options
\Drupal::cache()->set('years', $options);
}
/**
* Implements hook_webform_options_alter()
* Gets terms from licenses taxonomy and creates element options
*/
function ldbase_handlers_webform_options_alter(array &$options, array &$element, $options_id) {
$allowed_options = ['code_licenses','dataset_licenses','document_licenses'];
if (in_array($options_id, $allowed_options)) {
$type = explode('_', $options_id)[0];
// load cached options if avaliable
if ($cache = \Drupal::cache()->get($options_id)) {
$options = $cache->data;
return;
}
// get terms from licenses taxonomy that are valid for this type
$options = custom_get_license_terms($type);
//Add options to cache
\Drupal::cache()->set($options_id, $options);
}
}
function custom_get_license_terms($valid_for) {
$valid_list = ['document','code','dataset'];
if (!in_array($valid_for, $valid_list)) {
return $options = [];
}
// get taxonomy terms valid for given content type
$terms = \Drupal::entityTypeManager()
->getStorage('taxonomy_term')
->loadByProperties([
'vid' => 'licenses',
'field_valid_for' => $valid_for,
]);
$options = [];
foreach ($terms as $term) {
$options[$term->tid->value] = $term->name->value;
}
return $options;
}
/**
* Implements hook_webform_options_WEBFORM_OPTIONS_ID_alter().
*/
function ldbase_handlers_webform_options_project_tree_content_alter(array &$options, array $element) {
if ($node = \Drupal::routeMatch()->getParameter('node')) {
$ldbase_bundles = ['code','dataset','document','project'];
if (in_array($node->bundle(), $ldbase_bundles)) {
$this_nid = $node->id();
$parent_project_node = \Drupal::service('ldbase.object_service')->getLdbaseRootProjectNodeFromLdbaseObjectNid($this_nid);
$options = \Drupal\ldbase_content\Controller\LDbaseProjectTreeController::output_select_options($parent_project_node, $node);
}
else {
$options = [];
}
}
}
/**
* Implements HOOK_widget_form_alter()
*
*/
function ldbase_handlers_webform_element_managed_file_alter(&$element, &$form_state, $context) {
if ($element['#webform'] === 'create_update_dataset') {
if (isset($element['remove_button']['#value'])) {
$element['remove_button']['#value'] = t('Upload New Version');
}
if (!empty($element['#type']) && $element['#type'] == 'managed_file') {
$element['#process'][] = 'custom_remove_button_label';
}
}
}
// callback to change remove button text
function custom_remove_button_label($element, FormStateInterface $form_state, $form) {
if (isset($element['remove_button']['#value'])) {
$element['remove_button']['#value'] = t('Upload New Version');
}
return $element;
}
/**
* Implements hook_menu_local_tasks_alter().
* Removes local tasks from Group user management and User account page
* Changes Create New Account task link on User login page
*/
function ldbase_handlers_menu_local_tasks_alter(&$data, $route_name, &$cacheability) {
// remove local tasks from edit and delete group member forms
if ($route_name === 'entity.group_content.edit_form' ||
$route_name === 'entity.group_content.delete_form'
) {
unset($data['tabs'][0]);
}
// if this is the user account page
if ($route_name === 'entity.user.canonical') {
unset($data['tabs'][0]);
}
}
/**
* Implements hook_preprocess_page_title.
* Includes Project name on Add Member page rather than group content type
*/
function ldbase_handlers_preprocess_page_title(&$variables) {
if (\Drupal::routeMatch()->getRouteName() == 'entity.group_content.add_form') {
$destination_query = \Drupal::request()->query->get('destination');
if (!empty($destination_query) &&
$ldbase_object_uuid = \Drupal::service('ldbase.object_service')->isUrlAnLdbaseObjectUrl($destination_query)
) {
$ldbase_object = \Drupal::service('ldbase.object_service')->getLdbaseObjectFromUuid($ldbase_object_uuid);
$variables['title'] = t('Add Member to Project: @title', ['@title' => $ldbase_object->getTitle()]);
}
}
}
/**
* Implements HOOK_form_BASE_FORM_ID_alter()
* modify group membership add and edit forms
*/
function ldbase_handlers_form_group_content_form_alter(&$form, FormStateInterface $form_state, $form_id) {
// use entity reference view for member add for
if (strpos($form_id, 'group_membership_add_form')) {
$match_operator = $form['entity_id']['widget'][0]['target_id']['#selection_settings']['match_operator'];
$form['entity_id']['widget'][0]['target_id']['#selection_handler'] = 'views';
$form['entity_id']['widget'][0]['target_id']['#selection_settings'] = [
'view' => [
'view_name' => 'user_reference_autocomplete',
'display_name' => 'entity_reference_1',
'arguments' => [],
],
'match_operator' => $match_operator,
];
$description_text = "<p>Type in/Select the name of the person. This gives them
full access to edit the metadata and data associated with this project. They
must already have an account with LDbase.</p>";
$description_text .= "<div id='project-admins-form-description' class='container'>";
$description_text .= "<div class='row'>";
$description_text .= "<div id='manage-members-administrator-info' class='col-md'>";
$description_text .= "<h4>A Project Administrator can</h4>";
$description_text .= "<ul id='manage-members-administrator-list'>";
$description_text .= "<li>Add/Edit all project metadata</li>";
$description_text .= "<li>Upload data to the project (datasets, codebooks, code, and documents)</li>";
$description_text .= "<li>Approve exempt access to certain users for any data you have embargoed</li>";
$description_text .= "<li>Access/Edit embargoed data</li>";
$description_text .= "<li>Add/Remove Project Editors and other Project Administrators</li>";
$description_text .= "<li>Delete the project completely from LDbase</li>";
$description_text .= "</ul>";
$description_text .= "</div>";
$description_text .= "<div id='manage-members-editor-info' class='col-md'>";
$description_text .= "<h4>A Project Editor can</h4>";
$description_text .= "<ul id='manage-members-administrator-list'>";
$description_text .= "<li>Add/Edit all project metadata</li>";
$description_text .= "<li>Upload data to the project (datasets, codebooks, code, and documents)</li>";
$description_text .= "<li>Approve exempt access to certain users for any data you have embargoed</li>";
$description_text .= "<li>Access/Edit embargoed data</li>";
$description_text .= "</ul>";
$description_text .= "</div>";
$description_text .= "</div>";
$description_text .= "</div>";
$form['entity_id']['widget'][0]['target_id']['#description'] = t($description_text);
$roles_legend = "Roles";
$form['group_roles']['widget']['#title'] = t($roles_legend);
}
//prevent users from editing when member is the only project administrator
if (strpos($form_id, 'group_membership_edit_form')) {
$admin_role = 'project_group-administrator';
$member_group = \Drupal::routeMatch()->getParameter('group');
$group_admins = $member_group->getMembers($admin_role);
$member_uid = \Drupal::routeMatch()->getParameter('group_content')->get('entity_id')->target_id;
$member_account = \Drupal\user\Entity\User::load($member_uid);
$member_group_roles = $member_group->getMember($member_account)->getRoles();
// if there is only 1 project administrator, disable edit form options
if (array_key_exists($admin_role, $member_group_roles) && count($group_admins) === 1) {
$form['description']['#markup'] = t('You may not edit the only Project Administrator. To edit this member\'s roles, you must add another Project Administrator first.');
$form['group_roles']['#access'] = FALSE;
$form['actions']['delete']['#access'] = FALSE;
$form['actions']['submit']['#value'] = t("Cancel");
}
else {
$form['actions']['delete']['#title'] = t("Remove");
}
}
}
/**
* Implements HOOK_form_BASE_FORM_ID_alter().
* On Project membership delete forms, changes 'delete' to 'remove'
*/
function ldbase_handlers_form_group_content_confirm_form_alter(&$form, FormStateInterface $form_state, $form_id) {
if (strpos($form_id, 'group_membership_delete_form')) {
$admin_role = 'project_group-administrator';
$member_group = \Drupal::routeMatch()->getParameter('group');
$group_admins = $member_group->getMembers($admin_role);
$member_uid = \Drupal::routeMatch()->getParameter('group_content')->get('entity_id')->target_id;
$member_account = \Drupal\user\Entity\User::load($member_uid);
$member_group_roles = $member_group->getMember($member_account)->getRoles();
// if there is only 1 project administrator, disable delete form
if (array_key_exists($admin_role, $member_group_roles) && count($group_admins) === 1) {
$form['actions']['submit']['#access'] = FALSE;
$form['#title'] = t('You may not remove %name from the project!', ['%name' => $form['#title']->getArguments()['%name']]);
$form['description']['#markup'] = t('You may not remove the only Project Administrator. To remove this member, you must add another Project Administrator first.');
}
else {
$form['#title'] = t('Are you sure you want to remove %name from the project?', ['%name' => $form['#title']->getArguments()['%name']]);
$form['actions']['submit']['#value'] = t("Remove");
}
}
}
/**
* Implements hook_form_alter().
* changes password labels on Person webform
*/
function ldbase_handlers_form_alter(&$form, FormStateInterface $form_state, $form_id) {
if (isset($form['#webform_id'])) {
if ($form['#webform_id'] == 'create_update_person' || $form['#webform_id'] == 'update_password') {
$form['#after_build'][] = 'custom_password_confirmation_labels';
}
}
}
// callback to change password confirmation labels
function custom_password_confirmation_labels($form, $form_state) {
$form['elements']['ldbase_password']['pass1']['#title'] = t('New password ');
$form['elements']['ldbase_password']['pass2']['#title'] = t('Confirm new password ');
return $form;
}
/**
* Implements HOOK_preprocess_menu__MENU_NAME().
* Changes Document edit and delete tasks to identify Codebooks (type of document)
*/
function ldbase_handlers_preprocess_menu__document_tasks(&$variables) {
$node = \Drupal::RouteMatch()->getParameter('node');
if (!empty($node)) {
$uuid = $node->uuid();
$doc_type = \Drupal::service('ldbase.object_service')->isLdbaseCodebook($uuid) ? 'Codebook' : 'Document';
$variables['items']['ldbase_handlers.edit_document']['title'] = "Edit this " . $doc_type;
$variables['items']['ldbase_handlers.add_document_to_document']['title'] = "Add Document to this " . $doc_type;
}
}
/**
* Implements HOOK_preprocess_menu__MENU_NAME().
* Changes Document edit and delete tasks to identify Codebooks (type of document)
*/
function ldbase_handlers_preprocess_menu__second_document_tasks(&$variables) {
$node = \Drupal::RouteMatch()->getParameter('node');
if (!empty($node)) {
$uuid = $node->uuid();
$doc_type = \Drupal::service('ldbase.object_service')->isLdbaseCodebook($uuid) ? 'Codebook' : 'Document';
$variables['items']['ldbase_handlers.edit_document_2']['title'] = "Edit this " . $doc_type;
$variables['items']['ldbase_handlers.add_document_to_document_2']['title'] = "Add Document to this " . $doc_type;
$variables['items']['ldbase_handlers.confirm_document_deletion_2']['title'] = "Delete this " . $doc_type;
}
}
/**
* Implements HOOK_preprocess_menu__MENU_NAME().
* Disables Publish all link if there are no items to publish in Project Hierarchy.
*/
function ldbase_handlers_preprocess_menu__project_tasks(&$variables) {
$node = \Drupal::RouteMatch()->getParameter('node');
$uuid = $node->uuid();
$status = $node->status->value;
$has_unpublished_child = \Drupal::service('ldbase_handlers.publish_status_service')->hasUnpublishedChild($node->id());
if ($status && !$has_unpublished_child) {
unset($variables['items']['ldbase_handlers.publish_all_confirmation']);
}
}
/*function ldbase_handlers_preprocess_menu__ldbase_tools(&$variables) {
$node = \Drupal::RouteMatch()->getParameter('node');
if (!empty($node)) {
// dataset page
if ($node->bundle() != 'dataset') {
unset($variables['items']['ldbase_handlers.dataset_subscription_link']);
}
else {
$subscribed = false;
// check if user has already subscribed
$uid = \Drupal::currentUser()->id();
$field_subscribed_users = $node->field_subscribed_users->getValue();
foreach ($field_subscribed_users as $value) {
if ($value['target_id'] == $uid) {
$subscribed = true;
}
}
$change = $subscribed ? 'stop' : 'start';
$variables['items']['ldbase_handlers.dataset_subscription_link']['attributes']['class'] = $change . '-subscription-icon';
}
}
}*/
/**
* Implements hook_ENTITY_TYPE_presave().
* Saves message to user when added to a project group
*/
function ldbase_handlers_group_content_presave(Drupal\Core\Entity\EntityInterface $entity) {
if (\Drupal::RouteMatch()->getParameter('plugin_id') === 'group_membership') {
\Drupal::service('ldbase_handlers.message_service')->userAddedToGroupMessage($entity);
}
}
/**
* Implements hook_mail().
*/
function ldbase_handlers_mail($key, &$message, $params) {
switch ($key) {
case 'ldbase_contact_form':
$message['from'] = \Drupal::config('system.site')->get('mail');
$message['subject'] = $params['subject'];
$message['body'][] = $params['body'];
break;
}
}
/**
* Implements hook_views_pre_render().
*/
function ldbase_handlers_views_pre_render(\Drupal\views\ViewExecutable $view) {
if ($view->id() == 'my_messages' && $view->current_display == 'page_2') {
$view->element['#attached']['library'][] = 'ldbase_handlers/message_dialogs';
$uid = \Drupal::RouteMatch()->getParameter('user');
$view->element['#attached']['drupalSettings']['messageData']['uid'] = $uid;
$mid = \Drupal::RouteMatch()->getParameter('mid');
$view->element['#attached']['drupalSettings']['messageData']['mid'] = $mid;
}
}