/
dataentry.php
2400 lines (2155 loc) · 126 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 if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*
* 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 (Flexible Labels) 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 (Flexible Labels)
G - Gender
H - Array (Flexible Labels) 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)
: - Array (Flexible Labels) multiple drop down
; - Array (Flexible Labels) multiple texts
| - File Upload Question
*/
/**
* dataentry
*
* @package LimeSurvey
* @author
* @copyright 2011
* @access public
*/
class dataentry extends Survey_Common_Action
{
function __construct($controller, $id)
{
parent::__construct($controller, $id);
Yii::app()->loadHelper('surveytranslator');
}
/**
* Function responsible for importing responses from file (.csv)
*
* @param mixed $surveyid
* @return void
*/
function vvimport()
{
$aData = array();
$iSurveyId = sanitize_int(Yii::app()->request->getParam('surveyid'));
$aData['iSurveyId'] = $aData['surveyid'] = $iSurveyId;
$aData['clang'] = $this->getController()->lang;
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'] = $clang->gT("This survey is not active. You must activate the survey before attempting to import a VVexport file.");
$this->getController()->redirect($this->getController()->createUrl("/admin/survey/sa/view/surveyid/{$iSurveyId}"));
}
}
else
{
Yii::app()->session['flashmessage'] = $clang->gT("You do not have sufficient rights to access this page.");
$this->getController()->redirect($this->getController()->createUrl("/admin/survey/sa/view/surveyid/{$iSurveyId}"));
}
}
function iteratesurvey($surveyid)
{
$aData = array();
$surveyid = sanitize_int($surveyid);
$aData['surveyid'] = $surveyid;
$aData['clang'] = $this->getController()->lang;
$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);
}
}
private function _handleFileUpload($iSurveyId, $aData)
{
$vvoutput = '';
$donotimport = array();
$clang = $this->getController()->lang;
$filePath = $this->_moveUploadedFile($aData);
//$aFileContents = $this->_readFile($filePath);
Yii::app()->loadHelper('admin/import');
// Fill option
$aOptions=array();
$aOptions['bDeleteFistLine']=(Yii::app()->request->getPost('dontdeletefirstline') == "dontdeletefirstline")?false:true;// Force, maybe function change ;)
if(Yii::app()->request->getPost('noid')==="noid"){
$aOptions['sExistingId']='ignore';
}else{
$aOptions['sExistingId']=Yii::app()->request->getPost('insertmethod');
}
$aOptions['bNotFinalized']=(Yii::app()->request->getPost('notfinalized') == "notfinalized");
$aOptions['bForceImport']=(Yii::app()->request->getPost('forceimport') == "forceimport");
$aOptions['sCharset']=Yii::app()->request->getPost('vvcharset');
$aOptions['sSeparator']="\t";
$aResult=CSVImportResponses($filePath,$iSurveyId,$aOptions);
unlink($filePath); //delete the uploaded file
$aData['class']="";
$aData['title']=$clang->gT("Import a VV response data file");
$aData['aResult']['success'][]=$clang->gT("File upload succeeded.");
if(isset($aResult['success'])){
$aData['aResult']['success']=array_merge($aData['aResult']['success'],$aResult['success']);
}
$aData['aResult']['errors']=(isset($aResult['errors'])) ? $aResult['errors'] : false;
$aData['aResult']['warnings']=(isset($aResult['warnings'])) ? $aResult['warnings'] : false;
$this->_renderWrappedTemplate('dataentry', 'vvimport_result', $aData);
}
private function _getFieldInfo($aFileContents)
{
$aFieldnames = explode("\t", trim($aFileContents[1]));
$nbOfFields = count($aFieldnames) - 1;
while (trim($aFieldnames[$nbOfFields]) == "" && $nbOfFields > -1) // get rid of blank entries
{
unset($aFieldnames[$nbOfFields]);
$nbOfFields--;
}
return array($aFieldnames, $nbOfFields);
}
private function _readFile($filePath)
{ // Open the file for reading
$handle = fopen($filePath, "r");
// Read the file
while (!feof($handle))
{
$buffer = fgets($handle); //To allow for very long lines
$bigarray[] = @mb_convert_encoding($buffer, "UTF-8", $this->_getUploadCharset($this->_getEncodingsArray()));
}
// Close the file
fclose($handle);
return $bigarray;
}
private function _moveUploadedFile($aData)
{
$clang = $this->getController()->lang;
$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']=$clang->gT("Error");
$aData['aResult']['errors'][] = sprintf(
$clang->gT("An error occurred uploading your file. This may be caused by incorrect permissions in your %s folder."),
Yii::app()->getConfig('tempdir')
);
$aData['aResult']['errors'][] = "<pre>".
$aData['aUrls'][] = array(
'link'=>$this->getController()->createUrl('admin/dataentry/sa/vvimport/surveyid/'.$aData['surveyid']),
'text'=>$aData['aUrlText'][] = $clang->gT("Back to Response Import"),
);
$this->_renderWrappedTemplate('dataentry', 'vvimport_result', $aData);
die;
}
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']}"));
}
}
private function _showUploadForm($aEncodings, $surveyid, $aData)
{
unset($aEncodings['auto']);
asort($aEncodings);
$aData['aEncodings']=$aEncodings;
$aData['tableExists'] = tableExists("{{survey_$surveyid}}");
$aData['display']['menu_bars']['browse'] = $this->getController()->lang->gT("Import VV file");
$this->_renderWrappedTemplate('dataentry', 'vvimport', $aData);
}
/**
* dataentry::import()
* Function responsible to import responses from old survey table(s).
* @param int $iSurveyId
* @return void
*/
public function import($surveyid)
{
$iSurveyId = sanitize_int($surveyid);
if(Permission::model()->hasSurveyPermission($iSurveyId,'responses','create'))
{
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)')
);
//Get the menubar
$aData['display']['menu_bars']['browse'] = gT("Quick statistics");
$this->_renderWrappedTemplate('dataentry', 'import', $aData);
}
else
{
$targetSchema = SurveyDynamic::model($iSurveyId)->getTableSchema();
$sourceTable = PluginDynamic::model($_POST['table']);
$sourceSchema = $sourceTable->getTableSchema();
$fieldMap = array();
$pattern = '/([\d]+)X([\d]+)X([\d]+.*)/';
foreach ($sourceSchema->getColumnNames() as $name)
{
// Skip id field.
if ($name == 'id')
{
continue;
}
$sourceColumn = $sourceSchema->getColumn($name);
$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);
foreach ($sourceResponses as $sourceResponse)
{
// Using plugindynamic model because I dont trust surveydynamic.
$targetResponse = new PluginDynamic("{{survey_$iSurveyId}}");
foreach($fieldMap as $sourceField => $targetField)
{
$targetResponse[$targetField] = $sourceResponse[$sourceField];
}
$imported++;
$targetResponse->save();
unset($targetResponse);
}
Yii::app()->session['flashmessage'] = sprintf(gT("%s old response(s) were successfully imported."), $imported);
$sOldTimingsTable=substr($sourceTable->tableName(),0,strrpos($sourceTable->tableName(),'_')).'_timings'.substr($sourceTable->tableName(),strrpos($sourceTable->tableName(),'_'));
$sNewTimingsTable = "survey_{$surveyid}_timings";
if (isset($_POST['timings']) && $_POST['timings'] == 1 && tableExists($sOldTimingsTable) && tableExists($sNewTimingsTable))
{
// Import timings
$aFieldsOldTimingTable=array_values($schema->getTable($sOldTimingsTable)->columnNames);
$aFieldsNewTimingTable=array_values($schema->getTable($sNewTimingsTable)->columnNames);
$aValidTimingFields=array_intersect($aFieldsOldTimingTable,$aFieldsNewTimingTable);
$queryOldValues = "SELECT ".implode(", ",$aValidTimingFields)." FROM {$sOldTimingsTable} ";
$resultOldValues = dbExecuteAssoc($queryOldValues) or show_error("Error:<br />$queryOldValues<br />");
$iRecordCountT=0;
$aSRIDConversions=array();
foreach ($resultOldValues->readAll() as $sTable)
{
if (isset($aSRIDConversions[$sTable['id']]))
{
$sTable['id']=$aSRIDConversions[$sTable['id']];
}
else continue;
//$sInsertSQL=Yii::app()->db->GetInsertSQL($sNewTimingsTable,$row);
$sInsertSQL="INSERT into {$sNewTimingsTable} (".implode(",", array_map("dbQuoteID", array_keys($sTable))).") VALUES (".implode(",", array_map("dbQuoteAll", array_values($sTable))).")";
$aTables = dbExecuteAssoc($sInsertSQL) or show_error("Error:<br />$sInsertSQL<br />");
$iRecordCountT++;
}
Yii::app()->session['flashmessage'] = sprintf(gT("%s old response(s) and according timings were successfully imported."),$imported,$iRecordCountT);
}
$this->getController()->redirect(array("/admin/responses/sa/index/", 'surveyid' => $surveyid));
}
}
}
/**
* Takes a list of tablenames and creates a nice key value array.
* @param type $list
*/
protected function tableList($tables)
{
$list = array();
if (empty($tables))
{
$list['none'] = gT('No old responses found.');
}
foreach ($tables as $table)
{
$count = PluginDynamic::model($table)->count();
$timestamp = date_format(new DateTime(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
* @param type $qid
* @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.
*/
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 mixed $subaction
* @param mixed $id
* @param mixed $surveyid
* @param mixed $language
* @return
*/
public function editdata($subaction, $id, $surveyid, $language='')
{
if ($language == '') {
$language = Survey::model()->findByPk($surveyid)->language;
}
$surveyid = sanitize_int($surveyid);
$id = sanitize_int($id);
$aViewUrls = array();
if (!isset($sDataEntryLanguage))
{
$sDataEntryLanguage = Survey::model()->findByPk($surveyid)->language;
}
$surveyinfo = getSurveyInfo($surveyid);
if (Permission::model()->hasSurveyPermission($surveyid, 'responses','update'))
{
$surveytable = "{{survey_".$surveyid.'}}';
$aData['clang'] = $clang = $this->getController()->lang;
$aData['display']['menu_bars']['browse'] = $clang->gT("Data entry");
Yii::app()->loadHelper('database');
//FIRST LETS GET THE NAMES OF THE QUESTIONS AND MATCH THEM TO THE FIELD NAMES FOR THE DATABASE
$fnquery = "SELECT * FROM {{questions}}, {{groups}} g, {{surveys}} WHERE
{{questions}}.gid=g.gid AND
{{questions}}.language = '{$sDataEntryLanguage}' AND g.language = '{$sDataEntryLanguage}' AND
{{questions}}.sid={{surveys}}.sid AND {{questions}}.sid='$surveyid'
order by group_order, question_order";
$fnresult = dbExecuteAssoc($fnquery);
$fnresult=$fnresult->readAll();
$fncount = count($fnresult);
$fnrows = array(); //Create an empty array in case FetchRow does not return any rows
foreach ($fnresult as $fnrow)
{
$fnrows[] = $fnrow;
$private=$fnrow['anonymized'];
$datestamp=$fnrow['datestamp'];
$ipaddr=$fnrow['ipaddr'];
} // Get table output into array
// 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['completed'] = array('fieldname'=>"completed", 'question'=>$clang->gT("Completed"), 'type'=>'completed');
$fnames=array_merge($fnames,createFieldMap($surveyid,'full',false,false,$sDataEntryLanguage));
$nfncount = count($fnames)-1;
//SHOW INDIVIDUAL RECORD
if ($subaction == "edit" && Permission::model()->hasSurveyPermission($surveyid,'responses','update'))
{
$idquery = "SELECT * FROM $surveytable WHERE id=$id";
$idresult = dbExecuteAssoc($idquery) or safeDie ("Couldn't get individual record<br />$idquery<br />");
foreach ($idresult->readAll() as $idrow)
{
$results[]=$idrow;
}
}
elseif ($subaction == "editsaved" && Permission::model()->hasSurveyPermission($surveyid,'responses','update'))
{
if (isset($_GET['public']) && $_GET['public']=="true")
{
$password = md5(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)
);
foreach($svresult as $svrow)
{
$saver['email'] = $svrow['email'];
$saver['scid'] = $svrow['scid'];
$saver['ip'] = $svrow['ip'];
}
$svresult = SavedControl::model()->findAllByAttributes(array('scid'=>$saver['scid']));
foreach($svresult as $svrow)
{
$responses[$svrow['fieldname']] = $svrow['value'];
} // while
$fieldmap = createFieldMap($surveyid,'full',false,false,getBaseLanguageFromSurveyID($surveyid));
foreach($fieldmap as $fm)
{
if (isset($responses[$fm['fieldname']]))
{
$results1[$fm['fieldname']]=$responses[$fm['fieldname']];
}
else
{
$results1[$fm['fieldname']]="";
}
}
$results1['id'] = "";
$results1['datestamp'] = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", Yii::app()->getConfig('timeadjust'));
$results1['ipaddr'] = $saver['ip'];
$results[] = $results1;
}
$aData = array(
'id' => $id,
'surveyid' => $surveyid,
'subaction' => $subaction,
'part' => 'header',
'clang' => $clang,
);
$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--;
}
}
$aDataentryoutput = '';
foreach ($results as $idrow)
{
$fname = reset($fnames);
do
{
if (isset($idrow[$fname['fieldname']]) )
{
$answer = $idrow[ $fname['fieldname'] ];
}
$question = $fname['question'];
$aDataentryoutput .= "\t<tr";
if ($highlight) $aDataentryoutput .=" class='odd'";
else $aDataentryoutput .=" class='even'";
$highlight=!$highlight;
$aDataentryoutput .=">\n"
."<td>"
."\n";
$aDataentryoutput .= stripJavaScript($question);
$aDataentryoutput .= "</td>\n"
."<td>\n";
//$aDataentryoutput .= "\t-={$fname[3]}=-"; //Debugging info
if(isset($fname['qid']) && isset($fname['type']))
{
$qidattributes = getQuestionAttributeValues($fname['qid'], $fname['type']);
}
switch ($fname['type'])
{
case "completed":
// First compute the submitdate
if ($private == "Y")
{
// In case of anonymized responses survey with no datestamp
// then the the answer submitdate gets a conventional timestamp
// 1st Jan 1980
$mysubmitdate = date("Y-m-d H:i",mktime(0,0,0,1,1,1980)); // Note that the completed field only supports 17 chars (so no seconds!)
}
else
{
$mysubmitdate = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i", Yii::app()->getConfig('timeadjust')); // Note that the completed field only supports 17 chars (so no seconds!)
}
$completedate = empty($idrow['submitdate']) ? $mysubmitdate : $idrow['submitdate'];
$selected = (empty($idrow['submitdate'])) ? 'N' : $completedate;
$select_options = array(
'N' => $clang->gT('No'),
$completedate => $clang->gT('Yes')
);
$aDataentryoutput .= CHtml::dropDownList('completed', $selected, $select_options);
break;
case "X": //Boilerplate question
$aDataentryoutput .= "";
break;
case "Q":
case "K":
$aDataentryoutput .= $fname['subquestion'].' ';
$aDataentryoutput .= CHtml::textField($fname['fieldname'], $idrow[$fname['fieldname']]);
break;
case "id":
$aDataentryoutput .= CHtml::tag('span', array('style' => 'font-weight: bold;'), ' '.$idrow[$fname['fieldname']]);
break;
case "5": //5 POINT CHOICE radio-buttons
for ($i=1; $i<=5; $i++)
{
$checked = FALSE;
if ($idrow[$fname['fieldname']] == $i) { $checked = TRUE; }
$aDataentryoutput .= CHtml::radioButton($fname['fieldname'], $checked, array('class'=>'radiobtn', 'value'=>$i));
$aDataentryoutput .= $i;
}
break;
case "D": //DATE
$thisdate='';
$dateformatdetails = getDateFormatDataForQID($qidattributes, $surveyid)
;
if ($idrow[$fname['fieldname']]!='')
{
$datetimeobj = new Date_Time_Converter($idrow[$fname['fieldname']], "Y-m-d H:i:s");
$thisdate = $datetimeobj->convert($dateformatdetails['phpdate']);
}
else
{
$thisdate = '';
}
if(canShowDatePicker($dateformatdetails))
{
$goodchars = str_replace( array("m","d","y", "H", "M"), "", $dateformatdetails['dateformat']);
$goodchars = "0123456789".$goodchars[0];
$aDataentryoutput .= CHtml::textField($fname['fieldname'], $thisdate,
array(
'class' => 'popupdate',
'size' => '12',
'onkeypress' => 'return goodchars(event,\''.$goodchars.'\')'
)
);
$aDataentryoutput .= CHtml::hiddenField('dateformat'.$fname['fieldname'], $dateformatdetails['jsdate'],
array( 'id' => "dateformat{$fname['fieldname']}" )
);
// $aDataentryoutput .= "\t<input type='text' class='popupdate' size='12' name='{$fname['fieldname']}' value='{$thisdate}' onkeypress=\"return goodchars(event,'".$goodchars."')\"/>\n";
// $aDataentryoutput .= "\t<input type='hidden' name='dateformat{$fname['fieldname']}' id='dateformat{$fname['fieldname']}' value='{$dateformatdetails['jsdate']}' />\n";
}
else
{
$aDataentryoutput .= CHtml::textField($fname['fieldname'], $thisdate);
}
break;
case "G": //GENDER drop-down list
$select_options = array(
'' => $clang->gT("Please choose").'...',
'F' => $clang->gT("Female"),
'M' => $clang->gT("Male")
);
$aDataentryoutput .= CHtml::listBox($fname['fieldname'], $idrow[$fname['fieldname']], $select_options);
break;
case "L": //LIST drop-down
case "!": //List (Radio)
$qidattributes=getQuestionAttributeValues($fname['qid']);
if (isset($qidattributes['category_separator']) && trim($qidattributes['category_separator'])!='')
{
$optCategorySeparator = $qidattributes['category_separator'];
}
else
{
unset($optCategorySeparator);
}
if (substr($fname['fieldname'], -5) == "other")
{
$aDataentryoutput .= "\t<input type='text' name='{$fname['fieldname']}' value='"
.htmlspecialchars($idrow[$fname['fieldname']], ENT_QUOTES) . "' />\n";
}
else
{
$lquery = "SELECT * FROM {{answers}} WHERE qid={$fname['qid']} AND language = '{$sDataEntryLanguage}' ORDER BY sortorder, answer";
$lresult = dbExecuteAssoc($lquery);
$aDataentryoutput .= "\t<select name='{$fname['fieldname']}'>\n"
."<option value=''";
if ($idrow[$fname['fieldname']] == "") {$aDataentryoutput .= " selected='selected'";}
$aDataentryoutput .= ">".$clang->gT("Please choose")."..</option>\n";
if (!isset($optCategorySeparator))
{
foreach ($lresult->readAll() as $llrow)
{
$aDataentryoutput .= "<option value='{$llrow['code']}'";
if ($idrow[$fname['fieldname']] == $llrow['code']) {$aDataentryoutput .= " selected='selected'";}
$aDataentryoutput .= ">{$llrow['answer']}</option>\n";
}
}
else
{
$defaultopts = array();
$optgroups = array();
foreach ($lresult->readAll() as $llrow)
{
list ($categorytext, $answertext) = explode($optCategorySeparator,$llrow['answer']);
if ($categorytext == '')
{
$defaultopts[] = array ( 'code' => $llrow['code'], 'answer' => $answertext);
}
else
{
$optgroups[$categorytext][] = array ( 'code' => $llrow['code'], 'answer' => $answertext);
}
}
foreach ($optgroups as $categoryname => $optionlistarray)
{
$aDataentryoutput .= "<optgroup class=\"dropdowncategory\" label=\"".$categoryname."\">\n";
foreach ($optionlistarray as $optionarray)
{
$aDataentryoutput .= "\t<option value='{$optionarray['code']}'";
if ($idrow[$fname['fieldname']] == $optionarray['code']) {$aDataentryoutput .= " selected='selected'";}
$aDataentryoutput .= ">{$optionarray['answer']}</option>\n";
}
$aDataentryoutput .= "</optgroup>\n";
}
foreach ($defaultopts as $optionarray)
{
$aDataentryoutput .= "<option value='{$optionarray['code']}'";
if ($idrow[$fname['fieldname']] == $optionarray['code']) {$aDataentryoutput .= " selected='selected'";}
$aDataentryoutput .= ">{$optionarray['answer']}</option>\n";
}
}
$oquery="SELECT other FROM {{questions}} WHERE qid={$fname['qid']} AND {{questions}}.language = '{$sDataEntryLanguage}'";
$oresult=dbExecuteAssoc($oquery) or safeDie("Couldn't get other for list question<br />".$oquery."<br />");
foreach($oresult->readAll() as $orow)
{
$fother=$orow['other'];
}
if ($fother =="Y")
{
$aDataentryoutput .= "<option value='-oth-'";
if ($idrow[$fname['fieldname']] == "-oth-"){$aDataentryoutput .= " selected='selected'";}
$aDataentryoutput .= ">".$clang->gT("Other")."</option>\n";
}
$aDataentryoutput .= "\t</select>\n";
}
break;
case "O": //LIST WITH COMMENT drop-down/radio-button list + textarea
$lquery = "SELECT * FROM {{answers}} WHERE qid={$fname['qid']} AND language = '{$sDataEntryLanguage}' ORDER BY sortorder, answer";
$lresult = dbExecuteAssoc($lquery);
$aDataentryoutput .= "\t<select name='{$fname['fieldname']}'>\n"
."<option value=''";
if ($idrow[$fname['fieldname']] == "") {$aDataentryoutput .= " selected='selected'";}
$aDataentryoutput .= ">".$clang->gT("Please choose")."..</option>\n";
foreach ($lresult->readAll() as $llrow)
{
$aDataentryoutput .= "<option value='{$llrow['code']}'";
if ($idrow[$fname['fieldname']] == $llrow['code']) {$aDataentryoutput .= " selected='selected'";}
$aDataentryoutput .= ">{$llrow['answer']}</option>\n";
}
$fname=next($fnames);
$aDataentryoutput .= "\t</select>\n"
."\t<br />\n"
."\t<textarea cols='45' rows='5' name='{$fname['fieldname']}'>"
.htmlspecialchars($idrow[$fname['fieldname']]) . "</textarea>\n";
break;
case "R": //RANKING TYPE QUESTION
$thisqid=$fname['qid'];
$currentvalues=array();
$myfname=$fname['sid'].'X'.$fname['gid'].'X'.$fname['qid'];
$aDataentryoutput .= '<div id="question'.$thisqid.'" class="ranking-answers"><ul class="answers-list">';
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']];
}
$fname=next($fnames);
}
$ansquery = "SELECT * FROM {{answers}} WHERE language = '{$sDataEntryLanguage}' AND qid=$thisqid ORDER BY sortorder, answer";
$ansresult = Yii::app()->db->createCommand($ansquery)->query()->readAll(); //Checked
$anscount= count($ansresult);
$answers= array();
foreach ($ansresult as $ansrow)
{
$answers[] = $ansrow;
}
for ($i=1; $i<=$anscount; $i++)
{
$aDataentryoutput .= "\n<li class=\"select-item\">";
$aDataentryoutput .="<label for=\"answer{$myfname}{$i}\">";
if($i==1){
$aDataentryoutput .=$clang->gT('First choice');
}else{
$aDataentryoutput .=$clang->gT('Next choice');
}
$aDataentryoutput .="</label>";
$aDataentryoutput .= "<select name=\"{$myfname}{$i}\" id=\"answer{$myfname}{$i}\">\n";
(!isset($currentvalues[$i-1])) ? $selected=" selected=\"selected\"" : $selected="";
$aDataentryoutput .= "\t<option value=\"\" $selected>".$clang->gT('None')."</option>\n";
foreach ($answers as $ansrow)
{
(isset($currentvalues[$i-1]) && $currentvalues[$i-1]==$ansrow['code']) ? $selected=" selected=\"selected\"" : $selected="";
$aDataentryoutput .= "\t<option value=\"".$ansrow['code']."\" $selected>".flattenText($ansrow['answer'])."</option>\n";
}
$aDataentryoutput .= "</select\n";
$aDataentryoutput .="</li>";
}
$aDataentryoutput .= '</ul>';
$aDataentryoutput .= "<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>";
$aDataentryoutput .="<div style=\"display:none\">";
foreach ($answers as $ansrow)
{
$aDataentryoutput.="<div id=\"htmlblock-{$thisqid}-{$ansrow['code']}\">{$ansrow['answer']}</div>";
}
$aDataentryoutput .="</div>";
$aDataentryoutput .= '</div>';
App()->getClientScript()->registerPackage('jquery-actual');
App()->getClientScript()->registerScriptFile(Yii::app()->getConfig('generalscripts') . 'ranking.js');
App()->getClientScript()->registerCssFile(Yii::app()->getConfig('publicstyleurl') . 'ranking.css');
$aDataentryoutput .= "<script type='text/javascript'>\n"
. " <!--\n"
. "var aRankingTranslations = {
choicetitle: '".$clang->gT("Your Choices",'js')."',
ranktitle: '".$clang->gT("Your Ranking",'js')."'
};\n"
. "function checkconditions(){};"
. "$(function() {"
." doDragDropRank({$thisqid},0,true,true);\n"
. "});\n"
." -->\n"
."</script>\n";
unset($answers);
$fname=prev($fnames);
break;
case "M": //Multiple choice checkbox
$qidattributes=getQuestionAttributeValues($fname['qid']);
if (trim($qidattributes['display_columns'])!='')
{
$dcols=$qidattributes['display_columns'];
}
else
{
$dcols=0;
}
// while ($fname[3] == "M" && $question != "" && $question == $fname['type'])
$thisqid=$fname['qid'];
while ($fname['qid'] == $thisqid)
{
$fieldn = substr($fname['fieldname'], 0, strlen($fname['fieldname']));
//$aDataentryoutput .= substr($fname['fieldname'], strlen($fname['fieldname'])-5, 5)."<br />\n";
if (substr($fname['fieldname'], -5) == "other")
{
$aDataentryoutput .= "\t<input type='text' name='{$fname['fieldname']}' value='"
.htmlspecialchars($idrow[$fname['fieldname']], ENT_QUOTES) . "' />\n";
}
else
{
$aDataentryoutput .= "\t<input type='checkbox' class='checkboxbtn' name='{$fname['fieldname']}' value='Y'";
if ($idrow[$fname['fieldname']] == "Y") {$aDataentryoutput .= " checked";}
$aDataentryoutput .= " />{$fname['subquestion']}<br />\n";
}
$fname=next($fnames);
}
$fname=prev($fnames);
break;
case "I": //Language Switch
$lquery = "SELECT * FROM {{answers}} WHERE qid={$fname['qid']} AND language = '{$sDataEntryLanguage}' ORDER BY sortorder, answer";
$lresult = dbExecuteAssoc($lquery);
$slangs = Survey::model()->findByPk($surveyid)->additionalLanguages;
$baselang = Survey::model()->findByPk($surveyid)->language;
array_unshift($slangs,$baselang);
$aDataentryoutput.= "<select name='{$fname['fieldname']}'>\n";
$aDataentryoutput .= "<option value=''";
if ($idrow[$fname['fieldname']] == "") {$aDataentryoutput .= " selected='selected'";}
$aDataentryoutput .= ">".$clang->gT("Please choose")."..</option>\n";
foreach ($slangs as $lang)
{
$aDataentryoutput.="<option value='{$lang}'";
if ($lang == $idrow[$fname['fieldname']]) {$aDataentryoutput .= " selected='selected'";}
$aDataentryoutput.=">".getLanguageNameFromCode($lang,false)."</option>\n";
}
$aDataentryoutput .= "</select>";
break;
case "P": //Multiple choice with comments checkbox + text
$aDataentryoutput .= "<table>\n";
while (isset($fname) && $fname['type'] == "P")
{
$thefieldname=$fname['fieldname'];
if (substr($thefieldname, -7) == "comment")
{
$aDataentryoutput .= "<td><input type='text' name='{$fname['fieldname']}' size='50' value='"
.htmlspecialchars($idrow[$fname['fieldname']], ENT_QUOTES) . "' /></td>\n"
."\t</tr>\n";
}
elseif (substr($fname['fieldname'], -5) == "other")
{
$aDataentryoutput .= "\t<tr>\n"
."<td>\n"
."\t<input type='text' name='{$fname['fieldname']}' size='30' value='"
.htmlspecialchars($idrow[$fname['fieldname']], ENT_QUOTES) . "' />\n"
."</td>\n"
."<td>\n";
$fname=next($fnames);
$aDataentryoutput .= "\t<input type='text' name='{$fname['fieldname']}' size='50' value='"
.htmlspecialchars($idrow[$fname['fieldname']], ENT_QUOTES) . "' />\n"
."</td>\n"
."\t</tr>\n";
}
else
{
$aDataentryoutput .= "\t<tr>\n"
."<td><input type='checkbox' class='checkboxbtn' name=\"{$fname['fieldname']}\" value='Y'";
if ($idrow[$fname['fieldname']] == "Y") {$aDataentryoutput .= " checked";}
$aDataentryoutput .= " />{$fname['subquestion']}</td>\n";
}
$fname=next($fnames);
}
$aDataentryoutput .= "</table>\n";
$fname=prev($fnames);
break;
case "|": //FILE UPLOAD