/
export_helper.php
2784 lines (2467 loc) · 111 KB
/
export_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.
*
*/
/**
* Strips html tags and replaces new lines
*
* @param $string
* @return string
*/
function stripTagsFull($string)
{
$string = flattenText($string,false,true); // stripo whole + html_entities
$string = str_replace('-oth', '', $string);// Why ?
//The backslashes must be escaped twice, once for php, and again for the regexp
$string = str_replace("'|\\\\'", "'", $string);
return $string;
}
/**
* Returns true if passed $value is numeric
*
* @param $value
* @return bool
*/
function isNumericExtended($value)
{
if (empty($value)) {
return true;
}
$eng_or_world = preg_match('/^[+-]?'.// start marker and sign prefix
'(((([0-9]+)|([0-9]{1,4}(,[0-9]{3,4})+)))?(\\.[0-9])?([0-9]*)|'.// american
'((([0-9]+)|([0-9]{1,4}(\\.[0-9]{3,4})+)))?(,[0-9])?([0-9]*))'.// world
'(e[0-9]+)?'.// exponent
'$/', // end marker
$value) == 1;
return ($eng_or_world);
}
/**
* Returns splitted unicode string correctly
* source: http://www.php.net/manual/en/function.str-split.php#107658
*
* @param string $str
* @param $l
* @return string
*/
function strSplitUnicode($str, $l = 0)
{
if ($l > 0) {
$ret = array();
$len = mb_strlen($str, "UTF-8");
for ($i = 0; $i < $len; $i += $l) {
$ret[] = mb_substr($str, $i, $l, "UTF-8");
}
return $ret;
}
return preg_split("//u", $str, -1, PREG_SPLIT_NO_EMPTY);
}
/**
* Exports CSV response data for SPSS and R
*
* @param mixed $iSurveyID The survey ID
* @param string $iLength Maximum text lenght data, usually 255 for SPSS <v16 and 16384 for SPSS 16 and later
* @param string $na Value for N/A data
* @param string $q sep Quote separator. Use '\'' for SPSS, '"' for R
* @param bool $header logical $header If TRUE, adds SQGA code as column headings (used by export to R)
* @param string $sLanguage
*/
function SPSSExportData($iSurveyID, $iLength, $na = '', $q = '\'', $header = false, $sLanguage = '')
{
// Build array that has to be returned
$fields = SPSSFieldMap($iSurveyID, 'V', $sLanguage);
// Now see if we have parameters for from (offset) & num (limit)
$limit = App()->getRequest()->getParam('limit');
$offset = App()->getRequest()->getParam('offset');
//Now get the query string with all fields to export
$query = SPSSGetQuery($iSurveyID, $limit, $offset);
$result = $query->query();
$rownr = 0;
foreach ($result as $row) {
$rownr++;
if ($rownr == 1) {
$num_fields = safecount($row);
// Add column headers (used by R export)
if ($header == true) {
$i = 1;
foreach ($fields as $field) {
if (!$field['hide']) {
echo $q.strtoupper($field['sql_name']).$q;
}
if ($i < $num_fields && !$field['hide']) {
echo ',';
}
$i++;
}
echo("\n");
}
}
$row = array_change_key_case($row, CASE_UPPER);
//$row = $result->GetRowAssoc(true); //Get assoc array, use uppercase
reset($fields); //Jump to the first element in the field array
$i = 1;
foreach ($fields as $field) {
$fieldno = strtoupper($field['sql_name']);
if ($field['SPSStype'] == 'DATETIME23.2') {
// convert mysql datestamp (yyyy-mm-dd hh:mm:ss) to SPSS datetime (dd-mmm-yyyy hh:mm:ss) format
if (isset($row[$fieldno])) {
list($year, $month, $day, $hour, $minute, $second) = preg_split('([^0-9])', $row[$fieldno]);
if ($year != '' && (int) $year >= 1900) {
echo $q.date('d-m-Y H:i:s', mktime($hour, $minute, $second, $month, $day, $year)).$q;
} else {
echo ($na);
}
} else {
echo ($na);
}
} else {
switch ($field['LStype']) {
case 'Y': // Yes/No Question Type
switch ($row[$fieldno]) {
case 'Y':
echo($q.'1'.$q);
break;
case 'N':
echo($q.'2'.$q);
break;
default:
echo($na);
}
break;
case 'G': //Gender
switch ($row[$fieldno]) {
case 'F':
echo($q.'1'.$q);
break;
case 'M':
echo($q.'2'.$q);
break;
default:
echo($na);
}
break;
case 'C': //Yes/No/Uncertain
switch ($row[$fieldno]) {
case 'Y':
echo($q.'1'.$q);
break;
case 'N':
echo($q.'2'.$q);
break;
case 'U':
echo($q.'3'.$q);
break;
default:
echo($na);
}
break;
case 'E': //Increase / Same / Decrease
switch ($row[$fieldno]) {
case 'I':
echo($q.'1'.$q);
break;
case 'S':
echo($q.'2'.$q);
break;
case 'D':
echo($q.'3'.$q);
break;
default:
echo($na);
}
break;
case ':':
$aSize = explode(".", $field['size']);
if (isset($aSize[1]) && $aSize[1]) {
// We need to add decimal
echo $q.number_format($row[$fieldno], $aSize[1], ".", "").$q;
} else {
echo $q.$row[$fieldno].$q;
}
break;
case 'P':
case 'M':
if (substr($field['code'], -7) != 'comment' && substr($field['code'], -5) != 'other') {
if ($row[$fieldno] == 'Y') {
echo($q.'1'.$q);
} elseif (isset($row[$fieldno])) {
echo($q.'0'.$q);
} else {
echo($na);
}
break; // Break inside if : comment and other are string to be filtered
} // else do default action
default:
$strTmp = mb_substr(stripTagsFull($row[$fieldno]), 0, $iLength);
if (trim($strTmp) != '') {
if ($q == '\'') {
$strTemp = str_replace("'", "''", trim($strTmp));
}
if ($q == '"') {
$strTemp = str_replace('"', '""', trim($strTmp));
}
/*
* Temp quick fix for replacing decimal dots with comma's
if (isNumericExtended($strTemp)) {
$strTemp = str_replace('.',',',$strTemp);
}
*/
echo $q.$strTemp.$q;
} else {
echo $na;
}
}
}
if ($i < $num_fields && !$field['hide']) {
echo ',';
}
$i++;
}
echo "\n";
}
}
/**
* Check it the gives field has a labelset and return it as an array if true
*
* @param $field array field from SPSSFieldMap
* @param string $language
* @return array|bool
*/
function SPSSGetValues($field = array(), $qidattributes = null, $language)
{
$language = sanitize_paranoid_string($language);
$length_vallabel = 120; // Constant ?
if (!isset($field['LStype']) || empty($field['LStype'])) {
return false;
}
if (isset($field['hide']) && $field['hide']) {
return false;
}
$answers = array();
if (strpos("!LORFWZWH1", $field['LStype']) !== false) {
if (substr($field['code'], -5) == 'other' || substr($field['code'], -7) == 'comment') {
//We have a comment field, so free text
return array(
'SPSStype' => "A",
'size' => stringSize($field['sql_name']),
);
} else {
$query = "SELECT {{answers}}.code, {{answers}}.answer,
{{questions}}.type FROM {{answers}}, {{questions}} WHERE";
if (isset($field['scale_id'])) {
$query .= " {{answers}}.scale_id = ".(int) $field['scale_id']." AND";
}
$query .= " {{answers}}.qid = '".$field["qid"]."' and {{questions}}.language='".$language."' and {{answers}}.language='".$language."'
and {{questions}}.qid='".$field['qid']."' ORDER BY sortorder ASC";
$result = Yii::app()->db->createCommand($query)->query()->readAll(); //Checked
$num_results = safecount($result);
if ($num_results > 0) {
# Build array that has to be returned
foreach ($result as $row) {
$answers[] = array(
'code'=>$row['code'],
'value'=>mb_substr(stripTagsFull($row["answer"]), 0, $length_vallabel),
);
}
}
}
}
if ($field['LStype'] == ':') {
//Get the labels that could apply!
if (is_null($qidattributes)) {
$qidattributes = QuestionAttribute::model()->getQuestionAttributes($field["qid"],$language);
}
if ($qidattributes['multiflexible_checkbox']) {
$answers[] = array('code'=>1, 'value'=>1);
$answers[] = array('code'=>0, 'value'=>0); // 0 happen only when checked + unchecked. Not when just leave unchecked
} elseif ($qidattributes['input_boxes']) {
return array(
'SPSStype' => "F",
'size' => numericSize($field['sql_name']),
);
} else {
$minvalue = trim($qidattributes['multiflexible_min']) ? $qidattributes['multiflexible_min'] : 1;
$maxvalue = trim($qidattributes['multiflexible_max']) ? $qidattributes['multiflexible_max'] : 10;
$stepvalue = trim($qidattributes['multiflexible_step']) ? $qidattributes['multiflexible_step'] : 1;
for ($i = $minvalue; $i <= $maxvalue; $i += $stepvalue) {
$answers[] = array('code'=>$i, 'value'=>$i);
}
}
}
if ($field['LStype'] == 'M') {
if (substr($field['code'], -5) == 'other') {
return array(
'SPSStype' => "A",
'size' => stringSize($field['sql_name']),
);
} else {
$answers[] = array('code'=>1, 'value'=>gT('Yes'));
$answers[] = array('code'=>0, 'value'=>gT('Not Selected'));
}
}
if ($field['LStype'] == "P") {
if (substr($field['code'], -5) == 'other' || substr($field['code'], -7) == 'comment') {
return array(
'SPSStype' => "A",
'size' => stringSize($field['sql_name']),
);
} else {
$answers[] = array('code'=>1, 'value'=>gT('Yes'));
$answers[] = array('code'=>0, 'value'=>gT('Not Selected'));
}
}
if ($field['LStype'] == "G") {
$answers[] = array('code'=>1, 'value'=>gT('Female'));
$answers[] = array('code'=>2, 'value'=>gT('Male'));
}
if ($field['LStype'] == "Y") {
$answers[] = array('code'=>1, 'value'=>gT('Yes'));
$answers[] = array('code'=>2, 'value'=>gT('No'));
}
if ($field['LStype'] == "C") {
$answers[] = array('code'=>1, 'value'=>gT('Yes'));
$answers[] = array('code'=>2, 'value'=>gT('No'));
$answers[] = array('code'=>3, 'value'=>gT('Uncertain'));
}
if ($field['LStype'] == "E") {
$answers[] = array('code'=>1, 'value'=>gT('Increase'));
$answers[] = array('code'=>2, 'value'=>gT('Same'));
$answers[] = array('code'=>3, 'value'=>gT('Decrease'));
}
if (in_array($field['LStype'], array('N', 'K'))) {
return array(
'size' => numericSize($field['sql_name'],true),
);
}
if (in_array($field['LStype'], array('Q', 'S', 'T', 'U', ';', '*'))) {
return array(
'SPSStype' => "A",
'size' => stringSize($field['sql_name']),
);
}
if (count($answers) > 0) {
//check the max width of the answers
$size = 0;
$spsstype = $field['SPSStype'];
foreach ($answers as $answer) {
$len = mb_strlen($answer['code']);
if ($len > $size) {
$size = $len;
}
if ($spsstype == 'F' && (isNumericExtended($answer['code']) === false || $size > 16)) {
$spsstype = 'A';
}
}
$answers['SPSStype'] = $spsstype;
$answers['size'] = $size;
return $answers;
} else {
/* Not managed (currently): url, IP, … */
return;
}
}
/**
* Creates a fieldmap with all information necessary to output the fields
*
* @param $prefix string prefix for the variable ID
* @return array
*/
function SPSSFieldMap($iSurveyID, $prefix = 'V', $sLanguage = '')
{
$survey = Survey::model()->findByPk($iSurveyID);
$typeMap = array(
'5'=>Array('name'=>'5 Point Choice', 'size'=>1, 'SPSStype'=>'F', 'Scale'=>3),
'B'=>Array('name'=>'Array (10 Point Choice)', 'size'=>1, 'SPSStype'=>'F', 'Scale'=>3),
'A'=>Array('name'=>'Array (5 Point Choice)', 'size'=>1, 'SPSStype'=>'F', 'Scale'=>3),
'F'=>Array('name'=>'Array (Flexible Labels)', 'size'=>1, 'SPSStype'=>'F'),
'1'=>Array('name'=>'Array (Flexible Labels) Dual Scale', 'size'=>1, 'SPSStype'=>'F'),
'H'=>Array('name'=>'Array (Flexible Labels) by Column', 'size'=>1, 'SPSStype'=>'F'),
'E'=>Array('name'=>'Array (Increase, Same, Decrease)', 'size'=>1, 'SPSStype'=>'F', 'Scale'=>2),
'C'=>Array('name'=>'Array (Yes/No/Uncertain)', 'size'=>1, 'SPSStype'=>'F'),
'X'=>Array('name'=>'Boilerplate Question', 'size'=>1, 'SPSStype'=>'A', 'hide'=>1),
'D'=>Array('name'=>'Date', 'size'=>20, 'SPSStype'=>'DATETIME23.2'),
'G'=>Array('name'=>'Gender', 'size'=>1, 'SPSStype'=>'F'),
'U'=>Array('name'=>'Huge Free Text', 'size'=>1, 'SPSStype'=>'A'),
'I'=>Array('name'=>'Language Switch', 'size'=>1, 'SPSStype'=>'A'),
'!'=>Array('name'=>'List (Dropdown)', 'size'=>1, 'SPSStype'=>'F'),
'W'=>Array('name'=>'List (Flexible Labels) (Dropdown)', 'size'=>1, 'SPSStype'=>'F'),
'Z'=>Array('name'=>'List (Flexible Labels) (Radio)', 'size'=>1, 'SPSStype'=>'F'),
'L'=>Array('name'=>'List (Radio)', 'size'=>1, 'SPSStype'=>'F'),
'O'=>Array('name'=>'List With Comment', 'size'=>1, 'SPSStype'=>'F'),
'T'=>Array('name'=>'Long free text', 'size'=>1, 'SPSStype'=>'A'),
'K'=>Array('name'=>'Multiple Numerical Input', 'size'=>1, 'SPSStype'=>'F'), // Why not F32.10 because it's DECIMAL(30,10) in DB ? (32 because - and .)
'M'=>Array('name'=>'Multiple choice', 'size'=>1, 'SPSStype'=>'F'),
'P'=>Array('name'=>'Multiple choice with comments', 'size'=>1, 'SPSStype'=>'F'),
'Q'=>Array('name'=>'Multiple Short Text', 'size'=>1, 'SPSStype'=>'A'),
'N'=>Array('name'=>'Numerical Input', 'size'=>3, 'SPSStype'=>'F', 'Scale'=>3), // Why not F32.10 because it's DECIMAL(30,10) in DB ? (32 because - and .)
'R'=>Array('name'=>'Ranking', 'size'=>1, 'SPSStype'=>'F'),
'S'=>Array('name'=>'Short free text', 'size'=>1, 'SPSStype'=>'A'),
'Y'=>Array('name'=>'Yes/No', 'size'=>1, 'SPSStype'=>'F'),
':'=>Array('name'=>'Multi flexi numbers', 'size'=>1, 'SPSStype'=>'F', 'Scale'=>3),
';'=>Array('name'=>'Multi flexi text', 'size'=>1, 'SPSStype'=>'A'),
'|'=>Array('name'=>'File upload', 'size'=>1, 'SPSStype'=>'A'),
'*'=>Array('name'=>'Equation', 'size'=>1, 'SPSStype'=>'A'),
);
if (empty($sLanguage)) {
$sLanguage = $survey->language;
}
$fieldmap = createFieldMap($survey, 'full', true, false, $sLanguage);
#See if tokens are being used
$bTokenTableExists = tableExists('tokens_'.$iSurveyID);
// ... and if the survey uses anonymized responses
$sSurveyAnonymized = $survey->anonymized;
$iFieldNumber = 0;
$fields = array();
if ($bTokenTableExists && $sSurveyAnonymized == 'N' && Permission::model()->hasSurveyPermission($iSurveyID, 'tokens', 'read')) {
$tokenattributes = getTokenFieldsAndNames($iSurveyID, false);
foreach ($tokenattributes as $attributefield=>$attributedescription) {
//Drop the token field, since it is in the survey too
if ($attributefield != 'token') {
$iFieldNumber++;
$fields[] = array(
'id'=>"{$prefix}{$iFieldNumber}",
'name'=>mb_substr($attributefield, 0, 8),
'qid'=>0,
'code'=>'',
'SPSStype'=>'A',
'LStype'=>'Undef',
'VariableLabel'=>$attributedescription['description'],
'sql_name'=>$attributefield,
'size'=>'100',
'title'=>$attributefield,
'hide'=>0,
'scale'=>''
);
}
}
}
$fieldnames = array_keys($fieldmap);
$num_results = safecount($fieldnames);
$diff = 0;
$noQID = Array('id', 'token', 'datestamp', 'submitdate', 'startdate', 'startlanguage', 'ipaddr', 'refurl', 'lastpage');
# Build array that has to be returned
for ($i = 0; $i < $num_results; $i++) {
#Condition for SPSS fields:
# - Length may not be longer than 8 characters
# - Name may not begin with a digit
$fieldname = $fieldnames[$i];
$fieldtype = '';
$ftype = '';
$val_size = 1;
$hide = 0;
$export_scale = '';
$code = '';
$scale_id = null;
$aQuestionAttribs = array();
#Determine field type for specific column
switch ($fieldname) {
case 'submitdate':
case 'startdate':
case 'datestamp':
$fieldtype = 'DATETIME23.2';
break;
case 'startlanguage';
$fieldtype = 'A';
$val_size = 20;
break;
case 'token';
$fieldtype = 'A';
$val_size = $survey->tokenlength;
break;
case 'id';
$fieldtype = 'F';
$val_size = 7; //Arbitrarilty restrict to 9,999,999 (7 digits) responses/survey
break;
case 'ipaddr';
$fieldtype = 'A';
$val_size = 45; // IPv6 + IPv4-mapped feature : 39+1+15
break;
case 'refurl';
$fieldtype = 'A';
$val_size = 255;
break;
case 'lastpage';
$fieldtype = 'F';
$val_size = 7;
break;
case 'seed';
$fieldtype = 'A';
$val_size = 31;
break;
default:
// Not set for default
}
#Get qid (question id)
if (in_array($fieldname, $noQID) || substr($fieldname, 0, 10) == 'attribute_') {
$qid = 0;
$varlabel = $fieldname;
$ftitle = $fieldname;
} else {
//GET FIELD DATA
if (!isset($fieldmap[$fieldname])) {
//Field in database but no longer in survey... how is this possible?
//@TODO: think of a fix.
$fielddata = array();
$qid = 0;
$varlabel = $fieldname;
$ftitle = $fieldname;
$fieldtype = "F";
$val_size = 1;
} else {
$fielddata = $fieldmap[$fieldname];
$qid = $fielddata['qid'];
$ftype = $fielddata['type'];
$fsid = $fielddata['sid'];
$fgid = $fielddata['gid'];
$code = mb_substr($fielddata['fieldname'], strlen($fsid."X".$fgid."X".$qid));
$varlabel = $fielddata['question'];
if (isset($fielddata['scale'])) {
$varlabel = "[{$fielddata['scale']}] ".$varlabel;
}
if (isset($fielddata['subquestion'])) {
$varlabel = "[{$fielddata['subquestion']}] ".$varlabel;
}
if (isset($fielddata['subquestion2'])) {
$varlabel = "[{$fielddata['subquestion2']}] ".$varlabel;
}
if (isset($fielddata['subquestion1'])) {
$varlabel = "[{$fielddata['subquestion1']}] ".$varlabel;
}
$ftitle = $fielddata['title'];
if (!is_null($code) && $code <> "") {
$ftitle .= "_$code";
}
if (isset($typeMap[$ftype]['size'])) {
$val_size = $typeMap[$ftype]['size'];
}
if (isset($fielddata['scale_id'])) {
$scale_id = $fielddata['scale_id'];
}
if ($fieldtype == '') {
$fieldtype = $typeMap[$ftype]['SPSStype'];
}
if (isset($typeMap[$ftype]['hide'])) {
$hide = $typeMap[$ftype]['hide'];
$diff++;
}
//Get default scale for this type
if (isset($typeMap[$ftype]['Scale'])) {
$export_scale = $typeMap[$ftype]['Scale'];
}
//But allow override
$aQuestionAttribs = QuestionAttribute::model()->getQuestionAttributes($qid,$sLanguage);
if (isset($aQuestionAttribs['scale_export'])) {
$export_scale = $aQuestionAttribs['scale_export'];
}
}
}
$iFieldNumber++;
$fid = $iFieldNumber - $diff;
$lsLong = isset($typeMap[$ftype]["name"]) ? $typeMap[$ftype]["name"] : $ftype;
$tempArray = array(
'id'=>$prefix.$fid,
'name'=>mb_substr($fieldname, 0, 8),
'qid'=>$qid,
'code'=>$code,
'SPSStype'=>$fieldtype,
'LStype'=>$ftype,
'LSlong'=>$lsLong,
'ValueLabels'=>'',
'VariableLabel'=>$varlabel,
'sql_name'=>$fieldname,
'size'=>$val_size,
'title'=>$ftitle,
'hide'=>$hide,
'scale'=>$export_scale,
'scale_id'=>$scale_id
);
//Now check if we have to retrieve value labels
$answers = SPSSGetValues($tempArray, $aQuestionAttribs, $sLanguage);
if (is_array($answers)) {
//Ok we have answers
if (isset($answers['size'])) {
$tempArray['size'] = $answers['size'];
unset($answers['size']);
}
if (isset($answers['SPSStype'])) {
$tempArray['SPSStype'] = $answers['SPSStype'];
unset($answers['SPSStype']);
}
if (!empty($answers)) {
$tempArray['answers'] = $answers;
}
}
$fields[] = $tempArray;
}
return $fields;
}
/**
* Creates a query string with all fields for the export
* @param
* @return CDbCommand
*/
function SPSSGetQuery($iSurveyID, $limit = null, $offset = null)
{
$survey = Survey::model()->findByPk($iSurveyID);
#See if tokens are being used
$query = App()->db->createCommand();
$query->from($survey->responsesTableName.' s');
$columns = array('s.*');
if ($survey->hasTokensTable && !$survey->isAnonymized && Permission::model()->hasSurveyPermission($iSurveyID, 'tokens', 'read')) {
$tokenattributes = array_keys(getTokenFieldsAndNames($iSurveyID, false));
foreach ($tokenattributes as $attributefield) {
//Drop the token field, since it is in the survey too
if ($attributefield != 'token') {
$columns[] = 't.'.$attributefield;
}
}
$query->leftJoin($survey->tokensTableName.' t', App()->db->quoteColumnName('s.token').' = '.App()->db->quoteColumnName('t.token'));
//LEFT JOIN {{tokens_$iSurveyID}} t ON ";
}
$query->select($columns);
switch (incompleteAnsFilterState()) {
case 'incomplete':
//Inclomplete answers only
$query->where('s.submitdate IS NULL');
break;
case 'complete':
//Inclomplete answers only
$query->where('s.submitdate IS NOT NULL');
break;
}
if (!empty($limit) & !is_null($offset)) {
$query->limit((int) $limit, (int) $offset);
}
$query->order('id ASC');
return $query;
}
/**
* buildXMLFromQuery() creates a datadump of a table in XML using XMLWriter
*
* @param mixed $xmlwriter The existing XMLWriter object
* @param mixed $Query The table query to build from
* @param string $tagname If the XML tag of the resulting question should be named differently than the table name set it here
* @param string[] $excludes array of columnames not to include in export
*/
function buildXMLFromQuery($xmlwriter, $Query, $tagname = '', $excludes = array())
{
$iChunkSize = 3000; // This works even for very large result sets and leaves a minimal memory footprint
preg_match('/\bfrom\b\s*{{(\w+)}}/i', $Query, $MatchResults);
if ($tagname != '') {
$TableName = $tagname;
} else {
$TableName = $MatchResults[1];
}
// Read table in smaller chunks
$iStart = 0;
do {
$QueryResult = Yii::app()->db->createCommand($Query)->limit($iChunkSize, $iStart)->query();
$result = $QueryResult->readAll();
if ($iStart == 0 && safecount($result) > 0) {
$exclude = array_flip($excludes); //Flip key/value in array for faster checks
$xmlwriter->startElement($TableName);
$xmlwriter->startElement('fields');
$aColumninfo = array_keys($result[0]);
foreach ($aColumninfo as $fieldname) {
if (!isset($exclude[$fieldname])) {
$xmlwriter->writeElement('fieldname', $fieldname);
}
}
$xmlwriter->endElement(); // close columns
$xmlwriter->startElement('rows');
}
foreach ($result as $Row) {
$xmlwriter->startElement('row');
foreach ($Row as $Key=>$Value) {
if (!isset($exclude[$Key])) {
if (!(is_null($Value))) {
// If the $value is null don't output an element at all
if (is_numeric($Key[0])) {
// mask invalid element names with an underscore
$Key = '_'.$Key;
}
$Key = str_replace('#', '-', $Key);
if (!$xmlwriter->startElement($Key)) {
// Remove invalid XML characters
safeDie('Invalid element key: '.$Key);
}
if ($Value !== '') {
$Value = str_replace(']]>', ']] >', $Value);
$xmlwriter->writeCData(preg_replace('/[^\x9\xA\xD\x20-\x{D7FF}\x{E000}-\x{FFFD}\x{10000}-\x{10FFFF}]/u', '', $Value));
}
$xmlwriter->endElement();
}
}
}
$xmlwriter->endElement(); // close row
}
$iStart = $iStart + $iChunkSize;
} while (count($result) == $iChunkSize);
if (count($result) > 0) {
$xmlwriter->endElement(); // close rows
$xmlwriter->endElement(); // close tablename
}
}
/**
* from export_structure_xml.php
*/
function surveyGetXMLStructure($iSurveyID, $xmlwriter, $exclude = array())
{
if (!isset($exclude['answers'])) {
//Answer table
$aquery = "SELECT {{answers}}.*
FROM {{answers}}, {{questions}}
WHERE {{answers}}.language={{questions}}.language
AND {{answers}}.qid={{questions}}.qid
AND {{questions}}.sid=$iSurveyID";
buildXMLFromQuery($xmlwriter, $aquery);
}
// Assessments
$query = "SELECT {{assessments}}.*
FROM {{assessments}}
WHERE {{assessments}}.sid=$iSurveyID";
buildXMLFromQuery($xmlwriter, $query);
if (!isset($exclude['conditions'])) {
//Condition table
$cquery = "SELECT DISTINCT {{conditions}}.*
FROM {{conditions}}, {{questions}}
WHERE {{conditions}}.qid={{questions}}.qid
AND {{questions}}.sid=$iSurveyID";
buildXMLFromQuery($xmlwriter, $cquery);
}
//Default values
$query = "SELECT {{defaultvalues}}.*
FROM {{defaultvalues}} JOIN {{questions}} ON {{questions}}.qid = {{defaultvalues}}.qid AND {{questions}}.sid=$iSurveyID AND {{questions}}.language={{defaultvalues}}.language ";
buildXMLFromQuery($xmlwriter, $query);
// QuestionGroup
$gquery = "SELECT *
FROM {{groups}}
WHERE sid=$iSurveyID
ORDER BY gid";
buildXMLFromQuery($xmlwriter, $gquery);
//Questions
$qquery = "SELECT *
FROM {{questions}}
WHERE sid=$iSurveyID and parent_qid=0
ORDER BY qid";
buildXMLFromQuery($xmlwriter, $qquery);
//Subquestions
$qquery = "SELECT *
FROM {{questions}}
WHERE sid=$iSurveyID and parent_qid>0
ORDER BY qid";
buildXMLFromQuery($xmlwriter, $qquery, 'subquestions');
//Question attributes
$sBaseLanguage = Survey::model()->findByPk($iSurveyID)->language;
$platform = Yii::app()->db->getDriverName();
if ($platform == 'mssql' || $platform == 'sqlsrv' || $platform == 'dblib') {
$query = "SELECT qa.qid, qa.attribute, cast(qa.value as varchar(4000)) as value, qa.language
FROM {{question_attributes}} qa JOIN {{questions}} q ON q.qid = qa.qid AND q.sid={$iSurveyID}
where q.language='{$sBaseLanguage}' group by qa.qid, qa.attribute, cast(qa.value as varchar(4000)), qa.language";
} else {
$query = "SELECT qa.qid, qa.attribute, qa.value, qa.language
FROM {{question_attributes}} qa JOIN {{questions}} q ON q.qid = qa.qid AND q.sid={$iSurveyID}
where q.language='{$sBaseLanguage}' group by qa.qid, qa.attribute, qa.value, qa.language";
}
buildXMLFromQuery($xmlwriter, $query, 'question_attributes');
if (!isset($exclude['quotas'])) {
//Quota
$query = "SELECT {{quota}}.*
FROM {{quota}}
WHERE {{quota}}.sid=$iSurveyID";
buildXMLFromQuery($xmlwriter, $query);
//1Quota members
$query = "SELECT {{quota_members}}.*
FROM {{quota_members}}
WHERE {{quota_members}}.sid=$iSurveyID";
buildXMLFromQuery($xmlwriter, $query);
//Quota languagesettings
$query = "SELECT {{quota_languagesettings}}.*
FROM {{quota_languagesettings}}, {{quota}}
WHERE {{quota}}.id = {{quota_languagesettings}}.quotals_quota_id
AND {{quota}}.sid=$iSurveyID";
buildXMLFromQuery($xmlwriter, $query);
}
// Surveys
$squery = "SELECT *
FROM {{surveys}}
WHERE sid=$iSurveyID";
//Exclude some fields from the export
$excludeFromSurvey = array('owner_id', 'active', 'datecreated');
if (isset($exclude['dates']) && $exclude['dates']) {
$excludeFromSurvey[] = 'startdate';
$excludeFromSurvey[] = 'expires';
}
buildXMLFromQuery($xmlwriter, $squery, '', $excludeFromSurvey);
// Survey language settings
$slsquery = "SELECT *
FROM {{surveys_languagesettings}}
WHERE surveyls_survey_id=$iSurveyID";
buildXMLFromQuery($xmlwriter, $slsquery);
// Survey url parameters
$slsquery = "SELECT *
FROM {{survey_url_parameters}}
WHERE sid={$iSurveyID}";
buildXMLFromQuery($xmlwriter, $slsquery);
// Survey plugin(s)
$slsquery = " SELECT settings.id,name,".Yii::app()->db->quoteColumnName("key").",".Yii::app()->db->quoteColumnName("value")
. " FROM {{plugin_settings}} as settings JOIN {{plugins}} as plugins ON plugins.id = settings.plugin_id"
. " WHERE model='Survey' and model_id=$iSurveyID";
buildXMLFromQuery($xmlwriter, $slsquery);
}
/**
* from export_structure_xml.php
*/
function surveyGetXMLData($iSurveyID, $exclude = array())
{
$xml = getXMLWriter();
$xml->openMemory();
$xml->setIndent(true);
$xml->startDocument('1.0', 'UTF-8');
$xml->startElement('document');
$xml->writeElement('LimeSurveyDocType', 'Survey');
$xml->writeElement('DBVersion', getGlobalSetting("DBVersion"));
$xml->startElement('languages');
$surveylanguages = Survey::model()->findByPk($iSurveyID)->additionalLanguages;
$surveylanguages[] = Survey::model()->findByPk($iSurveyID)->language;
foreach ($surveylanguages as $surveylanguage) {
$xml->writeElement('language', $surveylanguage);
}
$xml->endElement();
surveyGetXMLStructure($iSurveyID, $xml, $exclude);
// survey theme configuration - db values
surveyGetThemeConfiguration($iSurveyID, $xml, false, 'themes');
// survey theme configuration - inherited values
surveyGetThemeConfiguration($iSurveyID, $xml, true, 'themes_inherited');
$xml->endElement(); // close columns
$xml->endDocument();
return $xml->outputMemory(true);
}
/**
* Exports a single table to XML
*
* @param integer $iSurveyID The survey ID
* @param string $sTableName The database table name of the table to be export
* @param string $sDocType What doctype should be written
* @param string $sXMLTableTagName Name of the tag table name in the XML file
* @return string|boolean XMLWriter object
*/
function getXMLDataSingleTable($iSurveyID, $sTableName, $sDocType, $sXMLTableTagName = '', $sFileName = '', $bSetIndent = true)
{
$xml = getXMLWriter();
if ($sFileName == '') {
$xml->openMemory();
} else {
$bOK = $xml->openURI($sFileName);
}
$xml->setIndent($bSetIndent);
$xml->startDocument('1.0', 'UTF-8');
$xml->startElement('document');
$xml->writeElement('LimeSurveyDocType', $sDocType);
$xml->writeElement('DBVersion', getGlobalSetting("DBVersion"));
$xml->startElement('languages');
$aSurveyLanguages = Survey::model()->findByPk($iSurveyID)->additionalLanguages;
$aSurveyLanguages[] = Survey::model()->findByPk($iSurveyID)->language;
foreach ($aSurveyLanguages as $sSurveyLanguage) {
$xml->writeElement('language', $sSurveyLanguage);
}
$xml->endElement();
$aquery = "SELECT * FROM {{{$sTableName}}}";
buildXMLFromQuery($xml, $aquery, $sXMLTableTagName);
$xml->endElement(); // close columns
$xml->endDocument();
if ($sFileName = '') {
return $xml->outputMemory(true);
} else {
return $bOK;
}
}
/**
* from export_structure_quexml.php
*/
function QueXMLCleanup($string, $allow = '<p><b><u><i><em>')
{
return str_replace("&", "&", html_entity_decode(trim(strip_tags(str_ireplace("<br />", "\n", $string), $allow)), ENT_QUOTES, 'UTF-8'));
}
/**
* from export_structure_quexml.php
*/
function QueXMLCreateFree($f, $len, $lab = "")
{
global $dom;
$free = $dom->createElement("free");
$format = $dom->createElement("format", QueXMLCleanup($f));
$length = $dom->createElement("length", QueXMLCleanup($len));
$label = $dom->createElement("label", QueXMLCleanup($lab));
$free->appendChild($format);
$free->appendChild($length);
$free->appendChild($label);
return $free;
}
/**
* from export_structure_quexml.php
*/
function QueXMLFixedArray($array)
{
global $dom;
$fixed = $dom->createElement("fixed");
foreach ($array as $key => $v) {
$category = $dom->createElement("category");
$label = $dom->createElement("label", QueXMLCleanup("$key", ''));
$value = $dom->createElement("value", QueXMLCleanup("$v", ''));
$category->appendChild($label);
$category->appendChild($value);
$fixed->appendChild($category);
}
return $fixed;
}