-
Notifications
You must be signed in to change notification settings - Fork 988
/
userstatistics_helper.php
2986 lines (2618 loc) · 142 KB
/
userstatistics_helper.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.
*/
/**
*
* Generate a chart for a question
* @param int $iQuestionID ID of the question
* @param int $iSurveyID ID of the survey
* @param mixed $type Type of the chart to be created - null produces bar chart, any other value produces pie chart
* @param array $lbl An array containing the labels for the chart items
* @param mixed $gdata An array containing the percentages for the chart items
* @param mixed $grawdata An array containing the raw count for the chart items
* @param pCache $cache An object containing [Hashkey] and [CacheFolder]
* @param mixed $sLanguageCode Language Code
* @param string $sQuestionType The question type
* @return false|string
*/
function createChart($iQuestionID, $iSurveyID, $type = null, $lbl, $gdata, $grawdata, $cache, $sLanguageCode, $sQuestionType)
{
/* This is a lazy solution to bug #6389. A better solution would be to find out how
the "T" gets passed to this function from the statistics.js file in the first place! */
if (substr($iSurveyID, 0, 1) == "T") {
$iSurveyID = substr($iSurveyID, 1);
}
static $bErrorGenerate = false;
if ($bErrorGenerate) {
return false;
}
$rootdir = Yii::app()->getConfig("rootdir");
$homedir = Yii::app()->getConfig("homedir");
$admintheme = Yii::app()->getConfig("admintheme");
$chartfontfile = Yii::app()->getConfig("chartfontfile");
$chartfontsize = Yii::app()->getConfig("chartfontsize");
$alternatechartfontfile = Yii::app()->getConfig("alternatechartfontfile");
$cachefilename = "";
/* Set the fonts for the chart */
if ($chartfontfile == 'auto') {
// Tested with ar,be,el,fa,hu,he,is,lt,mt,sr, and en (english)
// Not working for hi, si, zh, th, ko, ja : see $config['alternatechartfontfile'] to add some specific language font
$chartfontfile = 'DejaVuSans.ttf';
if (array_key_exists($sLanguageCode, $alternatechartfontfile)) {
$neededfontfile = $alternatechartfontfile[$sLanguageCode];
if (is_file($rootdir . "/assets/fonts/" . $neededfontfile)) {
$chartfontfile = $neededfontfile;
} else {
Yii::app()->setFlashMessage(sprintf(gT('The fonts file %s was not found in <limesurvey root folder>/fonts directory. Please, see the txt file for your language in fonts directory to generate the charts.'), $neededfontfile), 'error');
$bErrorGenerate = true; // Don't do a graph again.
return false;
}
}
}
if (count($lbl) > 72) {
$DataSet = array(1 => array(1 => 1));
if ($cache->IsInCache("graph" . $iSurveyID . $sLanguageCode . $iQuestionID, $DataSet) && Yii::app()->getConfig('debug') < 2) {
$cachefilename = basename($cache->GetFileFromCache("graph" . $iSurveyID . $sLanguageCode . $iQuestionID, $DataSet));
} else {
$graph = new pChart(690, 200);
$graph->loadColorPalette(Yii::app()->getConfig('styledir') . DIRECTORY_SEPARATOR . $admintheme . DIRECTORY_SEPARATOR . 'images/limesurvey.pal');
$graph->setFontProperties($rootdir . DIRECTORY_SEPARATOR . 'assets' . DIRECTORY_SEPARATOR . 'fonts' . DIRECTORY_SEPARATOR . $chartfontfile, $chartfontsize);
$graph->setFontProperties($rootdir . DIRECTORY_SEPARATOR . 'assets' . DIRECTORY_SEPARATOR . 'fonts' . DIRECTORY_SEPARATOR . $chartfontfile, $chartfontsize);
$graph->drawTitle(0, 0, gT('Sorry, but this question has too many answer options to be shown properly in a graph.', 'unescaped'), 30, 30, 30, 690, 200);
$cache->WriteToCache("graph" . $iSurveyID . $sLanguageCode . $iQuestionID, $DataSet, $graph);
$cachefilename = basename($cache->GetFileFromCache("graph" . $iSurveyID . $sLanguageCode . $iQuestionID, $DataSet));
unset($graph);
}
return $cachefilename;
}
if (array_sum($gdata) == 0) {
$DataSet = array(1 => array(1 => 1));
if ($cache->IsInCache("graph" . $iSurveyID . $sLanguageCode . $iQuestionID, $DataSet) && Yii::app()->getConfig('debug') < 2) {
$cachefilename = basename($cache->GetFileFromCache("graph" . $iSurveyID . $sLanguageCode . $iQuestionID, $DataSet));
} else {
$graph = new pChart(690, 200);
$graph->loadColorPalette(Yii::app()->getConfig('styledir') . DIRECTORY_SEPARATOR . $admintheme . DIRECTORY_SEPARATOR . 'images/limesurvey.pal');
$graph->setFontProperties($rootdir . DIRECTORY_SEPARATOR . 'assets' . DIRECTORY_SEPARATOR . 'fonts' . DIRECTORY_SEPARATOR . $chartfontfile, $chartfontsize);
$graph->setFontProperties($rootdir . DIRECTORY_SEPARATOR . 'assets' . DIRECTORY_SEPARATOR . 'fonts' . DIRECTORY_SEPARATOR . $chartfontfile, $chartfontsize);
$graph->drawTitle(0, 0, gT('Sorry, but this question has no responses yet so a graph cannot be shown.', 'unescaped'), 30, 30, 30, 690, 200);
$cache->WriteToCache("graph" . $iSurveyID . $sLanguageCode . $iQuestionID, $DataSet, $graph);
$cachefilename = basename($cache->GetFileFromCache("graph" . $iSurveyID . $sLanguageCode . $iQuestionID, $DataSet));
unset($graph);
}
return $cachefilename;
}
if (array_sum($gdata) > 0) {
//Make sure that the percentages add up to more than 0
$i = 0;
foreach ($gdata as $data) {
if ($data != 0) {
$i++;
}
}
/* Totatllines is the number of entries to show in the key and we need to reduce the font
and increase the size of the chart if there are lots of them (ie more than 15) */
$totallines = $i;
if ($totallines > 15) {
$gheight = 320 + (6.7 * ($totallines - 15));
} else {
$gheight = 320;
}
if (!$type) {
// Bar chart
$DataSet = new pData();
$counter = 0;
$maxyvalue = 0;
foreach ($grawdata as $datapoint) {
$DataSet->AddPoint(array($datapoint), "Serie" . $counter);
$DataSet->AddSerie("Serie" . $counter);
$counter++;
if ($datapoint > $maxyvalue) {
$maxyvalue = $datapoint;
}
}
if ($sLanguageCode == 'ar') {
if (!class_exists('I18N_Arabic_Glyphs', false)) {
$Arabic = new I18N_Arabic('Glyphs');
} else {
$Arabic = new I18N_Arabic_Glyphs();
}
foreach ($lbl as $kkey => $kval) {
if (preg_match("^[A-Za-z]^", $kkey)) {
//auto detect if english
$lblout[] = $kkey . ' (' . $kval . ')';
} else {
$lblout[] = $Arabic->utf8Glyphs($kkey . ' )' . $kval . '(');
}
}
} elseif (getLanguageRTL($sLanguageCode)) {
foreach ($lbl as $kkey => $kval) {
$lblout[] = UTF8Strrev($kkey . ' )' . $kval . '(');
}
} else {
foreach ($lbl as $kkey => $kval) {
$lblout[] = $kkey . ' (' . $kval . ')';
}
}
$counter = 0;
foreach ($lblout as $sLabelName) {
$DataSet->SetSerieName(html_entity_decode($sLabelName, null, 'UTF-8'), "Serie" . $counter);
$counter++;
}
if ($cache->IsInCache("graph" . $iSurveyID . $sLanguageCode . $iQuestionID, $DataSet->GetData()) && Yii::app()->getConfig('debug') < 2) {
$cachefilename = basename($cache->GetFileFromCache("graph" . $iSurveyID . $sLanguageCode . $iQuestionID, $DataSet->GetData()));
} else {
$graph = new pChart(1, 1);
$graph->setFontProperties($rootdir . DIRECTORY_SEPARATOR . 'assets' . DIRECTORY_SEPARATOR . 'fonts' . DIRECTORY_SEPARATOR . $chartfontfile, $chartfontsize);
$legendsize = $graph->getLegendBoxSize($DataSet->GetDataDescription());
if ($legendsize[1] < 320) {
$gheight = 420;
} else {
$gheight = $legendsize[1] + 100;
}
$graph = new pChart(690 + $legendsize[0], $gheight);
$graph->drawFilledRectangle(0, 0, 690 + $legendsize[0], $gheight, 254, 254, 254, false);
$graph->loadColorPalette(Yii::app()->getConfig('styledir') . DIRECTORY_SEPARATOR . $admintheme . DIRECTORY_SEPARATOR . 'images/limesurvey.pal');
$graph->setFontProperties($rootdir . DIRECTORY_SEPARATOR . 'assets' . DIRECTORY_SEPARATOR . 'fonts' . DIRECTORY_SEPARATOR . $chartfontfile, $chartfontsize);
$graph->setGraphArea(50, 30, 500, $gheight - 60);
$graph->drawFilledRoundedRectangle(7, 7, 523 + $legendsize[0], $gheight - 7, 5, 254, 255, 254);
$graph->drawRoundedRectangle(5, 5, 525 + $legendsize[0], $gheight - 5, 5, 230, 230, 230);
$graph->drawGraphArea(254, 254, 254, true);
$graph->drawScale($DataSet->GetData(), $DataSet->GetDataDescription(), SCALE_START0, 150, 150, 150, true, 90, 0, true, 5, false);
$graph->drawGrid(4, true, 230, 230, 230, 50);
// Draw the 0 line
$graph->setFontProperties($rootdir . DIRECTORY_SEPARATOR . 'assets' . DIRECTORY_SEPARATOR . 'fonts' . DIRECTORY_SEPARATOR . $chartfontfile, $chartfontsize);
$graph->drawTreshold(0, 143, 55, 72, true, true);
// Draw the bar graph
$graph->drawBarGraph($DataSet->GetData(), $DataSet->GetDataDescription(), false);
//$Test->setLabel($DataSet->GetData(),$DataSet->GetDataDescription(),"Serie4","1","Important point!");
// Finish the graph
$graph->setFontProperties($rootdir . DIRECTORY_SEPARATOR . 'assets' . DIRECTORY_SEPARATOR . 'fonts' . DIRECTORY_SEPARATOR . $chartfontfile, $chartfontsize);
$graph->drawLegend(510, 30, $DataSet->GetDataDescription(), 250, 250, 250);
$cache->WriteToCache("graph" . $iSurveyID . $sLanguageCode . $iQuestionID, $DataSet->GetData(), $graph);
$cachefilename = basename($cache->GetFileFromCache("graph" . $iSurveyID . $sLanguageCode . $iQuestionID, $DataSet->GetData()));
unset($graph);
}
} //end if (bar chart)
//Pie Chart
else {
// this block is to remove the items with value == 0
// and an inelegant way to remove comments from List with Comments questions
$i = 0;
$j = 0;
$labelTmp = array();
while (isset($gdata[$i])) {
$aHelperArray = array_keys($lbl);
if ($gdata[$i] == 0 || ($sQuestionType == Question::QT_O_LIST_WITH_COMMENT && substr($aHelperArray[$i], 0, strlen(gT("Comments"))) == gT("Comments"))) {
array_splice($gdata, $i, 1);
} else {
$i++;
$labelTmp = $labelTmp + array_slice($lbl, $j, 1, true); // Preserve numeric keys for the labels!
}
$j++;
}
$lbl = $labelTmp;
if ($sLanguageCode == 'ar') {
if (!class_exists('I18N_Arabic_Glyphs', false)) {
$Arabic = new I18N_Arabic('Glyphs');
} else {
$Arabic = new I18N_Arabic_Glyphs();
}
foreach ($lbl as $kkey => $kval) {
if (preg_match("^[A-Za-z]^", $kkey)) {
//auto detect if english
$lblout[] = $kkey . ' (' . $kval . ')';
} else {
$lblout[] = $Arabic->utf8Glyphs($kkey . ' )' . $kval . '(');
}
}
} elseif (getLanguageRTL($sLanguageCode)) {
foreach ($lbl as $kkey => $kval) {
$lblout[] = UTF8Strrev(html_entity_decode($kkey, null, 'UTF-8') . ' )' . $kval . '(');
}
} else {
foreach ($lbl as $kkey => $kval) {
$lblout[] = html_entity_decode($kkey, null, 'UTF-8') . ' (' . $kval . ')';
}
}
//create new 3D pie chart
$DataSet = new pData();
$DataSet->AddPoint($gdata, "Serie1");
$DataSet->AddPoint($lblout, "Serie2");
$DataSet->AddAllSeries();
$DataSet->SetAbsciseLabelSerie("Serie2");
if ($cache->IsInCache("graph" . $iSurveyID . $sLanguageCode . $iQuestionID, $DataSet->GetData()) && Yii::app()->getConfig('debug') < 2) {
$cachefilename = basename($cache->GetFileFromCache("graph" . $iSurveyID . $sLanguageCode . $iQuestionID, $DataSet->GetData()));
} else {
$gheight = ceil($gheight);
$graph = new pChart(690, $gheight);
$graph->drawFilledRectangle(0, 0, 690, $gheight, 254, 254, 254, false);
$graph->loadColorPalette($homedir . '/assets/styles/' . $admintheme . '/images/limesurvey.pal');
$graph->drawFilledRoundedRectangle(7, 7, 687, $gheight - 3, 5, 254, 255, 254);
$graph->drawRoundedRectangle(5, 5, 689, $gheight - 1, 5, 230, 230, 230);
// Draw the pie chart
$graph->setFontProperties($rootdir . DIRECTORY_SEPARATOR . 'assets' . DIRECTORY_SEPARATOR . 'fonts' . DIRECTORY_SEPARATOR . $chartfontfile, $chartfontsize);
$graph->drawPieGraph($DataSet->GetData(), $DataSet->GetDataDescription(), 225, round($gheight / 2), 170, PIE_PERCENTAGE, true, 50, 20, 5);
$graph->setFontProperties($rootdir . DIRECTORY_SEPARATOR . 'assets' . DIRECTORY_SEPARATOR . 'fonts' . DIRECTORY_SEPARATOR . $chartfontfile, $chartfontsize);
$graph->drawPieLegend(430, 12, $DataSet->GetData(), $DataSet->GetDataDescription(), 250, 250, 250);
$cache->WriteToCache("graph" . $iSurveyID . $sLanguageCode . $iQuestionID, $DataSet->GetData(), $graph);
$cachefilename = basename($cache->GetFileFromCache("graph" . $iSurveyID . $sLanguageCode . $iQuestionID, $DataSet->GetData()));
unset($graph);
}
} //end else -> pie charts
}
return $cachefilename;
}
/**
* Return data to populate a Google Map
* @param string$sField Field name
* @param $qsid Survey id
* @param string $sField
* @return array
*/
function getQuestionMapData($sField, $qsid)
{
$aresult = SurveyDynamic::model($qsid)->findAll();
$d = array();
//loop through question data
foreach ($aresult as $arow) {
$alocation = explode(";", $arow->$sField);
if (count($alocation) >= 2) {
$d[] = "{$alocation[0]} {$alocation[1]}";
}
}
return $d;
}
/** Builds the list of addon SQL select statements
* that builds the query result set
*
* @param array $allfields An array containing the names of the fields/answers we want to display in the statistics summary
* @param integer $surveyid
* @param string $language The language to use
*
* @return array $selects array of individual select statements that can be added/appended to
* the 'where' portion of a SQL statement to restrict the result set
* ie: array("`FIELDNAME`='Y'", "`FIELDNAME2`='Hello'");
*
*/
function buildSelects($allfields, $surveyid, $language)
{
//Create required variables
$selects = array();
$aQuestionMap = array();
$survey = Survey::model()->findByPk($surveyid);
$fieldmap = createFieldMap($survey, "full", false, false, $language);
foreach ($fieldmap as $field) {
if (isset($field['qid']) && $field['qid'] != '') {
$aQuestionMap[] = $field['sid'] . 'X' . $field['gid'] . 'X' . $field['qid'];
}
}
// creates array of post variable names
for (reset($_POST); $key = key($_POST); next($_POST)) {
$postvars[] = $key;
}
/*
* Iterate through postvars to create "nice" data for SQL later.
*
* Remember there might be some filters applied which have to be put into an SQL statement
*
* This foreach iterates through the name ($key) of each post value and builds a SELECT
* statement out of it. It returns an array called $selects[] which will have a select query
* for each filter chosen. ie: $select[0]="`74X71X428EXP` ='Y'";
*
* This array is used later to build the overall query used to limit the number of responses
*
*/
if (isset($postvars)) {
foreach ($postvars as $pv) {
//Only do this if there is actually a value for the $pv
if (
in_array($pv, $allfields) || in_array(substr($pv, 1), $aQuestionMap) || in_array($pv, $aQuestionMap)
|| (
(
$pv[0] == 'D' || $pv[0] == 'N' || $pv[0] == 'K'
)
&& (in_array(substr($pv, 1, strlen($pv) - 2), $aQuestionMap) || in_array(substr($pv, 1, strlen($pv) - 3), $aQuestionMap) || in_array(substr($pv, 1, strlen($pv) - 5), $aQuestionMap))
)
) {
$firstletter = substr($pv, 0, 1);
}
/*
* these question types WON'T be handled here:
* M = Multiple choice
* T - Long free text
* Q - Multiple Short Text
* D - Date
* N - Numerical Input
* | - File Upload
* K - Multiple Numerical Input
*/
if (
$pv != "sid" && $pv != "display" && $firstletter != "M" && $firstletter != "P" && $firstletter != "T" &&
$firstletter != "Q" && $firstletter != "D" && $firstletter != "N" && $firstletter != "K" && $firstletter != "|" &&
$pv != "summary" && substr($pv, 0, 2) != "id" && substr($pv, 0, 9) != "datestamp"
) {
//pull out just the fieldnames
//put together some SQL here
$thisquestion = Yii::app()->db->quoteColumnName($pv) . " IN (";
foreach ($_POST[$pv] as $condition) {
$thisquestion .= "'$condition', ";
}
$thisquestion = substr($thisquestion, 0, -2)
. ")";
//we collect all the to be selected data in this array
$selects[] = $thisquestion;
}
//M - Multiple choice
//P - Multiple choice with comments
elseif ($firstletter == "M" || $firstletter == "P") {
$mselects = array();
//create a list out of the $pv array
list($lsid, $lgid, $lqid) = explode("X", $pv);
$aresult = Question::model()->findAll(array('order' => 'question_order', 'condition' => 'parent_qid=:parent_qid AND scale_id=0', 'params' => array(":parent_qid" => $lqid)));
foreach ($aresult as $arow) {
// only add condition if answer has been chosen
if (in_array($arow['title'], $_POST[$pv])) {
$mselects[] = Yii::app()->db->quoteColumnName(substr($pv, 1, strlen($pv)) . $arow['title']) . " = 'Y'";
}
}
/* If there are mutliple conditions generated from this multiple choice question, join them using the boolean "OR" */
if ($mselects) {
$thismulti = implode(" OR ", $mselects);
$selects[] = "($thismulti)";
unset($mselects);
}
}
//N - Numerical Input
//K - Multiple Numerical Input
elseif ($firstletter == "N" || $firstletter == "K") {
//value greater than
if (substr($pv, strlen($pv) - 1, 1) == "G" && $_POST[$pv] != "") {
$selects[] = Yii::app()->db->quoteColumnName(substr($pv, 1, -1)) . " > " . sanitize_int($_POST[$pv]);
}
//value less than
if (substr($pv, strlen($pv) - 1, 1) == "L" && $_POST[$pv] != "") {
$selects[] = Yii::app()->db->quoteColumnName(substr($pv, 1, -1)) . " < " . sanitize_int($_POST[$pv]);
}
}
//| - File Upload Question Type
elseif ($firstletter == "|") {
// no. of files greater than
if (substr($pv, strlen($pv) - 1, 1) == "G" && $_POST[$pv] != "") {
$selects[] = Yii::app()->db->quoteColumnName(substr($pv, 1, -1) . "_filecount") . " > " . sanitize_int($_POST[$pv]);
}
// no. of files less than
if (substr($pv, strlen($pv) - 1, 1) == "L" && $_POST[$pv] != "") {
$selects[] = Yii::app()->db->quoteColumnName(substr($pv, 1, -1) . "_filecount") . " < " . sanitize_int($_POST[$pv]);
}
}
//"id" is a built in field, the unique database id key of each response row
elseif (substr($pv, 0, 2) == "id") {
if (substr($pv, strlen($pv) - 1, 1) == "G" && $_POST[$pv] != "") {
$selects[] = Yii::app()->db->quoteColumnName(substr($pv, 0, -1)) . " > " . sanitize_int($_POST[$pv]);
}
if (substr($pv, strlen($pv) - 1, 1) == "L" && $_POST[$pv] != "") {
$selects[] = Yii::app()->db->quoteColumnName(substr($pv, 0, -1)) . " < " . sanitize_int($_POST[$pv]);
}
}
//T - Long free text
//Q - Multiple Short Text
elseif (($firstletter == "T" || $firstletter == "Q") && $_POST[$pv] != "") {
$selectSubs = array();
//We intepret and * and % as wildcard matches, and use ' OR ' and , as the separators
$pvParts = explode(",", str_replace('*', '%', str_replace(' OR ', ',', $_POST[$pv])));
if (is_array($pvParts) and count($pvParts)) {
foreach ($pvParts as $pvPart) {
$selectSubs[] = Yii::app()->db->quoteColumnName(substr($pv, 1, strlen($pv))) . " LIKE " . App()->db->quoteValue($pvPart);
}
if (count($selectSubs)) {
$selects[] = ' (' . implode(' OR ', $selectSubs) . ') ';
}
}
}
//D - Date
elseif ($firstletter == "D" && $_POST[$pv] != "") {
//Date equals
if (substr($pv, -2) == "eq") {
$selects[] = Yii::app()->db->quoteColumnName(substr($pv, 1, strlen($pv) - 3)) . " = " . App()->db->quoteValue($_POST[$pv]);
} else {
//date less than
if (substr($pv, -4) == "less") {
$selects[] = Yii::app()->db->quoteColumnName(substr($pv, 1, strlen($pv) - 5)) . " >= " . App()->db->quoteValue($_POST[$pv]);
}
//date greater than
if (substr($pv, -4) == "more") {
$selects[] = Yii::app()->db->quoteColumnName(substr($pv, 1, strlen($pv) - 5)) . " <= " . App()->db->quoteValue($_POST[$pv]);
}
}
}
//check for datestamp of given answer
elseif (substr($pv, 0, 9) == "datestamp") {
//timestamp equals
$formatdata = getDateFormatData(Yii::app()->session['dateformat']);
if (substr($pv, -1, 1) == "E" && !empty($_POST[$pv])) {
$datetimeobj = DateTime::createFromFormat($formatdata['phpdate'] . ' H:i', $_POST[$pv]);
$sDateValue = $datetimeobj->format("Y-m-d");
$selects[] = Yii::app()->db->quoteColumnName('datestamp') . " >= " . App()->db->quoteValue($sDateValue . " 00:00:00") . " and " . Yii::app()->db->quoteColumnName('datestamp') . " <= " . App()->db->quoteValue($sDateValue . " 23:59:59");
} else {
//timestamp less than
if (substr($pv, -1, 1) == "L" && !empty($_POST[$pv])) {
$datetimeobj = DateTime::createFromFormat($formatdata['phpdate'] . ' H:i', $_POST[$pv]);
$sDateValue = $datetimeobj->format("Y-m-d H:i:s");
$selects[] = Yii::app()->db->quoteColumnName('datestamp') . " < " . App()->db->quoteValue($sDateValue);
}
//timestamp greater than
if (substr($pv, -1, 1) == "G" && !empty($_POST[$pv])) {
$datetimeobj = DateTime::createFromFormat($formatdata['phpdate'] . ' H:i', $_POST[$pv]);
$sDateValue = $datetimeobj->format("Y-m-d H:i:s");
$selects[] = Yii::app()->db->quoteColumnName('datestamp') . " > " . App()->db->quoteValue($sDateValue);
}
}
}
}
} //end foreach -> loop through filter options to create SQL
return $selects;
}
/**
* Simple function to square a value
*
* @param mixed $number Value to square
*/
function square($number)
{
if ($number == 0) {
$squarenumber = 0;
} else {
$squarenumber = $number * $number;
}
return $squarenumber;
}
class userstatistics_helper
{
/**
* @var pdf
*/
protected $pdf;
/**
* The Excel worksheet we are working on
*
* @var Spreadsheet_Excel_Writer_Worksheet
*/
protected $sheet;
protected $xlsPercents;
protected $formatBold;
/**
* The current Excel workbook we are working on
*
* @var Writer
*/
protected $workbook;
/**
* Keeps track of the current row in Excel sheet
*
* @var int
*/
protected $xlsRow = 0;
/**
* Builds an array containing information about this particular question/answer combination
*
* @param string $rt The code passed from the statistics form listing the field/answer (SGQA) combination to be displayed
* @param mixed $language The language to present output in
* @param mixed $surveyid The survey id
* @param string $outputType
* @param boolean $browse
*
* @output array $output An array containing "alist"=>A list of answers to the question in the form of an array ($alist array
* contains an array for every field to be displayed - with the Actual Question Code/Title, The text (flattened)
* of the question, and the fieldname where the data is stored.
* "qtitle"=>The title of the question,
* "qquestion"=>The description of the question,
* "qtype"=>The question type code
*/
protected function buildOutputList($rt, $language, $surveyid, $outputType, $sql, $oLanguage, $browse = true)
{
//Set up required variables
$survey = Survey::model()->findByPk($surveyid);
$alist = array();
$qtitle = "";
$qquestion = "";
$qtype = "";
$firstletter = substr($rt, 0, 1);
$fieldmap = createFieldMap($survey, "full", false, false, $language);
$sDatabaseType = Yii::app()->db->getDriverName();
$statisticsoutput = "";
$qqid = "";
/* Some variable depend on output type, actually : only line feed */
$linefeed = $this->getLinefeed($outputType);
//M - Multiple choice, therefore multiple fields - one for each answer
if ($firstletter == "M" || $firstletter == "P") {
//get SGQ data
list($qsid, $qgid, $qqid) = explode("X", substr($rt, 1, strlen($rt)), 3);
//select details for this question
$nresult = Question::model()->with('questionl10ns')->find('language=:language AND parent_qid=0 AND t.qid=:qid', array(':language' => $language, ':qid' => $qqid));
$qtitle = $nresult->title;
$qtype = $nresult->type;
$qquestion = flattenText($nresult->questionl10ns[$language]->question);
$qlid = $nresult->parent_qid;
$qother = $nresult->other;
//1. Get list of answers
$result = Question::model()->with('questionl10ns')->findAll(array(
'order' => 'question_order',
'condition' => 'language=:language AND parent_qid=:qid AND scale_id=0',
'params' => array(':language' => $language, ':qid' => $qqid)
));
foreach ($result as $row) {
$mfield = substr($rt, 1, strlen($rt)) . $row->title;
$alist[] = array($row->title, flattenText($row->questionl10ns[$language]->question), $mfield);
}
//Add the "other" answer if it exists
if ($qother == "Y") {
$mfield = substr($rt, 1, strlen($rt)) . "other";
$alist[] = array(gT("Other"), gT("Other"), $mfield);
}
} //S - Short Free Text and T - Long free text
elseif ($firstletter == "T" || $firstletter == "S") {
//Short and long text
//search for key
$fld = substr($rt, 1, strlen($rt));
$fielddata = $fieldmap[$fld];
//get question data
$nresult = Question::model()->find('language=:language AND parent_qid=0 AND qid=:qid', array(':language' => $language, ':qid' => $fielddata['qid']));
$qtitle = $nresult->title;
$qtype = $nresult->type;
$qquestion = flattenText($nresult->question);
$mfield = substr($rt, 1, strlen($rt));
//Text questions either have an answer, or they don't. There's no other way of quantising the results.
// So, instead of building an array of predefined answers like we do with lists & other types,
// we instead create two "types" of possible answer - either there is a response.. or there isn't.
// This question type then can provide a % of the question answered in the summary.
$alist[] = array("Answer", gT("Answer"), $mfield);
$alist[] = array("NoAnswer", gT("No answer"), $mfield);
if ($qtype == Question::QT_SEMICOLON_ARRAY_MULTI_FLEX_TEXT) {
$qqid = $fielddata['qid']; // setting $qqid variable to parent qid enables graph for Array Text to be shown
}
} //Q - Multiple short text
elseif ($firstletter == "Q") {
//Build an array of legitimate qid's for testing later
$aQuestionInfo = $fieldmap[substr($rt, 1)];
$qqid = $aQuestionInfo['qid'];
$qaid = $aQuestionInfo['aid'];
//get question data
$nresult = Question::model()->find('language=:language AND parent_qid=0 AND qid=:qid', array(':language' => $language, ':qid' => $qqid));
$qtitle = $nresult->title;
$qtype = $nresult->type;
$qquestion = flattenText($nresult->question);
//get answers / subquestion text
$nresult = Question::model()->find(array(
'order' => 'question_order',
'condition' => 'language=:language AND parent_qid=:parent_qid AND title=:title',
'params' => array(':language' => $language, ':parent_qid' => $qqid, ':title' => $qaid)
));
$atext = flattenText($nresult->question);
//add this to the question title
$qtitle .= " [$atext]";
//even more substrings...
$mfield = substr($rt, 1, strlen($rt));
//Text questions either have an answer, or they don't. There's no other way of quantising the results.
// So, instead of building an array of predefined answers like we do with lists & other types,
// we instead create two "types" of possible answer - either there is a response.. or there isn't.
// This question type then can provide a % of the question answered in the summary.
$alist[] = array("Answer", gT("Answer"), $mfield);
$alist[] = array("NoAnswer", gT("No answer"), $mfield);
} //RANKING OPTION
elseif ($firstletter == "R") {
//getting the needed IDs somehow
$lengthofnumeral = substr($rt, strpos($rt, "-") + 1, 1);
list($qsid, $qgid, $qqid) = explode("X", substr($rt, 1, strpos($rt, "-") - ($lengthofnumeral + 1)), 3);
//get question data
$nresult = Question::model()->with('questionl10ns')->findAll(array(
'order' => 'question_order',
'condition' => 'language=:language AND t.qid=:qid',
'params' => array(':language' => $language, ':qid' => $qqid)
));
//loop through question data
foreach ($nresult as $nrow) {
$qtitle = flattenText($nrow->title) . " [" . substr($rt, strpos($rt, "-") - ($lengthofnumeral), $lengthofnumeral) . "]";
$qtype = $nrow->type;
$qquestion = flattenText($nrow->questionl10ns[$language]->question) . "[" . gT("Ranking") . " " . substr($rt, strpos($rt, "-") - ($lengthofnumeral), $lengthofnumeral) . "]";
}
//get answers
$result = Answer::model()->with('answerl10ns')->findAll([
'condition' => 'language=:language AND qid=:qid',
'params' => [':language' => $language, ':qid' => $qqid],
'order' => 'sortorder'
]);
//loop through answers
foreach ($result as $row) {
//create an array containing answer code, answer and fieldname(??)
$mfield = substr($rt, 1, strpos($rt, "-") - 1);
$alist[] = array("$row->code", flattenText($row->answerl10ns[$language]->answer), $mfield);
}
} else {
if ($firstletter == "|") {
// File Upload
//get SGQ data
list($qsid, $qgid, $qqid) = explode("X", substr($rt, 1, strlen($rt)), 3);
//select details for this question
/**
* FIXME $iQuestionIDlength not defined!!
*/
$nresult = Question::model()->find('language=:language AND parent_qid=0 AND qid=:qid', array(':language' => $language, ':qid' => substr($qqid, 0, $iQuestionIDlength)));
$qtitle = $nresult->title;
$qtype = $nresult->type;
$qquestion = flattenText($nresult->question);
/*
4) Average size of file per respondent
5) Average no. of files
5) Summary/count of file types (ie: 37 jpg, 65 gif, 12 png)
6) Total size of all files (useful if you re about to download them all)
7) You could also add things like smallest file size, largest file size, median file size
8) no. of files corresponding to each extension
9) max file size
10) min file size
*/
// 1) Total number of files uploaded
// 2) Number of respondents who uploaded at least one file (with the inverse being the number of respondents who didn t upload any)
$fieldname = substr($rt, 1, strlen($rt));
$query = "SELECT SUM(" . Yii::app()->db->quoteColumnName($fieldname . '_filecount') . ") as sum, AVG(" . Yii::app()->db->quoteColumnName($fieldname . '_filecount') . ") as avg FROM {{survey_$surveyid}}";
$result = Yii::app()->db->createCommand($query)->query();
$showem = array();
foreach ($result->readAll() as $row) {
$showem[] = array(gT("Total number of files"), $row['sum']);
$showem[] = array(gT("Average no. of files per respondent"), $row['avg']);
}
$query = "SELECT " . $fieldname . " as json FROM {{survey_$surveyid}}";
$result = Yii::app()->db->createCommand($query)->query();
$responsecount = 0;
$filecount = 0;
$size = 0;
foreach ($result->readAll() as $row) {
$json = $row['json'];
$phparray = json_decode($json);
foreach ($phparray as $metadata) {
$size += (int)$metadata->size;
$filecount++;
}
$responsecount++;
}
$showem[] = array(gT("Total size of files"), $size . " KB");
$showem[] = array(gT("Average file size"), $size / $filecount . " KB");
$showem[] = array(gT("Average size per respondent"), $size / $responsecount . " KB");
/* $query="SELECT title, question FROM {{questions}} WHERE parent_qid='$qqid' AND language='{$language}' ORDER BY question_order";
$result=db_execute_num($query) or safeDie("Couldn't get list of subquestions for multitype<br />$query<br />");
//loop through multiple answers
while ($row=$result->FetchRow())
{
$mfield=substr($rt, 1, strlen($rt))."$row[0]";
//create an array containing answer code, answer and fieldname(??)
$alist[]=array("$row[0]", flattenText($row[1]), $mfield);
}
*/
//outputting
switch ($outputType) {
case 'xls':
$xlsTitle = sprintf(gT("Summary for %s"), html_entity_decode($qtitle, ENT_QUOTES, 'UTF-8'));
$xlsDesc = html_entity_decode($qquestion, ENT_QUOTES, 'UTF-8');
$this->xlsRow++;
$this->xlsRow++;
$this->xlsRow++;
$this->sheet->write($this->xlsRow, 0, $xlsTitle);
$this->xlsRow++;
$this->sheet->write($this->xlsRow, 0, $xlsDesc);
$this->xlsRow++;
$this->sheet->write($this->xlsRow, 0, gT("Calculation"));
$this->sheet->write($this->xlsRow, 1, gT("Result"));
break;
case 'pdf':
$headPDF = array();
$headPDF[] = array(gT("Calculation"), gT("Result"));
break;
case 'html':
$statisticsoutput .= "\n<table class='table table-striped statisticstable' >\n"
. "\t<thead><tr><th colspan='2' class='text-center'><strong>" . sprintf(gT("Summary for %s"), $qtitle) . ":</strong>"
. "</th></tr>\n"
. "\t<tr><th colspan='2' class='text-left'><strong>$qquestion</strong></th></tr>\n"
. "\t<tr>\n\t\t<th width='50%' class='text-right'><strong>"
. gT("Calculation") . "</strong></th>\n"
. "\t\t<th width='50%' class='text-right'><strong>"
. gT("Result") . "</strong></th>\n"
. "\t</tr></thead>\n";
foreach ($showem as $res) {
$statisticsoutput .= "<tr><td>" . $res[0] . "</td><td>" . $res[1] . "</td></tr>";
}
break;
default:
break;
}
}
//N = numerical input
//K = multiple numerical input
elseif ($firstletter == "N" || $firstletter == "K") {
//NUMERICAL TYPE
//Zero handling
if (!isset($excludezeros)) {
//If this hasn't been set, set it to on as default:
$excludezeros = 1;
}
//check last character, greater/less/equals don't need special treatment
if (substr($rt, -1) == "G" || substr($rt, -1) == "L" || substr($rt, -1) == "=") {
//DO NOTHING
} else {
$showem = array();
$fld = substr($rt, 1, strlen($rt));
$fielddata = $fieldmap[$fld];
$qtitle = flattenText($fielddata['title']);
$qtype = $fielddata['type'];
$qquestion = $fielddata['question'];
//Get answer texts for multiple numerical
if (substr($rt, 0, 1) == "K") {
//put single items in brackets at output
$qtitle .= " [" . $fielddata['subquestion'] . "]";
}
//outputting
switch ($outputType) {
case 'xls':
$xlsTitle = sprintf(gT("Summary for %s"), html_entity_decode($qtitle, ENT_QUOTES, 'UTF-8'));
$xlsDesc = html_entity_decode($qquestion, ENT_QUOTES, 'UTF-8');
$this->xlsRow++;
$this->xlsRow++;
$this->xlsRow++;
$this->sheet->write($this->xlsRow, 0, $xlsTitle);
$this->xlsRow++;
$this->sheet->write($this->xlsRow, 0, $xlsDesc);
$this->xlsRow++;
$this->sheet->write($this->xlsRow, 0, gT("Calculation"));
$this->sheet->write($this->xlsRow, 1, gT("Result"));
break;
case 'pdf':
$headPDF = array();
$tablePDF = array();
$footPDF = array();
$pdfTitle = sprintf(gT("Summary for %s"), html_entity_decode($qtitle, ENT_QUOTES, 'UTF-8'));
$titleDesc = html_entity_decode($qquestion, ENT_QUOTES, 'UTF-8');
$headPDF[] = array(gT("Calculation"), gT("Result"));
break;
case 'html':
// Multiple numerical and numerical field summary
$statisticsoutput .= "\n<div class='well'><table class='table table-striped statisticstable' >\n"
. "\t<thead><tr><th colspan='2' class='text-center'><strong>" . sprintf(gT("Summary for %s"), $qtitle) . ":</strong>"
. "</th></tr>\n"
. "\t<tr><th colspan='2' class='text-center'><strong>$qquestion</strong></th></tr>\n"
. "\t<tr>\n\t\t<th width='50%' style='text-align:left'><strong>"
. gT("Calculation") . "</strong></th>\n"
. "\t\t<th width='50%' style='text-align:right'><strong>"
. gT("Result") . "</strong></th>\n"
. "\t</tr></thead>\n";
break;
default:
break;
}
//this field is queried using mathematical functions
$fieldname = substr($rt, 1, strlen($rt));
//special treatment for MS SQL databases
if ($sDatabaseType == 'mssql' || $sDatabaseType == 'sqlsrv' || $sDatabaseType == 'dblib') {
//standard deviation
$query = "SELECT STDEVP(" . Yii::app()->db->quoteColumnName($fieldname) . "*1) as stdev";
} //other databases (MySQL, Postgres)
else {
//standard deviation
$query = "SELECT STDDEV(" . Yii::app()->db->quoteColumnName($fieldname) . ") as stdev";
}
//sum
$query .= ", SUM(" . Yii::app()->db->quoteColumnName($fieldname) . "*1) as sum";
//average
$query .= ", AVG(" . Yii::app()->db->quoteColumnName($fieldname) . "*1) as average";
//min
$query .= ", MIN(" . Yii::app()->db->quoteColumnName($fieldname) . "*1) as minimum";
//max
$query .= ", MAX(" . Yii::app()->db->quoteColumnName($fieldname) . "*1) as maximum";
//Only select responses where there is an actual number response, ignore nulls and empties (if these are included, they are treated as zeroes, and distort the deviation/mean calculations)
//special treatment for MS SQL databases
if ($sDatabaseType == 'mssql' || $sDatabaseType == 'sqlsrv' || $sDatabaseType == 'dblib') {
//no NULL/empty values please
$query .= " FROM {{survey_$surveyid}} WHERE " . Yii::app()->db->quoteColumnName($fieldname) . " IS NOT NULL";
if (!$excludezeros) {
//NO ZERO VALUES
$query .= " AND (" . Yii::app()->db->quoteColumnName($fieldname) . " <> 0)";
}
} //other databases (MySQL, Postgres)
else {
//no NULL/empty values please
$query .= " FROM {{survey_$surveyid}} WHERE " . Yii::app()->db->quoteColumnName($fieldname) . " IS NOT NULL";
if (!$excludezeros) {
//NO ZERO VALUES
$query .= " AND (" . Yii::app()->db->quoteColumnName($fieldname) . " != 0)";
}
}
//filter incomplete answers if set
if (incompleteAnsFilterState() == "incomplete") {
$query .= " AND submitdate is null";
} elseif (incompleteAnsFilterState() == "complete") {
$query .= " AND submitdate is not null";
}
//$sql was set somewhere before
if (!empty($sql)) {
$query .= " AND $sql";
}
//execute query
$result = Yii::app()->db->createCommand($query)->queryAll();
//get calculated data
foreach ($result as $row) {
//put translation of mean and calculated data into $showem array
$showem[] = array(gT("Sum"), $row['sum']);
$showem[] = array(gT("Standard deviation"), round($row['stdev'], 2));
$showem[] = array(gT("Average"), round($row['average'], 2));
$showem[] = array(gT("Minimum"), $row['minimum']);
//Display the maximum and minimum figures after the quartiles for neatness
$maximum = $row['maximum'];
}
//CALCULATE QUARTILES
$medcount = $this->getQuartile(0, $fieldname, $surveyid, $sql, $excludezeros); // Get the recordcount
$quartiles = array();
$quartiles[1] = $this->getQuartile(1, $fieldname, $surveyid, $sql, $excludezeros);
$quartiles[2] = $this->getQuartile(2, $fieldname, $surveyid, $sql, $excludezeros);
$quartiles[3] = $this->getQuartile(3, $fieldname, $surveyid, $sql, $excludezeros);
//we just put the total number of records at the beginning of this array
array_unshift($showem, array(gT("Count"), $medcount));
/* IMPORTANT IMPORTANT IMPORTANT IMPORTANT IMPORTANT IMPORTANT */
/* IF YOU DON'T UNDERSTAND WHAT QUARTILES ARE DO NOT MODIFY THIS CODE */
/* Quartiles and Median values are NOT related to average, and the sum is irrelevent */
if (isset($quartiles[1])) {
$showem[] = array(gT("1st quartile (Q1)"), $quartiles[1]);
}
if (isset($quartiles[2])) {
$showem[] = array(gT("2nd quartile (Median)"), $quartiles[2]);
}
if (isset($quartiles[3])) {
$showem[] = array(gT("3rd quartile (Q3)"), $quartiles[3]);
}
$showem[] = array(gT("Maximum"), $maximum);
//output results
foreach ($showem as $shw) {