-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathiform.module
1524 lines (1464 loc) · 58.1 KB
/
iform.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
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* @file
* Integrates Drupal with Indicia.
*/
use Drupal\Core\StreamWrapper\PrivateStream;
use Drupal\Core\StreamWrapper\PublicStream;
use Drupal\Core\Cache\Cache;
use Drupal\node\NodeInterface;
use Drupal\node\Entity\Node;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Markup;
require_once 'iform.hostsite_api.inc';
define('IFORM_GRANT_ALL', 50);
global $_iform_base_resources;
$_iform_base_resources = [
'jquery',
'jquery_ui',
'indiciaFns',
];
/**
* Stores page specific warehouse connection info.
*
* If the loaded node connects to a non-standard warehouse, then stores the
* URL, id and password in an array.
*
* @var array|bool
*/
global $_iform_warehouse_override;
$_iform_warehouse_override = FALSE;
/**
* Implements hook_preprocess_node().
*
* Allows iform code to override the page header <title>.
*/
function iform_preprocess_html(&$variables) {
global $_iform_page_title;
if (isset($_iform_page_title)) {
$variables['head_title'] = $_iform_page_title;
}
}
/**
* Implements hook_preprocess_page_title().
*
* Sets H1 element if defined programmatically.
*/
function iform_preprocess_page_title(&$variables) {
global $_iform_page_title;
if (isset($_iform_page_title)) {
$variables['title'] = $_iform_page_title;
}
}
/**
* Implements hook_preprocess_node().
*
* Allows iform code to override the page title.
*/
function iform_preprocess_node(&$variables) {
global $_iform_page_title;
if (isset($_iform_page_title)) {
$variables['label'] = $_iform_page_title;
}
}
/**
* Implements hook_help().
*
* Display help and module information.
*/
function iform_help($route_name) {
$output = '';
switch ($route_name) {
case 'help.page.iform':
$output = '';
$output .= '<h3>' . t('About') . '</h3>';
$output .= '<p>' . t('Generates Indicia powered data entry forms and reports. <a href="!link">More info</a>.',
['!link' => 'http://indicia-docs.readthedocs.org/en/latest/site-building/iform/index.html']) . '</p>';
return $output;
}
return $output;
}
/**
* Returns a list of unique permission names.
*
* Permissions are generated by any Indicia node which uses the View access
* control option.
*
* @return array
* List of permissions.
*/
function iform_all_permissions() {
$cached = \Drupal::cache()->get('iform:permissions');
if ($cached === FALSE) {
// Get list of iform nodes
$query = \Drupal::database()->select('node', 'n');
$query->fields('n', ['nid']);
$query->condition('type', "iform_page", "=");
$nids = $query->execute();
$permissions = [];
foreach ($nids as $row) {
$node = Node::load($row->nid);
if ($node->field_iform->value && !empty($node->params['view_access_control'])) {
if (empty($node->params['permission_name'])) {
$permissions['access iform ' . $node->id()] = ['iform', $node->id()];
}
else {
$permissions[$node->params['permission_name']] = [
'iform ' . $node->params['permission_name'],
IFORM_GRANT_ALL,
];
}
}
}
\Drupal::cache()->set('iform:permissions', $permissions, Cache::PERMANENT, ['node_list:iform_page']);
} else {
$permissions = $cached->data;
}
return $permissions;
}
/**
* Implements hook_node_grants().
*/
function iform_node_grants(AccountInterface $account, $op) {
$grants = [];
$permissions = iform_all_permissions();
foreach ($permissions as $permission => $grantInfo) {
if ($account->hasPermission($permission)) {
$grants[$grantInfo[0]] = [$grantInfo[1]];
}
}
if ($op == 'view' && $account->hasPermission('access iform content')) {
$grants['iform_view'] = [IFORM_GRANT_ALL];
}
if (($op == 'update' || $op == 'delete') && $account->hasPermission('admin iform')) {
$grants['iform_edit'] = [IFORM_GRANT_ALL];
}
return $grants;
}
/**
* Implements hook_node_access_records().
*
* Returns grants required to access a particular iform node.
*/
function iform_node_access_records(NodeInterface $node) {
if ($node->getType() === 'iform_page') {
// Invalidate our cache tag so that the permissions are reloaded.
Cache::invalidateTags(['node_list:iform_page']);
$grants = [];
$grants[] = [
'realm' => 'iform_edit',
'gid' => IFORM_GRANT_ALL,
'grant_view' => 1,
'grant_update' => 1,
'grant_delete' => 1,
];
if ($node->isPublished()) {
$hasAccessControl = isset($node->params['view_access_control']) && $node->params['view_access_control'];
if ($hasAccessControl && empty($node->params['permission_name'])) {
$realm = 'iform';
$gid = $node->id();
} elseif ($hasAccessControl) {
$realm = 'iform ' . $node->params['permission_name'];
$gid = IFORM_GRANT_ALL;
}
else {
$realm = 'iform_view';
$gid = IFORM_GRANT_ALL;
}
$grants[] = [
'realm' => $realm,
'gid' => $gid,
'grant_view' => 1,
'grant_update' => 0,
'grant_delete' => 0,
];
}
return $grants;
}
}
/**
* Implements hook_form_BASE_FORM_ID_alter().
*
* Modifies the Edit form for an Indicia page to add the controls required to
* configure an Indicia page.
*/
function iform_form_node_form_alter(&$form, FormStateInterface $form_state, $form_id) {
if ($form_id === 'node_iform_page_form' || $form_id === 'node_iform_page_edit_form') {
$node = $form_state->getFormObject()->getEntity();
$iform = $node->field_iform->value;
iform_load_helpers(['form_helper']);
// @todo This needs to use $node to get the correct node specific connection
$connection = iform_get_connection_details($node);
if (empty($connection['base_url']) || empty($connection['website_id']) || empty($connection['password'])) {
\Drupal::messenger()->addMessage(t('Indicia configuration is incomplete. Indicia pages cannot be set up until the warehouse settings are provided.'), 'warning');
return;
}
// Define the new form fields.
$form['iform_forms'] = [
'#type' => 'details',
'#title' => t('Form Selection'),
'#weight' => 35,
];
$config = \Drupal::config('iform.settings');
$readAuth = form_helper::get_read_auth($connection['website_id'], $connection['password']);
$form['iform_forms']['picker'] = [
'#markup' => Markup::create(form_helper::prebuilt_form_picker($readAuth, [
'form' => $iform,
'base_url' => $connection['base_url'],
'website_id' => $connection['website_id'],
'password' => $connection['password'],
'allowConnectionOverride' => $config->get('allow_connection_override'),
'available_for_groups' => $node->field_available_for_groups->value === '1',
'limit_to_group_id' => isset($node->field_limit_to_group_id->value) ? $node->field_limit_to_group_id->value : NULL,
])),
];
if ($iform) {
$form['form-params'] = [
'#markup' => Markup::create(form_helper::prebuiltFormParamsForm([
'form' => $iform,
// @todo Load params properly from node
'currentSettings' => $node->params,
'readAuth' => form_helper::get_read_auth($connection['website_id'], $connection['password']),
])),
'#prefix' => '<div id="form-params">',
'#suffix' => '</div>',
'#weight' => 36,
];
form_helper::enable_validation('node-form');
}
else {
$form['form-params'] = [
// Must be a space or Drupal drops the div.
'#markup' => ' ',
'#prefix' => '<div id="form-params">',
'#suffix' => '</div>',
'#weight' => 36,
];
}
}
}
/**
* Retrieves iform parameters.
*
* Retrieves the parameters required by an iform and creates a JSON string to
* store them in the database. The iform data must be in the $_POST array or in
* the node if not in the $_POST.
*
* @return string
* JSON encoded string containing the parameter values.
*/
function get_custom_param_values($node) {
// We need to grab the parameter values for the custom parameters that were
// defined by the form.
if (isset($_POST['iform']) && $_POST['iform'] != -1) {
iform_load_helpers(['form_helper']);
ob_start();
$connection = iform_get_connection_details($node);
$readAuth = form_helper::get_read_auth($connection['website_id'], $connection['password']);
$params = form_helper::getFormParameters($_POST['iform'], $readAuth);
ob_end_clean();
$values = [];
// Always want the website id and password.
$values['website_id'] = $_POST['website_id'];
$values['password'] = $_POST['password'];
if (!empty($_POST['base_url'])) {
$values['base_url'] = $_POST['base_url'];
}
// Now get the rest of the parameters.
foreach ($params as $param) {
if (isset($_POST[$param['fieldname']])) {
$values[$param['fieldname']] = $_POST[$param['fieldname']];
}
}
// Json encode the parameters to store them in the Drupal database.
return json_encode($values);
}
else {
return json_encode($node->params);
}
}
/**
* Implements hook_ENTITY_presave().
*
* Saves iform specific information.
*/
function iform_node_presave(EntityInterface $entity) {
if ($entity->bundle() === 'iform_page' && isset($_POST['iform'])) {
$iform = $_POST['iform'];
$entity->field_iform->setValue($iform);
$params = get_custom_param_values($entity);
$entity->field_params->setValue($params);
$entity->field_available_for_groups->setValue(
empty($_POST['available_for_groups']) ? '0' : '1'
);
$entity->field_limit_to_group_id->setValue(
empty($_POST['limit_to_group_id']) ? NULL : $_POST['limit_to_group_id']
);
// @todo limit_to_group_id
}
}
/**
* Implemenation of hook_entity_load().
*
* Updates the iform node objects so that their params property contains a
* decoded array of parameters rather than a JSON object.
*/
function iform_node_load(array $entities) {
foreach ($entities as &$node) {
if ($node->bundle() === 'iform_page') {
// Get the parameters, using the translated version if necessary.
$currentLang = \Drupal::languageManager()->getCurrentLanguage()->getId();
$translationsAvailable = array_keys($node->getTranslationLanguages());
if ($currentLang !== \Drupal::languageManager()->getDefaultLanguage()->getId()
&& in_array($currentLang, $translationsAvailable)) {
$translation = $node->getTranslation($currentLang);
$params = json_decode($translation->field_params->value, TRUE);
}
else {
$params = json_decode($node->field_params->value, TRUE);
}
unset($node->params);
$node->params = [];
if (function_exists('iform_user_ui_options_preprocess_iform')) {
iform_user_ui_options_preprocess_iform($params);
}
if (!is_array($params)) {
\Drupal::messenger()->addMessage(t("This page's configuration has not been stored correctly.") . ' ' .
$node->field_params->value, 'warning');
}
if (is_array($params)) {
// Merge the params into the loaded object.
foreach ($params as $k => $v) {
$node->params[$k] = $v;
}
// For the currently loading node only, we might want to globally
// switch to a different warehouse. Can't use routeMatch as the node is
// not yet loaded!
if (\Drupal::service('path.current')->getPath() === '/node/' . $node->id()
&& isset($node->params['base_url'])) {
$config = \Drupal::config('iform.settings');
if ($config->get('allow_connection_override')) {
iform_load_helpers(['data_entry_helper']);
if ($node->params['base_url'] !== data_entry_helper::$base_url) {
global $_iform_warehouse_override;
$_iform_warehouse_override = [
'base_url' => $node->params['base_url'],
'website_id' => $node->params['website_id'],
'password' => $node->params['password'],
];
data_entry_helper::$base_url = $node->params['base_url'];
iform_setup_cache_folder();
}
}
}
}
}
}
}
/**
* Implement hook_form_user_login_alter.
* Adds instructions to the login form if accessed via a link given out to join a recording group.
* @param $form
* @param $form_state
* @throws \exception
*
function iform_form_user_login_alter(&$form, &$form_state) {
if (!empty($_GET['group_id'])) {
iform_load_helpers(array('data_entry_helper'));
$auth = data_entry_helper::get_read_auth(variable_get('indicia_website_id'), variable_get('indicia_password'));
$groups = data_entry_helper::get_population_data(array(
'table' => 'group',
'extraParams' => $auth + array(
'view' => 'detail',
'id' => $_GET['group_id'],
'joining_method' => 'P', // only public groups can be joined this way
'website_id' => variable_get('indicia_website_id')
),
'caching' => false
));
if (count($groups)===1) {
module_load_include('inc', 'iform', 'iform.groups');
$group = $groups[0];
$link = url("join/$group[url_safe_title]", array('absolute' => TRUE));
$path = data_entry_helper::get_uploaded_image_folder();
$img = empty($group['logo_path']) ? '' : "<img style=\"width: 20%; float: left; padding-right: 5%\" alt=\"Logo\" src=\"$path$group[logo_path]\"/>";
$form['intro'] = array(
'#markup' => "<fieldset><legend>$group[title]</legend>$img<div style=\"float: left; width: 70%\"><p>" .
t('You\'ve followed a link to join the @group. This needs you to log in to @site.',
array('@group' => iform_readable_group_title($group), '@site' => variable_get('site_name'))) . '</p><ul>' .
'<li>' . t('If you already have an account on @site, then log in using the form below.', array('@site' => variable_get('site_name'))) . '</li>' .
'<li>' . t('If this is your first time using @site, then click the Create new account link and follow the steps to register. Once you have ' .
'confirmed your account please visit the join link you just used (<a href="@link">@link</a>) to join the @group.',
array('@group' => iform_readable_group_title($group), '@site' => variable_get('site_name'), '@link' => $link)) .'</li></ul></div></fieldset>',
'#weight' => -50
);
}
}
}
/**
* Utility method that gets the base_url, website_id and password appropriate to connect
* a given node to the warehouse.
* @param mixed $node A node object or nid.
* @return array Connection details, including website_id and password. Also
* contains a boolean using_drupal_vars which is true if the site-wide
* configuration is being used.
*/
function iform_get_connection_details($node = NULL) {
// Node is not null and override set for this node, use it.
// Node is not null load node,
// and has override settings - use them and store them.
global $_iform_warehouse_override;
// If we don't know the node but the current node overrides the config, use
// the override.
if ($node === NULL && $_iform_warehouse_override) {
return $_iform_warehouse_override;
}
// Load the default config.
$config = \Drupal::config('iform.settings');
$r = [
'base_url' => $config->get('base_url'),
'website_id' => $config->get('website_id'),
'password' => $config->get('password'),
];
if ($node && $config->get('allow_connection_override')) {
if (!is_object($node))
$node = \Drupal\node\Entity\Node::load($node);
if (isset($node->params['base_url']) && $node->params['base_url'] !== $r['base_url']) {
iform_load_helpers(['data_entry_helper']);
$r['base_url'] = $node->params['base_url'];
}
if (isset($node->params['website_id'])) {
$r['website_id'] = $node->params['website_id'];
}
if (isset($node->params['password'])) {
$r['password'] = $node->params['password'];
}
}
return $r;
}
/**
* Implementation for hook_node_view. Prepares the displayed Indicia page content.
*/
function iform_node_view(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display, $view_mode) {
if ($entity->bundle() === 'iform_page' && $view_mode !== 'search_index') {
global $language;
iform_load_helpers(['data_entry_helper', 'form_helper'], empty($entity->params['base_url']) ? '' : $entity->params['base_url']);
// @todo Drupal 8 might allow us to be more intelligent rather than killing the entire page cache
\Drupal::service('page_cache_kill_switch')->trigger();
$helperPath = realpath(iform_client_helpers_path());
$iform = $entity->field_iform->value;
if (!empty($iform)) {
$nid = $entity->id();
data_entry_helper::$indiciaData['nid'] = $nid;
if (\Drupal::service('module_handler')->moduleExists('eu_cookie_compliance')) {
data_entry_helper::$indiciaData['cookieCompliance'] = 'eu_cookie_compliance';
}
iform_load_language_files($iform, $nid);
$language = \Drupal::languageManager()->getCurrentLanguage();
$args = ['language' => $language->getId()];
// Require the file containing the code for the $iform.
if (\Drupal::moduleHandler()->moduleExists('iform_custom_forms')) {
// Enable autoloader for classes in iform_custom_forms module.
$iformCustomFormsList = \Drupal::service('iform_custom_forms.list');
}
if (!class_exists("iform_$iform")) {
require_once "$helperPath/prebuilt_forms/$iform.php";
}
ob_start();
// Also force the theme path to be local.
global $indicia_theme_path;
$indicia_theme_path = iform_media_folder_path() . 'themes/';
$connection = iform_get_connection_details($entity);
$readAuth = form_helper::get_read_auth($connection['website_id'], $connection['password']);
$args['base_url'] = $connection['base_url'];
$args['website_id'] = $connection['website_id'];
$args['password'] = $connection['password'];
$args['available_for_groups'] = $entity->field_available_for_groups->value;
if (isset($entity->limit_to_group_id->value)) {
$args['limit_to_group_id'] = $entity->limit_to_group_id->value;
}
// We need to grab each requested parameter from the node to pass to the
// form.
$params = form_helper::getFormParameters($iform, $readAuth);
foreach ($params as $param) {
if (isset($entity->params[$param['fieldname']])) {
$args[$param['fieldname']] = $entity->params[$param['fieldname']];
}
elseif (isset($param['default'])) {
// Apply the default, this was an old saved form configuration which
// doesn't have a new parameter.
$args[$param['fieldname']] = $param['default'];
}
}
$r = '';
$response = NULL;
// If the form defines some remembered fields, call it from within this
// module rather than inside indicia so it can have access to the
// arguments.
if (method_exists("iform_$iform", 'indicia_define_remembered_fields')) {
call_user_func([
"iform_$iform",
'indicia_define_remembered_fields',
], $args);
}
$r .= iform_handle_posted_form($entity, $args, $response);
// Make buttons have a hover effect.
data_entry_helper::$javascript .= "indiciaFns.enableHoverEffect();\n";
$config = \Drupal::config('iform.settings');
_iform_apply_variables_to_args($args, $config);
// Preferred location for custom node configuration files now under
// Drupal files folder.
$filePath = hostsite_get_public_file_path();
// A drupal theme can override the templates.
if (file_exists(\Drupal::theme()
->getActiveTheme()
->getPath() . '/indicia.templates.php')) {
require \Drupal::theme()
->getActiveTheme()
->getPath() . '/indicia.templates.php';
}
// Or we can override the templates in the iform module, either globally,
// per form or per node.
if (file_exists("$helperPath/prebuilt_forms/templates/global.php")) {
require "$helperPath/prebuilt_forms/templates/global.php";
}
if (file_exists("$helperPath/prebuilt_forms/templates/$iform.php")) {
require "$helperPath/prebuilt_forms/templates/$iform.php";
}
if (file_exists("$filePath/indicia/templates/node.$nid.php")) {
require "$filePath/indicia/templates/node.$nid.php";
}
// Templates may also come from the iform_custom_forms module.
if (isset($iformCustomFormsList)){
$searchTemplates = ['global.php', "$iform.php", "node.$nid.php"];
$customTemplates = $iformCustomFormsList->getCustomisations()['templates'];
foreach ($searchTemplates as $searchTemplate) {
if (array_key_exists($searchTemplate, $customTemplates)){
require $iformCustomFormsList->getAbsoluteModulePath() .
'/' . $customTemplates[$searchTemplate] .
'/' . $searchTemplate;
}
}
}
// Link in custom additional template files.
if (!empty($args['additional_templates'])) {
$templateFiles = data_entry_helper::explode_lines($args['additional_templates']);
foreach ($templateFiles as $file) {
$file = str_replace('{prebuiltformtemplates}', "$helperPath/prebuilt_forms/templates", $file);
require $file;
}
}
// Now retrieve the form content.
try {
$r .= call_user_func([
'iform_' . $iform,
'get_form',
], $args, $entity->id(), $response);
} catch (Exception $e) {
\Drupal::logger('iform')->notice('Error occurred loading form');
\Drupal::logger('iform')->notice($e->getMessage());
\Drupal::logger('iform')->notice($e->getTraceAsString());
$r .= $e->getMessage();
}
ob_end_clean();
$build['iform'] = [
'#markup' => Markup::create($r),
'#weight' => 1,
'#cache' => [
'contexts' => [
// The "current user" is used above, which depends on the request,
// so we tell Drupal to vary by the 'user' cache context.
// @todo Could we separate out the user specific content and token specific content
// into a separate build array entry, then use JS to copy it into it's destinations?]
// Then whole page can get cached
'user',
],
// @todo currently we've disabled caching until we work out handling of write tokens
'max-age' => 0,
],
];
}
}
}
/**
* Handle posting an Indicia form.
*
* When an Indicia form sends POST data back, this method handles the
* submission of the data to the warehouse.
*
* @param object $node
* Node object.
* @param array $args
* Form arguments.
*
* @return string|void
*/
function iform_handle_posted_form($node, array $args, &$response) {
$iform = $node->field_iform->value;
$r = '';
if ($_POST && (array_key_exists('website_id', $_POST)) && method_exists("iform_$iform", 'get_submission')) {
$helperPath = realpath(iform_client_helpers_path());
$nid = $node->id();
if (!empty($_POST['delete-button'])) {
$_POST['deleted'] = 't';
}
// Ask the form to submit itself.
try {
// Attach the path to the input form for new samples. It'll just get
// skipped if we are not posting a sample.
if (empty($_POST['sample:id'])) {
$_POST['sample:input_form'] = trim(\Drupal::service('path_alias.manager')
->getAliasByPath("/node/$nid"), '/');
}
$s = call_user_func([
"iform_$iform",
'get_submission',
], $_POST, $args, $nid);
} catch (Exception $e) {
\Drupal::logger('iform')
->notice('Exception occurred during build of form submission: ' . $e->getMessage());
\Drupal::messenger()->addMessage(t('An error occurred whilst saving the new site details.'));
unset($s);
}
// And allow the form or calling URL to dynamically set the destination
// after post.
if (!empty($_REQUEST['redirect_on_success'])) {
$args['redirect_on_success'] = $_REQUEST['redirect_on_success'];
}
if (method_exists("iform_$iform", 'get_redirect_on_success')) {
$redirect = call_user_func([
"iform_$iform",
'get_redirect_on_success',
], $_POST, $args);
if (!empty($redirect)) {
$args['redirect_on_success'] = $redirect;
}
}
// if for some reason the iform gives back an empty submission, ignore it
if (isset($s) && $s) {
$errors = [];
// does this Drupal node have any in-built validation code?
if (method_exists("iform_$iform", 'get_validation_errors')) {
$errors = call_user_func([
"iform_$iform",
'get_validation_errors',
], $_POST, $args);
}
// Does this Drupal node have any custom validation code?
$validation_path = '';
// Preferred location for custom validation code in iform_custom_forms
// module.
if (\Drupal::moduleHandler()->moduleExists('iform_custom_forms')) {
$iformCustomFormsList = \Drupal::service('iform_custom_forms.list');
$customValidationsFiles = $iformCustomFormsList->getCustomisations()['validation'];
$file = "node.$nid.php";
if (array_key_exists($file, $customValidationsFiles)) {
$validation_path = $iformCustomFormsList->getAbsoluteModulePath() .
'/' . $customValidationsFiles[$file] .
'/' . $file;
}
}
if (empty($validation_path)) {
// Check legacy locations for validation files.
$legacy_path = "$helperPath/prebuilt_forms/validation/validate.$nid.php";
// Alternative location for custom node validation files under
// Drupal files folder.
$filePath = hostsite_get_public_file_path();
$new_path = "$filePath/indicia/validation/node.$nid.php";
if (file_exists($legacy_path)) {
$validation_path = $legacy_path;
}
elseif (file_exists($new_path)) {
$validation_path = $new_path;
}
}
if (!empty($validation_path)) {
require_once $validation_path;
$errors = array_merge($errors, iform_custom_validation($_POST));
}
if (!empty($errors)) {
$r .= data_entry_helper::dump_errors(['errors' => $errors]);
}
else {
$response = data_entry_helper::forward_post_to('save', $s);
// Clear the Drupal cache tag so user record based reports refresh.
Cache::invalidateTags(['user_records:' . hostsite_get_user_field('indicia_user_id')]);
if (is_array($response) && array_key_exists('success', $response)) {
if (!empty($_POST['delete-button'])) {
$op = 'D';
}
elseif (!empty($_POST["$s[id]:id"])) {
$op = 'U';
}
else {
$op = 'C';
}
$msg = data_entry_helper::getSuccessMessage($response, $op);
\Drupal::moduleHandler()->invokeAll('iform_after_submit', [
$s,
$op,
$response,
&$msg,
]);
if (!isset($args['message_after_save']) || $args['message_after_save']) {
\Drupal::messenger()->addMessage($msg);
}
}
// Does the form redirect after success?
if (is_array($response) && array_key_exists('success', $response) &&
array_key_exists('redirect_on_success', $args) && $args['redirect_on_success']
) {
$parts = explode('?', $args['redirect_on_success'], 2);
// First item removed from array.
$url = array_shift($parts);
if (count($parts)) {
$parts = explode('#', $parts[0], 2);
// Info between the ? and # is the query string.
$queryStr = array_shift($parts);
// Get an array of the redirect_on_success specified query string
// params.
parse_str($queryStr, $params);
}
else {
// Split bookmark fragment off.
$parts = explode('#', $url, 2);
$url = array_shift($parts);
$params = [];
}
// pass through $_GET parameters
$params = array_merge($_GET, $params);
// Merge the information about the saved record in
$idKey = array_search('{id}', $params);
if ($idKey) {
$params[$idKey] = $response['outer_id'];
}
else {
$params = array_merge(array(
'table' => $response['outer_table'],
'id' => $response['outer_id'],
), $params);
}
$replacements = preg_grep('/\{[a-z_]+\}/', $params);
foreach ($replacements as $key => $value) {
$params[$key] = $_GET[str_replace(['{', '}'], '', $value)];
}
// anything left in $parts is the bookmark
$fragment = count($parts) ? $parts[0] : false;
return hostsite_goto_page($url, $params, $fragment);
}
elseif (!array_key_exists('success', $response)) {
$r .= data_entry_helper::dump_errors($response, TRUE);
}
}
}
}
return $r;
}
/**
* Implements hook_library_info_build.
*
* Dynamically build a set of Drupal 8 asset libraries. In Drupal 8, drupal_add_js and
* drupal_add_css are removed with the definition of libraries to define the assets required
* now the preferred way forward. This method creates a list of libraries that might be
* required by the Indicia forms module, including libraries for the general client helper
* code and libraries containing JS and CSS specific to each node.
* @return array Libraries to create
*/
function iform_library_info_build() {
$libraries = [];
iform_build_client_helper_libraries($libraries);
iform_build_node_specific_libraries($libraries);
return $libraries;
}
/**
* Creates the asset libraries for Drupal which provide the JS and CSS files for
* client helper resource.
* @param $libraries Array of library definitions to which the required libraries will
* be appended.
*/
function iform_build_client_helper_libraries(&$libraries) {
iform_load_helpers(array('data_entry_helper'));
global $_iform_base_resources;
$resources = data_entry_helper::get_resources();
$fullPaths = array(data_entry_helper::$css_path, data_entry_helper::$js_path, 'http://');
$shortPaths = array('media/css/', 'media/js/', '//');
foreach ($resources as $name => $def) {
// some resources are always included, forcing the Drupal version of jQuery.
if (in_array($name, $_iform_base_resources))
continue;
$libraries[$name] = [
'version' => 'VERSION'
];
if (!empty($def['javascript'])) {
$libraries[$name]['js'] = [];
foreach ($def['javascript'] as $js) {
// skip IE specific scripts (which only applied to IE < 9) since D8 does not support IE<=8.
if (substr($js, 0, 4)!=='[IE]')
$libraries[$name]['js'][str_replace($fullPaths, $shortPaths, $js)] = [];
}
}
if (!empty($def['stylesheets'])) {
$libraries[$name]['css'] = ['component' => []];
foreach ($def['stylesheets'] as $css) {
$libraries[$name]['css']['component'][str_replace($fullPaths, $shortPaths, $css)] = [];
}
}
if (!empty($def['deps'])) {
$libraries[$name]['dependencies'] = [];
foreach ($def['deps'] as $dependency) {
if (in_array($dependency, $_iform_base_resources))
continue;
$libraries[$name]['dependencies'][] = "iform/$dependency";
}
}
}
}
/**
* Creates the asset libraries for Drupal which provide the JS and CSS files specific
* to each node.
* @param $libraries Array of library definitions to which the required libraries will
* be appended.
*/
function iform_build_node_specific_libraries(&$libraries) {
$nids = \Drupal::entityQuery('node')
->condition('type', 'iform_page')
->accessCheck(FALSE)
->execute();
$node_storage = \Drupal::entityTypeManager()->getStorage('node');
$nodes = $node_storage->loadMultiple($nids);
$helperPath = realpath(iform_client_helpers_path());
$filePath = hostsite_get_public_file_path();
foreach ($nodes as $node) {
$nid = $node->id();
$lib = "node_$nid";
$form = $node->field_iform->value;
$libraries[$lib] = [
'version' => 'VERSION',
'js' => [],
'css' => [
'base' => []
]
];
// Prebuilt form specific CSS
if (file_exists("$helperPath/prebuilt_forms/css/$form.css")) {
$libraries[$lib]['css']['base']["client_helpers/prebuilt_forms/css/$form.css"] = [];
}
// Node specific CSS
if (file_exists("$filePath/indicia/css/node.$nid.css")) {
$libraries[$lib]['css']['base']["/$filePath/indicia/css/node.$nid.css"] = [];
}
if (file_exists("$helperPath/prebuilt_forms/css/node.$nid.css")) {
$libraries[$lib]['css']['base']["client_helpers/prebuilt_forms/css/node.$nid.css"] = [];
}
if (!empty($node->params['additional_css'])) {
$cssFiles = data_entry_helper::explode_lines($node->params['additional_css']);
// @todo Theme path replacement
// @todo Also need to implement way to get to public::indicia/css folder.
foreach ($cssFiles as $file) {
$file = str_replace([
'{mediacss}',
//'{theme}',
'{prebuiltformcss}',
],
[
'media/css',
//path_to_theme(),
'client_helpers/prebuilt_forms/css',
],
$file
);
$libraries[$lib]['css']['component'][$file] = [];
}
}
// Prebuilt form specific JS
if (file_exists("$helperPath/prebuilt_forms/js/$form.js")) {
$libraries[$lib]['js']["client_helpers/prebuilt_forms/js/$form.js"] = [];
}
// Node specific JS
if (file_exists("$filePath/indicia/js/node.$nid.js")) {
$libraries[$lib]['js']["/$filePath/indicia/js/node.$nid.js"] = [];
}
if (file_exists("$helperPath/prebuilt_forms/js/node.$nid.js")) {
$libraries[$lib]['js']["client_helpers/prebuilt_forms/js/node.$nid.js"] = [];
}
// Extension classes can be referred to in the form structure parameter of any page
// and can contain JS or CSS code in addition to the PHP class.
if (!empty($node->params['structure'])) {
if (preg_match_all('/\[[a-z_]+\.[a-z_]+\]/', $node->params['structure'], $extensions)) {
foreach ($extensions[0] as $extension) {
preg_match('/\[(?P<class>[a-z_]+)/', $extension, $matches);
if (file_exists("$helperPath/prebuilt_forms/extensions/$matches[class].js"))
$libraries[$lib]['js']["client_helpers/prebuilt_forms/extensions/$matches[class].js"] = [];
if (file_exists("$helperPath/prebuilt_forms/extensions/$matches[class].css")) {
$libraries[$lib]['css']['base']["client_helpers/prebuilt_forms/extensions/$matches[class].css"] = [];
}
}
}
}
// Skip any unnecessary empty libraries
if (empty($libraries[$lib]['css']['base']) && empty($libraries[$lib]['js'])) {
unset($libraries[$lib]);
}
}
}
/**
* @todo Document
* @param $args
*/
function _iform_apply_variables_to_args(&$args, $config) {
_iform_apply_variable_to_args('map_centroid_lat', $args, $config);
_iform_apply_variable_to_args('map_centroid_long', $args, $config);
_iform_apply_variable_to_args('map_zoom', $args, $config);
_iform_apply_variable_to_args('spatial_systems', $args, $config);
}
/**
* @todo Document
* @param $variable
* @param $args
* @param $config
*/
function _iform_apply_variable_to_args($variable, &$args, $config) {
$default = $config->get($variable);
if (isset($args[$variable]) && ((string) $args[$variable] == t('default') || $args[$variable] == 'default' || $args[$variable] == '') && !empty($default)) {
$args[$variable] = $default;
}
}
/**
* Implements hook_preprocess_page().
*
* We use this to detect messages set before a redirection and show them on the
* redirected page. A bit of custom handling required here because under Drupal
* 8 messenger service messages are cleared when you redirect, so we have to
* store them in a custom session var to ensure they aren't lost.
*/
function iform_preprocess_page(&$variables) {
if (isset($_SESSION['iform-messages']) && $_SESSION['iform-redirect-from'] !== hostsite_get_current_page_path()) {
foreach ($_SESSION['iform-messages'] as $message) {
\Drupal::messenger()->addMessage($message[0]);
}
unset($_SESSION['iform-messages']);
}
}
/**
* Implements hook_page_attachments().
* For any page that has Indicia functionality, add all the scripts and CSS that
* we require.
*/
function iform_page_attachments(array &$attachments) {
if (hostsite_get_user_field('training', false)) {
$message = t('You are in training mode. Records you add will be for training purposes only and you can only see training records.');
\Drupal::messenger()->addWarning($message);
}
if (class_exists('helper_base')) {
global $_iform_base_resources;
$attachments['#attached']['library'][] = 'iform/base';
$config = \Drupal::config('iform.settings');
// Attach theme specific library.
$baseTheme = $config->get('base_theme');
$baseTheme = $baseTheme ? $baseTheme : 'generic';
$attachments['#attached']['library'][] = "iform/theme.$baseTheme";