/
responses.php
1386 lines (1248 loc) · 57.2 KB
/
responses.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.
*
*/
/**
* Responses Controller
*
* This controller performs browse actions.
*
* The browse() action is responsible for rendering the response view, which loads the JQGrid table.
* ...The grid in turns issues a JSON POST request to the getResponses_json() action.
* ...
* ...It is important that the order of fields generated by both actions match.
* ...For the browse() action, the $column_model is built up for each column in the table. The grid
* ...uses the column model to render column headings and search bar.
* ...The getResponses_json() action populated the $aSurveyEntry array with the values that must be
* ...populated for each row and column of the table.
*
*
*
* @package LimeSurvey
* @subpackage Backend
*/
class responses extends Survey_Common_Action
{
/**
* @var string : Default layout is bare : temporary to real layout
*/
public $layout = 'bare';
function __construct($controller, $id)
{
parent::__construct($controller, $id);
Yii::app()->loadHelper('surveytranslator');
}
private function _getData($params)
{
if (is_numeric($params))
{
$iSurveyId = $params;
}
elseif (is_array($params))
{
extract($params);
}
$aData = array();
// Set the variables in an array
$aData['surveyid'] = $aData['iSurveyId'] = (int) $iSurveyId;
if (!empty($iId))
{
$aData['iId'] = (int) $iId;
}
$aData['imageurl'] = Yii::app()->getConfig('imageurl');
$aData['action'] = Yii::app()->request->getParam('action');
$aData['all']=Yii::app()->request->getParam('all');
$thissurvey=getSurveyInfo($iSurveyId);
if(!$thissurvey)// Already done in Survey_Common_Action
{
Yii::app()->session['flashmessage'] = gT("Invalid survey ID");
$this->getController()->redirect(array("admin/index"));
}
elseif($thissurvey['active'] != 'Y')
{
Yii::app()->session['flashmessage'] = gT("This survey has not been activated. There are no results to browse.");
$this->getController()->redirect(array("/admin/survey/sa/view/surveyid/{$iSurveyId}"));
}
//OK. IF WE GOT THIS FAR, THEN THE SURVEY EXISTS AND IT IS ACTIVE, SO LETS GET TO WORK.
$aData['surveyinfo'] = $thissurvey;
if (Yii::app()->request->getParam('browselang'))
{
$aData['language'] = Yii::app()->request->getParam('browselang');
$aData['languagelist'] = $languagelist = Survey::model()->findByPk($iSurveyId)->additionalLanguages;
$aData['languagelist'][] = Survey::model()->findByPk($iSurveyId)->language;
if (!in_array($aData['language'], $languagelist))
{
$aData['language'] = $thissurvey['language'];
}
}
else
{
$aData['language'] = $thissurvey['language'];
}
$aData['qulanguage'] = Survey::model()->findByPk($iSurveyId)->language;
$aData['surveyoptions'] = '';
$aData['browseoutput'] = '';
return $aData;
}
public function view($iSurveyID, $iId, $sBrowseLang = '')
{
if(Permission::model()->hasSurveyPermission($iSurveyID,'responses','read'))
{
$aData = $this->_getData(array('iId' => $iId, 'iSurveyId' => $iSurveyID, 'browselang' => $sBrowseLang));
$sBrowseLanguage = $aData['language'];
extract($aData);
$aViewUrls = array();
$fncount = 0;
$fieldmap = createFieldMap($iSurveyID, 'full', false, false, $aData['language']);
//add token to top of list if survey is not private
if ($aData['surveyinfo']['anonymized'] == "N" && tableExists('tokens_' . $iSurveyID) && Permission::model()->hasSurveyPermission($iSurveyID,'tokens','read'))
{
$fnames[] = array("token", gT("Token ID"), 'code'=>'token');
$fnames[] = array("firstname", gT("First name"), 'code'=>'firstname');// or token:firstname ?
$fnames[] = array("lastname", gT("Last name"), 'code'=>'lastname');
$fnames[] = array("email", gT("Email"), 'code'=>'email');
}
$fnames[] = array("submitdate", gT("Submission date"), gT("Completed"), "0", 'D','code'=>'submitdate');
$fnames[] = array("completed", gT("Completed"), "0");
foreach ($fieldmap as $field)
{
if ($field['fieldname'] == 'lastpage' || $field['fieldname'] == 'submitdate')
continue;
if ($field['type'] == 'interview_time')
continue;
if ($field['type'] == 'page_time')
continue;
if ($field['type'] == 'answer_time')
continue;
//$question = $field['question'];
$question = viewHelper::getFieldText($field);
if ($field['type'] != "|")
{
$fnames[] = array($field['fieldname'], viewHelper::getFieldText($field),'code'=>viewHelper::getFieldCode($field,array('LEMcompat'=>true)));
}
elseif ($field['aid'] !== 'filecount')
{
$qidattributes = getQuestionAttributeValues($field['qid']);
for ($i = 0; $i < $qidattributes['max_num_of_files']; $i++)
{
$filenum=sprintf(gT("File %s"),$i + 1);
if ($qidattributes['show_title'] == 1)
$fnames[] = array($field['fieldname'], "{$filenum} - {$question} (".gT('Title').")",'code'=>viewHelper::getFieldCode($field).'(title)', "type" => "|", "metadata" => "title", "index" => $i);
if ($qidattributes['show_comment'] == 1)
$fnames[] = array($field['fieldname'], "{$filenum} - {$question} (".gT('Comment').")",'code'=>viewHelper::getFieldCode($field).'(comment)', "type" => "|", "metadata" => "comment", "index" => $i);
$fnames[] = array($field['fieldname'], "{$filenum} - {$question} (".gT('File name').")",'code'=>viewHelper::getFieldCode($field).'(name)', "type" => "|", "metadata" => "name", "index" => $i);
$fnames[] = array($field['fieldname'], "{$filenum} - {$question} (".gT('File size').")",'code'=>viewHelper::getFieldCode($field).'(size)', "type" => "|", "metadata" => "size", "index" => $i);
//$fnames[] = array($field['fieldname'], "File ".($i+1)." - ".$field['question']." (extension)", "type"=>"|", "metadata"=>"ext", "index"=>$i);
}
}
else
{
$fnames[] = array($field['fieldname'], gT("File count"));
}
}
$nfncount = count($fnames) - 1;
if ($iId < 1)
{
$iId = 1;
}
$exist = SurveyDynamic::model($iSurveyID)->exist($iId);
$next = SurveyDynamic::model($iSurveyID)->next($iId,true);
$previous = SurveyDynamic::model($iSurveyID)->previous($iId,true);
$aData['exist'] = $exist;
$aData['next'] = $next;
$aData['previous'] = $previous;
$aData['id'] = $iId;
$aViewUrls[] = 'browseidheader_view';
if($exist)
{
$oPurifier=new CHtmlPurifier();
//SHOW INDIVIDUAL RECORD
$oCriteria = new CDbCriteria();
if ($aData['surveyinfo']['anonymized'] == 'N' && tableExists("{{tokens_$iSurveyID}}}") && Permission::model()->hasSurveyPermission($iSurveyID,'tokens','read'))
{
$oCriteria = SurveyDynamic::model($iSurveyID)->addTokenCriteria($oCriteria);
}
$oCriteria->addCondition("id = {$iId}");
$iIdresult = SurveyDynamic::model($iSurveyID)->findAllAsArray($oCriteria);
foreach ($iIdresult as $iIdrow)
{
$iId = $iIdrow['id'];
$rlanguage = $iIdrow['startlanguage'];
}
$next = SurveyDynamic::model($iSurveyID)->next($iId);
$previous = SurveyDynamic::model($iSurveyID)->previous($iId);
$aData['bHasFile']=false;
if (isset($rlanguage))
{
$aData['rlanguage'] = $rlanguage;
}
foreach ($iIdresult as $iIdrow)
{
$highlight = false;
for ($i = 0; $i < $nfncount + 1; $i++)
{
if ($fnames[$i][0] != 'completed' && is_null($iIdrow[$fnames[$i][0]]))
{
continue; // irrelevant, so don't show
}
$inserthighlight = '';
if ($highlight)
$inserthighlight = "class='highlight'";
if ($fnames[$i][0] == 'completed')
{
if ($iIdrow['submitdate'] == NULL || $iIdrow['submitdate'] == "N")
{
$answervalue = "N";
}
else
{
$answervalue = "Y";
}
}
else
{
if (isset($fnames[$i]['type']) && $fnames[$i]['type'] == "|")
{
$index = $fnames[$i]['index'];
$metadata = $fnames[$i]['metadata'];
$phparray = json_decode_ls($iIdrow[$fnames[$i][0]]);
if (isset($phparray[$index]))
{
switch ($metadata)
{
case "size":
$answervalue = sprintf(gt("%s KB"),intval($phparray[$index][$metadata]));
break;
case "name":
$answervalue = CHtml::link(
$oPurifier->purify(rawurldecode($phparray[$index][$metadata])),
$this->getController()->createUrl("/admin/responses",array("sa"=>"actionDownloadfile","surveyid"=>$surveyid,"iResponseId"=>$iId,"sFileName"=>$phparray[$index][$metadata]))
);
break;
default:
$answervalue = htmlspecialchars(strip_tags(stripJavaScript($phparray[$index][$metadata])));
}
$aData['bHasFile']=true;
}
else
$answervalue = "";
}
else
{
$answervalue = htmlspecialchars(strip_tags(stripJavaScript(getExtendedAnswer($iSurveyID, $fnames[$i][0], $iIdrow[$fnames[$i][0]], $sBrowseLanguage))), ENT_QUOTES);
}
}
$aData['answervalue'] = $answervalue;
$aData['inserthighlight'] = $inserthighlight;
$aData['fnames'] = $fnames;
$aData['i'] = $i;
$aViewUrls['browseidrow_view'][] = $aData;
}
}
}
else
{
Yii::app()->session['flashmessage'] = gT("This response ID is invalid.");
}
$aViewUrls[] = 'browseidfooter_view';
$this->_renderWrappedTemplate('',$aViewUrls, $aData);
}
else
{
$aData['surveyid'] = $iSurveyID;
App()->getClientScript()->registerPackage('jquery-superfish');
$message['title']= gT('Access denied!');
$message['message']= gT('You do not have sufficient rights to access this page.');
$message['class']= "error";
$this->_renderWrappedTemplate('survey', array("message"=>$message), $aData);
}
}
public function index($iSurveyID)
{
$aData = $this->_getData($iSurveyID);
extract($aData);
$aViewUrls = array();
$sBrowseLanguage = $aData['language'];
/**
* fnames is used as informational array
* it containts
* $fnames[] = array(<dbfieldname>, <some strange title>, <questiontext>, <group_id>, <questiontype>);
*/
if (Yii::app()->request->getPost('sql'))
{
$aViewUrls[] = 'browseallfiltered_view';
}
$aData['num_total_answers'] = SurveyDynamic::model($iSurveyID)->count();
$aData['num_completed_answers'] = SurveyDynamic::model($iSurveyID)->count('submitdate IS NOT NULL');
if (tableExists('{{tokens_' . $iSurveyID . '}}') && Permission::model()->hasSurveyPermission($iSurveyID,'tokens','read'))
{
$aData['with_token']= Yii::app()->db->schema->getTable('{{tokens_' . $iSurveyID . '}}');
$aData['tokeninfo'] = Token::model($iSurveyID)->summary();
}
$aViewUrls[] = 'browseindex_view';
$this->_renderWrappedTemplate('',$aViewUrls, $aData);
}
function browse($iSurveyId)
{
if(!Permission::model()->hasSurveyPermission($iSurveyId,'responses','read'))
{
$aData['surveyid'] = $iSurveyId;
$message['title']= gT('Access denied!');
$message['message']= gT('You do not have sufficient rights to access this page.');
$message['class']= "error";
$this->_renderWrappedTemplate('survey', array("message"=>$message), $aData);
Yii::app()->end();
}
App()->getClientScript()->registerPackage('jqgrid');
App()->getClientScript()->registerScriptFile(Yii::app()->getConfig('adminscripts') . "listresponse.js");
$aData = $this->_getData($iSurveyId);
extract($aData);
$aViewUrls = array();
$sBrowseLanguage = $aData['language'];
// Some specific column
$aSpecificColumns=array(
'submitdate', // Replaced by completed : TODO : add it if is a real date
'token', // Replaced by tokens.token
'id', // Allways adding it at start
'lastpage', // After id, before completed
);
// The column model must be built dynamically, since the columns will differ from survey to survey, depending on the questions.
$column_model = array();
// The first few colums are fixed.
$column_model[] = array(
'name' => 'actions',
'index'=> 'actions',
'sorttype' => 'string',
'sortable' => false,
'width' => '100',
'resizable' => true,
'align' => 'left',
'label' => gt("Actions"),
'search' => false,
'hidedlg'=>true,
);
$fields = createFieldMap($iSurveyId,'full', true, false, $aData['language']);
// Specific columns at start
$column_model[] = array(
'name'=>'id',
'index'=>'id',
'sorttype'=>'integer',
'sortable'=>true,
'width'=>'100',
'resizable' => true,
'align'=>'center',
'title'=>viewHelper::getFieldText($fields['id']),
'hidedlg'=>true,
);
$column_model[] = array(
'name'=>'lastpage',
'index'=>'lastpage',
'sorttype'=>'integer',
'sortable'=>true,
'width'=>'100',
'resizable' => true,// Strangely : don't work
'align'=>'center',
'title'=>viewHelper::getFieldText($fields['lastpage']),
);
$bHidden=false;
if (isset($_SESSION['survey_'.$iSurveyId]['HiddenFields']))
{
$bHidden=in_array('completed',$_SESSION['survey_'.$iSurveyId]['HiddenFields']);
}
$column_model[] = array(
'name' => 'completed',
'index'=>'completed',
'sorttype'=>'string',
'stype'=>'select',
'editoptions'=>array(
'value'=>array(
""=>gt("All"),
"Y"=>gt("Yes"),
"N"=>gt("No"),
),
),
'sortable'=>true,
'hidden'=>$bHidden,
'width'=>'100',
'align'=>'center',
'label' => gt("Completed"),
);
//add token to top of list if survey is not private
if ($aData['surveyinfo']['anonymized'] == "N" && tableExists('tokens_' . $iSurveyId)) //add token to top of list if survey is not private
{
$column_model[] = array(
'name'=>'token',
'index'=>'token',
'sorttype'=>'string',
'sortable'=>true, 'width'=>'100',
'align'=>'left',
'title'=>gt('Token')
);
$column_model[] = array(
'name'=>'firstname',
'index'=>'firstname',
'sorttype'=>'string',
'sortable'=>true,
'width'=>'100',
'align'=>'left',
'title'=>gt('First name'),
);
$column_model[] = array(
'name'=>'lastname',
'index'=>'lastname',
'sorttype'=>'string',
'sortable'=>true,
'width'=>'100',
'align'=>'left',
'title'=>gt('Last Name'),
);
$column_model[] = array(
'name'=>'email',
'index'=>'email',
'sorttype'=>'string',
'sortable'=>true,
'width'=>'100',
'align'=>'left',
'title'=>gt('Email'),
);
}
// All other columns are based on the questions.
// An array to control unicity of $code (EM code)
$aCodes=array();
foreach ($fields as $fielddetails)
{
if(in_array($fielddetails['fieldname'],$aSpecificColumns))
continue;
// no headers for time data
if ($fielddetails['type'] == 'interview_time')
continue;
if ($fielddetails['type'] == 'page_time')
continue;
if ($fielddetails['type'] == 'answer_time')
continue;
$question = $fielddetails['question'];
if ($fielddetails['type'] == "|")
{
$fnames=array();
$code=viewHelper::getFieldCode($fielddetails,array('LEMcompat'=>true));// This must be unique ......
if ($fielddetails['aid'] !== 'filecount')
{
$qidattributes = getQuestionAttributeValues($fielddetails['qid']);
for ($i = 0; $i < $qidattributes['max_num_of_files']; $i++)
{
if ($qidattributes['show_title'] == 1)
$fnames[] = array($code.'_'.$i.'_title', "File " . ($i + 1) . " - " . $fielddetails['question'] . "(Title)", "type" => "|", "metadata" => "title", "index" => $i);
if ($qidattributes['show_comment'] == 1)
$fnames[] = array($code.'_'.$i.'_comment', "File " . ($i + 1) . " - " . $fielddetails['question'] . "(Comment)", "type" => "|", "metadata" => "comment", "index" => $i);
$fnames[] = array($code.'_'.$i.'_name', "File " . ($i + 1) . " - " . $fielddetails['question'] . "(File name)", "type" => "|", "metadata" => "name", "index" => $i);
$fnames[] = array($code.'_'.$i.'_size', "File " . ($i + 1) . " - " . $fielddetails['question'] . "(File size)", "type" => "|", "metadata" => "size", "index" => $i);
}
}
else
$fnames[] = array($code.'_count', "File count");
$bHidden=false;
if (isset($_SESSION['survey_'.$iSurveyId]['HiddenFields']))
{
$bHidden=in_array($fielddetails['fieldname'],$_SESSION['survey_'.$iSurveyId]['HiddenFields']);
}
foreach ($fnames as $aFileInfoField)
{
$column_model[] = array(
'name' => $aFileInfoField[0],
'index' => $aFileInfoField[0],
'sortable' => false,
'width' => '100',
'align' => 'left',
'editable' => false,
'search' => false,
'hidden' => $bHidden,
'title' => $aFileInfoField[1],
);
}
continue;
}
// TODO: upload question type have more than one column (see before)
// Construction of clean name and title
$code=viewHelper::getFieldCode($fielddetails,array('LEMcompat'=>true));// This must be unique ......
//fix unicity of $code
if(isset($aCodes[$code]))
{
$aCodes[$code]++;
$code="{$code}-{$aCodes[$code]}";
}
else
{
$aCodes[$code]=0;
}
$text=viewHelper::getFieldText($fielddetails);
$textabb=viewHelper::getFieldText($fielddetails,array('abbreviated'=>10));
$bHidden=false;
if (isset($_SESSION['survey_'.$iSurveyId]['HiddenFields']))
{
$bHidden=in_array($fielddetails['fieldname'],$_SESSION['survey_'.$iSurveyId]['HiddenFields']);
}
$column_model[] = array(
'name' => $code,
'index' => $fielddetails['fieldname'],
'sorttype' => 'string',// Depend of question type can be excellent
'sortable' => true,
'width' => '100',
'align' => 'left',
'editable' => false,
'hidden' => (bool)$bHidden,
'title' => $text,
);
}
$column_model_txt = ls_json_encode($column_model);
$column_names = array();
foreach ($column_model as $column)
{
if(isset($column['title']))
$column_names[] = "<strong class='qcode'>{$column['name']}</strong> <span class='separator hidden'>:</span> <span class='questiontext'>".ellipsize($column['title'],30,0.6,"...")."</span>";
elseif(isset($column['label']))
$column_names[] = $column['label'];
else
$column_names[] = $column['name'];
}
$aData['issuperadmin'] = Permission::model()->hasGlobalPermission('superadmin');
$aData['surveyid']= $iSurveyId;
$aData['column_model_txt']= $column_model_txt;
$aData['column_names_txt']= ls_json_encode($column_names);;
$aData['hasUpload']=hasFileUploadQuestion($iSurveyId);
$this->_renderWrappedTemplate('responses', 'listResponses_view', $aData);
}
/**
* Returns survey responses in json format for a given survey
*
* @access public
* @param $iSurveyID : survey id
* @return json
*/
public function getResponses_json($iSurveyID)
{
if(!Permission::model()->hasSurveyPermission($iSurveyID,'responses','read'))
{
Yii::app()->end();
}
$aData = $this->_getData($iSurveyID);
$bHaveToken=$aData['surveyinfo']['anonymized'] == "N" && tableExists('tokens_' . $iSurveyID) && Permission::model()->hasSurveyPermission($iSurveyID,'tokens','read');
extract($aData);
$aViewUrls = array();
$sBrowseLanguage = $aData['language'];
$sImageURL = Yii::app()->getConfig('adminimageurl');
$fnames = array();
$aSpecificColumns=array(
'submitdate', // Replaced by completed : TODO : add it if is a real date
'token', // Replaced by tokens.token
'id', // Allways adding it at start
'lastpage',
);
$aFieldmap = createFieldMap($iSurveyID, 'full', true, false, $aData['language']);
// Get the survey responses
$sOrder=Yii::app()->request->getPost('sord') == 'desc' ? 'desc' : 'asc';
$sOrderBy=Yii::app()->request->getPost('sidx','id');
$iPage=Yii::app()->request->getPost('page',1);
$iLimit=Yii::app()->request->getPost('rows',50); // Default to 50 ?
// Old behaviour : ajax default request from jqgrid need sort / rows (limit) / page (start) / sidx for order by : use javacript log please ....
$oCriteria = new CDbCriteria;
//Create the query
if ($aData['surveyinfo']['anonymized'] == "N" && tableExists("{{tokens_{$iSurveyID}}}") && Permission::model()->hasSurveyPermission($iSurveyID,'tokens','read'))
{
$oCriteria = SurveyDynamic::model($iSurveyID)->addTokenCriteria($oCriteria);
$aSpecificColumns=array_merge($aSpecificColumns,TokenDynamic::model($iSurveyID)->getTableSchema()->getColumnNames());
}
if (incompleteAnsFilterState() == "incomplete")
{
$oCriteria->addCondition("submitdate IS NULL");
}
elseif (incompleteAnsFilterState() == "complete")
{
$oCriteria->addCondition("submitdate IS NOT NULL");
}
//Get the filter data
//if (Yii::app()->request->getPost('sql') && stripcslashes(Yii::app()->request->getPost('sql')) !== "" && Yii::app()->request->getPost('sql') != "NULL")
// $oCriteria->addCondition(stripcslashes(Yii::app()->request->getPost('sql')));
$aKnowColumns=array_keys(SurveyDynamic::model($iSurveyID)->attributes);
if($bHaveToken){
$aKnowColumns[]='firstname';
$aKnowColumns[]='lastname';
$aKnowColumns[]='email';
}
switch ($sOrderBy)
{
case 'completed':
$sOrderBy='submitdate';
break;
default:
if(!in_array($sOrderBy,$aKnowColumns))
{
Yii::trace("unknow column $sOrderBy in json request");
$sOrderBy='id';
}
}
$sOrderBy = Yii::app()->db->quoteColumnName($sOrderBy); // Maybe need to fix if $sOrderBy is in columns name
$oCriteria->order = "{$sOrderBy} {$sOrder}";
if(Yii::app()->request->getParam('_search'))
{
if(($value=Yii::app()->request->getParam('completed')) && !incompleteAnsFilterState()) //
{
if($value=='Y')
$oCriteria->addCondition("submitdate IS NOT NULL");
elseif($value=='N')
$oCriteria->addCondition("submitdate IS NULL");
}
foreach($aKnowColumns as $sFiltering)
{
if($value=Yii::app()->request->getParam($sFiltering))
{
if($sFiltering=='token')
$sFiltering='tokens.token';
$oCriteria->compare(Yii::app()->db->quoteColumnName($sFiltering),$value,true);
}
}
if($sFilters=Yii::app()->request->getParam('filters'))
{
$aFilters=json_decode($sFilters);
// TODO : groupOp and rules
}
}
// Elements for nav bar of jquery
$iCount = SurveyDynamic::model($iSurveyID)->count($oCriteria);// or die("Couldn't get response data<br />");
$iLimit=((int)$iLimit>0) ?(int)$iLimit : 50 ;
if (!$iLimit || $iLimit > $iCount)
{
$iLimit = $iCount;
}
$iStart=((int)$iPage>0) ? ((int)$iPage*$iLimit - $iLimit) : 0;
$aSurveyEntries = new stdClass();
$aSurveyEntries->page = $iPage; // Did we need to fix page ?
$aSurveyEntries->total = ($iCount>0)?ceil($iCount/$iLimit):0;
$aSurveyEntries->records= $iCount;
// Last criteria update
$oCriteria->offset = $iStart;
$oCriteria->limit = $iLimit;
// Get the rows
$dtresult = SurveyDynamic::model($iSurveyID)->findAllAsArray($oCriteria);
$all_rows = array();
foreach ($dtresult as $row) {
$action_html = "<a href='" . Yii::app()->createUrl("admin/responses/view/surveyid/$surveyid/id/{$row['id']}") . "'><img src='" . $sImageURL . "token_viewanswer.png' alt='" . gT('View response details') . "'/></a>";
if (Permission::model()->hasSurveyPermission($iSurveyID,'responses','update')) {
$action_html .= "<a href='" . Yii::app()->createUrl("admin/dataentry/editdata/subaction/edit/surveyid/{$surveyid}/id/{$row['id']}") . "'><img src='" . $sImageURL . "edit_16.png' alt='" . gT('Edit this response') . "'/></a>";
}
if (hasFileUploadQuestion($surveyid)) {
if(Response::model($surveyid)->findByPk($row['id'])->getFiles())
$action_html .= CHtml::link(
CHtml::image("{$sImageURL}down.png",gT('Download all files in this response as a zip file'),array("class"=>"downloadfile")),
Yii::app()->createUrl("admin/responses",array("sa"=>"actionDownloadfiles","surveyid"=>$surveyid,"sResponseId"=>$row['id']))
);
}
if (Permission::model()->hasSurveyPermission($iSurveyID,'responses','delete')) {
$action_html .= "<a href='".Yii::app()->createUrl("admin/responses",array("sa"=>"actionDelete","surveyid"=>$surveyid,"sResponseId"=>$row['id']))."' data-delete='".$row['id']."'><img src='" . $sImageURL . "token_delete.png' alt='" . sprintf(gT('Delete response %s'),$row['id']) . "' class='deleteresponse'/></a>";
}
$aSurveyEntry = array();
$aSurveyEntry[] = $action_html;
$aSurveyEntry[] = $row['id'];
$aSurveyEntry[] = $row['lastpage'];
// completed
$aSurveyEntry[] = empty($row['submitdate'])?'N':'Y';
if ($bHaveToken)
{
if(is_null($row['tid']))
$aSurveyEntry[] = strip_tags($row['token']);
else
$aSurveyEntry[] = "<a href='".Yii::app()->createUrl("admin/tokens",array("sa"=>"edit","surveyid"=>$surveyid,"tokenid"=>$row['tid']))."'>".strip_tags($row['token'])."</a>";
$aSurveyEntry[] = strip_tags($row['firstname']);
$aSurveyEntry[] = strip_tags($row['lastname']);
$aSurveyEntry[] = strip_tags($row['email']);
}
// startlanguage
//$aSurveyEntry[] = $row['startlanguage'];
foreach ($row as $aFieldName => $mFieldValue) {
if(in_array($aFieldName,$aSpecificColumns))
continue;
$sSurveyEntry=strip_tags(getExtendedAnswer($iSurveyID, $aFieldName, $mFieldValue, $sBrowseLanguage)); // This fix XSS and get the value
if($aFieldmap[$aFieldName]['type']=='|' && strpos($aFieldName,'filecount')===false)
{
$aQuestionAttributes = getQuestionAttributeValues($aFieldmap[$aFieldName]['qid']);
$aFilesInfo = json_decode_ls($mFieldValue);
for ($iFileIndex = 0; $iFileIndex < $aQuestionAttributes['max_num_of_files']; $iFileIndex++)
{
if (isset($aFilesInfo[$iFileIndex]))
{
$aSurveyEntry[] = $aFilesInfo[$iFileIndex]['title'];
$aSurveyEntry[] = $aFilesInfo[$iFileIndex]['comment'];
$aSurveyEntry[] = CHtml::link(rawurldecode($aFilesInfo[$iFileIndex]['name']), $this->getController()->createUrl("/admin/responses",array("sa"=>"actionDownloadfile","surveyid"=>$surveyid,"iResponseId"=>$row['id'],"sFileName"=>$aFilesInfo[$iFileIndex]['name'])) );
$aSurveyEntry[] = sprintf('%s Mb',round($aFilesInfo[$iFileIndex]['size']/1000,2));
}
else
{
$aSurveyEntry[] = "";
$aSurveyEntry[] = "";
$aSurveyEntry[] = "";
$aSurveyEntry[] = "";
}
}
}
else
{
$aSurveyEntry[] = $sSurveyEntry;
}
}
$all_rows[] = array('id' => $row['id'], 'cell' => $aSurveyEntry);
}
$aSurveyEntries->rows = $all_rows;
viewHelper::disableHtmlLogging();// It's better with but we need to fix error actually
header('Content-type: application/json');
echo json_encode($aSurveyEntries);
Yii::app()->end();
}
/**
* Saves the hidden columns for response browsing in the session
*
* @access public
* @param $iSurveyID : survey id
*/
public function setHiddenColumns($iSurveyId)
{
if(Permission::model()->hasSurveyPermission($iSurveyId,'responses','read'))
{
$aHiddenFields=explode('|',Yii::app()->request->getPost('aHiddenFields'));
$_SESSION['survey_'.$iSurveyId]['HiddenFields']=$aHiddenFields;
}
}
/**
* Do an actions on response
*
* @access public
* @param $iSurveyId : survey id
* @return void
*/
public function actionResponses($iSurveyId)
{
$action=Yii::app()->request->getPost('oper');
$sResponseId=Yii::app()->request->getPost('id');
switch ($action)
{
case 'downloadzip':
$this->actionDownloadfiles($iSurveyId,$sResponseId);
break;
case 'del':
$this->actionDelete($iSurveyId,$sResponseId);
break;
default:
break;
}
}
/**
* Delete response
* Allow to delete directly : leave it ? Can take $sResponseId by POST
* @access public
* @param $iSurveyId : survey id
* @param $sResponseId : list of response
* @return void
*/
public function actionDelete($iSurveyId,$sResponseId)
{
if(Permission::model()->hasSurveyPermission($iSurveyId,'responses','delete'))
{
$oSurvey=Survey::model()->findByPk($iSurveyId);
//SurveyDynamic::model($iSurveyId)->deleteByPk($sResponseId);
Response::model($iSurveyId)->findByPk($sResponseId)->delete(true);
if($oSurvey->savetimings == "Y"){// TODO : add it to response delete (maybe test if timing table exist)
SurveyTimingDynamic::model($iSurveyID)->deleteByPk($iResponseID);
}
}
}
/**
* Download individual file by response and filename
*
* @access public
* @param $iSurveyId : survey id
* @param $iResponseId : response if
* @param $sFileName : The filename
* @return application/octet-stream
*/
public function actionDownloadfile($iSurveyId,$iResponseId,$sFileName)
{
if(Permission::model()->hasSurveyPermission($iSurveyId,'responses','read'))
{
$oResponse = Response::model($iSurveyId)->findByPk($iResponseId);
foreach ($oResponse->getFiles() as $aFile)
{
if (rawurldecode($aFile['name']) == rawurldecode($sFileName))
{
$sFileRealName = Yii::app()->getConfig('uploaddir') . "/surveys/" . $iSurveyId . "/files/" . $aFile['filename'];
if (file_exists($sFileRealName))
{
@ob_clean();
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');// Find the real type ?
header('Content-Disposition: attachment; filename="' . rawurldecode($aFile['name']) . '"');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($sFileRealName));
readfile($sFileRealName);
exit;
}
break;
}
}
Yii::app()->setFlashMessage(gT("Sorry, This file was not found"),'error');
$this->getController()->redirect(array("admin/responses","sa"=>"browse","surveyid"=>$surveyid));
}
}
/**
* Construct a zip files from a list of response
*
* @access public
* @param $iSurveyId : survey id
* @param $sResponseId : list of response
* @return application/zip
*/
public function actionDownloadfiles($iSurveyId,$sResponseId)
{
if(Permission::model()->hasSurveyPermission($iSurveyId,'responses','read'))
{
if(!$sResponseId) // No response id : get all survey files
{
$oCriteria = new CDbCriteria();
$oCriteria->select = "id";
$oSurvey = SurveyDynamic::model($iSurveyId);
$aResponseId = $oSurvey->getCommandBuilder()
->createFindCommand($oSurvey->tableSchema, $oCriteria)
->queryColumn();
}
else
{
$aResponseId=explode(",",$sResponseId);
}
if(!empty($aResponseId))
{
// Now, zip all the files in the filelist
if(count($aResponseId)==1)
$zipfilename = "Files_for_survey_{$iSurveyId}_response_{$aResponseId[0]}.zip";
else
$zipfilename = "Files_for_survey_{$iSurveyId}.zip";
$this->_zipFiles($iSurveyId, $aResponseId, $zipfilename);
}
else
{
// No response : redirect to browse with a alert
Yii::app()->setFlashMessage(gT("Sorry, no reponse in this survey"),'error');
$this->getController()->redirect(array("admin/responses","sa"=>"browse","surveyid"=>$surveyid));
}
}
}
/**
* @deprecated
* */
function oldbrowse($iSurveyID)
{
$aData = $this->_getData($iSurveyID);
extract($aData);
$aViewUrls = array();
$sBrowseLanguage = $aData['language'];
$tokenRequest = Yii::app()->request->getParam('token', null);
/**
* fnames is used as informational array
* it containts
* $fnames[] = array(<dbfieldname>, <some strange title>, <questiontext>, <group_id>, <questiontype>);
*/
if(Permission::model()->hasSurveyPermission($iSurveyID,'responses','read'))
{
if (Yii::app()->request->getPost('sql'))
{
$aViewUrls[] = 'browseallfiltered_view';
}
//add token to top of list if survey is not private
if ($aData['surveyinfo']['anonymized'] == "N" && tableExists('tokens_' . $iSurveyID) ) //add token to top of list if survey is not private
{
if(Permission::model()->hasSurveyPermission($iSurveyID,'tokens','read'))
{
$fnames[] = array("token", gT("Token ID"), 'code'=>'token');
$fnames[] = array("firstname", gT("First name"), 'code'=>'firstname');// or token:firstname ?
$fnames[] = array("lastname", gT("Last name"), 'code'=>'lastname');
$fnames[] = array("email", gT("Email"), 'code'=>'email');
}
}
$fnames[] = array("submitdate", gT("Completed"), gT("Completed"), "0", 'D');
$fields = createFieldMap($iSurveyID, 'full', false, false, $aData['language']);
foreach ($fields as $fielddetails)
{
if ($fielddetails['fieldname'] == 'lastpage' || $fielddetails['fieldname'] == 'submitdate')
continue;
$question = $fielddetails['question'];
if ($fielddetails['type'] != "|")
{
if ($fielddetails['fieldname'] == 'lastpage' || $fielddetails['fieldname'] == 'submitdate' || $fielddetails['fieldname'] == 'token')
continue;
// no headers for time data
if ($fielddetails['type'] == 'interview_time')
continue;
if ($fielddetails['type'] == 'page_time')
continue;
if ($fielddetails['type'] == 'answer_time')
continue;
$fnames[] = array($fielddetails['fieldname'], viewHelper::getFieldText($fielddetails),'code'=>viewHelper::getFieldCode($fielddetails,array('LEMcompat'=>true)));
}
elseif ($fielddetails['aid'] !== 'filecount')
{
$qidattributes = getQuestionAttributeValues($fielddetails['qid']);
for ($i = 0; $i < $qidattributes['max_num_of_files']; $i++)
{
$filenum=sprintf(gT("File %s"),$i + 1);