/
statistics_function.php
3144 lines (2539 loc) · 147 KB
/
statistics_function.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 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.
*
* $Id: statistics.php 7134 2009-06-17 15:08:47Z wahrendorff $
*
*/
/*
* We need this later:
* 1 - Array Dual Scale
* 5 - 5 Point Choice
* A - Array (5 Point Choice)
* B - Array (10 Point Choice)
* C - Array (Yes/No/Uncertain)
* D - Date
* E - Array (Increase, Same, Decrease)
* F - Array
* G - Gender
* H - Array by column
* I - Language Switch
* K - Multiple Numerical Input
* L - List (Radio)
* M - Multiple Options
* N - Numerical Input
* O - List With Comment
* P - Multiple Options 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 multiple drop down
* ; - Array multiple texts
Debugging help:
echo '<script language="javascript" type="text/javascript">alert("HI");</script>';
*/
//split up results to extend statistics -> NOT WORKING YET! DO NOT ENABLE THIS!
//$showcombinedresults = 0;
//don't call this script directly!
if (isset($_REQUEST['homedir'])) {die('You cannot start this script directly');}
/**
* Generates statistics
*
* @param int $surveyid The survey id
* @param mixed $allfields
* @param mixed $q2show
* @param mixed $usegraph
* @param string $outputType Optional - Can be xls, html or pdf - Defaults to pdf
* @param string $pdfOutput Sets the target for the PDF output: DD=File download , F=Save file to local disk
* @param string $statlangcode Lamguage for statistics
* @param mixed $browse Show browse buttons
* @return buffer
*/
function generate_statistics($surveyid, $allfields, $q2show='all', $usegraph=0, $outputType='pdf', $pdfOutput='DD',$statlangcode=null, $browse = true)
{
//$allfields ="";
global $connect, $dbprefix, $clang,
$rooturl, $rootdir, $homedir, $homeurl, $tempdir, $tempurl, $scriptname,
$chartfontfile, $chartfontsize, $admintheme, $pdfdefaultfont, $pdffontsize;
$fieldmap=createFieldMap($surveyid, "full");
if (is_null($statlangcode))
{
$statlang=$clang;
}
else
{
$statlang = new limesurvey_lang($statlangcode);
}
/*
* this variable is used in the function shortencode() which cuts off a question/answer title
* after $maxchars and shows the rest as tooltip (in html mode)
*/
$maxchars = 13;
//we collect all the html-output within this variable
$statisticsoutput ='';
/**
* $outputType: html || pdf ||
*/
/**
* get/set Survey Details
*/
//no survey ID? -> come and get one
if (!isset($surveyid)) {$surveyid=returnglobal('sid');}
//Get an array of codes of all available languages in this survey
$surveylanguagecodes = GetAdditionalLanguagesFromSurveyID($surveyid);
$surveylanguagecodes[] = GetBaseLanguageFromSurveyID($surveyid);
// Set language for questions and answers to base language of this survey
$language=$statlangcode;
if ($usegraph==1)
{
//for creating graphs we need some more scripts which are included here
require_once(dirname(__FILE__).'/../classes/pchart/pchart/pChart.class');
require_once(dirname(__FILE__).'/../classes/pchart/pchart/pData.class');
require_once(dirname(__FILE__).'/../classes/pchart/pchart/pCache.class');
$MyCache = new pCache($tempdir.'/');
//pick the best font file if font setting is 'auto'
if ($chartfontfile=='auto')
{
$chartfontfile='vera.ttf';
if ( $language=='ar')
{
$chartfontfile='KacstOffice.ttf';
}
elseif ($language=='fa' )
{
$chartfontfile='KacstFarsi.ttf';
}
}
}
if($q2show=='all' )
{
$summarySql=" SELECT gid, parent_qid, qid, type "
." FROM {$dbprefix}questions WHERE parent_qid=0"
." AND sid=$surveyid ";
$summaryRs = db_execute_assoc($summarySql);
foreach($summaryRs as $field)
{
$myField = $surveyid."X".$field['gid']."X".$field['qid'];
// Multiple Options get special treatment
if ($field['type'] == "M") {$myField = "M$myField";}
if ($field['type'] == "P") {$myField = "P$myField";}
//numerical input will get special treatment (arihtmetic mean, standard derivation, ...)
if ($field['type'] == "N") {$myField = "N$myField";}
if ($field['type'] == "Q") {$myField = "Q$myField";}
// textfields get special treatment
if ($field['type'] == "S" || $field['type'] == "T" || $field['type'] == "U"){$myField = "T$myField";}
//statistics for Date questions are not implemented yet.
if ($field['type'] == "D") {$myField = "D$myField";}
if ($field['type'] == "F" || $field['type'] == "H")
{
//Get answers. We always use the answer code because the label might be too long elsewise
$query = "SELECT code, answer FROM ".db_table_name("answers")." WHERE qid='".$field['qid']."' AND scale_id=0 AND language='{$language}' ORDER BY sortorder, answer";
$result = db_execute_num($query) or safe_die ("Couldn't get answers!<br />$query<br />".$connect->ErrorMsg());
$counter2=0;
//check all the answers
while ($row=$result->FetchRow())
{
$myField = "$myField{$row[0]}";
}
//$myField = "{$surveyid}X{$flt[1]}X{$flt[0]}{$row[0]}[]";
}
if($q2show=='all')
$summary[]=$myField;
//$allfields[]=$myField;
}
}
else
{
// This gets all the 'to be shown questions' from the POST and puts these into an array
if (!is_array($q2show))
$summary = returnglobal('summary');
else
$summary = $q2show;
//print_r($_POST);
//if $summary isn't an array we create one
if (isset($summary) && !is_array($summary))
{
$summary = explode("+", $summary);
}
}
/**
* pdf Config
*/
if($outputType=='pdf')
{
require_once('classes/tcpdf/config/lang/eng.php');
require_once('classes/tcpdf/mypdf.php');
// create new PDF document
$pdf = new MyPDF();
$pdf->SetFont($pdfdefaultfont,'',$pdffontsize);
$surveyInfo = getSurveyInfo($surveyid,$language);
// set document information
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('LimeSurvey');
$pdf->SetTitle('Statistic Survey '.$surveyid);
$pdf->SetSubject($surveyInfo['surveyls_title']);
$pdf->SetKeywords('LimeSurvey, Statistics, Survey '.$surveyid.'');
$pdf->SetDisplayMode('fullpage', 'two');
// set header and footer fonts
$pdf->setHeaderFont(Array($pdfdefaultfont, '', PDF_FONT_SIZE_MAIN));
$pdf->setFooterFont(Array($pdfdefaultfont, '', PDF_FONT_SIZE_DATA));
// set default header data
$pdf->SetHeaderData("statistics.png", 10, $statlang->gT("Quick statistics",'unescaped') , $statlang->gT("Survey")." ".$surveyid." '".html_entity_decode($surveyInfo['surveyls_title'],ENT_QUOTES,'UTF-8')."'");
// set default monospaced font
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
//set margins
$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
//set auto page breaks
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
//set image scale factor
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
//set some language-dependent strings
$pdf->setLanguageArray($l);
}
if($outputType=='xls')
{
/**
* Initiate the Spreadsheet_Excel_Writer
*/
include_once(dirname(__FILE__)."/classes/pear/Spreadsheet/Excel/Writer.php");
if($pdfOutput=='F')
$workbook = new Spreadsheet_Excel_Writer($tempdir.'/statistic-survey'.$surveyid.'.xls');
else
$workbook = new Spreadsheet_Excel_Writer();
$workbook->setVersion(8);
// Inform the module that our data will arrive as UTF-8.
// Set the temporary directory to avoid PHP error messages due to open_basedir restrictions and calls to tempnam("", ...)
if (!empty($tempdir)) {
$workbook->setTempDir($tempdir);
}
if($pdfOutput!='F')
$workbook->send('statistic-survey'.$surveyid.'.xls');
// Creating the first worksheet
$sheet =& $workbook->addWorksheet(utf8_decode('results-survey'.$surveyid));
$sheet->setInputEncoding('utf-8');
$sheet->setColumn(0,20,20);
$separator="~|";
/**XXX*/
}
/**
* Start generating
*/
// creates array of post variable names
for (reset($_POST); $key=key($_POST); next($_POST)) { $postvars[]=$key;}
$aQuestionMap=array();
foreach ($fieldmap as $field)
{
if(isset($field['qid']) && $field['qid']!='')
$aQuestionMap[]=$field['sid'].'X'.$field['gid'].'X'.$field['qid'];
}
/*
* 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
*/
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))
{
$firstletter=substr($pv,0,1);
/*
* these question types WON'T be handled here:
* M = Multiple Options
* T - Long Free Text
* Q - Multiple Short Text
* D - Date
* N - Numerical Input
* K - Multiple Numerical Input
*/
if ($pv != "sid" && $pv != "display" && $firstletter != "M" && $firstletter != "P" && $firstletter != "T" &&
$firstletter != "Q" && $firstletter != "D" && $firstletter != "N" && $firstletter != "K" &&
$pv != "summary" && substr($pv, 0, 2) != "id" && substr($pv, 0, 9) != "datestamp") //pull out just the fieldnames
{
//put together some SQL here
$thisquestion = db_quote_id($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 Options
//P - Multiple Options with comments
elseif ($firstletter == "M" || $firstletter == "P")
{
$mselects=array();
//create a list out of the $pv array
list($lsid, $lgid, $lqid) = explode("X", $pv);
$aquery="SELECT title FROM ".db_table_name("questions")." WHERE parent_qid=$lqid AND language='{$language}' and scale_id=0 ORDER BY question_order";
$aresult=db_execute_num($aquery) or safe_die ("Couldn't get subquestions<br />$aquery<br />".$connect->ErrorMsg());
// go through every possible answer
while ($arow=$aresult->FetchRow())
{
// only add condition if answer has been chosen
if (in_array($arow[0], $_POST[$pv]))
{
$mselects[]=db_quote_id(substr($pv, 1, strlen($pv)).$arow[0])." = 'Y'";
}
}
if ($mselects)
{
$thismulti=implode(" OR ", $mselects);
$selects[]="($thismulti)";
$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[]=db_quote_id(substr($pv, 1, -1))." > ".sanitize_int($_POST[$pv]);
}
//value less than
if (substr($pv, strlen($pv)-1, 1) == "L" && $_POST[$pv] != "")
{
$selects[]=db_quote_id(substr($pv, 1, -1))." < ".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[]=db_quote_id(substr($pv, 0, -1))." > '".$_POST[$pv]."'";
}
if (substr($pv, strlen($pv)-1, 1) == "L" && $_POST[$pv] != "")
{
$selects[]=db_quote_id(substr($pv, 0, -1))." < '".$_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 seperators
$pvParts = explode(",",str_replace('*','%', str_replace(' OR ',',',$_POST[$pv])));
if(is_array($pvParts) AND count($pvParts)){
foreach($pvParts AS $pvPart){
$selectSubs[]=db_quote_id(substr($pv, 1, strlen($pv)))." LIKE '".trim($pvPart)."'";
}
if(count($selectSubs)){
$selects[] = ' ('.implode(' OR ',$selectSubs).') ';
}
}
}
//D - Date
elseif ($firstletter == "D" && $_POST[$pv] != "")
{
//Date equals
if (substr($pv, -1, 1) == "=")
{
$selects[]=db_quote_id(substr($pv, 1, strlen($pv)-2))." = '".$_POST[$pv]."'";
}
else
{
//date less than
if (substr($pv, -1, 1) == "<")
{
$selects[]= db_quote_id(substr($pv, 1, strlen($pv)-2)) . " >= '".$_POST[$pv]."'";
}
//date greater than
if (substr($pv, -1, 1) == ">")
{
$selects[]= db_quote_id(substr($pv, 1, strlen($pv)-2)) . " <= '".$_POST[$pv]."'";
}
}
}
//check for datestamp of given answer
elseif (substr($pv, 0, 9) == "datestamp")
{
//timestamp equals
$formatdata=getDateFormatData($_SESSION['dateformat']);
if (substr($pv, -1, 1) == "E" && !empty($_POST[$pv]))
{
$datetimeobj = new Date_Time_Converter($_POST[$pv], $formatdata['phpdate'].' H:i');
$_POST[$pv]=$datetimeobj->convert("Y-m-d");
$selects[] = db_quote_id('datestamp')." >= '".$_POST[$pv]." 00:00:00' and ".db_quote_id('datestamp')." <= '".$_POST[$pv]." 23:59:59'";
}
else
{
//timestamp less than
if (substr($pv, -1, 1) == "L" && !empty($_POST[$pv]))
{
$datetimeobj = new Date_Time_Converter($_POST[$pv], $formatdata['phpdate'].' H:i');
$_POST[$pv]=$datetimeobj->convert("Y-m-d H:i:s");
$selects[]= db_quote_id('datestamp')." < '".$_POST[$pv]."'";
}
//timestamp greater than
if (substr($pv, -1, 1) == "G" && !empty($_POST[$pv]))
{
$datetimeobj = new Date_Time_Converter($_POST[$pv], $formatdata['phpdate'].' H:i');
$_POST[$pv]=$datetimeobj->convert("Y-m-d H:i:s");
$selects[]= db_quote_id('datestamp')." > '".$_POST[$pv]."'";
}
}
}
}
else
{
$statisticsoutput .= "<!-- $pv DOES NOT EXIST IN ARRAY -->";
}
} //end foreach -> loop through filter options to create SQL
//count number of answers
$query = "SELECT count(*) FROM ".db_table_name("survey_$surveyid");
//if incompleted answers should be filtert submitdate has to be not null
if (incompleteAnsFilterstate() == "inc") {$query .= " WHERE submitdate is null";}
elseif (incompleteAnsFilterstate() == "filter") {$query .= " WHERE submitdate is not null";}
$result = db_execute_num($query) or safe_die ("Couldn't get total<br />$query<br />".$connect->ErrorMsg());
//$total = total number of answers
while ($row=$result->FetchRow()) {$total=$row[0];}
//are there any filters that have to be taken care of?
if (isset($selects) && $selects)
{
//filter incomplete answers?
if (incompleteAnsFilterstate() == "filter" || incompleteAnsFilterstate() == "inc") {$query .= " AND ";}
else {$query .= " WHERE ";}
//add filter criteria to SQL
$query .= implode(" AND ", $selects);
}
//$_POST['sql'] is a post field that is sent from the statistics script to the export script in order
// to export just those results filtered by this statistics script. It can also be passed to the statistics
// script to filter from external scripts.
elseif (!empty($_POST['sql']) && !isset($_POST['id=']))
{
$newsql=substr($_POST['sql'], strpos($_POST['sql'], "WHERE")+5, strlen($_POST['sql']));
//for debugging only
//$query = $_POST['sql'];
//filter incomplete answers?
if (incompleteAnsFilterstate() == "inc") {$query .= " AND ".$newsql;}
elseif (incompleteAnsFilterstate() == "filter") {$query .= " AND ".$newsql;}
else {$query .= " WHERE ".$newsql;}
}
//get me some data Scotty
$result=db_execute_num($query) or safe_die("Couldn't get results<br />$query<br />".$connect->ErrorMsg());
//put all results into $results
while ($row=$result->FetchRow()) {$results=$row[0];}
if ($total)
{
$percent=sprintf("%01.2f", ($results/$total)*100);
}
switch($outputType)
{
case "xls":
$xlsRow = 0;
$sheet->write($xlsRow,0,$statlang->gT("Number of records in this query:"));
$sheet->write($xlsRow,1,$results);
++$xlsRow;
$sheet->write($xlsRow,0,$statlang->gT("Total records in survey:"));
$sheet->write($xlsRow,1,$total);
if($total)
{
++$xlsRow;
$sheet->write($xlsRow,0,$statlang->gT("Percentage of total:"));
$sheet->write($xlsRow,1,$percent."%");
}
break;
case 'pdf':
// add summary to pdf
$array = array();
//$array[] = array($statlang->gT("Results"),"");
$array[] = array($statlang->gT("Number of records in this query:"), $results);
$array[] = array($statlang->gT("Total records in survey:"), $total);
if($total)
$array[] = array($statlang->gT("Percentage of total:"), $percent."%");
$pdf->addPage('P','A4');
$pdf->Bookmark($pdf->delete_html($statlang->gT("Results")), 0, 0);
$pdf->titleintopdf($statlang->gT("Results"),$statlang->gT("Survey")." ".$surveyid);
$pdf->tableintopdf($array);
$pdf->addPage('P','A4');
break;
case 'html':
$statisticsoutput .= "<br />\n<table class='statisticssummary' >\n"
."\t<thead><tr><th colspan='2'>".$statlang->gT("Results")."</th></tr></thead>\n"
."\t<tr><th >".$statlang->gT("Number of records in this query:").'</th>'
."<td>$results</td></tr>\n"
."\t<tr><th>".$statlang->gT("Total records in survey:").'</th>'
."<td>$total</td></tr>\n";
//only calculate percentage if $total is set
if ($total)
{
$percent=sprintf("%01.2f", ($results/$total)*100);
$statisticsoutput .= "\t<tr><th align='right'>".$statlang->gT("Percentage of total:").'</th>'
."<td>$percent%</td></tr>\n";
}
$statisticsoutput .="</table>\n";
break;
default:
break;
}
//put everything from $selects array into a string connected by AND
if (isset ($selects) && $selects) {$sql=implode(" AND ", $selects);}
elseif (!empty($newsql)) {$sql = $newsql;}
if (!isset($sql) || !$sql) {$sql="NULL";}
//only continue if we have something to output
if ($results > 0)
{
if($outputType=='html' && $browse === true)
{
//add a buttons to browse results
$statisticsoutput .= "<form action='$scriptname?action=browse' method='post' target='_blank'>\n"
."\t\t<p><input type='submit' value='".$statlang->gT("Browse")."' />\n"
."\t\t\t<input type='hidden' name='sid' value='$surveyid' />\n"
."\t\t\t<input type='hidden' name='sql' value=\"$sql\" />\n"
."\t\t\t<input type='hidden' name='subaction' value='all' />\n"
."\t\t</form>";
}
} //end if (results > 0)
//Show Summary results
if (isset($summary) && $summary)
{
//let's run through the survey
$runthrough=$summary;
//START Chop up fieldname and find matching questions
//GET LIST OF LEGIT QIDs FOR TESTING LATER
$lq = "SELECT DISTINCT qid FROM ".db_table_name("questions")." WHERE sid=$surveyid and parent_qid=0";
$lr = db_execute_assoc($lq);
//loop through the IDs
while ($lw = $lr->FetchRow())
{
//this creates an array of question id's'
$legitqids[] = $lw['qid'];
}
//loop through all selected questions
foreach ($runthrough as $rt)
{
$firstletter = substr($rt, 0, 1);
// 1. Get answers for question ##############################################################
//M - Multiple Options, therefore multiple fields
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
$nquery = "SELECT title, type, question, parent_qid, other FROM ".db_table_name("questions")." WHERE language='{$language}' AND parent_qid=0 AND qid='$qqid'";
$nresult = db_execute_num($nquery) or safe_die ("Couldn't get question<br />$nquery<br />".$connect->ErrorMsg());
//loop through question data
while ($nrow=$nresult->FetchRow())
{
$qtitle=$nrow[0];
$qtype=$nrow[1];
$qquestion=FlattenText($nrow[2]);
$qlid=$nrow[3];
$qother=$nrow[4];
}
//1. Get list of answers
$query="SELECT title, question FROM ".db_table_name("questions")." WHERE parent_qid='$qqid' AND language='{$language}' and scale_id=0 ORDER BY question_order";
$result=db_execute_num($query) or safe_die("Couldn't get list of subquestions for multitype<br />$query<br />".$connect->ErrorMsg());
//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);
}
//check "other" field. is it set?
if ($qother == "Y")
{
$mfield=substr($rt, 1, strlen($rt))."other";
//create an array containing answer code, answer and fieldname(??)
$alist[]=array($statlang->gT("Other"), $statlang->gT("Other"), $mfield);
}
}
//S - Short Free Text
//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 SGQA IDs
$qsid=$fielddata['sid'];
$qgid=$fielddata['gid'];
$qqid=$fielddata['qid'];
list($qanswer, $qlid)=!empty($fielddata['aid']) ? explode("_", $fielddata['aid']) : array("", "");
//get SGQ data
//list($qsid, $qgid, $qqid) = explode("X", substr($rt, 1, strlen($rt)), 3);
//get question data
$nquery = "SELECT title, type, question, other, parent_qid FROM ".db_table_name("questions")." WHERE parent_qid=0 AND qid='$qqid' AND language='{$language}'";
$nresult = db_execute_num($nquery) or safe_die("Couldn't get text question<br />$nquery<br />".$connect->ErrorMsg());
//loop through question data
while ($nrow=$nresult->FetchRow())
{
$qtitle=FlattenText($nrow[0]);
$qtype=$nrow[1];
$qquestion=FlattenText($nrow[2]);
$nlid=$nrow[4];
}
$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("Answers", $statlang->gT("Answer"), $mfield);
$alist[]=array("NoAnswer", $statlang->gT("No answer"), $mfield);
}
//Multiple short text
elseif ($firstletter == "Q")
{
//get SGQ data
list($qsid, $qgid, $qqid) = explode("X", substr($rt, 1, strlen($rt)), 3);
//separating another ID
$tmpqid=substr($qqid, 0, strlen($qqid)-1);
//check if we have legid QIDs. if not create them by substringing
while (!in_array ($tmpqid,$legitqids)) $tmpqid=substr($tmpqid, 0, strlen($tmpqid)-1);
//length of QID
$qidlength=strlen($tmpqid);
//we somehow get the answer code (see SQL later) from the $qqid
$qaid=substr($qqid, $qidlength, strlen($qqid)-$qidlength);
//get some question data
$nquery = "SELECT title, type, question, other FROM ".db_table_name("questions")." WHERE qid='".substr($qqid, 0, $qidlength)."' AND parent_qid=0 AND language='{$language}'";
$nresult = db_execute_num($nquery) or safe_die("Couldn't get text question<br />$nquery<br />".$connect->ErrorMsg());
//more substrings
$count = substr($qqid, strlen($qqid)-1);
//loop through question data
while ($nrow=$nresult->FetchRow())
{
$qtitle=FlattenText($nrow[0]).'-'.$count;
$qtype=$nrow[1];
$qquestion=FlattenText($nrow[2]);
}
//get answers
$qquery = "SELECT title as code, question as answer FROM ".db_table_name("questions")." WHERE parent_qid='".substr($qqid, 0, $qidlength)."' AND title='$qaid' AND language='{$language}' ORDER BY question_order";
$qresult=db_execute_num($qquery) or safe_die ("Couldn't get answer details (Array 5p Q)<br />$qquery<br />".$connect->ErrorMsg());
//loop through answer data
while ($qrow=$qresult->FetchRow())
{
//store each answer here
$atext=FlattenText($qrow[1]);
}
//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("Answers", $statlang->gT("Answer"), $mfield);
$alist[]=array("NoAnswer", $statlang->gT("No answer"), $mfield);
}
//RANKING OPTION THEREFORE CONFUSING
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
$nquery = "SELECT title, type, question FROM ".db_table_name("questions")." WHERE parent_qid=0 AND qid='$qqid' AND language='{$language}'";
$nresult = db_execute_num($nquery) or safe_die ("Couldn't get question<br />$nquery<br />".$connect->ErrorMsg());
//loop through question data
while ($nrow=$nresult->FetchRow())
{
$qtitle=FlattenText($nrow[0]). " [".substr($rt, strpos($rt, "-")-($lengthofnumeral), $lengthofnumeral)."]";
$qtype=$nrow[1];
$qquestion=FlattenText($nrow[2]). "[".$statlang->gT("Ranking")." ".substr($rt, strpos($rt, "-")-($lengthofnumeral), $lengthofnumeral)."]";
}
//get answers
$query="SELECT code, answer FROM ".db_table_name("answers")." WHERE qid='$qqid' AND scale_id=0 AND language='{$language}' ORDER BY sortorder, answer";
$result=db_execute_num($query) or safe_die("Couldn't get list of answers for multitype<br />$query<br />".$connect->ErrorMsg());
//loop through answers
while ($row=$result->FetchRow())
{
//create an array containing answer code, answer and fieldname(??)
$mfield=substr($rt, 1, strpos($rt, "-")-1);
$alist[]=array("$row[0]", FlattenText($row[1]), $mfield);
}
}
//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
{
//create SGQ identifier
list($qsid, $qgid, $qqid) = explode("X", $rt, 3);
//multiple numerical input
if($firstletter == "K")
{
// This is a multiple numerical question so we need to strip of the answer id to find the question title
$tmpqid=substr($qqid, 0, strlen($qqid)-1);
//did we get a valid ID?
while (!in_array ($tmpqid,$legitqids))
$tmpqid=substr($tmpqid, 0, strlen($tmpqid)-1);
//check lenght of ID
$qidlength=strlen($tmpqid);
//get answer ID from qid
$qaid=substr($qqid, $qidlength, strlen($qqid)-$qidlength);
//get question details from DB
$nquery = "SELECT title, type, question, qid, parent_qid
FROM ".db_table_name("questions")."
WHERE parent_qid=0 AND qid='".substr($qqid, 0, $qidlength)."'
AND language='{$language}'";
$nresult = db_execute_num($nquery) or safe_die("Couldn't get text question<br />$nquery<br />".$connect->ErrorMsg());
}
//probably question type "N" = numerical input
else
{
//we can use the qqid without any editing
$nquery = "SELECT title, type, question, qid, parent_qid FROM ".db_table_name("questions")." WHERE parent_qid=0 AND qid='$qqid' AND language='{$language}'";
$nresult = db_execute_num($nquery) or safe_die ("Couldn't get question<br />$nquery<br />".$connect->ErrorMsg());
}
//loop through results
while ($nrow=$nresult->FetchRow())
{
$qtitle=FlattenText($nrow[0]); //clean up title
$qtype=$nrow[1];
$qquestion=FlattenText($nrow[2]);
$qiqid=$nrow[3];
$qlid=$nrow[4];
}
//Get answer texts for multiple numerical
if(substr($rt, 0, 1) == "K")
{
//get answer data
$atext=$connect->GetOne("SELECT question FROM ".db_table_name("questions")." WHERE parent_qid='{$qiqid}' AND scale_id=0 AND title='{$qaid}' AND language='{$language}'");
//put single items in brackets at output
$qtitle .= " [$atext]";
}
//outputting
switch($outputType)
{
case 'xls':
$headXLS = array();
$tableXLS = array();
$footXLS = array();
$xlsTitle = sprintf($statlang->gT("Field summary for %s"),html_entity_decode($qtitle,ENT_QUOTES,'UTF-8'));
$xlsDesc = html_entity_decode($qquestion,ENT_QUOTES,'UTF-8');
++$xlsRow;
++$xlsRow;
++$xlsRow;
$sheet->write($xlsRow, 0,$xlsTitle);
++$xlsRow;
$sheet->write($xlsRow, 0,$xlsDesc);
$headXLS[] = array($statlang->gT("Calculation"),$statlang->gT("Result"));
++$xlsRow;
$sheet->write($xlsRow, 0,$statlang->gT("Calculation"));
$sheet->write($xlsRow, 1,$statlang->gT("Result"));
break;
case 'pdf':
$headPDF = array();
$tablePDF = array();
$footPDF = array();
$pdfTitle = sprintf($statlang->gT("Field summary for %s"),html_entity_decode($qtitle,ENT_QUOTES,'UTF-8'));
$titleDesc = html_entity_decode($qquestion,ENT_QUOTES,'UTF-8');
$headPDF[] = array($statlang->gT("Calculation"),$statlang->gT("Result"));
break;
case 'html':
$statisticsoutput .= "\n<table class='statisticstable' >\n"
."\t<thead><tr><th colspan='2' align='center'><strong>".sprintf($statlang->gT("Field summary for %s"),$qtitle).":</strong>"
."</th></tr>\n"
."\t<tr><th colspan='2' align='center'><strong>$qquestion</strong></th></tr>\n"
."\t<tr>\n\t\t<th width='50%' align='center' ><strong>"
.$statlang->gT("Calculation")."</strong></th>\n"
."\t\t<th width='50%' align='center' ><strong>"
.$statlang->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 ($connect->databaseType == 'odbc_mssql' || $connect->databaseType == 'odbtp' || $connect->databaseType == 'mssql_n' || $connect->databaseType == 'mssqlnative')
{
//standard deviation
$query = "SELECT STDEVP(".db_quote_id($fieldname)."*1) as stdev";
}
//other databases (MySQL, Postgres)
else
{
//standard deviation
$query = "SELECT STDDEV(".db_quote_id($fieldname).") as stdev";
}
//sum
$query .= ", SUM(".db_quote_id($fieldname)."*1) as sum";
//average
$query .= ", AVG(".db_quote_id($fieldname)."*1) as average";
//min
$query .= ", MIN(".db_quote_id($fieldname)."*1) as minimum";
//max
$query .= ", MAX(".db_quote_id($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 ($connect->databaseType == 'odbc_mssql' || $connect->databaseType == 'odbtp' || $connect->databaseType == 'mssql_n' || $connect->databaseType == 'mssqlnative')
{
//no NULL/empty values please
$query .= " FROM ".db_table_name("survey_$surveyid")." WHERE ".db_quote_id($fieldname)." IS NOT NULL";
if(!$excludezeros)
{
//NO ZERO VALUES
$query .= " AND (".db_quote_id($fieldname)." <> 0)";
}
}
//other databases (MySQL, Postgres)
else
{
//no NULL/empty values please
$query .= " FROM ".db_table_name("survey_$surveyid")." WHERE ".db_quote_id($fieldname)." IS NOT NULL";
if(!$excludezeros)
{
//NO ZERO VALUES
$query .= " AND (".db_quote_id($fieldname)." != 0)";
}
}
//filter incomplete answers if set
if (incompleteAnsFilterstate() == "inc") {$query .= " AND submitdate is null";}
elseif (incompleteAnsFilterstate() == "filter") {$query .= " AND submitdate is not null";}
//$sql was set somewhere before
if ($sql != "NULL") {$query .= " AND $sql";}
//execute query
$result=db_execute_assoc($query) or safe_die("Couldn't do maths testing<br />$query<br />".$connect->ErrorMsg());
//get calculated data