-
Notifications
You must be signed in to change notification settings - Fork 988
/
export.php
1123 lines (941 loc) · 41.2 KB
/
export.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*
* LimeSurvey
* Copyright (C) 2007-2011 The LimeSurvey Project Team / Carsten Schmitz
* All rights reserved.
* License: GNU/GPL License v2 or later, see LICENSE.php
* LimeSurvey is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYRIGHT.php for copyright notices and details.
*
*/
/**
* Export Action
*
* This controller performs export actions
*
* @package LimeSurvey
* @subpackage Backend
*/
class export extends Survey_Common_Action {
function __construct($controller, $id)
{
parent::__construct($controller, $id);
Yii::app()->loadHelper('export');
}
public function survey()
{
$action = Yii::app()->request->getParam('action');
$iSurveyID = sanitize_int(Yii::app()->request->getParam('surveyid'));
if ( Permission::model()->hasSurveyPermission($iSurveyID, 'surveycontent', 'export') )
{
$this->_surveyexport($action, $iSurveyID);
return;
}
}
/**
* This function exports a ZIP archives of several ZIP archives - it is used in the listSurvey controller
* The SIDs are read from session flashdata.
*
*/
public function surveyarchives()
{
if ( ! Permission::model()->hasGlobalPermission('superadmin','read') )
{
die('Access denied.');
}
$aSurveyIDs = $this->session->flashdata('sids');
$aExportedFiles = array();
foreach ($aSurveyIDs as $iSurveyID)
{
$iSurveyID = (int)$iSurveyID;
if ( $iSurveyID > 0 )
{
$aExportedFiles[$iSurveyID] = $this->_exportarchive($iSurveyID,FALSE);
}
}
if ( count($aExportedFiles) > 0 )
{
$aZIPFileName=$this->config->item("tempdir") . DIRECTORY_SEPARATOR . randomChars(30);
$this->load->library("admin/pclzip", array('p_zipname' => $aZIPFileName));
$zip = new PclZip($aZIPFileName);
foreach ($aExportedFiles as $iSurveyID=>$sFileName)
{
$zip->add(
array(
array(
PCLZIP_ATT_FILE_NAME => $sFileName,
PCLZIP_ATT_FILE_NEW_FULL_NAME => 'survey_archive_' . $iSurveyID . '.zip')
)
);
unlink($sFileName);
}
}
if ( is_file($aZIPFileName) )
{
//Send the file for download!
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Type: application/force-download");
header( "Content-Disposition: attachment; filename=survey_archives_pack.zip" );
header( "Content-Description: File Transfer");
@readfile($aZIPFileName);
//Delete the temporary file
unlink($aZIPFileName);
return;
}
}
public function group()
{
$gid = sanitize_int(Yii::app()->request->getParam('gid'));
$iSurveyID = sanitize_int(Yii::app()->request->getParam('surveyid'));
group_export("exportstructurecsvGroup", $iSurveyID, $gid);
return;
}
public function question()
{
$gid = sanitize_int(Yii::app()->request->getParam('gid'));
$qid = sanitize_int(Yii::app()->request->getParam('qid'));
$iSurveyID = sanitize_int(Yii::app()->request->getParam('surveyid'));
questionExport("exportstructurecsvQuestion", $iSurveyID, $gid, $qid);
}
public function exportresults()
{
$iSurveyID = sanitize_int(Yii::app()->request->getParam('surveyid'));
if ( ! isset($imageurl) ) { $imageurl = "./images"; }
if ( ! isset($iSurveyID) ) { $iSurveyID = returnGlobal('sid'); }
if ( ! isset($exportstyle) ) { $exportstyle = returnGlobal('exportstyle'); }
if ( ! isset($answers) ) { $answers = returnGlobal('answers'); }
if ( ! isset($type) ) { $type = returnGlobal('type'); }
if ( ! isset($convertyto1) ) { $convertyto1 = returnGlobal('convertyto1'); }
if ( ! isset($convertnto2) ) { $convertnto2 = returnGlobal('convertnto2'); }
if ( ! isset($convertyto) ) { $convertyto = returnGlobal('convertyto'); }
if ( ! isset($convertnto) ) { $convertnto = returnGlobal('convertnto'); }
if ( ! isset($convertspacetous) ) { $convertspacetous = returnGlobal('convertspacetous'); }
$clang = Yii::app()->lang;
if ( ! Permission::model()->hasSurveyPermission($iSurveyID, 'responses', 'export') )
{
$this->getController()->error('Access denied!');
}
Yii::app()->loadHelper("admin/exportresults");
App()->getClientScript()->registerScriptFile(Yii::app()->getConfig('generalscripts')."expressions/em_javascript.js");
App()->getClientScript()->registerScriptFile(Yii::app()->getConfig('adminscripts') . '/exportresults.js');
$surveybaselang = Survey::model()->findByPk($iSurveyID)->language;
$exportoutput = "";
// Get info about the survey
$thissurvey = getSurveyInfo($iSurveyID);
// Load ExportSurveyResultsService so we know what exports are available
$resultsService = new ExportSurveyResultsService();
$exports = $resultsService->getExports();
if ( ! $exportstyle )
{
//FIND OUT HOW MANY FIELDS WILL BE NEEDED - FOR 255 COLUMN LIMIT
$aFieldMap = createFieldMap($iSurveyID,'full',false,false,getBaseLanguageFromSurveyID($iSurveyID));
if ($thissurvey['savetimings'] === "Y") {
//Append survey timings to the fieldmap array
$aFieldMap = $aFieldMap + createTimingsFieldMap($iSurveyID, 'full',false,false,getBaseLanguageFromSurveyID($iSurveyID));
}
$iFieldCount = count($aFieldMap);
$selecthide = "";
$selectshow = "";
$selectinc = "";
if ( incompleteAnsFilterState() == "complete" )
{
$selecthide = "selected='selected'";
}
elseif ( incompleteAnsFilterState() == "incomplete" )
{
$selectinc = "selected='selected'";
}
else
{
$selectshow = "selected='selected'";
}
$aFields=array();
foreach($aFieldMap as $sFieldName=>$fieldinfo)
{
$sCode=viewHelper::getFieldCode($fieldinfo);
$aFields[$sFieldName]=$sCode.' - '.htmlspecialchars(ellipsize(html_entity_decode(viewHelper::getFieldText($fieldinfo)),30,.6,'...'));
}
$data['SingleResponse']=(int)returnGlobal('id');
$data['selecthide'] = $selecthide;
$data['selectshow'] = $selectshow;
$data['selectinc'] = $selectinc;
$data['afieldcount'] = $iFieldCount;
$data['aFields'] = $aFields;
//get max number of datasets
$iMaximum = SurveyDynamic::model($iSurveyID)->getMaxId();
$data['max_datasets'] = $iMaximum;
$data['surveyid'] = $iSurveyID;
$data['imageurl'] = Yii::app()->getConfig('imageurl');
$data['thissurvey'] = $thissurvey;
$data['display']['menu_bars']['browse'] = $clang->gT("Export results");
// Export plugins, leave out all entries that are not plugin
$exports = array_filter($exports);
$exportData = array();
foreach ($exports as $key => $plugin) {
$event = new PluginEvent('listExportOptions');
$event->set('type', $key);
$oPluginManager = App()->getPluginManager();
$oPluginManager->dispatchEvent($event, $plugin);
$exportData[$key] = array(
'onclick' => $event->get('onclick'),
'label' => $event->get('label'),
'checked' => $event->get('default', false),
'tooltip' => $event->get('tooltip', null)
);
}
$data['exports'] = $exportData; // Pass available exports
$this->_renderWrappedTemplate('export', 'exportresults_view', $data);
return;
}
// Export Language is set by default to surveybaselang
// * the explang language code is used in SQL queries
// * the alang object is used to translate headers and hardcoded answers
// In the future it might be possible to 'post' the 'export language' from
// the exportresults form
$explang = $surveybaselang;
$elang = new limesurvey_lang($explang);
//Get together our FormattingOptions and then call into the exportSurvey
//function.
$options = new FormattingOptions();
$options->selectedColumns = Yii::app()->request->getPost('colselect');
$options->responseMinRecord = sanitize_int(Yii::app()->request->getPost('export_from'));
$options->responseMaxRecord = sanitize_int(Yii::app()->request->getPost('export_to'));
$options->answerFormat = $answers;
$options->convertN = $convertnto2;
$options->output = 'display';
if ( $options->convertN )
{
$options->nValue = $convertnto;
}
$options->convertY = $convertyto1;
if ( $options->convertY )
{
$options->yValue = $convertyto;
}
$options->headerSpacesToUnderscores = $convertspacetous;
$options->headingFormat = $exportstyle;
$options->responseCompletionState = incompleteAnsFilterState();
// Replace token information by the column name
if ( in_array('first_name', Yii::app()->request->getPost('attribute_select', array())) )
{
$options->selectedColumns[]="firstname";
}
if ( in_array('last_name', Yii::app()->request->getPost('attribute_select', array())) )
{
$options->selectedColumns[]="lastname";
}
if ( in_array('email_address', Yii::app()->request->getPost('attribute_select', array())) )
{
$options->selectedColumns[]="email";
}
$attributeFields = array_keys(getTokenFieldsAndNames($iSurveyID, TRUE));
foreach ($attributeFields as $attr_name)
{
if ( in_array($attr_name, Yii::app()->request->getPost('attribute_select',array())) )
{
$options->selectedColumns[]=$attr_name;
}
}
if (Yii::app()->request->getPost('response_id'))
{
$sFilter="{{survey_{$iSurveyID}}}.id=".(int)Yii::app()->request->getPost('response_id');
}
else
{
$sFilter='';
}
viewHelper::disableHtmlLogging();
$resultsService->exportSurvey($iSurveyID, $explang, $type, $options, $sFilter);
exit;
}
/*
* The SPSS DATA LIST / BEGIN DATA parser is rather simple minded, the number after the type
* specifier identifies the field width (maximum number of characters to scan)
* It will stop short of that number of characters, honouring quote delimited
* space separated strings, however if the width is too small the remaining data in the current
* line becomes part of the next column. Since we want to restrict this script to ONE scan of
* the data (scan & output at same time), the information needed to construct the
* DATA LIST is held in the $fields array, while the actual data is written to a
* to a temporary location, updating length (size) values in the $fields array as
* the tmp file is generated (uses @fwrite's return value rather than strlen).
* Final output renders $fields to a DATA LIST, and then stitches in the tmp file data.
*
* Optimization opportunities remain in the VALUE LABELS section, which runs a query / column
*/
public function exportspss()
{
global $length_vallabel;
$iSurveyID = sanitize_int(Yii::app()->request->getParam('sid'));
$clang = $this->getController()->lang;
//for scale 1=nominal, 2=ordinal, 3=scale
// $typeMap = $this->_getTypeMap();
$filterstate = incompleteAnsFilterState();
$spssver = returnGlobal('spssver');
if ( is_null($spssver) )
{
if ( ! Yii::app()->session['spssversion'] )
{
Yii::app()->session['spssversion'] = 2; //Set default to 2, version 16 or up
}
$spssver = Yii::app()->session['spssversion'];
}
else
{
Yii::app()->session['spssversion'] = $spssver;
}
$length_varlabel = '231'; // Set the max text length of Variable Labels
$length_vallabel = '120'; // Set the max text length of Value Labels
switch ( $spssver )
{
case 1: //<16
$iLength = '255'; // Set the max text length of the Value
break;
case 2: //>=16
$iLength = '16384'; // Set the max text length of the Value
break;
default:
$iLength = '16384'; // Set the max text length of the Value
}
$headerComment = '*$Rev: 121017 $' . " $filterstate $spssver.\n";
if ( isset($_POST['dldata']) ) $subaction = "dldata";
if ( isset($_POST['dlstructure']) ) $subaction = "dlstructure";
if ( ! isset($subaction) )
{
$selecthide = "";
$selectshow = "";
$selectinc = "";
switch ($filterstate)
{
case "incomplete":
$selectinc="selected='selected'";
break;
case "complete":
$selecthide="selected='selected'";
break;
default:
$selectshow="selected='selected'";
}
$data['selectinc'] = $selectinc;
$data['selecthide'] = $selecthide;
$data['selectshow'] = $selectshow;
$data['spssver'] = $spssver;
$data['surveyid'] = $iSurveyID;
$data['display']['menu_bars']['browse'] = $clang->gT('Export results');
$this->_renderWrappedTemplate('export', 'spss_view', $data);
return;
}
// Get Base language:
$language = Survey::model()->findByPk($iSurveyID)->language;
$clang = new limesurvey_lang($language);
Yii::app()->loadHelper("admin/exportresults");
viewHelper::disableHtmlLogging();
if ( $subaction == 'dldata' )
{
header("Content-Disposition: attachment; filename=survey_" . $iSurveyID . "_SPSS_data_file.dat");
header("Content-type: text/comma-separated-values; charset=UTF-8");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Pragma: public");
if ( $spssver == 2 )
{
echo "\xEF\xBB\xBF";
}
SPSSExportData($iSurveyID, $iLength);
exit;
}
if ( $subaction == 'dlstructure' )
{
header("Content-Disposition: attachment; filename=survey_" . $iSurveyID . "_SPSS_syntax_file.sps");
header("Content-type: application/download; charset=UTF-8");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Pragma: public");
// Build array that has to be returned
$fields = SPSSFieldMap($iSurveyID);
//Now get the query string with all fields to export
$query = SPSSGetQuery($iSurveyID, 500, 0); // Sample first 500 responses for adjusting fieldmap
$result = $query->query();
$num_fields = 0;
//Now we check if we need to adjust the size of the field or the type of the field
foreach ( $result as $row )
{
if($num_fields==0) {
$num_fields = count($row);
}
$row = array_values($row);
$fieldno = 0;
while ( $fieldno < $num_fields )
{
//Performance improvement, don't recheck fields that have valuelabels
if ( ! isset($fields[$fieldno]['answers']) )
{
$strTmp = mb_substr(stripTagsFull($row[$fieldno]), 0, $iLength);
$len = mb_strlen($strTmp);
if ( $len > $fields[$fieldno]['size'] ) $fields[$fieldno]['size'] = $len;
if ( trim($strTmp) != '' )
{
if ( $fields[$fieldno]['SPSStype'] == 'F' && (isNumericExtended($strTmp) === FALSE || $fields[$fieldno]['size'] > 16) )
{
$fields[$fieldno]['SPSStype'] = 'A';
}
}
}
$fieldno++;
}
}
$result->close();
/**
* End of DATA print out
*
* Now $fields contains accurate length data, and the DATA LIST can be rendered -- then the contents of the temp file can
* be sent to the client.
*/
if ( $spssver == 2 )
{
echo "\xEF\xBB\xBF";
}
echo $headerComment;
if ($spssver == 2 )
{
echo "SET UNICODE=ON.\n";
}
echo "SHOW LOCALE.\n";
echo "PRESERVE LOCALE.\n";
echo "SET LOCALE='en_UK'.\n";
echo "GET DATA\n"
." /TYPE=TXT\n"
." /FILE='survey_" . $iSurveyID . "_SPSS_data_file.dat'\n"
." /DELCASE=LINE\n"
." /DELIMITERS=\",\"\n"
." /QUALIFIER=\"'\"\n"
." /ARRANGEMENT=DELIMITED\n"
." /FIRSTCASE=1\n"
." /IMPORTCASE=ALL\n"
." /VARIABLES=";
foreach ( $fields as $field )
{
if( $field['SPSStype'] == 'DATETIME23.2' ) $field['size'] = '';
if($field['SPSStype'] == 'F' && ($field['LStype'] == 'N' || $field['LStype'] == 'K'))
{
$field['size'] .= '.' . ($field['size']-1);
}
if ( !$field['hide'] ) echo "\n {$field['id']} {$field['SPSStype']}{$field['size']}";
}
echo ".\nCACHE.\n"
."EXECUTE.\n";
//Create the variable labels:
echo "*Define Variable Properties.\n";
foreach ( $fields as $field )
{
if ( ! $field['hide'] )
{
$label_parts = strSplitUnicode(str_replace('"','""',stripTagsFull($field['VariableLabel'])), $length_varlabel-strlen($field['id']));
//if replaced quotes are splitted by, we need to mve the first quote to the next row
foreach($label_parts as $idx => $label_part)
{
if($idx != count($label_parts) && substr($label_part,-1) == '"' && substr($label_part,-2) != '"')
{
$label_parts[$idx] = rtrim($label_part, '"');
$label_parts[$idx + 1] = '"' . $label_parts[$idx + 1];
}
}
echo "VARIABLE LABELS " . $field['id'] . " \"" . implode("\"+\n\"", $label_parts) . "\".\n";
}
}
// Create our Value Labels!
echo "*Define Value labels.\n";
foreach ( $fields as $field )
{
if ( isset($field['answers']) )
{
$answers = $field['answers'];
//print out the value labels!
echo "VALUE LABELS {$field['id']}\n";
$i=0;
foreach ( $answers as $answer )
{
$i++;
if ( $field['SPSStype'] == "F" && isNumericExtended($answer['code']) )
{
$str = "{$answer['code']}";
}
else
{
$str = "\"{$answer['code']}\"";
}
if ( $i < count($answers) )
{
echo " $str \"{$answer['value']}\"\n";
}
else
{
echo " $str \"{$answer['value']}\".\n";
}
}
}
}
foreach ( $fields as $field )
{
if( $field['scale'] !== '' )
{
switch ( $field['scale'] )
{
case 2:
echo "VARIABLE LEVEL {$field['id']}(ORDINAL).\n";
break;
case 3:
echo "VARIABLE LEVEL {$field['id']}(SCALE).\n";
}
}
}
//Rename the Variables (in case somethings goes wrong, we still have the OLD values
foreach ( $fields as $field )
{
if ( isset($field['sql_name']) && $field['hide'] === 0 )
{
$ftitle = $field['title'];
if ( ! preg_match ("/^([a-z]|[A-Z])+.*$/", $ftitle) )
{
$ftitle = "q_" . $ftitle;
}
$ftitle = str_replace(array(" ","-",":",";","!","/","\\","'"), array("_","_hyph_","_dd_","_dc_","_excl_","_fs_","_bs_",'_qu_'), $ftitle);
if ( $ftitle != $field['title'] )
{
echo "* Variable name was incorrect and was changed from {$field['title']} to $ftitle .\n";
}
echo "RENAME VARIABLE ( " . $field['id'] . ' = ' . $ftitle . " ).\n";
}
}
echo "RESTORE LOCALE.\n";
exit;
}
}
public function vvexport()
{
$iSurveyId = sanitize_int(Yii::app()->request->getParam('surveyid'));
$subaction = Yii::app()->request->getParam('subaction');
//Exports all responses to a survey in special "Verified Voting" format.
$clang = $this->getController()->lang;
if ( ! Permission::model()->hasSurveyPermission($iSurveyId, 'responses','export') )
{
Yii::app()->session['flashmessage'] = $clang->gT("You do not have sufficient rights to access this page.");
$this->getController()->redirect($this->getController()->createUrl("/admin/survey/sa/view/surveyid/{$iSurveyId}"));
}
if ( $subaction != "export" )
{
$aData['selectincansstate']=incompleteAnsFilterState();
$aData['surveyid'] = $iSurveyId;
$aData['display']['menu_bars']['browse'] = $clang->gT("Export VV file");
$fieldmap = createFieldMap($iSurveyId,'full',false,false,getBaseLanguageFromSurveyID($iSurveyId));
Survey::model()->findByPk($iSurveyId)->language;
$surveytable = "{{survey_$iSurveyId}}";
// Control if fieldcode are unique
$fieldnames = Yii::app()->db->schema->getTable($surveytable)->getColumnNames();
foreach ( $fieldnames as $field )
{
$fielddata=arraySearchByKey($field, $fieldmap, "fieldname", 1);
$fieldcode[]=viewHelper::getFieldCode($fielddata,array("LEMcompat"=>true));
}
$aData['uniquefieldcode']=(count(array_unique ($fieldcode))==count($fieldcode)); // Did we need more control ?
$aData['vvversionseleted']=($aData['uniquefieldcode'])?2:1;
$this->_renderWrappedTemplate('export', 'vv_view', $aData);
}
elseif ( isset($iSurveyId) && $iSurveyId )
{
//Export is happening
$extension = sanitize_paranoid_string(returnGlobal('extension'));
$vvVersion = (int) Yii::app()->request->getPost('vvversion');
$vvVersion = (in_array($vvVersion,array(1,2)))?$vvVersion:2;// Only 2 version actually, default to 2
$fn = "vvexport_$iSurveyId." . $extension;
$this->_addHeaders($fn, "text/comma-separated-values", 0, "cache");
$s="\t";
$fieldmap = createFieldMap($iSurveyId,'full',false,false,getBaseLanguageFromSurveyID($iSurveyId));
$surveytable = "{{survey_$iSurveyId}}";
Survey::model()->findByPk($iSurveyId)->language;
$fieldnames = Yii::app()->db->schema->getTable($surveytable)->getColumnNames();
//Create the human friendly first line
$firstline = "";
$secondline = "";
foreach ( $fieldnames as $field )
{
$fielddata=arraySearchByKey($field, $fieldmap, "fieldname", 1);
if ( count($fielddata) < 1 )
{
$firstline .= $field;
}
else
{
$firstline.=preg_replace('/\s+/', ' ', strip_tags($fielddata['question']));
}
$firstline .= $s;
if($vvVersion==2){
$fieldcode=viewHelper::getFieldCode($fielddata,array("LEMcompat"=>true));
$fieldcode=($fieldcode)?$fieldcode:$field;// $fieldcode is empty for token if there are no token table
}else{
$fieldcode=$field;
}
$secondline .= $fieldcode.$s;
}
$vvoutput = $firstline . "\n";
$vvoutput .= $secondline . "\n";
$query = "SELECT * FROM ".Yii::app()->db->quoteTableName($surveytable);
if (incompleteAnsFilterState() == "incomplete")
{
$query .= " WHERE submitdate IS NULL ";
}
elseif (incompleteAnsFilterState() == "complete")
{
$query .= " WHERE submitdate >= '01/01/1980' ";
}
$result = Yii::app()->db->createCommand($query)->query();
echo $vvoutput;
foreach ($result as $row)
{
foreach ( $fieldnames as $field )
{
if ( is_null($row[$field]) )
{
$value = '{question_not_shown}';
}
else
{
$value = trim($row[$field]);
// sunscreen for the value. necessary for the beach.
// careful about the order of these arrays:
// lbrace has to be substituted *first*
$value = str_replace(
array(
"{",
"\n",
"\r",
"\t"),
array("{lbrace}",
"{newline}",
"{cr}",
"{tab}"
),
$value
);
}
// one last tweak: excel likes to quote values when it
// exports as tab-delimited (esp if value contains a comma,
// oddly enough). So we're going to encode a leading quote,
// if it occurs, so that we can tell the difference between
// strings that "really are" quoted, and those that excel quotes
// for us.
$value = preg_replace('/^"/','{quote}',$value);
// yay! that nasty soab won't hurt us now!
if( $field == "submitdate" && !$value ) { $value = "NULL"; }
$sun[]=$value;
}
/* it is important here to stream output data, line by line
* in order to avoid huge memory consumption when exporting large
* quantities of answers */
echo implode($s, $sun)."\n";
unset($sun);
}
exit;
}
}
/**
* quexml survey export
*/
public function showquexmlsurvey()
{
$iSurveyID = sanitize_int(Yii::app()->request->getParam('surveyid'));
$lang = ( isset($_GET['lang']) ) ? Yii::app()->request->getParam('lang') : NULL;
$tempdir = Yii::app()->getConfig("tempdir");
// Set the language of the survey, either from GET parameter of session var
if ( $lang != NULL )
{
$lang = preg_replace("/[^a-zA-Z0-9-]/", "", $lang);
if ( $lang ) $surveyprintlang = $lang;
}
else
{
$surveyprintlang=Survey::model()->findByPk($iSurveyID)->language;
}
// Setting the selected language for printout
$clang = new limesurvey_lang($surveyprintlang);
Yii::import("application.libraries.admin.quexmlpdf", TRUE);
$quexmlpdf = new quexmlpdf($this->getController());
$quexmlpdf->setLanguage($surveyprintlang);
set_time_limit(120);
$noheader = TRUE;
$quexml = quexml_export($iSurveyID, $surveyprintlang);
$quexmlpdf->create($quexmlpdf->createqueXML($quexml));
//NEED TO GET QID from $quexmlpdf
$qid = intval($quexmlpdf->getQuestionnaireId());
$zipdir= $this->_tempdir($tempdir);
$f1 = "$zipdir/quexf_banding_{$qid}_{$surveyprintlang}.xml";
$f2 = "$zipdir/quexmlpdf_{$qid}_{$surveyprintlang}.pdf";
$f3 = "$zipdir/quexml_{$qid}_{$surveyprintlang}.xml";
$f4 = "$zipdir/readme.txt";
file_put_contents($f1, $quexmlpdf->getLayout());
file_put_contents($f2, $quexmlpdf->Output("quexml_$qid.pdf", 'S'));
file_put_contents($f3, $quexml);
file_put_contents($f4, $clang->gT('This archive contains a PDF file of the survey, the queXML file of the survey and a queXF banding XML file which can be used with queXF: http://quexf.sourceforge.net/ for processing scanned surveys.'));
Yii::app()->loadLibrary('admin.pclzip');
$zipfile="$tempdir/quexmlpdf_{$qid}_{$surveyprintlang}.zip";
$z = new PclZip($zipfile);
$z->create($zipdir, PCLZIP_OPT_REMOVE_PATH, $zipdir);
unlink($f1);
unlink($f2);
unlink($f3);
unlink($f4);
rmdir($zipdir);
$fn = "quexmlpdf_{$qid}_{$surveyprintlang}.zip";
$this->_addHeaders($fn, "application/zip", 0);
header('Content-Transfer-Encoding: binary');
// load the file to send:
readfile($zipfile);
unlink($zipfile);
}
public function resources()
{
switch ( Yii::app()->request->getParam('export') )
{
case 'survey' :
$iSurveyID = sanitize_int(Yii::app()->getRequest()->getParam('surveyid'));
$resourcesdir = 'surveys/' . $iSurveyID;
$zipfilename = "resources-survey-$iSurveyID.zip";
break;
case 'label' :
$lid = sanitize_int(Yii::app()->getRequest()->getParam('lid'));
$resourcesdir = 'labels/' . $lid;
$zipfilename = "resources-labelset-$lid.zip";
break;
}
if (!empty($zipfilename) && !empty($resourcesdir))
{
$resourcesdir = Yii::app()->getConfig('uploaddir') . "/{$resourcesdir}/";
$tmpdir = Yii::app()->getConfig('tempdir') . '/';
$zipfilepath = $tmpdir . $zipfilename;
Yii::app()->loadLibrary('admin.pclzip');
$zip = new PclZip($zipfilepath);
$zipdirs = array();
foreach (array('files', 'flash', 'images') as $zipdir)
{
if (is_dir($resourcesdir . $zipdir))
$zipdirs[] = $resourcesdir . $zipdir . '/';
}
if ($zip->create($zipdirs, PCLZIP_OPT_REMOVE_PATH, $resourcesdir) === 0)
{
die("Error : ".$zip->errorInfo(true));
}
elseif (file_exists($zipfilepath))
{
$this->_addHeaders($zipfilename, 'application/force-download', 0);
readfile($zipfilepath);
unlink($zipfilepath);
exit;
}
}
}
public function dumplabel()
{
$lid = sanitize_int(Yii::app()->request->getParam('lid'));
// DUMP THE RELATED DATA FOR A SINGLE QUESTION INTO A SQL FILE FOR IMPORTING LATER ON OR
// ON ANOTHER SURVEY SETUP DUMP ALL DATA WITH RELATED QID FROM THE FOLLOWING TABLES
// 1. questions
// 2. answers
$lids=returnGlobal('lids');
if ( ! $lid && ! $lids )
{
die('No LID has been provided. Cannot dump label set.');
}
if ( $lid )
{
$lids = array($lid);
}
$lids = array_map('sanitize_int', $lids);
$fn = "limesurvey_labelset_" . implode('_', $lids) . ".lsl";
$xml = getXMLWriter();
$this->_addHeaders($fn, "text/html/force-download", "Mon, 26 Jul 1997 05:00:00 GMT", "cache");
$xml->openURI('php://output');
$xml->setIndent(TRUE);
$xml->startDocument('1.0', 'UTF-8');
$xml->startElement('document');
$xml->writeElement('LimeSurveyDocType', 'Label set');
$xml->writeElement('DBVersion', getGlobalSetting("DBVersion"));
// Label sets table
$lsquery = "SELECT * FROM {{labelsets}} WHERE lid=" . implode(' or lid=', $lids);
buildXMLFromQuery($xml, $lsquery, 'labelsets');
// Labels
$lquery = "SELECT lid, code, title, sortorder, language, assessment_value FROM {{labels}} WHERE lid=" . implode(' or lid=', $lids);
buildXMLFromQuery($xml, $lquery, 'labels');
$xml->endElement(); // close columns
$xml->endDocument();
exit;
}
/**
* Exports a archive (ZIP) of the current survey (structure, responses, timings, tokens)
*
* @param integer $iSurveyID The ID of the survey to export
* @param boolean $bSendToBrowser If TRUE (default) then the ZIP file is sent to the browser
* @return string Full path of the ZIP filename if $bSendToBrowser is set to TRUE, otherwise no return value
*/
private function _exportarchive($iSurveyID, $bSendToBrowser=TRUE)
{
$aSurveyInfo = getSurveyInfo($iSurveyID);
$sTempDir = Yii::app()->getConfig("tempdir");
$aZIPFileName = $sTempDir . DIRECTORY_SEPARATOR . randomChars(30);
$sLSSFileName = $sTempDir . DIRECTORY_SEPARATOR . randomChars(30);
$sLSRFileName = $sTempDir . DIRECTORY_SEPARATOR . randomChars(30);
$sLSTFileName = $sTempDir . DIRECTORY_SEPARATOR . randomChars(30);
$sLSIFileName = $sTempDir . DIRECTORY_SEPARATOR . randomChars(30);
Yii::import('application.libraries.admin.pclzip', TRUE);
$zip = new PclZip($aZIPFileName);
file_put_contents($sLSSFileName, surveyGetXMLData($iSurveyID));
$this->_addToZip($zip, $sLSSFileName, 'survey_' . $iSurveyID . '.lss');
unlink($sLSSFileName);
if ( $aSurveyInfo['active'] == 'Y' )
{
getXMLDataSingleTable($iSurveyID, 'survey_' . $iSurveyID, 'Responses', 'responses', $sLSRFileName, FALSE);
$this->_addToZip($zip, $sLSRFileName, 'survey_' . $iSurveyID . '_responses.lsr');
unlink($sLSRFileName);
}
if ( Yii::app()->db->schema->getTable('{{tokens_' . $iSurveyID . '}}') )
{
getXMLDataSingleTable($iSurveyID, 'tokens_' . $iSurveyID, 'Tokens', 'tokens', $sLSTFileName);
$this->_addToZip($zip, $sLSTFileName, 'survey_' . $iSurveyID . '_tokens.lst');
unlink($sLSTFileName);
}
if ( Yii::app()->db->schema->getTable('{{survey_' . $iSurveyID . '_timings}}') )
{
getXMLDataSingleTable($iSurveyID, 'survey_' . $iSurveyID . '_timings', 'Timings', 'timings', $sLSIFileName);
$this->_addToZip($zip, $sLSIFileName, 'survey_' . $iSurveyID . '_timings.lsi');
unlink($sLSIFileName);
}
if ( is_file($aZIPFileName) )
{
if ( $bSendToBrowser )
{
$fn = "survey_archive_{$iSurveyID}.lsa";
//Send the file for download!
$this->_addHeaders($fn, "application/force-download", 0);
@readfile($aZIPFileName);
//Delete the temporary file
unlink($aZIPFileName);
return;
}
else
{
return($aZIPFileName);
}
}
}
private function _addToZip($zip, $name, $full_name)
{
$zip->add(