-
Notifications
You must be signed in to change notification settings - Fork 988
/
DataEntry.php
2456 lines (2271 loc) · 131 KB
/
DataEntry.php
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
/*
* LimeSurvey
* Copyright (C) 2007-2011 The LimeSurvey Project Team / Carsten Schmitz
* All rights reserved.
* License: GNU/GPL License v2 or later, see LICENSE.php
* LimeSurvey is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYRIGHT.php for copyright notices and details.
*
*/
/*
* We need this later:
*
* 1 - Array dual scale
*5 - 5 point choice
*A - Array (5 point choice)
*B - Array (10 point choice)
*C - Array (Yes/No/Uncertain)
*D - Date
*E - Array (Increase, Same, Decrease)
*F - Array
*G - Gender
*H - Array by Column
*I - Language Switch
*K - Multiple numerical input
*L - List (Radio)
*M - Multiple choice
*N - Numerical input
*O - List With Comment
*P - Multiple choice with comments
*Q - Multiple short text
*R - Ranking
*S - Short free text
*T - Long free text
*U - Huge free text
*X - Boilerplate Question
*Y - Yes/No
*! - List (Dropdown)
*| - File Upload Question
*/
/**
* dataentry
*
* @package LimeSurvey
* @author
* @copyright 2011
* @access public
*/
class DataEntry extends SurveyCommonAction
{
/**
* Dataentry Constructor
* @inherit
*/
public function __construct($controller, $id)
{
parent::__construct($controller, $id);
Yii::app()->loadHelper('surveytranslator');
}
/**
* Function responsible for importing responses from file (.csv)
*
* @return void
*/
public function vvimport()
{
$aData = array();
$aData['display']['menu_bars']['browse'] = gT("Data entry");
$aData['title_bar']['title'] = gT("Data entry");
$aData['sidemenu']['state'] = false;
$aData['topBar']['name'] = 'baseTopbar_view';
$aData['topBar']['showImportButton'] = true;
$aData['topBar']['showCloseButton'] = true;
$iSurveyId = sanitize_int(Yii::app()->request->getParam('surveyid'));
$aData['iSurveyId'] = $aData['surveyid'] = $iSurveyId;
if (Permission::model()->hasSurveyPermission($iSurveyId, 'responses', 'create')) {
if (tableExists("{{survey_$iSurveyId}}")) {
// First load the database helper
Yii::app()->loadHelper('database'); // Really needed ?
$subAction = Yii::app()->request->getPost('subaction');
if ($subAction != "upload") {
$this->showUploadForm($this->getEncodingsArray(), $iSurveyId, $aData);
} else {
$this->handleFileUpload($iSurveyId, $aData);
}
} else {
Yii::app()->session['flashmessage'] = gT("This survey is not active. You must activate the survey before attempting to import a VVexport file.");
$this->getController()->redirect($this->getController()->createUrl("/surveyAdministration/view/surveyid/{$iSurveyId}"));
}
} else {
Yii::app()->session['flashmessage'] = gT("You do not have permission to access this page.");
$this->getController()->redirect($this->getController()->createUrl("/surveyAdministration/view/surveyid/{$iSurveyId}"));
}
}
/**
* Iterate Survey Method.
* @param int $surveyid Given Survey ID
* @return void
*/
public function iteratesurvey($surveyid)
{
$aData = array();
$surveyid = sanitize_int($surveyid);
$aData['surveyid'] = $surveyid;
$aData['success'] = false;
if (Permission::model()->hasSurveyPermission($surveyid, 'surveyactivation', 'update')) {
if (Yii::app()->request->getParam('unfinalizeanswers') == 'true') {
SurveyDynamic::sid($surveyid);
Yii::app()->db->createCommand("DELETE from {{survey_$surveyid}} WHERE submitdate IS NULL AND token in (SELECT * FROM ( SELECT answ2.token from {{survey_$surveyid}} AS answ2 WHERE answ2.submitdate IS NOT NULL) tmp )")->execute();
// Then set all remaining answers to incomplete state
Yii::app()->db->createCommand("UPDATE {{survey_$surveyid}} SET submitdate=NULL, lastpage=NULL")->execute();
// Finally, reset the token completed and sent status
Yii::app()->db->createCommand("UPDATE {{tokens_$surveyid}} SET sent='N', remindersent='N', remindercount=0, completed='N', usesleft=1 where usesleft=0")->execute();
$aData['success'] = true;
}
$this->renderWrappedTemplate('dataentry', 'iteratesurvey', $aData);
}
}
/**
* Handles file upload Method.
* @param int $iSurveyId Given Survey ID
* @param array $aData Given Data
* @return void
*/
private function handleFileUpload($iSurveyId, $aData)
{
$filePath = $this->moveUploadedFile($aData);
Yii::app()->loadHelper('admin/import');
// Fill option
$aOptions = array();
$aOptions['bDeleteFistLine'] = !(bool) Yii::app()->request->getPost('dontdeletefirstline');
if (Yii::app()->request->getPost('noid')) {
$aOptions['sExistingId'] = 'ignore';
} else {
$aOptions['sExistingId'] = Yii::app()->request->getPost('insertmethod');
}
$aOptions['bNotFinalized'] = (bool) Yii::app()->request->getPost('notfinalized');
$aOptions['bForceImport'] = (bool) Yii::app()->request->getPost('forceimport');
$aOptions['sCharset'] = Yii::app()->request->getPost('vvcharset');
$aOptions['sSeparator'] = "\t";
$aResult = CSVImportResponses($filePath, $iSurveyId, $aOptions);
$aData['class'] = "";
$aData['title'] = gT("Import a VV response data file");
$aData['aResult']['success'][] = gT("File upload succeeded.");
if (isset($aResult['success'])) {
$aData['aResult']['success'] = array_merge($aData['aResult']['success'], $aResult['success']);
}
if (isset($aResult['warnings'])) {
$aData['class'] = "message-box-warning";
}
if (isset($aResult['errors'])) {
$aData['class'] = "message-box-error";
}
$aData['aResult']['errors'] = $aResult['errors'] ?? false;
$aData['aResult']['warnings'] = $aResult['warnings'] ?? false;
$this->renderWrappedTemplate('dataentry', 'vvimport_result', $aData);
}
/**
* Move uploaded files Method.
*
* @param array $aData Given Data
* @return void|string
*/
private function moveUploadedFile($aData)
{
$sFullFilePath = Yii::app()->getConfig('tempdir') . "/" . randomChars(20);
$fileVV = CUploadedFile::getInstanceByName('csv_vv_file');
if ($fileVV) {
if (!$fileVV->SaveAs($sFullFilePath)) {
$aData['class'] = 'error warningheader';
$aData['title'] = gT("Error");
$aData['aResult']['errors'][] = sprintf(
gT("An error occurred uploading your file. This may be caused by incorrect permissions for the application /tmp folder."),
Yii::app()->getConfig('tempdir')
);
$aData['aUrls'][] = array(
'link' => $this->getController()->createUrl('admin/dataentry/sa/vvimport/surveyid/' . $aData['surveyid']),
'text' => $aData['aUrlText'][] = gT("Back to Response Import"),
);
$this->renderWrappedTemplate('dataentry', 'vvimport_result', $aData);
} else {
return $sFullFilePath;
}
} else {
Yii::app()->session['flashmessage'] = gT("You have to select a file.");
$this->getController()->redirect($this->getController()->createUrl("admin/dataentry/sa/vvimport/surveyid/{$aData['surveyid']}"));
}
}
/**
* Show upload form Method.
* @param string[] $aEncodings Given Encoding
* @param int $surveyid Given Survey ID
* @param array $aData Given Data
* @return void
*/
private function showUploadForm($aEncodings, $surveyid, $aData)
{
unset($aEncodings['auto']);
asort($aEncodings);
// Get default character set from global settings
$thischaracterset = getGlobalSetting('characterset');
// If no encoding was set yet, use the old "utf8" default
if ($thischaracterset == "") {
$thischaracterset = "utf8";
}
// Create encodings list using the Yii's CHtml helper
$charsetsout = CHtml::listOptions($thischaracterset, $aEncodings, $aEncodings);
$aData['charsetsout'] = $charsetsout;
$aData['aEncodings'] = $aEncodings;
$aData['tableExists'] = tableExists("{{survey_$surveyid}}");
$aData['display']['menu_bars']['browse'] = gT("Import VV file");
$this->renderWrappedTemplate('dataentry', 'vvimport', $aData);
}
/**
* dataentry::import()
* Function responsible to import responses from old survey table(s).
* @param int $surveyid Given Survey ID
* @return void
*/
public function import($surveyid)
{
$iSurveyId = sanitize_int($surveyid);
if (!Permission::model()->hasSurveyPermission($iSurveyId, 'responses', 'create')) {
Yii::app()->setFlashMessage(gT("No permission"), 'error');
return;
}
if (!App()->getRequest()->isPostRequest || App()->getRequest()->getPost('table') == 'none') {
// Schema that serves as the base for compatibility checks.
$baseSchema = SurveyDynamic::model($iSurveyId)->getTableSchema();
$tables = App()->getApi()->getOldResponseTables($iSurveyId);
$compatible = array();
$coercible = array();
foreach ($tables as $table) {
$schema = PluginDynamic::model($table)->getTableSchema();
if (PluginDynamic::model($table)->count() > 0) {
if ($this->isCompatible($baseSchema, $schema)) {
$compatible[] = $table;
} elseif ($this->isCompatible($baseSchema, $schema, false)) {
$coercible[] = $table;
}
}
}
$aData = array();
$aData['surveyid'] = $iSurveyId;
$aData['settings']['table'] = array(
'label' => gT('Source table'),
'type' => 'select',
'options' => array(
gT('Compatible') => $this->tableList($compatible),
gT('Compatible with type coercion') => $this->tableList($coercible)
)
);
$aData['settings']['timings'] = array(
'type' => 'checkbox',
'label' => gT('Import timings (if exist)')
);
$aData['settings']['preserveIDs'] = array(
'type' => 'checkbox',
'label' => gT('Preserve response IDs')
);
//Get the menubar
$aData['display']['menu_bars']['browse'] = gT("Quick statistics");
$survey = Survey::model()->findByPk($iSurveyId);
$aData['title_bar']['title'] = gT('Browse responses') . ': ' . $survey->currentLanguageSettings->surveyls_title;
$aData['sidemenu']['state'] = false;
$aData['topBar']['name'] = 'baseTopbar_view';
$aData['topBar']['showImportButton'] = true;
$aData['topBar']['showCloseButton'] = true;
$this->renderWrappedTemplate('dataentry', 'import', $aData);
} else {
$aSRIDConversions = array();
$targetSchema = SurveyDynamic::model($iSurveyId)->getTableSchema();
$sourceTable = PluginDynamic::model($_POST['table']);
$sourceSchema = $sourceTable->getTableSchema();
$encryptedAttributes = Response::getEncryptedAttributes($iSurveyId);
$tbl_name = $sourceSchema->name;
if (strpos($sourceSchema->name, Yii::app()->db->tablePrefix) === 0) {
$tbl_name = substr($sourceSchema->name, strlen(Yii::app()->db->tablePrefix));
}
$archivedTableSettings = ArchivedTableSettings::model()->findByAttributes(['tbl_name' => $tbl_name]);
$archivedEncryptedAttributes = [];
if ($archivedTableSettings) {
$archivedEncryptedAttributes = json_decode($archivedTableSettings->properties);
}
$fieldMap = [];
$pattern = '/([\d]+)X([\d]+)X([\d]+.*)/';
foreach ($sourceSchema->getColumnNames() as $name) {
// Skip id field.
if ($name == 'id') {
continue;
}
$matches = array();
// Exact match.
if ($targetSchema->getColumn($name)) {
$fieldMap[$name] = $name;
} elseif (preg_match($pattern, $name, $matches)) {
// Column name is SIDXGIDXQID
$qid = $matches[3];
$targetColumn = $this->getQidColumn($targetSchema, $qid);
if (isset($targetColumn)) {
$fieldMap[$name] = $targetColumn->name;
}
}
}
$imported = 0;
$sourceResponses = new CDataProviderIterator(new CActiveDataProvider($sourceTable), 500);
/* @var boolean preserveIDs */
$preserveIDs = boolval(App()->getRequest()->getPost('preserveIDs'));
foreach ($sourceResponses as $sourceResponse) {
$iOldID = $sourceResponse->id;
// Using plugindynamic model because I dont trust surveydynamic.
$targetResponse = new PluginDynamic("{{survey_$iSurveyId}}");
if ($preserveIDs) {
$targetResponse->id = $sourceResponse->id;
}
foreach ($fieldMap as $sourceField => $targetField) {
$targetResponse[$targetField] = $sourceResponse[$sourceField];
if (in_array($sourceField, $archivedEncryptedAttributes, false) && !in_array($sourceField, $encryptedAttributes, false)) {
$targetResponse[$targetField] = $sourceResponse->decryptSingle($sourceResponse[$sourceField]);
}
if (!in_array($sourceField, $archivedEncryptedAttributes, false) && in_array($sourceField, $encryptedAttributes, false)) {
$targetResponse[$targetField] = $sourceResponse->encryptSingle($sourceResponse[$sourceField]);
}
}
if (isset($targetSchema->columns['startdate']) && empty($targetResponse['startdate'])) {
$targetResponse['startdate'] = date("Y-m-d H:i", (int) mktime(0, 0, 0, 1, 1, 1980));
}
if (isset($targetSchema->columns['datestamp']) && empty($targetResponse['datestamp'])) {
$targetResponse['datestamp'] = date("Y-m-d H:i", (int) mktime(0, 0, 0, 1, 1, 1980));
}
$beforeDataEntryImport = new PluginEvent('beforeDataEntryImport');
$beforeDataEntryImport->set('iSurveyID', $iSurveyId);
$beforeDataEntryImport->set('oModel', $targetResponse);
App()->getPluginManager()->dispatchEvent($beforeDataEntryImport);
$imported++;
if ($preserveIDs) {
switchMSSQLIdentityInsert("survey_$iSurveyId", true);
}
$targetResponse->save();
if ($preserveIDs) {
switchMSSQLIdentityInsert("survey_$iSurveyId", false);
}
$aSRIDConversions[$iOldID] = $targetResponse->id;
unset($targetResponse);
}
Yii::app()->session['flashmessage'] = sprintf(gT("%s old response(s) were successfully imported."), $imported);
$sOldTimingsTable = (string) substr(substr($sourceTable->tableName(), 0, (string) strrpos($sourceTable->tableName(), '_')) . '_timings' . (string) substr($sourceTable->tableName(), (string) strrpos($sourceTable->tableName(), '_')), strlen(Yii::app()->db->tablePrefix));
$sNewTimingsTable = "survey_{$surveyid}_timings";
if (isset($_POST['timings']) && $_POST['timings'] == 1 && tableExists($sOldTimingsTable) && tableExists($sNewTimingsTable)) {
// Import timings
$aFieldsOldTimingTable = array_values(Yii::app()->db->schema->getTable('{{' . $sOldTimingsTable . '}}')->columnNames);
$aFieldsNewTimingTable = array_values(Yii::app()->db->schema->getTable('{{' . $sNewTimingsTable . '}}')->columnNames);
$aValidTimingFields = array_intersect($aFieldsOldTimingTable, $aFieldsNewTimingTable);
$sQueryOldValues = "SELECT " . implode(", ", $aValidTimingFields) . " FROM {{{$sOldTimingsTable}}} ";
$aQueryOldValues = Yii::app()->db->createCommand($sQueryOldValues)->query()->readAll(); //Checked
$iRecordCountT = 0;
foreach ($aQueryOldValues as $sRecord) {
if (isset($aSRIDConversions[$sRecord['id']])) {
$sRecord['id'] = $aSRIDConversions[$sRecord['id']];
} else {
continue;
}
Yii::app()->db->createCommand()->insert("{{{$sNewTimingsTable}}}", $sRecord);
$iRecordCountT++;
}
Yii::app()->session['flashmessage'] = sprintf(gT("%s old response(s) and according timings were successfully imported."), $imported, $iRecordCountT);
}
$this->getController()->redirect(["/responses/index/", 'surveyId' => $surveyid]);
}
}
/**
* Takes a list of tablenames and creates a nice key value array.
* @param array $tables Given Tables
* @return array
*/
protected function tableList($tables)
{
$list = array();
if (empty($tables)) {
$list['none'] = gT('No old responses found.', 'unescaped');
}
foreach ($tables as $table) {
$count = PluginDynamic::model($table)->count();
$timestamp = date_format(new DateTime((string) substr($table, -14)), 'Y-m-d H:i:s');
$list[$table] = "$timestamp ($count responses)";
}
return $list;
}
/**
* Takes a table schema and finds the field for some question id.
* @param CDbTableSchema $schema Given Schema
* @param string $qid Given Question ID
* @return CDbColumnSchema
*/
protected function getQidColumn(CDbTableSchema $schema, $qid)
{
foreach ($schema->columns as $name => $column) {
$pattern = '/([\d]+)X([\d]+)X([\d]+.*)/';
$matches = array();
if (preg_match($pattern, $name, $matches)) {
if ($matches[3] == $qid) {
return $column;
}
}
}
}
/**
* Compares 2 table schema to see if they are compatible.
* @param CDbTableSchema $base Given Base Database Schema
* @param CDbTableSchema $old Given Old Database Schema
* @param bool $checkColumnTypes Checks Column Types
* @return bool
*/
protected function isCompatible(CDbTableSchema $base, CDbTableSchema $old, $checkColumnTypes = true)
{
$pattern = '/([\d]+)X([\d]+)X([\d]+.*)/';
foreach ($old->columns as $name => $column) {
// The following columns are always compatible.
if (in_array($name, array('id', 'token', 'submitdate', 'lastpage', 'startlanguage'))) {
continue;
}
$matches = array();
if (preg_match($pattern, $name, $matches)) {
$qid = $matches[3];
$baseColumn = $this->getQidColumn($base, $qid);
if ($baseColumn) {
if ($baseColumn && $checkColumnTypes && ($baseColumn->dbType != $column->dbType)) {
return false;
}
}
}
}
return true;
}
/**
* dataentry::editdata()
* Edit dataentry.
* @param string $subaction Given Subaction
* @param int $id Given ID
* @param int $surveyid Given Survey ID
* @return void
* TODO: This function has to be smaller. Create subfunctions for this or move it to another place!
*/
public function editdata($subaction, $id, $surveyid)
{
$surveyid = (int) $surveyid;
$oSurvey = Survey::model()->findByPk($surveyid);
$id = (int) $id;
$aViewUrls = array();
if (!Permission::model()->hasSurveyPermission($surveyid, 'responses', 'update')) {
throw new CHttpException(403, gT("You do not have permission to access this page."));
}
if (!$oSurvey->hasResponsesTable) {
/* Same than ResponsesController->getData */
App()->setFlashMessage(gT("This survey has not been activated. There are no results to browse."), 'warning');
$this->getController()->redirect(["surveyAdministration/view", 'surveyid' => $surveyid]);
App()->end();
}
$idresult = Response::model($surveyid)->findByPk($id);
if (empty($idresult)) {
throw new CHttpException(404, gT("Invalid response id."));
}
$sDataEntryLanguage = $oSurvey->language;
$aData = [];
$aData['display']['menu_bars']['browse'] = gT("Data entry");
Yii::app()->loadHelper('database');
// Perform a case insensitive natural sort on group name then question title of a multidimensional array
// $fnames = (Field Name in Survey Table, Short Title of Question, Question Type, Field Name, Question Code, Predetermined Answer if exist)
$fnames = [];
$fnames['completed'] = array('fieldname' => "completed", 'question' => gT("Completed"), 'type' => 'completed');
$fnames = array_merge($fnames, createFieldMap($oSurvey, 'full', false, false, $sDataEntryLanguage));
// Fix private if disallowed to view token
if (!Permission::model()->hasSurveyPermission($surveyid, 'tokens', 'read')) {
unset($fnames['token']);
}
$nfncount = count($fnames) - 1;
//SHOW INDIVIDUAL RECORD
$results = array();
if ($subaction == "edit") {
// $idresult is response
$idresult->decrypt();
$results[] = $idresult->attributes;
} elseif ($subaction == "editsaved") {
if (isset($_GET['public']) && $_GET['public'] == "true") {
$password = hash('sha256', Yii::app()->request->getParam('accesscode'));
} else {
$password = Yii::app()->request->getParam('accesscode');
}
$svresult = SavedControl::model()->findAllByAttributes(
array(
'sid' => $surveyid,
'identifier' => Yii::app()->request->getParam('identifier'),
'access_code' => $password)
);
$saver = array();
foreach ($svresult as $svrow) {
$svrow->decrypt();
$saver['email'] = $svrow['email'];
$saver['scid'] = $svrow['scid'];
$saver['ip'] = $svrow['ip'];
}
$svresult = SavedControl::model()->findAllByAttributes(array('scid' => $saver['scid']));
$responses = [];
foreach ($svresult as $svrow) {
$svrow->decrypt();
$responses[$svrow['fieldname']] = $svrow['value'];
}
$fieldmap = createFieldMap($oSurvey, 'full', false, false, $oSurvey->language);
$results1 = array();
foreach ($fieldmap as $fm) {
if (isset($responses[$fm['fieldname']])) {
$results1[$fm['fieldname']] = $responses[$fm['fieldname']];
} else {
$results1[$fm['fieldname']] = "";
}
}
$results1['id'] = "";
$results1['datestamp'] = dateShift((string) date("Y-m-d H:i:s"), "Y-m-d H:i", Yii::app()->getConfig('timeadjust'));
$results1['ipaddr'] = $saver['ip'];
$results[] = $results1;
}
$aData = array(
'id' => $id,
'surveyid' => $surveyid,
'subaction' => $subaction,
'part' => 'header'
);
$aViewUrls[] = 'dataentry_header_view';
$aViewUrls[] = 'edit';
$highlight = false;
unset($fnames['lastpage']);
// unset timings
foreach ($fnames as $fname) {
if ($fname['type'] == "interview_time" || $fname['type'] == "page_time" || $fname['type'] == "answer_time") {
unset($fnames[$fname['fieldname']]);
$nfncount--;
}
}
$questionTypes = QuestionType::modelsAttributes();
$aDataentryoutput = '';
foreach ($results as $idrow) {
$fname = reset($fnames);
do {
$question = $fname['question'];
$questionTypeClass = isset($questionTypes[$fname['type']]) ? $questionTypes[$fname['type']]['class'] : '';
$aDataentryoutput .= "\t<tr";
if ($highlight) {
$aDataentryoutput .= " class='odd $questionTypeClass'";
} else {
$aDataentryoutput .= " class='even $questionTypeClass'";
}
$highlight = !$highlight;
$aDataentryoutput .= ">\n";
// First column (Question)
$aDataentryoutput .= "<td class=\"question-cell\">";
$aDataentryoutput .= stripJavaScript($question);
$aDataentryoutput .= "</td>\n";
// Second column (Answer)
$aDataentryoutput .= "<td class=\"answers-cell\">\n";
//$aDataentryoutput .= "\t-={$fname[3]}=-"; //Debugging info
$qidattributes = [];
if (isset($fname['qid']) && isset($fname['type'])) {
$qidattributes = QuestionAttribute::model()->getQuestionAttributes($fname['qid']);
}
/** @var array<string,string> */
$questionInputs = [];
/** @var array<string,bool> "Unseen" status for each field. */
$unseenStatus = [
$fname['fieldname'] => !isset($idrow[$fname['fieldname']])
];
$answerWrapperClass = '';
$fieldType = $fname['type'];
switch ($fieldType) {
case "completed":
$selected = (empty($idrow['submitdate'])) ? 'N' : 'Y';
$select_options = array(
'N' => gT('No', 'unescaped'),
'Y' => gT('Yes', 'unescaped')
);
$aDataentryoutput .= CHtml::dropDownList('completed', $selected, $select_options, array('class' => 'form-control'));
break;
case Question::QT_X_TEXT_DISPLAY: //Boilerplate question
// We add an empty entry here so the "Unseen" checkbox is displayed.
// Although a value can't be entered, there is still a difference between
// Text Display questions shown and not shown.
$questionInputs[$fname['fieldname']] = "";
break;
case Question::QT_Q_MULTIPLE_SHORT_TEXT:
$questionInput = $fname['subquestion'] . ' ';
$questionInput .= CHtml::textField($fname['fieldname'], $idrow[$fname['fieldname']]);
$questionInputs[$fname['fieldname']] = $questionInput;
break;
case Question::QT_K_MULTIPLE_NUMERICAL:
$questionInput = $fname['subquestion'] . ' ';
/* Fix DB DECIMAL type */
$value = $idrow[$fname['fieldname']];
if (strpos($value, ".")) {
$value = rtrim(rtrim($value, "0"), ".");
}
$questionInput .= CHtml::textField($fname['fieldname'], $value, array('pattern' => "[-]?([0-9]{0,20}([\.][0-9]{0,10})?)?",'title' => gT("Only numbers may be entered in this field.")));
$questionInputs[$fname['fieldname']] = $questionInput;
break;
case "id":
$aDataentryoutput .= CHtml::tag('span', array('style' => 'font-weight: bold;'), ' ' . $idrow[$fname['fieldname']]);
break;
case "seed":
$aDataentryoutput .= CHtml::tag('span', array(), ' ' . $idrow[$fname['fieldname']]);
break;
case Question::QT_5_POINT_CHOICE: //5 POINT CHOICE radio-buttons
$questionInput = '';
for ($i = 1; $i <= 5; $i++) {
$checked = false;
if ($idrow[$fname['fieldname']] == $i) {
$checked = true;
}
$questionInput .= '<span class="five-point">';
$questionInput .= CHtml::radioButton($fname['fieldname'], $checked, array('class' => '', 'value' => $i, 'id' => '5-point-choice-' . $i));
$questionInput .= '<label for="5-point-choice-' . $i . '">' . $i . '</label>';
$questionInput .= '</span> ';
}
//Add 'No Answer'
$questionInput .= "<input type='radio' class='' name='{$fname['fieldname']}' value=''";
if ($idrow[$fname['fieldname']] == '') {
$questionInput .= " checked";
}
$questionInput .= " />" . gT("No answer") . " \n";
$questionInputs[$fname['fieldname']] = $questionInput;
break;
case Question::QT_D_DATE: //DATE
$dateformatdetails = getDateFormatDataForQID($qidattributes, $surveyid);
$datetimeobj = null;
$thisdate = '';
if ($idrow[$fname['fieldname']] != '') {
$datetimeobj = DateTime::createFromFormat("Y-m-d H:i:s", $idrow[$fname['fieldname']]);
if ($datetimeobj == null) { //MSSQL uses microseconds by default in any datetime object
$datetimeobj = DateTime::createFromFormat("Y-m-d H:i:s.u", $idrow[$fname['fieldname']]);
}
}
if (canShowDatePicker($dateformatdetails)) {
if ($datetimeobj) {
$thisdate = $datetimeobj->format($dateformatdetails['phpdate']);
}
$goodchars = str_replace(array("m", "d", "y", "H", "M"), "", $dateformatdetails['dateformat']);
$goodchars = "0123456789" . $goodchars[0];
$questionInput = CHtml::textField(
$fname['fieldname'],
$thisdate,
array(
'class' => 'popupdate',
'size' => '12',
'onkeypress' => 'return window.LS.goodchars(event,\'' . $goodchars . '\')'
)
);
$questionInput .= CHtml::hiddenField(
'dateformat' . $fname['fieldname'],
$dateformatdetails['jsdate'],
array('id' => "dateformat{$fname['fieldname']}")
);
$questionInputs[$fname['fieldname']] = $questionInput;
} else {
if ($datetimeobj) {
$thisdate = $datetimeobj->format("Y-m-d\TH:i");
}
$questionInputs[$fname['fieldname']] = CHtml::dateTimeLocalField($fname['fieldname'], $thisdate);
}
break;
case Question::QT_G_GENDER: //GENDER drop-down list
$select_options = array(
'' => gT("Please choose") . '...',
'F' => gT("Female"),
'M' => gT("Male")
);
$questionInputs[$fname['fieldname']] = CHtml::listBox($fname['fieldname'], $idrow[$fname['fieldname']], $select_options);
break;
case Question::QT_L_LIST: //LIST drop-down
case Question::QT_EXCLAMATION_LIST_DROPDOWN: //List (Radio)
$qidattributes = QuestionAttribute::model()->getQuestionAttributes($fname['qid']);
if (isset($qidattributes['category_separator']) && trim($qidattributes['category_separator']) != '') {
$optCategorySeparator = $qidattributes['category_separator'];
} else {
unset($optCategorySeparator);
}
if (substr($fname['fieldname'], -5) == "other") {
$questionInputs[$fname['fieldname']] = "\t<input type='text' name='{$fname['fieldname']}' value='"
. htmlspecialchars($idrow[$fname['fieldname']], ENT_QUOTES) . "' />\n";
} else {
$lresult = Answer::model()->with('answerl10ns')->findAll(array('condition' => 'qid =:qid AND language = :language', 'params' => array('qid' => $fname['qid'], 'language' => $sDataEntryLanguage)));
$questionInput = "\t<select name='{$fname['fieldname']}' class='form-control'>\n"
. "<option value=''";
if ($idrow[$fname['fieldname']] == "") {
$questionInput .= " selected='selected'";
}
$questionInput .= ">" . gT("Please choose") . "..</option>\n";
if (!isset($optCategorySeparator)) {
foreach ($lresult as $llrow) {
$questionInput .= "<option value='{$llrow['code']}'";
if ($idrow[$fname['fieldname']] == $llrow['code']) {
$questionInput .= " selected='selected'";
}
$questionInput .= ">{$llrow->answerl10ns[$sDataEntryLanguage]->answer}</option>\n";
}
} else {
$defaultopts = array();
$optgroups = array();
foreach ($lresult as $llrow) {
list ($categorytext, $answertext) = explode($optCategorySeparator, $llrow->answerl10ns[$sDataEntryLanguage]->answer);
if ($categorytext == '') {
$defaultopts[] = array('code' => $llrow['code'], 'answer' => $answertext);
} else {
$optgroups[$categorytext][] = array('code' => $llrow['code'], 'answer' => $answertext);
}
}
foreach ($optgroups as $categoryname => $optionlistarray) {
$questionInput .= "<optgroup class=\"dropdowncategory\" label=\"" . $categoryname . "\">\n";
foreach ($optionlistarray as $optionarray) {
$questionInput .= "\t<option value='{$optionarray['code']}'";
if ($idrow[$fname['fieldname']] == $optionarray['code']) {
$questionInput .= " selected='selected'";
}
$questionInput .= ">{$optionarray['answer']}</option>\n";
}
$questionInput .= "</optgroup>\n";
}
foreach ($defaultopts as $optionarray) {
$questionInput .= "<option value='{$optionarray['code']}'";
if ($idrow[$fname['fieldname']] == $optionarray['code']) {
$questionInput .= " selected='selected'";
}
$questionInput .= ">{$optionarray['answer']}</option>\n";
}
}
$oresult = Question::model()->findByPk($fname['qid']);
if ($oresult->other == "Y") {
$questionInput .= "<option value='-oth-'";
if ($idrow[$fname['fieldname']] == "-oth-") {
$questionInput .= " selected='selected'";
}
$questionInput .= ">" . gT("Other") . "</option>\n";
}
$questionInput .= "\t</select>\n";
$questionInputs[$fname['fieldname']] = $questionInput;
}
break;
case Question::QT_O_LIST_WITH_COMMENT: //LIST WITH COMMENT drop-down/radio-button list + textarea
$lresult = Answer::model()->findAll("qid={$fname['qid']}");
$questionInput = "\t<select name='{$fname['fieldname']}' class='form-control'>\n"
. "<option value=''";
if ($idrow[$fname['fieldname']] == "") {
$questionInput .= " selected='selected'";
}
$questionInput .= ">" . gT("Please choose") . "..</option>\n";
foreach ($lresult as $llrow) {
$questionInput .= "<option value='{$llrow['code']}'";
if ($idrow[$fname['fieldname']] == $llrow['code']) {
$questionInput .= " selected='selected'";
}
$questionInput .= ">{$llrow->answerl10ns[$sDataEntryLanguage]->answer}</option>\n";
}
$baseFieldName = $fname['fieldname'];
$fname = next($fnames);
$questionInput .= "\t</select>\n"
. "\t<br />\n"
. CHtml::textArea($fname['fieldname'], $idrow[$fname['fieldname']], array('cols' => 45,'rows' => 5));
$questionInputs[$baseFieldName] = $questionInput;
break;
case Question::QT_R_RANKING: // Ranking TYPE QUESTION
$thisqid = $fname['qid'];
$currentvalues = array();
$rawvalues = [];
$myfname = $fname['sid'] . 'X' . $fname['gid'] . 'X' . $fname['qid'];
$questionInput = '<div id="question' . $thisqid . '" class="ranking-answers"><ul class="answers-list select-list">';
$unseen = true;
while (isset($fname['type']) && $fname['type'] == "R" && $fname['qid'] == $thisqid) {
//Let's get all the existing values into an array
if ($idrow[$fname['fieldname']]) {
$currentvalues[] = $idrow[$fname['fieldname']];
}
// If any ranking field is not null, we mark the question as seen.
if (isset($idrow[$fname['fieldname']])) {
$unseen = false;
}
$rawvalues[] = $idrow[$fname['fieldname']];
$fname = next($fnames);
}
$ansresult = Answer::model()->with('answerl10ns')->findAll(array('condition' => 'qid =:qid AND language = :language', 'params' => array('qid' => $thisqid, 'language' => $sDataEntryLanguage)));
$anscount = count($ansresult);
$answers = array();
foreach ($ansresult as $ansrow) {
$answers[] = $ansrow;
}
for ($i = 1; $i <= $anscount; $i++) {
$questionInput .= "\n<li class=\"select-item\">";
$questionInput .= "<label for=\"answer{$myfname}{$i}\">";
if ($i == 1) {
$questionInput .= gT('First choice');
} else {
$questionInput .= gT('Next choice');
}
$questionInput .= "</label>";
$questionInput .= "<select name=\"{$myfname}{$i}\" id=\"answer{$myfname}{$i}\" class='form-control'>\n";
(!isset($currentvalues[$i - 1])) ? $selected = " selected=\"selected\"" : $selected = "";
$questionInput .= "\t<option value=\"\" $selected>" . gT('None') . "</option>\n";
foreach ($ansresult as $ansrow) {
(isset($currentvalues[$i - 1]) && $currentvalues[$i - 1] == $ansrow['code']) ? $selected = " selected=\"selected\"" : $selected = "";
$questionInput .= "\t<option value=\"" . $ansrow['code'] . "\" $selected>" . flattenText($ansrow->answerl10ns[$sDataEntryLanguage]->answer) . "</option>\n";
}
$questionInput .= "</select\n";
$questionInput .= "</li>";
}
$questionInput .= '</ul>';
$questionInput .= "<div style='display:none' id='ranking-{$thisqid}-maxans'>{$anscount}</div>"
. "<div style='display:none' id='ranking-{$thisqid}-minans'>0</div>"
. "<div style='display:none' id='ranking-{$thisqid}-name'>javatbd{$myfname}</div>";
$questionInput .= "<div style=\"display:none\">";
foreach ($ansresult as $ansrow) {
$questionInput .= "<div id=\"htmlblock-{$thisqid}-{$ansrow['code']}\">{$ansrow->answerl10ns[$sDataEntryLanguage]->answer}</div>";
}
$questionInput .= "</div>";
$questionInput .= '</div>';
App()->getClientScript()->registerPackage('jquery-actual');
App()->getClientScript()->registerScriptFile(App()->getConfig('generalscripts') . 'ranking.js');
App()->getClientScript()->registerCssFile(Yii::app()->getConfig('publicstyleurl') . 'ranking.css');
App()->getClientScript()->registerCssFile(Yii::app()->getConfig('publicstyleurl') . 'jquery-ui-custom.css');
$questionInput .= "<script type='text/javascript'>\n"
. " <!--\n"
. "var aRankingTranslations = {
choicetitle: '" . gT("Your Choices", 'js') . "',
ranktitle: '" . gT("Your Ranking", 'js') . "'
};\n"
. "function checkconditions(){};"
. "$(function() {"
. " doDragDropRank({$thisqid},0,true,true);\n"
. "});\n"
. " -->\n"
. "</script>\n";
$questionInputs[$myfname] = $questionInput;
$unseenStatus = [$myfname => $unseen];
unset($answers);
$fname = prev($fnames);
break;
case Question::QT_M_MULTIPLE_CHOICE: //Multiple choice checkbox
$thisqid = $fname['qid'];
while (isset($fname['qid']) && $fname['qid'] == $thisqid) {
if (substr($fname['fieldname'], -5) == "other") {
$questionInput = "\t<input type='text' name='{$fname['fieldname']}' value='"
. htmlspecialchars($idrow[$fname['fieldname']], ENT_QUOTES) . "' />\n";
} else {
$questionInput = "<div class='checkbox'>\t<input type='checkbox' class='checkboxbtn' name='{$fname['fieldname']}' id='{$fname['fieldname']}' value='Y'";
if ($idrow[$fname['fieldname']] == "Y") {
$questionInput .= " checked";
}
$questionInput .= " /><label for='{$fname['fieldname']}'>{$fname['subquestion']}</label></div>\n";
}
$questionInputs[$fname['fieldname']] = $questionInput;
$unseenStatus[$fname['fieldname']] = is_null($idrow[$fname['fieldname']]);
$fname = next($fnames);
}
$fname = prev($fnames);
break;
case Question::QT_I_LANGUAGE: //Language Switch
$slangs = $oSurvey->allLanguages;
$baselang = $oSurvey->language;
$questionInput = "<select name='{$fname['fieldname']}' class='form-control'>\n";
$questionInput .= "<option value=''";
if ($idrow[$fname['fieldname']] == "") {
$questionInput .= " selected='selected'";
}
$questionInput .= ">" . gT("Please choose") . "..</option>\n";
foreach ($slangs as $lang) {
$questionInput .= "<option value='{$lang}'";
if ($lang == $idrow[$fname['fieldname']]) {
$questionInput .= " selected='selected'";
}
$questionInput .= ">" . getLanguageNameFromCode($lang, false) . "</option>\n";
}
$questionInput .= "</select>";
$questionInputs[$fname['fieldname']] = $questionInput;
break;
case Question::QT_P_MULTIPLE_CHOICE_WITH_COMMENTS: //Multiple choice with comments checkbox + text
$questionInput = '';
while (isset($fname) && $fname['type'] == Question::QT_P_MULTIPLE_CHOICE_WITH_COMMENTS) {
$thefieldname = $fname['fieldname'];
$subquestionValue = $idrow[$fname['fieldname']];
if (substr($fname['fieldname'], -5) == "other") {
$questionInput = CHtml::textField($fname['fieldname'], $idrow[$fname['fieldname']], array('size' => 30));
$fname = next($fnames);
$questionInput .= CHtml::textField($fname['fieldname'], $idrow[$fname['fieldname']], array('size' => 50));
} else {
$questionInput = "<div class='checkbox'><input type='checkbox' class='checkboxbtn' name=\"{$fname['fieldname']}\" id=\"{$fname['fieldname']}\" value='Y'";
if ($idrow[$fname['fieldname']] == "Y") {
$questionInput .= " checked";
}
$questionInput .= " /><label for=\"{$fname['fieldname']}\">{$fname['subquestion']}</label></div>\n";
$fname = next($fnames);
$questionInput .= CHtml::textField($fname['fieldname'], $idrow[$fname['fieldname']], array('size' => 50));
}
$questionInputs[$thefieldname] = $questionInput;
$unseenStatus[$thefieldname] = is_null($subquestionValue);
$fname = next($fnames);
}
$fname = prev($fnames);
break;
case Question::QT_VERTICAL_FILE_UPLOAD: //FILE UPLOAD
$questionInput = "<table class='table'>\n";
if ($fname['aid'] !== 'filecount' && isset($idrow[$fname['fieldname'] . '_filecount']) && ($idrow[$fname['fieldname'] . '_filecount'] > 0)) {
//file metadata
$metadata = json_decode($idrow[$fname['fieldname']], true);
$qAttributes = QuestionAttribute::model()->getQuestionAttributes($fname['qid']);
for ($i = 0; ($i < $qAttributes['max_num_of_files']) && isset($metadata[$i]); $i++) {
if ($qAttributes['show_title']) {
$questionInput .= '<tr><td>' . gT("Title") . '</td><td><input type="text" class="' . $fname['fieldname'] . '" id="' . $fname['fieldname'] . '_title_' . $i . '" name="title" size=50 value="' . htmlspecialchars($metadata[$i]["title"]) . '" /></td></tr>';
}
if ($qAttributes['show_comment']) {
$questionInput .= '<tr><td >' . gT("Comment") . '</td><td><input type="text" class="' . $fname['fieldname'] . '" id="' . $fname['fieldname'] . '_comment_' . $i . '" name="comment" size=50 value="' . htmlspecialchars($metadata[$i]["comment"]) . '" /></td></tr>';
}
$questionInput .= '<tr><td>' . gT("File name") . '</td><td><input class="' . $fname['fieldname'] . '" id="' . $fname['fieldname'] . '_name_' . $i . '" name="name" size=50 value="' . htmlspecialchars(rawurldecode($metadata[$i]["name"])) . '" /></td></tr>'