This repository has been archived by the owner on Sep 30, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tide_webform.module
629 lines (575 loc) · 21.9 KB
/
tide_webform.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
<?php
/**
* @file
* Tide Webform.
*/
use Drupal\Component\Utility\NestedArray;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\taxonomy\Entity\Term;
use Drupal\webform\Entity\Webform;
use Drupal\webform\Entity\WebformSubmission;
use Drupal\webform\WebformSubmissionForm;
/**
* Implements hook_config_ignore_settings_alter().
*/
function tide_webform_config_ignore_settings_alter(array &$settings) {
// Ignore the Content Rating webform so that it won't be reverted
// during config sync.
$settings[] = 'webform.webform.tide_webform_content_rating';
}
/**
* Implements hook_form_alter().
*/
function tide_webform_form_alter(&$form, FormStateInterface $form_state, $form_id) {
if (!empty($form['#webform_id']) && $form['#webform_id'] == 'tide_webform_content_rating') {
$form['#attached']['library'][] = 'tide_webform/content_rating';
// Restricting access for anonymous user from BE.
if (\Drupal::currentUser()->isAnonymous()) {
$form['#access'] = FALSE;
$form['#markup'] = t('Access Denied.');
}
}
if ($form_id == 'webform_ui_element_form') {
$form['#after_build'][] = 'tide_webform_webform_ui_element_form_after_build';
$form['#attached']['library'][] = 'tide_webform/webform';
if (isset($form['properties']['form']['length_container']['maxlength']) && array_key_exists('#default_value', $form['properties']['form']['length_container']['maxlength'])) {
$default_value = NestedArray::getValue($form,
[
'properties',
'form',
'length_container',
'maxlength',
'#default_value',
]);
if ($default_value === NULL) {
NestedArray::setValue($form,
[
'properties',
'form',
'length_container',
'maxlength',
'#default_value',
],
'255');
}
}
}
if ($form_id == 'webform_submission_filter_form') {
$options = $form['filter']['state']['#options'];
$options['processed'] = 'Exported [' . tide_webform_submission_filter_query(1) . ']';
$options['unprocessed'] = 'New [' . tide_webform_submission_filter_query(0) . ']';
$form['filter']['state']['#options'] = $options;
}
if (strstr($form_id, 'webform_submission') && strstr($form_id, 'notes_form')) {
$webform_submission = \Drupal::routeMatch()->getParameter('webform_submission');
$form['processed'] = [
'#type' => 'checkbox',
'#title' => t('Has this submission been exported?'),
'#description' => t('If checked, this submission will be flagged as exported. If unchecked, it will be flagged as a new submission.'),
'#default_value' => tide_webform_get_processed($webform_submission),
'#return_value' => TRUE,
];
}
if ($form_id == 'webform_results_export') {
$form['export']['download']['unprocessed_submissions'] = [
'#type' => 'checkbox',
'#title' => t('Only download new submissions'),
'#default_value' => TRUE,
];
$form['export']['download']['process_submissions'] = [
'#type' => 'checkbox',
'#title' => t('Download submissions marked as exported'),
'#default_value' => TRUE,
];
$form['#submit'][] = 'tide_webform_form_webform_results_export_form_submit';
}
}
/**
* After_build callback.
*
* @param array $form
* The form.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* Form state.
*
* @return array
* The form.
*/
function tide_webform_webform_ui_element_form_after_build(array $form, FormStateInterface $form_state) {
$storage = $form_state->getStorage();
// Unset the default properties of the Privacy Statement element to force
// webform to save them in the YAML source of the element.
if (isset($storage['element_properties']['type'])
&& $storage['element_properties']['type'] == 'webform_privacy_statement'
) {
unset($storage['default_properties']['title']);
unset($storage['default_properties']['required']);
unset($storage['default_properties']['privacy_statement_heading']);
unset($storage['default_properties']['privacy_statement_content']);
$form_state->setStorage($storage);
}
return $form;
}
/**
* Implements hook_form_FORM_ID_alter().
*
* @see \Drupal\webform\Form\AdminConfig\WebformAdminConfigElementsForm::buildForm()
*/
function tide_webform_form_webform_admin_config_elements_form_alter(&$form, FormStateInterface $form_state, $form_id) {
$config = \Drupal::config('tide_webform.defaults');
$form['privacy_statement'] = [
'#type' => 'details',
'#title' => t('Default Privacy statement'),
'#description' => t('Set the default values for new Privacy Statement webform elements.'),
'#description_display' => 'before',
'#open' => TRUE,
'#tree' => TRUE,
];
$form['privacy_statement']['add_to_new_form'] = [
'#type' => 'checkbox',
'#title' => t('Add a default Privacy Statement element when creating a new webform'),
'#default_value' => $config->get('privacy_statement.add_to_new_form'),
];
$form['privacy_statement']['agreement'] = [
'#type' => 'textfield',
'#title' => t('Title'),
'#description' => t('This message will be displayed with a checkbox on frontend.'),
'#default_value' => $config->get('privacy_statement.agreement'),
'#required' => TRUE,
];
$form['privacy_statement']['heading'] = [
'#type' => 'textfield',
'#title' => t('Heading'),
'#default_value' => $config->get('privacy_statement.heading'),
];
$form['privacy_statement']['content'] = [
'#type' => 'webform_html_editor',
'#title' => t('Content'),
'#default_value' => $config->get('privacy_statement.content'),
'#required' => TRUE,
];
$form['privacy_statement']['token_tree_link'] = \Drupal::service('webform.token_manager')->buildTreeElement();
$form['#submit'][] = 'tide_webform_form_webform_admin_config_elements_form_submit';
}
/**
* Submit callback.
*
* @param array $form
* The form.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* Form state.
*/
function tide_webform_form_webform_admin_config_elements_form_submit(array $form, FormStateInterface $form_state) {
$config = \Drupal::service('config.factory')->getEditable('tide_webform.defaults');
$privacy_statement = $form_state->getValue('privacy_statement');
$config->set('privacy_statement', $privacy_statement)->save();
}
/**
* Implements hook_entity_base_field_info_alter().
*
* @see \Drupal\webform\Entity\WebformSubmission::baseFieldDefinitions()
*/
function tide_webform_entity_base_field_info_alter(&$fields, EntityTypeInterface $entity_type) {
if ($entity_type->id() == 'webform_submission') {
// Expose the data attribute as a field.
if (empty($fields['data'])) {
$fields['data'] = BaseFieldDefinition::create('string_long')
->setName('data')
->setLabel('Data')
->setDescription(t('Webform Submission Data'))
->setDefaultValue('')
->setTargetEntityTypeId('webform_submission')
->setComputed(TRUE);
}
}
}
/**
* Implements hook_entity_base_field_info().
*
* @see \Drupal\webform\Entity\WebformSubmission::baseFieldDefinitions()
*/
function tide_webform_entity_base_field_info(EntityTypeInterface $entity_type) {
$fields = [];
if ($entity_type->id() == 'webform_submission') {
$fields['processed'] = BaseFieldDefinition::create('boolean')
->setName('Exported')
->setLabel(t('Exported'))
->setDescription(t('A flag that indicates whether the submission has been downloaded'))
->setDefaultValue(FALSE)
->setDisplayConfigurable('form', FALSE);
}
return $fields;
}
/**
* Implements hook_ENTITY_TYPE_create_access().
*
* @see \Drupal\webform\WebformSubmissionAccessControlHandler::checkAccess()
*/
function tide_webform_webform_submission_create_access(AccountInterface $account, array $context, $entity_bundle) {
// Check webform create access.
// This hook should be only invoked if the webform_submission is created
// via JSON:API requests.
$is_jsonapi = \Drupal::request()->attributes->get('_is_jsonapi', FALSE);
if ($is_jsonapi) {
$webform = Webform::load($entity_bundle);
if ($webform) {
/** @var \Drupal\webform\WebformAccessRulesManagerInterface $webform_access_rules_manager */
$webform_access_rules_manager = \Drupal::service('webform.access_rules_manager');
/** @var \Drupal\Core\Access\AccessResultInterface $webform_access */
$webform_access = $webform_access_rules_manager->checkWebformAccess('create', $account, $webform);
if ($webform_access->isAllowed()) {
return $webform_access;
}
}
}
return AccessResult::neutral();
}
/**
* Implements hook_form_FORM_ID_alter().
*/
function tide_webform_form_webform_add_form_alter(&$form, FormStateInterface $form_state, $form_id) {
/** @var \Drupal\webform\WebformEntityAddForm $form_object */
$form_object = $form_state->getFormObject();
/** @var \Drupal\webform\WebformInterface $webform */
$webform = $form_object->getEntity();
if ($webform->isNew()) {
// Expose the webform to API requests by default.
$access_rules = $webform->getAccessRules();
$access_rules['configuration']['roles'][] = 'anonymous';
$access_rules['configuration']['roles'][] = 'authenticated';
$webform->setAccessRules($access_rules);
// Add a Privacy Statement element to the new webform.
$default_privacy_statement = \Drupal::config('tide_webform.defaults')->get('privacy_statement');
if (!empty($default_privacy_statement['add_to_new_form'])) {
$elements = $webform->getElementsDecoded();
if (empty($elements)) {
$elements['privacy_statement'] = [
'#type' => 'webform_privacy_statement',
'#required' => TRUE,
'#privacy_statement_heading' => $default_privacy_statement['heading'] ?? '',
'#privacy_statement_content' => $default_privacy_statement['content'] ?? '',
'#title' => $default_privacy_statement['agreement'] ?? t('I have read and understood the privacy statement.'),
];
$webform->setElements($elements);
}
}
// Make default submit button name.
if (!isset($elements['actions'])) {
$elements['actions'] = [
'#type' => 'webform_actions',
'#title' => 'Submit',
];
$webform->setElements($elements);
}
}
$form_object->setEntity($webform);
}
/**
* Implements hook_ENTITY_TYPE_presave().
*/
function tide_webform_webform_submission_presave(WebformSubmission $webform_submission) {
// Preparing confirmation message.
$webform = $webform_submission->getWebform();
if ($webform->getElement('confirmation_message') !== NULL) {
$webform_submission->set('notes', $webform_submission->uuid());
}
$elements = $webform_submission->getWebform()->getElementsDecoded();
// SDPAP-5181 Front end submits the value as numeric.
// Triggers invalid validation error from core.
// See /Drupal/Core/Form/FormValidator.php $is_empty_value.
$submission_data = $webform_submission->getData();
foreach ($elements as $key => $element) {
// It will not validate for multi step form.
if (isset($element['#type']) && $element['#type'] == 'wizard_page') {
return;
}
if (isset($element['#type']) && $element['#type'] == 'number') {
if (is_numeric($submission_data[$key])) {
$submission_data[$key] = strval($submission_data[$key]);
$webform_submission->setData($submission_data);
}
}
// SDPAP-6627 temporary fix until contrib module patch is created.
// Validation isolated to specific webform.
// @todo refactior the code and submit a patch.
// Look at webform issue - 3170790.
// Server side validation from API submission.
if (isset($element['#required']) && $element['#required'] == TRUE && $webform->get('id') === 'tide_webform_content_rating') {
if (empty($submission_data[$key]) && $submission_data[$key] == "") {
// Throw an exception to prevent saving the webform.
throw new \Exception("The required field '{$element['#title']}' is empty.");
}
}
}
$errors = WebformSubmissionForm::validateWebformSubmission($webform_submission);
if ($errors) {
foreach ($elements as $key => $element) {
if (isset($errors[$key]) && !empty($errors[$key])) {
throw new Exception($errors[$key]);
}
}
}
}
/**
* Implements hook_entity_type_alter().
*/
function tide_webform_entity_type_alter(array &$entity_types) {
/** @var \Drupal\Core\Entity\EntityTypeInterface[] $entity_types */
$entity_types['webform_submission']->setListBuilderClass('Drupal\tide_webform\TideWebformSubmissionListBuilder');
}
/**
* Function to get value of processed field.
*
* @param Drupal\webform\Entity\WebformSubmission $webform_submission
* Webform submission.
*
* @return processed[0][value]
* Returns value of processed field from Webform Submission.
*/
function tide_webform_get_processed(WebformSubmission $webform_submission) {
$processed = $webform_submission->processed->getValue();
if ($processed == NULL) {
return 0;
}
else {
return $processed[0]['value'];
}
}
/**
* Function to build query for filter on webform submissions pages.
*
* @return total
* Returns total from the webform submission count.
*/
function tide_webform_submission_filter_query($value) {
$query = \Drupal::entityQuery('webform_submission');
$query->condition('processed', $value)->accessCheck(TRUE);
$webform_submission = \Drupal::routeMatch()->getParameter('webform');
if ($webform_submission != NULL) {
$id = $webform_submission->id();
$query->condition('webform_id', $id);
}
$query->count();
$total = $query->execute();
return $total;
}
/**
* Submit callback.
*
* @param array $form
* The form.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* Form state.
*/
function tide_webform_form_webform_results_export_form_submit(array $form, FormStateInterface $form_state) {
$unprocessed_submissions = $form_state->getValue('unprocessed_submissions');
$process_submissions = $form_state->getValue('process_submissions');
$route = $form_state->getRedirect();
$route_parameters = $route->getRouteParameters();
$options = $route->getOptions();
$query = $options['query'];
$query['unprocessed_submissions'] = $unprocessed_submissions;
$query['process_submissions'] = $process_submissions;
$options = ['query' => $query];
$form_state->setRedirect('entity.webform.results_export', $route_parameters, $options);
}
/**
* Alter a webform element's default properties.
*
* @param array &$properties
* An associative array containing an element's default properties.
* @param array $definition
* The webform element's definition.
*
* @see webform_example_element_properties.module
*/
function tide_webform_webform_element_default_properties_alter(array &$properties, array &$definition) {
if (($definition["id"] === "textfield") && (empty($properties["counter_type"]))) {
$properties["counter_type"] = "character";
$properties["counter_maximum"] = 255;
}
}
/**
* Implements hook_ENTITY_TYPE_update().
*/
function tide_webform_webform_update(EntityInterface $entity) {
\Drupal::cache()->invalidate('webform_text_fields_default_maxlength');
}
/**
* Implements hook_webform_third_party_settings_form_alter().
*/
function tide_webform_webform_third_party_settings_form_alter(array &$form, FormStateInterface $form_state) {
$webform = $form_state->getFormObject()->getEntity();
$third_party_settings = $webform->getThirdPartySettings('tide_webform_captcha');
$user_input = $form_state->getUserInput();
$taxonomy_storage = \Drupal::entityTypeManager()->getStorage('taxonomy_term');
$captcha_type = NULL;
$allowed_values = [];
try {
$field_definition = \Drupal::entityTypeManager()->getStorage('field_storage_config')->load('taxonomy_term.field_captcha_type');
if ($field_definition) {
$allowed_values = $field_definition->getSetting('allowed_values');
}
else {
throw new \Exception('Field storage configuration not found for taxonomy_term.field_captcha_type');
}
}
catch (\Exception $e) {
\Drupal::messenger()->addWarning('Unable to load CAPTCHA type options. Please contact the site administrator.');
\Drupal::logger('tide_webform')
->error('Error loading CAPTCHA type options for webform @webform: @message',
['@webform' => $webform->id(), '@message' => $e->getMessage()]);
return;
}
if (isset($third_party_settings['captcha_type'])) {
$captcha_type = $third_party_settings['captcha_type'];
}
if (isset($user_input['third_party_settings']['tide_webform_captcha']['captcha_type'])) {
$captcha_type = $user_input['third_party_settings']['tide_webform_captcha']['captcha_type'];
}
$query = $taxonomy_storage->getQuery()
->accessCheck(TRUE)
->condition('vid', 'captcha_widgets')
->condition('field_captcha_type', $captcha_type);
$tids = $query->execute();
$terms = $taxonomy_storage->loadMultiple($tids);
$options = array_map(function (Term $term) {
return $term->label() . ' (' . $term->id() . ')';
}, $terms);
$form['third_party_settings']['tide_webform_captcha'] = [
'#type' => 'fieldset',
'#title' => t('Tide webform CAPTCHA'),
'#open' => TRUE,
];
$form['third_party_settings']['tide_webform_captcha']['enable_captcha'] = [
'#type' => 'checkbox',
'#default_value' => !empty($third_party_settings['enable_captcha']) ? $third_party_settings['enable_captcha'] : NULL,
'#title' => t('Enable captcha'),
];
$form['third_party_settings']['tide_webform_captcha']['captcha_type'] = [
'#type' => 'select',
'#title' => t('Captcha type'),
'#options' => [
'all' => '-Select-',
] + $allowed_values,
'#default_value' => !empty($third_party_settings['captcha_type']) ? $third_party_settings['captcha_type'] : NULL,
'#ajax' => [
'callback' => '_tide_webform_captcha_type_dropdown_callback',
'wrapper' => 'captcha-type-dropdown-container',
],
];
$score_threshold = NULL;
if (isset($third_party_settings['score_threshold']) && $third_party_settings['score_threshold'] === 0.0) {
$score_threshold = '0.0';
}
elseif (!empty($third_party_settings['score_threshold'])) {
$score_threshold = (string) $third_party_settings['score_threshold'];
}
$form['third_party_settings']['tide_webform_captcha']['score_threshold'] = [
'#type' => 'textfield',
'#title' => t('Score threshold (reCAPTCHA v3)'),
'#size' => 2,
'#maxlength' => 3,
'#number_type' => 'decimal',
'#element_validate' => ['_tide_webform_threshold_validate'],
'#states' => [
'visible' => [
':input[name="third_party_settings[tide_webform_captcha][captcha_type]"]' => ['value' => 'google_recaptcha_v3'],
],
],
'#default_value' => $score_threshold,
'#description' => 'Enter a value between 0.0 and 1.0. Use only one decimal place (e.g., 0.0, 0.5, 1.0).',
];
$form['third_party_settings']['tide_webform_captcha']['captcha_type_dropdown_container'] = [
'#type' => 'fieldset',
'#attributes' => ['id' => 'captcha-type-dropdown-container'],
];
$form['third_party_settings']['tide_webform_captcha']['captcha_type_dropdown_container']['captcha_details'] = [
'#type' => \Drupal::moduleHandler()->moduleExists('select2') ? 'select2' : 'select',
'#title' => ('Site key'),
'#target_type' => 'taxonomy_term',
'#options' => $options,
'#tags' => TRUE,
'#select2' => [
'allowClear' => TRUE,
'dropdownAutoWidth' => FALSE,
'width' => '20%',
'closeOnSelect' => FALSE,
],
'#default_value' => !empty($third_party_settings['captcha_details']['term_id']) ? $third_party_settings['captcha_details']['term_id'] : NULL,
'#selection_settings' => [
'target_bundles' => ['captcha_widgets'],
],
];
$form['#validate'][] = '_tide_webform_captcha_form_validate';
}
/**
* Captcha form validate.
*/
function _tide_webform_captcha_form_validate(&$form, FormStateInterface $form_state) {
$settings = &$form_state->getValue(['third_party_settings', 'tide_webform_captcha']);
$captcha_details = $settings['captcha_type_dropdown_container']['captcha_details'] ?? NULL;
if (is_array($captcha_details) && isset($captcha_details[0]['target_id'])) {
$term_id = $captcha_details[0]['target_id'];
}
elseif (is_numeric($captcha_details)) {
$term_id = $captcha_details;
}
else {
$term_id = NULL;
}
if ($term_id) {
$term = Term::load($term_id);
$settings['captcha_details'] = [
'site_key' => $term->get('field_site_key')->value,
'term_id' => (int) $term_id,
'captcha_id' => _tide_webform_get_captcha_id($term),
];
}
else {
$settings['captcha_details'] = NULL;
}
unset($settings['captcha_type_dropdown_container']);
}
/**
* Captcha options callback.
*/
function _tide_webform_captcha_type_dropdown_callback($form, FormStateInterface $form_state) {
return $form['third_party_settings']['tide_webform_captcha']['captcha_type_dropdown_container'];
}
/**
* Threshold element validation.
*/
function _tide_webform_threshold_validate($element, FormStateInterface $form_state) {
$number = $form_state->getUserInput()['third_party_settings']['tide_webform_captcha']['score_threshold'];
if ($number === 0 || $number === '' || $number === NULL) {
$form_state->setValue([
'third_party_settings',
'tide_webform_captcha',
'score_threshold',
], NULL);
return;
}
if (preg_match('/^(0(\.[0-9])?|1(\.0)?)$/', (string) $number)) {
$form_state->setValue([
'third_party_settings',
'tide_webform_captcha',
'score_threshold',
], (float) $number);
}
else {
$form_state->setError($element, t('Enter a value between 0.0 and 1.0. Use only one decimal place (e.g., 0.0, 0.5, 1.0).'));
}
}
/**
* Gets captcha id.
*/
function _tide_webform_get_captcha_id(Term $term) {
$uri = $term->toLink()->getUrl()->toString();
return pathinfo(rtrim($uri, '/'), PATHINFO_BASENAME);
}