-
Notifications
You must be signed in to change notification settings - Fork 174
/
NDB_BVL_Instrument.class.inc
3439 lines (3138 loc) · 115 KB
/
NDB_BVL_Instrument.class.inc
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 declare(strict_types=1);
use \Psr\Http\Message\ServerRequestInterface;
use \Psr\Http\Server\RequestHandlerInterface;
use \Psr\Http\Message\ResponseInterface;
use \LORIS\StudyEntities\Candidate\CandID;
use \LORIS\Data\Dictionary\DictionaryItem;
/**
* Base class for all LORIS behavioural instruments.
*
* @license http://www.gnu.org/licenses/gpl-3.0.txt GPLv3
*/
abstract class NDB_BVL_Instrument extends NDB_Page
{
protected const ERROR_CERTIFICATION_BAD_FORMATTING
= 'Certification settings are not formatted correctly in the '
. 'configuration file. Cannot continue.';
/**
* Determines whether this instrument should load data in
* JSON format from the "Data" column of the flag table, or
* from the traditional SQL tables.
*/
protected $jsonData = false;
/**
* The form object for this instrument.
*
* @var LorisForm
*/
public $form;
/**
* Variable defining the type of form in use
*
* Note: this seems to always be defined as 'XIN'
*
* @var string
*/
public $formType;
/**
* Array holding the date format
*
* @var array
*/
public $dateOptions;
/**
* Type of instrument. Can be 'normal' or 'DirectEntry'
*
* @var string
*/
public $DataEntryType;
/**
* Array holding XIN rules
*
* @var array
*/
public $XINRules;
/**
* Boolean enabling/disabling debugging statements for XIN rules
*
* @var boolean
*/
public $XINDebug;
/**
* A flag determining whether the ControlPanel changed
* the Data_entry flag status on this page load.
*/
private $_DataEntryChanged;
/**
* Test name (short name), equivalent to test_names.Test_name
*/
public $testName;
/**
* Instrument instance CommentID
*
* @access public
*/
public $commentID;
/**
* The data associated with the commentID for this instrument
*
* @var ?array
*/
protected $instanceData = null;
/**
* Database table containing data referenced by $this->commentID
*
* @access public
*/
public $table;
/**
* Cache location for the date of administration
*
* @access public
*/
public $dateOfAdministration;
/**
* Additional form defaults - should only be used for lorisform
* static elements!
*
* @access public
*/
public $localDefaults = ['emptyCell' => ' '];
/**
* String to separate the group elements
*/
var $_GUIDelimiter = "</td>\n<td>";
/**
* Commonly used level of indentation
*
* @access public
*/
public $indent = " ";
/**
* Array of required fields to check
*
* @access public
*/
var $_requiredElements = [];
/**
* Array of column names to be ignored by the double data entry conflict
* detector.
*
* @access public
*/
var $_doubleDataEntryDiffIgnoreColumns
= [
'CommentID',
'UserID',
'Testdate',
'Window_Difference',
'Candidate_Age',
];
/**
* Whether the "Validity" field is shown as a flag for an instrument
* or not.
*
* @access public
*/
public $ValidityEnabled = true;
/**
* Whether the "Validity" field is required before flagging an instrument
* as complete or not.
*
* @access public
*/
public $ValidityRequired = true;
/**
* True if the instrument page is being loaded by a script
* such as the lorisform_parser where all elements should be added to form,
* ignoring age-dependent or other conditional display logic in the form.
* To be called from within individual instrument forms.
*/
public $displayAllFields = false;
public $WrapperTextElements = [];
public $WrapperNumericElements = [];
public $WrapperDateWithStatusElements = [];
/**
* True if the instrument is administered after the candidate's death.
* This is used to determine which candidate age should be displayed as
* part of metadata fields. (Either Candidate Age or Candidate Age at Death).
* To be called from within individual instrument forms.
*
* @var bool
* @access protected
*/
protected $postMortem = false;
/**
* True if the page is being previewed from the instrument builder,
* and not really loaded. only applies to LINST instrument.
*/
public $preview = false;
/**
* Array containing all multiselect elements in an instrument.
*/
protected $selectMultipleElements = [];
/**
* Factory generates a new instrument instance of type
* $instrument, and runs the setup() method on that new
* instrument.
*
* @param \LORIS\LorisInstance $loris The LORIS instance with the
* instrument
* @param string $instrument The name of the instrument to
* use
* @param string $commentID The CommentID identifying the
* data to load
* @param string $page If a multipage form, the page to
* show
* @param boolean $guarantee_exists If true the factory will throw
* an error if the file does not
* exist, otherwise will silently
* return if the instrument is
* missing.
*
* @return object|null the new object of $instrument type
* @access public
* @throws NotFound
* @throws Exception
*/
public static function factory(
\LORIS\LORISInstance $loris,
string $instrument,
string $commentID = '',
string $page = '',
bool $guarantee_exists = true
) {
$class = "NDB_BVL_Instrument_$instrument";
// Make sure the instrument class has been included/required!
$factory = NDB_Factory::singleton();
$config = $factory->config();
$base = $config->getSetting('base');
// The conflict resolver doesn't care if the instrument exists or not, it
// just tries to load, score, and save. If it doesn't exist, for instance
// in the case of figs_year3_relatives, we shouldn't require because it
// isn't necessarily an error.
if (!file_exists($base."project/instruments/$class.class.inc")
&& !file_exists($base."project/instruments/$instrument.linst")
&& $guarantee_exists==false
) {
return null;
}
if (file_exists($base."project/instruments/$instrument.linst")
) {
include_once 'NDB_BVL_Instrument_LINST.class.inc';
$obj = new \Loris\Behavioural\NDB_BVL_Instrument_LINST(
// The module directory we use for instruments is arbitrary,
// since it isn't a real module, but it's required for the page
// constructor.
$loris,
$loris->getModule("instruments"),
$page,
$commentID,
$commentID,
);
} else {
if (!class_exists($class)
&& ($guarantee_exists === true
&& !file_exists($base."project/instruments/$class.class.inc"))
) {
throw new NotFound("Instrument does not exist");
}
if (!class_exists($class)) {
include_once $base."project/instruments/$class.class.inc";
}
// Now go ahead and instantiate it
$obj = new $class(
$loris,
$loris->getModule("instruments"),
$page,
$commentID,
$commentID,
'test_form'
);
}
// if a script is loading this form without a commentID, display all fields
if (!isset($commentID)) {
$obj->displayAllFields = true;
}
// Set page name to testName
$obj->name = $instrument;
// Sets up page variables such as $this->commentID and $this->form
$obj->setup($commentID, $page);
if (!empty($commentID)) {
$obj->setupCandidateInfoTables();
}
if (file_exists($base."project/instruments/$instrument.meta")) {
$obj->loadInstrumentMetadata(
$base . "project/instruments/$instrument.meta"
);
}
// Set DataEntryType to normal or DirectEntry
if (isset($_REQUEST['key'])) {
$obj->DataEntryType = 'DirectEntry';
} else {
$obj->DataEntryType = 'normal';
}
// Adds all of the form element and form rules to the page after
// having instantiated the form above
$obj->loadInstrumentFile(
$base . "project/instruments/$instrument.linst"
);
// Add rules only if they exist.
$obj->loadInstrumentRules(
$base . "project/instruments/$instrument.rules"
);
return $obj;
}
/**
* Checks if the user has permissions to view the instrument.
*
* Relies on <instrumentPermissions> settings in the config.xml file.
*
* This follows a permissive scheme.
* If the instrument is not listed in the instrumentPermissions section,
* access is granted.
* If the user has ANY of the permissions listed in the config.xml file for
* the instrument, access is granted.
*
* @param \User $user The user whose access is being checked
*
* @return bool
*/
function _hasAccess(\User $user) : bool
{
$DB = $this->loris->getDatabaseConnection();
$instrumentPermissions = $DB->pselectCol(
"SELECT code FROM testnames_permissions_rel rel
LEFT JOIN test_names ON (test_names.ID=rel.TestID)
LEFT JOIN permissions ON (permissions.permID=rel.PermID)
WHERE test_names.Test_name=:tn",
['tn' => $this->testName]
);
if (empty($instrumentPermissions)) {
// no permissions configured for this instrument
return true;
}
return $user->hasAnyPermission($instrumentPermissions);
}
/**
* Sets up basic data.
*
* @param string|null $commentID The CommentID identifying the data to load
* @param string|null $page If a multipage form, the page to show
*
* @return void
* @access public
* @abstract
*/
function setup(?string $commentID = null, ?string $page = null): void
{
$this->commentID = $commentID;
$this->page = $page;
}
/**
* Gets data for candidate and timepoint to display the tables at the top of the
* page. This info is then set in the tpl_data array.
*
* @return void
*/
function setupCandidateInfoTables(): void
{
try {
$timePoint = \TimePoint::singleton($this->getSessionID());
} catch (Exception $e) {
throw new LorisException($e->getMessage());
}
try {
$candidate = \Candidate::singleton($timePoint->getCandID());
} catch (Exception $e) {
throw new LorisException($e->getMessage());
}
$this->tpl_data['candidate'] = $candidate->getData();
$this->tpl_data['timePoint'] = $timePoint->getData();
// convert DoB And EDC date to years and months
// DoB to Derived Age
$dob = $candidate->getCandidateDoB();
if (is_string($dob) && strtotime($dob) !== false) {
$dob_date = new \DateTime($dob);
$current_date = new \DateTime();
$dob_year = abs($current_date->diff($dob_date)->y);
$dob_month = abs($current_date->diff($dob_date)->m);
$dob_age = $dob_year . " y / " . $dob_month . " m";
$this->tpl_data['dob_age'] = $dob_age;
}
// EDC to EDC Age
$edc = $candidate->getCandidateEDC();
if (is_string($edc) && strtotime($edc) !== false) {
$edc_date = new DateTime($edc);
$current_date = new DateTime();
$edc_year = abs($current_date->diff($edc_date)->y);
$edc_month = abs($current_date->diff($edc_date)->m);
$edc_age = $edc_year . " y / " . $edc_month . " m";
$this->tpl_data['edc_age'] = $edc_age;
}
}
/**
* Method to compute scores - by default will run a script named
* after the testName in the instrument directory if it exists,
* but any instrument with a scoring algorithm to implement can override
* it in PHP.
*
* @return void
* @access public
*/
function score(): void
{
$config = NDB_Config::singleton();
$base = $config->getSetting('base');
$scorer = $base . "project/instruments/" . $this->testName . ".score";
$this->logger->debug("Running scoring script $scorer");
if (file_exists($scorer)) {
if (is_executable($scorer) === false) {
$this->logger->critical(
"Scoring script $scorer exists but is not executable"
);
throw new \ConfigurationException(
"Scoring script not executable"
);
}
$output = [];
exec(
escapeshellarg($scorer) . " " . escapeshellarg(
$this->getCommentID()
),
$output,
$retVal
);
if ($retVal != 0) {
$this->logger->warning(
"An error occurred while running the scoring
algorithm of instrument ".$this->testName."."
);
}
}
}
/**
* Method to display the form for an instrument
*
* @return string
* @access public
*/
function display(): string
{
// ALWAYS INCLUDE THESE!
if ($this->DataEntryType === 'normal') {
// These are required for Save Data to work properly, but not when it's
// a direct data entry page
$this->addHidden(
'candID',
isset($_REQUEST["candID"]) ? $_REQUEST['candID'] : ''
);
$this->addHidden(
'sessionID',
isset($_REQUEST["sessionID"]) ? $_REQUEST['sessionID'] : ''
);
}
$this->addHidden('commentID', $this->getCommentID());
$this->addHidden('test_name', $this->testName);
$this->addHidden('page', $this->page);
$this->addHidden('subtest', $this->page);
// Don't show save button for Direct Data entry type,
// because that's part of the DirectEntry template
// and has Save/Continue and go back buttons
if (!$this->form->isFrozen() && $this->DataEntryType === 'normal') {
$buttons = [];
$buttons[] = $this->form->createElement(
'submit',
'fire_away',
'Save Data',
['class' => 'button']
);
//$buttons[] = $this->form->createElement('reset', null, 'Reset');
$this->addGroup($buttons, '', '', " ");
}
$defaults = $this->getInstanceData();
// set the defaults (call private method _setDefaultsArray
// which could be overridden if necessary)
$defaults = $this->_setDefaultsArray($defaults ?? []);
// merge in the localDefaults property so that simple
// additions to the defaults array no longer requires
// overriding the _setDefaultsArray method
$defaults = array_merge($defaults, $this->localDefaults);
$this->form->setDefaults($defaults);
if ($this->DataEntryType == 'DirectEntry') {
$smarty = new Smarty_NeuroDB;
$formArray = $this->form->toElementArray();
if (isset($this->testName)) {
$formArray['tableID'] = "instrument_$this->testName";
} else {
$formArray['tableID'] = "instrument";
}
$smarty->assign('form', $formArray);
$html = $smarty->fetch("directentry_form.tpl");
} elseif (isset($_REQUEST['json']) == 'true') {
// Mostly here for debugging. Realisticly, the JSON
// representation will be retrieved through the API,
// not the display function.
return $this->toJSON();
} else {
$smarty = new Smarty_NeuroDB;
$formArray = $this->form->toElementArray();
$smarty->assign('form', $formArray);
$smarty->assign($this->tpl_data);
$html = $smarty->fetch("instrument_html.tpl");
}
return $html;
}
/**
* Accepts an array of existing values and sets them as defaults on the
* instrument
*
* @param array $defaults the array of default values
*
* @return array the processed array ready for setDefaults()
* @access private
*/
function _setDefaultsArray(array $defaults): array
{
if (isset($defaults['Window_Difference'])
&& $defaults['Window_Difference'] != 0
) {
$defaults['Candidate_Age']
= $defaults['Candidate_Age'] . " (Age out of range)";
}
//Convert select multiple elements into a lorisform array
if (!empty($this->selectMultipleElements)) {
foreach ($this->selectMultipleElements AS $elname) {
if (isset($defaults[$elname])) {
$defaults[$elname] = explode("{@}", $defaults[$elname]);
}
}
}
// return the defaults array ready for $form->setDefaults
return $defaults;
}
/**
* Attempts to validate the form (using the defined rules) and
* saves the validated data into the database
*
* @return bool false if failure to save data
* @access public
*/
function save(): bool
{
if ($this->form->validate()) {
$this->form->process([&$this, '_saveValues'], true);
$this->score();
$this->updateRequiredElementsCompletedFlag();
$this->propagateData();
} else {
$submittedData = $this->form->getSubmitValues();
if (count($submittedData)) {
// the form WAS submitted but validate() failed...
// main error message
$this->form->addElement('static', 'mainError');
$this->form->setElementError(
'mainError',
"<p>
<font color='red'>
A data entry error has been detected so this data
<b>WAS NOT SAVED</b>
</font>
</p>\n"
);
return false;
}
}
return true;
}
/**
* This checks the current status of and instrument's data entry and updates
* it accordingly in the database
*
* @return void
*/
public function updateRequiredElementsCompletedFlag(): void
{
// determine the required elements completed flag, and store that in
// the database
$requiredElementsCompletedFlag
= $this->_determineRequiredElementsCompletedFlag();
$this->_setRequiredElementsCompletedFlag(
$requiredElementsCompletedFlag
);
}
/**
* This handles the saving of the Candidate_Age and Window_Difference columns
* to the database when the save function is called with a Date_taken.
*
* @param array $values A reference to the values saved from the form that
* will be passed to update. This will be modified to
* have Candidate_Age and Window_Difference if the
* Date_taken field is included.
*
* @return void (but as a side-effect modifies array that was passed.)
*/
function _saveCandidateAge(array &$values): void
{
if (!empty($values['Date_taken'])) {
$DB = $this->loris->getDatabaseConnection();
$age = $this->getCandidateAge($values['Date_taken']);
if (empty($age)) {
throw new LorisException("Candidate age could not be found.");
}
$agedays = $this->calculateAgeDays($age);
$agemonths = $this->calculateAgeMonths($age);
if (!empty($age)) {
$query_params = [
'TN' => $this->testName,
'CID' => $this->getCommentID(),
];
$validage = $DB->pselectOne(
"SELECT MAX($agedays BETWEEN AgeMinDays AND AgeMaxDays)
FROM test_battery tb
JOIN test_names tn USING(Test_name)
JOIN flag f ON (f.TestID=tn.ID)
JOIN session s ON (s.ID=f.SessionID)
WHERE tb.Active='Y'
AND tb.Test_name=:TN
AND tb.CohortID=s.CohortID
AND f.CommentID=:CID",
$query_params
);
$values['Candidate_Age'] = $agemonths;
$values['Window_Difference'] = 0;
// Age isn't valid, so find out how far out it is
if ($validage == 0) {
$Windows = $DB->pselect(
"SELECT AgeMinDays, AgeMaxDays
FROM test_battery tb
JOIN test_names tn USING(Test_name)
JOIN flag f ON (f.TestID=tn.ID)
JOIN session s ON (s.ID=f.SessionID)
WHERE tb.Active='Y' AND tb.Test_name=:TN
AND tb.CohortID=s.CohortID
AND f.CommentID=:CID",
$query_params
);
foreach ($Windows as $window) {
if ($agedays < $window['AgeMinDays']) {
$delta = intval($window['AgeMinDays']) - $agedays;
if (abs($delta) < abs($values['Window_Difference'])
|| $values['Window_Difference'] == 0
) {
$values['Window_Difference'] = 0-abs($delta);
}
}
if ($agedays > $window['AgeMaxDays']) {
$delta = $agedays - intval($window['AgeMaxDays']);
if (abs($delta) < abs($values['Window_Difference'])
|| $values['Window_Difference'] == 0
) {
$values['Window_Difference'] = abs($delta);
}
}
}
}
}
}
}
/**
* Calculate age in months given and array with years months and days
*
* @param array $age containing the years, months and days of the age
*
* @return float
*/
function calculateAgeMonths(array $age): float
{
$months = $age['year']*12 + $age['mon'] + ($age['day']/30);
// 1 Decimal.
$months = (round($months*10) / 10.0);
return $months;
}
/**
* Calculate age in days given and array with years months and days
*
* @param array $age containing the years, months and days of the age
*
* @return int
*/
function calculateAgeDays(array $age): int
{
$days = $age['year']*365 + $age['mon']*30 + $age['day'];
return $days;
}
/**
* This removes all the value of any field which has its accompagning
* _status field set.
*
* @param array $values A reference to the array which will be passed
* to $DB->update().
*
* @return void (but as a side-effect modifies &$values array)
*/
function _nullStatus(array &$values): void
{
//Remove the values of all fields who have had statuses assigned
foreach (array_keys($values) AS $field) {
if (substr($field, -7)=="_status") {
if (!empty($values[$field])) {
$baseField = substr($field, 0, (strlen($field)-7));
$values[$baseField] = "";
}
}
}
}
/**
* Preprocesses the array of values to be saved into the database
* (such as to rearrange date fields or process uploaded files)
*
* @param array $values the array of values ready to be passed to
* an Database::update call as the set array
*
* @return void
*/
function _saveValues(array $values): void
{
if (strrpos($this->testName, "_proband") === false) {
$this->_saveCandidateAge($values);
}
// Save UserID, the data entry personnel, into flag Data and
// instrument table
$user = \NDB_Factory::singleton()->user();
if (! $user instanceof \LORIS\AnonymousUser) {
// Add UserID to $values
$values['UserID'] = $user->getUsername();
}
//Convert select multiple elements into database storable values
if (!empty($this->selectMultipleElements)) {
foreach ($this->selectMultipleElements AS $elname) {
if (isset($values[$elname]) && is_array($values[$elname])) {
$values[$elname] = implode("{@}", $values[$elname]);
}
}
}
//XIN specific functionality
if ($this->formType=="XIN") {
$this->_nullStatus($values);
}
// do not alter this when overwriting the method
unset(
$values['candID'],
$values['sessionID'],
$values['commentID'],
$values['test_name'],
$values['page'],
$values['fire_away'],
$values['subtest']
);
// nor these -- these ones are for direct data entry
unset($values['key'], $values['nextpage'], $values['pageNum']);
$this->_save($values);
}
/**
* Uses the array generated by _saveValues() and runs the
* Database::update() call.
*
* @param array $values the array generated by _saveValues()
*
* @return void
*/
function _save(array $values): void
{
$db = $this->loris->getDatabaseConnection();
// clear any fields starting with __
foreach (array_keys($values) AS $key) {
if (strpos($key, '__') === 0) {
unset($values[$key]);
}
$values = Utility::nullifyEmpty($values, $key);
}
if ($this->jsonData !== true && !empty($values)) {
// If the instrument is saving as JSON into the Data column, the
// table may not exist, so don't try and update it.
$db->update(
$this->table,
$values,
['CommentID' => $this->getCommentID()]
);
}
// Extract the old data and merge it with what was submitted so that we
// don't overwrite data from other pages.
$oldData = $db->pselectOne(
"SELECT id.Data FROM flag f
JOIN instrument_data id ON (id.ID=f.DataID)
WHERE CommentID=:cid",
['cid' => $this->getCommentID()]
);
// (The PDO driver seems to return null as "null" for JSON column types)
if (!empty($oldData) && $oldData !== "null") {
$oldData = json_decode($oldData, true);
} else {
$oldData = [];
}
$newData = array_merge($oldData ?? [], $values);
// If there's already a row with the same data, re-use the DataID.
// Otherwise, insert it, then update the DataID on flag.
$jsonencoded = json_encode($newData);
$newDataID = $db->pselectOne(
"SELECT ID FROM instrument_data WHERE Data=:json",
[ 'json' => $jsonencoded]
);
if ($newDataID === null) {
$db->unsafeInsert(
"instrument_data",
['Data' => $jsonencoded],
);
$newDataID = $db->getLastInsertId();
}
assert($newDataID !== null);
$db->update(
"flag",
["DataID" => $newDataID],
['CommentID' => $this->getCommentID()],
);
$this->instanceData = $newData;
}
/**
* Adds metadata fields (such as Examiner and Date_taken) to the
* current form
*
* @return void
* @access private
*/
function _addMetadataFields(): void
{
$factory = \NDB_Factory::singleton();
$config = $factory->config();
$dateOptions = [
'language' => 'en',
'format' => 'YMd',
'minYear' => $config->getSetting('startYear'),
'maxYear' => $config->getSetting('endYear'),
'addEmptyOption' => true,
'emptyOptionValue' => null,
];
$this->dateOptions = $dateOptions;
$this->addBasicDate('Date_taken', 'Date of Administration', $dateOptions);
if (strrpos($this->testName ?? '', '_proband') === false) {
if (!$this->postMortem) {
$this->addScoreColumn(
'Candidate_Age',
'Candidate Age (Months)'
);
} else {
$this->addScoreColumn(
'Candidate_Age',
'Candidate Age at Death (Months)'
);
}
$this->addScoreColumn(
'Window_Difference',
'Window Difference (+/- Days)'
);
}
$examiners = $this->_getExaminerNames();
$this->addSelect('Examiner', 'Examiner', $examiners);
$this->addRule(
'Date_taken',
'Date of Administration is required',
'required'
);
$this->addRule('Examiner', 'Examiner is required', 'required');
}
/**
* Process the Config file. This results in:
* 1. $CertificationEnabled being true or false,
* 2. $CertificationProjects being a list of projects which
* use ceritification and,
* 3. $CertificationInstruments being a list of instruments
* that use certification.
* This is put in a different function so that instruments that
* override getExaminerNames() can still easily get the config
* settings and don't need to parse the config file themselves.
*
* @return array
* @throws \ConfigurationException
*/
function _getCertificationConfig(): array
{
$config = \NDB_Config::singleton();
$CertificationConfig = $config->getSetting("Certification");
$CertificationEnabled = $CertificationConfig['EnableCertification'];
$CertificationProjects = [];
$CertificationInstruments = [];
if ($CertificationEnabled) {
// Throw exception if config file is formatted incorrectly.
if (!is_array(
$CertificationConfig['CertificationProjects']
)
|| !is_array(
$CertificationConfig['CertificationInstruments']
)
) {
throw new \ConfigurationException(
self::ERROR_CERTIFICATION_BAD_FORMATTING
);
}
foreach (
Utility::associativeToNumericArray(
$CertificationConfig['CertificationProjects']
)
as $value
) {
if (is_array($value['CertificationProject'])) {
$value = $value['CertificationProject'];
}
foreach ($value as $projID) {
$CertificationProjects[$projID] = $projID;
}
}
foreach (
Utility::associativeToNumericArray(
$CertificationConfig['CertificationInstruments']
)
as $instrument
) {
foreach (
Utility::associativeToNumericArray($instrument['test'])
as $test
) {
$CertificationInstruments[] = $test['@']['value'];
}
}