/
import_helper.php
2836 lines (2475 loc) · 120 KB
/
import_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.
*/
/**
* This function imports a LimeSurvey .lsg question group XML file
*
* @param string $sFullFilePath The full filepath of the uploaded file
* @param integer $iNewSID The new survey id - the group will always be added after the last group in the survey
*/
function XMLImportGroup($sFullFilePath, $iNewSID)
{
$sBaseLanguage = Survey::model()->findByPk($iNewSID)->language;
if (\PHP_VERSION_ID < 80000) {
$bOldEntityLoaderState = libxml_disable_entity_loader(true); // @see: http://phpsecurity.readthedocs.io/en/latest/Injection-Attacks.html#xml-external-entity-injection
}
$sXMLdata = file_get_contents($sFullFilePath);
$xml = simplexml_load_string($sXMLdata, 'SimpleXMLElement', LIBXML_NONET);
if ($xml === false || $xml->LimeSurveyDocType != 'Group') {
safeDie('This is not a valid LimeSurvey group structure XML file.');
}
$iDBVersion = (int) $xml->DBVersion;
$aQIDReplacements = array();
$aQuestionCodeReplacements = [];
$results['defaultvalues'] = 0;
$results['answers'] = 0;
$results['question_attributes'] = 0;
$results['subquestions'] = 0;
$results['conditions'] = 0;
$results['groups'] = 0;
$results['importwarnings'] = [];
if ($iDBVersion>=400) {
$results['fatalerror'] = gT("The file is not compatible with this LimeSurvey version.");
return $results;
}
$importlanguages = array();
foreach ($xml->languages->language as $language) {
$importlanguages[] = (string) $language;
}
if (!in_array($sBaseLanguage, $importlanguages)) {
$results['fatalerror'] = gT("The languages of the imported group file must at least include the base language of this survey.");
return $results;
}
// First get an overview of fieldnames - it's not useful for the moment but might be with newer versions
/*
$fieldnames=array();
foreach ($xml->questions->fields->fieldname as $fieldname ){
$fieldnames[]=(string)$fieldname;
};*/
// Import group table ===================================================================================
$iGroupOrder = Yii::app()->db->createCommand()->select('MAX(group_order)')->from('{{groups}}')->where('sid=:sid', array(':sid'=>$iNewSID))->queryScalar();
if ($iGroupOrder === false) {
$iNewGroupOrder = 0;
} else {
$iNewGroupOrder = $iGroupOrder + 1;
}
foreach ($xml->groups->rows->row as $row) {
$insertdata = array();
foreach ($row as $key=>$value) {
$insertdata[(string) $key] = (string) $value;
}
$iOldSID = $insertdata['sid'];
$insertdata['sid'] = $iNewSID;
$insertdata['group_order'] = $iNewGroupOrder;
$oldgid = $insertdata['gid']; unset($insertdata['gid']); // save the old qid
// now translate any links
$insertdata['group_name'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['group_name']);
$insertdata['description'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['description']);
// Insert the new question
if (isset($aGIDReplacements[$oldgid])) {
$insertdata['gid'] = $aGIDReplacements[$oldgid];
}
if (isset($insertdata['gid'])) {
switchMSSQLIdentityInsert('groups', true);
}
Yii::app()->db->createCommand()->insert('{{groups}}', $insertdata);
if (isset($insertdata['gid'])) {
switchMSSQLIdentityInsert('groups', false);
}
if (!isset($aGIDReplacements[$oldgid])) {
$newgid = getLastInsertID('{{groups}}');
$aGIDReplacements[$oldgid] = $newgid; // add old and new qid to the mapping array
$results['groups']++;
}
}
// Import questions table ===================================================================================
// We have to run the question table data two times - first to find all main questions
// then for subquestions (because we need to determine the new qids for the main questions first)
$results['questions'] = 0;
if (isset($xml->questions)) {
foreach ($xml->questions->rows->row as $row) {
$insertdata = array();
foreach ($row as $key=>$value) {
$insertdata[(string) $key] = (string) $value;
}
$iOldSID = $insertdata['sid'];
$insertdata['sid'] = $iNewSID;
if (!isset($aGIDReplacements[$insertdata['gid']]) || trim($insertdata['title']) == '') {
// Skip questions with invalid group id
continue;
}
$insertdata['gid'] = $aGIDReplacements[$insertdata['gid']];
$oldqid = $insertdata['qid']; unset($insertdata['qid']); // save the old qid
// now translate any links
$insertdata['title'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['title']);
$insertdata['question'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['question']);
$insertdata['help'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['help']);
// Insert the new question
if (isset($aQIDReplacements[$oldqid])) {
$insertdata['qid'] = $aQIDReplacements[$oldqid];
}
if (isset($insertdata['qid'])) {
switchMSSQLIdentityInsert('questions', true);
}
$oQuestion = new Question('import');
$oQuestion->setAttributes($insertdata, false);
// Try to fix question title for valid question code enforcement
if (!$oQuestion->validate(['title'])) {
$sOldTitle = $oQuestion->title;
$sNewTitle = preg_replace("/[^A-Za-z0-9]/", '', $sOldTitle);
if (is_numeric(substr($sNewTitle, 0, 1))) {
$sNewTitle = 'q'.$sNewTitle;
}
$oQuestion->title = $sNewTitle;
}
$attempts = 0;
// Try to fix question title for unique question code enforcement
$index = 0;
$rand = mt_rand(0, 1024);
while (!$oQuestion->validate(['title'])) {
$sNewTitle = 'r'.$rand.'q'.$index;
$index++;
$oQuestion->title = $sNewTitle;
$attempts++;
if ($attempts > 10) {
safeDie(gT("Error").": Failed to resolve question code problems after 10 attempts.<br />");
}
}
if (!$oQuestion->save()) {
// safeDie(gT("Error while saving: "). print_r($oQuestion->errors, true));
//
// In PHP 5.2.10 a bug is triggered that resets the foreach loop when inserting a record
// For this reason we ignore insertion errors (because it is most likely a duplicate)
// and continue with the next one
continue;
}
// Set a warning if question title was updated
if (isset($sNewTitle) && isset($sOldTitle)) {
$results['importwarnings'][] = sprintf(gT("Question code %s was updated to %s."), $sOldTitle, $sNewTitle);
$aQuestionCodeReplacements[$sOldTitle] = $sNewTitle;
unset($sNewTitle);
unset($sOldTitle);
}
if (isset($insertdata['qid'])) {
switchMSSQLIdentityInsert('questions', false);
}
$newqid = $oQuestion->qid;
if (!isset($aQIDReplacements[$oldqid])) {
$aQIDReplacements[$oldqid] = $newqid;
$results['questions']++;
}
}
}
// Import subquestions --------------------------------------------------------------
if (isset($xml->subquestions)) {
foreach ($xml->subquestions->rows->row as $row) {
$insertdata = array();
foreach ($row as $key=>$value) {
$insertdata[(string) $key] = (string) $value;
}
$insertdata['sid'] = $iNewSID;
if (!isset($aGIDReplacements[$insertdata['gid']])) {
// Skip questions with invalid group id
continue;
}
$insertdata['gid'] = $aGIDReplacements[(int) $insertdata['gid']]; ;
$oldsqid = (int) $insertdata['qid']; unset($insertdata['qid']); // save the old qid
if (!isset($aQIDReplacements[(int) $insertdata['parent_qid']])) {
// Skip questions with invalid parent qid
continue;
}
$insertdata['parent_qid'] = $aQIDReplacements[(int) $insertdata['parent_qid']]; // remap the parent_qid
// now translate any links
$insertdata['title'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['title']);
$insertdata['question'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['question']);
$insertdata['help'] = translateLinks('survey', $iOldSID, $iNewSID, !empty($insertdata['help']) ? $insertdata['help'] : '');
if (isset($aQIDReplacements[$oldsqid])) {
$insertdata['qid'] = $aQIDReplacements[$oldsqid];
}
if (isset($insertdata['qid'])) {
switchMSSQLIdentityInsert('questions', true);
}
$oQuestion = new Question('import');
$oQuestion->setAttributes($insertdata, false);
// Try to fix question title for valid question code enforcement
if (!$oQuestion->validate(['title'])) {
$sOldTitle = $oQuestion->title;
$sNewTitle = preg_replace("/[^A-Za-z0-9]/", '', $sOldTitle);
if (is_numeric(substr($sNewTitle, 0, 1))) {
$sNewTitle = 'sq'.$sNewTitle;
}
$oQuestion->title = $sNewTitle;
}
$attempts = 0;
// Try to fix question title for unique question code enforcement
$index = 0;
$rand = mt_rand(0, 1024);
while (!$oQuestion->validate(['title'])) {
$sNewTitle = 'r'.$rand.'sq'.$index;
$index++;
$oQuestion->title = $sNewTitle;
$attempts++;
if ($attempts > 10) {
safeDie(gT("Error").": Failed to resolve question code problems after 10 attempts.<br />");
}
}
if (!$oQuestion->save()) {
// safeDie(gT("Error while saving: "). print_r($oQuestion->errors, true));
//
// In PHP 5.2.10 a bug is triggered that resets the foreach loop when inserting a record
// For this reason we ignore insertion errors (because it is most likely a duplicate)
// and continue with the next one
continue;
}
// Set a warning if question title was updated
if (isset($sNewTitle) && isset($sOldTitle)) {
$results['importwarnings'][] = sprintf(gT("Title of subquestion %s was updated to %s."), $sOldTitle, $sNewTitle); // Maybe add the question title ?
$aQuestionCodeReplacements[$sOldTitle] = $sNewTitle;
unset($sNewTitle);
unset($sOldTitle);
}
$newsqid = $oQuestion->qid;
if (!isset($insertdata['qid'])) {
$aQIDReplacements[$oldsqid] = $newsqid; // add old and new qid to the mapping array
} else {
switchMSSQLIdentityInsert('questions', false);
}
$results['subquestions']++;
}
}
// Import answers --------------------------------------------------------------
if (isset($xml->answers)) {
foreach ($xml->answers->rows->row as $row) {
$insertdata = array();
foreach ($row as $key=>$value) {
$insertdata[(string) $key] = (string) $value;
}
if (!isset($aQIDReplacements[(int) $insertdata['qid']])) {
// Skip questions with invalid group id
continue;
}
$insertdata['qid'] = $aQIDReplacements[(int) $insertdata['qid']]; // remap the parent_qid
// now translate any links
Yii::app()->db->createCommand()->insert('{{answers}}', $insertdata);
$results['answers']++;
}
}
// Import questionattributes --------------------------------------------------------------
if (isset($xml->question_attributes)) {
$aAllAttributes = \LimeSurvey\Helpers\questionHelper::getAttributesDefinitions();
foreach ($xml->question_attributes->rows->row as $row) {
$insertdata = array();
foreach ($row as $key=>$value) {
$insertdata[(string) $key] = (string) $value;
}
unset($insertdata['qaid']);
if (!isset($aQIDReplacements[(int) $insertdata['qid']])) {
// Skip questions with invalid group id
continue;
}
$insertdata['qid'] = $aQIDReplacements[(int) $insertdata['qid']]; // remap the parent_qid
if ($iDBVersion < 156 && isset($aAllAttributes[$insertdata['attribute']]['i18n']) && $aAllAttributes[$insertdata['attribute']]['i18n']) {
foreach ($importlanguages as $sLanguage) {
$insertdata['language'] = $sLanguage;
Yii::app()->db->createCommand()->insert('{{question_attributes}}', $insertdata);
}
} else {
Yii::app()->db->createCommand()->insert('{{question_attributes}}', $insertdata);
}
$results['question_attributes']++;
}
}
// Import defaultvalues --------------------------------------------------------------
if (isset($xml->defaultvalues)) {
$results['defaultvalues'] = 0;
foreach ($xml->defaultvalues->rows->row as $row) {
$insertdata = array();
foreach ($row as $key=>$value) {
$insertdata[(string) $key] = (string) $value;
}
$insertdata['qid'] = $aQIDReplacements[(int) $insertdata['qid']]; // remap the qid
if ($insertdata['sqid'] > 0) {
if (!isset($aQIDReplacements[(int) $insertdata['sqid']])) {
// Skip questions with invalid subquestion id
continue;
}
$insertdata['sqid'] = $aQIDReplacements[(int) $insertdata['sqid']]; // remap the subquestion id
}
// now translate any links
Yii::app()->db->createCommand()->insert('{{defaultvalues}}', $insertdata);
$results['defaultvalues']++;
}
}
// Import conditions --------------------------------------------------------------
if (isset($xml->conditions)) {
foreach ($xml->conditions->rows->row as $row) {
$insertdata = array();
foreach ($row as $key=>$value) {
$insertdata[(string) $key] = (string) $value;
}
// replace the qid for the new one (if there is no new qid in the $aQIDReplacements array it mean that this condition is orphan -> error, skip this record)
if (isset($aQIDReplacements[$insertdata['qid']])) {
$insertdata['qid'] = $aQIDReplacements[$insertdata['qid']]; // remap the qid
} else {
// a problem with this answer record -> don't consider
continue;
}
if (isset($aQIDReplacements[$insertdata['cqid']])) {
$insertdata['cqid'] = $aQIDReplacements[$insertdata['cqid']]; // remap the qid
} else {
// a problem with this answer record -> don't consider
continue;
}
list($oldcsid, $oldcgid, $oldqidanscode) = explode("X", $insertdata["cfieldname"], 3);
if ($oldcgid != $oldgid) {
// this means that the condition is in another group (so it should not have to be been exported -> skip it
continue;
}
unset($insertdata["cid"]);
// recreate the cfieldname with the new IDs
if (preg_match("/^\+/", $oldcsid)) {
$newcfieldname = '+'.$iNewSID."X".$newgid."X".$insertdata["cqid"].substr($oldqidanscode, strlen($oldqid));
} else {
$newcfieldname = $iNewSID."X".$newgid."X".$insertdata["cqid"].substr($oldqidanscode, strlen($oldqid));
}
$insertdata["cfieldname"] = $newcfieldname;
if (trim($insertdata["method"]) == '') {
$insertdata["method"] = '==';
}
// now translate any links
Yii::app()->db->createCommand()->insert('{{conditions}}', $insertdata);
$results['conditions']++;
}
}
replaceExpressionCodes($iNewSID, $aQuestionCodeReplacements);
LimeExpressionManager::RevertUpgradeConditionsToRelevance($iNewSID);
LimeExpressionManager::UpgradeConditionsToRelevance($iNewSID);
$results['newgid'] = $newgid;
$results['labelsets'] = 0;
$results['labels'] = 0;
if (\PHP_VERSION_ID < 80000) {
libxml_disable_entity_loader($bOldEntityLoaderState); // Put back entity loader to its original state, to avoid contagion to other applications on the server
}
return $results;
}
/**
* This function imports a LimeSurvey .lsq question XML file
*
* @param string $sFullFilePath The full filepath of the uploaded file
* @param integer $iNewSID The new survey id
* @param mixed $newgid The new question group id -the question will always be added after the last question in the group
*/
function XMLImportQuestion($sFullFilePath, $iNewSID, $newgid, $options = array('autorename'=>false))
{
$sBaseLanguage = Survey::model()->findByPk($iNewSID)->language;
$sXMLdata = file_get_contents($sFullFilePath);
$xml = simplexml_load_string($sXMLdata, 'SimpleXMLElement', LIBXML_NONET);
if ($xml->LimeSurveyDocType != 'Question') {
safeDie('This is not a valid LimeSurvey question structure XML file.');
}
$iDBVersion = (int) $xml->DBVersion;
if ($iDBVersion>=400) {
$results['fatalerror'] = gT("The file is not compatible with this LimeSurvey version.");
return $results;
}
$aQIDReplacements = array();
$aSQIDReplacements = array(0=>0);
$results['defaultvalues'] = 0;
$results['answers'] = 0;
$results['question_attributes'] = 0;
$results['subquestions'] = 0;
$importlanguages = array();
foreach ($xml->languages->language as $language) {
$importlanguages[] = (string) $language;
}
if (!in_array($sBaseLanguage, $importlanguages)) {
$results['fatalerror'] = gT("The languages of the imported question file must at least include the base language of this survey.");
return $results;
}
// First get an overview of fieldnames - it's not useful for the moment but might be with newer versions
/*
$fieldnames=array();
foreach ($xml->questions->fields->fieldname as $fieldname ){
$fieldnames[]=(string)$fieldname;
};*/
// Import questions table ===================================================================================
// We have to run the question table data two times - first to find all main questions
// then for subquestions (because we need to determine the new qids for the main questions first)
$query = "SELECT MAX(question_order) AS maxqo FROM {{questions}} WHERE sid=$iNewSID AND gid=$newgid";
$res = Yii::app()->db->createCommand($query)->query();
$resrow = $res->read();
$newquestionorder = $resrow['maxqo'] + 1;
if (is_null($newquestionorder)) {
$newquestionorder = 0;
} else {
$newquestionorder++;
}
foreach ($xml->questions->rows->row as $row) {
$insertdata = array();
foreach ($row as $key=>$value) {
$insertdata[(string) $key] = (string) $value;
}
$iOldSID = $insertdata['sid'];
$insertdata['sid'] = $iNewSID;
$insertdata['gid'] = $newgid;
$insertdata['question_order'] = $newquestionorder;
$oldqid = $insertdata['qid']; unset($insertdata['qid']); // save the old qid
// now translate any links
$insertdata['title'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['title']);
$insertdata['question'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['question']);
$insertdata['help'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['help']);
// Insert the new question
if (isset($aQIDReplacements[$oldqid])) {
$insertdata['qid'] = $aQIDReplacements[$oldqid];
}
$oQuestion = new Question('import');
$oQuestion->setAttributes($insertdata, false);
if (!$oQuestion->validate(array('title')) && $options['autorename']) {
if (isset($sNewTitle)) {
$oQuestion->title = $sNewTitle;
} else {
$sOldTitle = $oQuestion->title;
$oQuestion->title = $sNewTitle = $oQuestion->getNewTitle();
if (!$sNewTitle) {
$results['fatalerror'] = CHtml::errorSummary($oQuestion, gT("The question could not be imported for the following reasons:"));
return $results;
}
$results['importwarnings'][] = sprintf(gT("Question code %s was updated to %s."), $sOldTitle, $sNewTitle);
}
}
if (isset($insertdata['qid'])) {
switchMSSQLIdentityInsert('questions', true);
}
if (!$oQuestion->save()) {
$results['fatalerror'] = CHtml::errorSummary($oQuestion, gT("The question could not be imported for the following reasons:"));
return $results;
}
if (isset($insertdata['qid'])) {
switchMSSQLIdentityInsert('questions', false);
}
if (!isset($aQIDReplacements[$oldqid])) {
$newqid = $aQIDReplacements[$oldqid] = $oQuestion->qid;
}
}
// Import subquestions --------------------------------------------------------------
if (isset($xml->subquestions)) {
foreach ($xml->subquestions->rows->row as $row) {
$insertdata = array();
foreach ($row as $key=>$value) {
$insertdata[(string) $key] = (string) $value;
}
$insertdata['sid'] = $iNewSID;
$insertdata['gid'] = $newgid;
$oldsqid = (int) $insertdata['qid']; unset($insertdata['qid']); // save the old qid
$insertdata['parent_qid'] = $aQIDReplacements[(int) $insertdata['parent_qid']]; // remap the parent_qid
// now translate any links
$insertdata['question'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['question']);
if (isset($insertdata['help'])) {
$insertdata['help'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['help']);
}
if (isset($aQIDReplacements[$oldsqid])) {
$insertdata['qid'] = $aQIDReplacements[$oldsqid];
}
$ques = new Question;
foreach ($insertdata as $k => $v) {
$ques->$k = $v;
}
$result = $ques->save();
if ($result) {
$newsqid = getLastInsertID($ques->tableName());
if (!isset($insertdata['qid'])) {
$aQIDReplacements[$oldsqid] = $newsqid; // add old and new qid to the mapping array
}
$results['subquestions']++;
}
}
}
// Import answers --------------------------------------------------------------
if (isset($xml->answers)) {
foreach ($xml->answers->rows->row as $row) {
$insertdata = array();
foreach ($row as $key=>$value) {
$insertdata[(string) $key] = (string) $value;
}
$insertdata['qid'] = $aQIDReplacements[(int) $insertdata['qid']]; // remap the parent_qid
$answers = new Answer;
foreach ($insertdata as $k => $v) {
$answers->$k = $v;
}
$answers->save();
$results['answers']++;
}
}
// Import questionattributes --------------------------------------------------------------
if (isset($xml->question_attributes)) {
$aAllAttributes = \LimeSurvey\Helpers\questionHelper::getAttributesDefinitions();
foreach ($xml->question_attributes->rows->row as $row) {
$insertdata = array();
foreach ($row as $key=>$value) {
$insertdata[(string) $key] = (string) $value;
}
unset($insertdata['qaid']);
$insertdata['qid'] = $aQIDReplacements[(integer) $insertdata['qid']]; // remap the parent_qid
if ($iDBVersion < 156 && isset($aAllAttributes[$insertdata['attribute']]['i18n']) && $aAllAttributes[$insertdata['attribute']]['i18n']) {
foreach ($importlanguages as $sLanguage) {
$insertdata['language'] = $sLanguage;
$attributes = new QuestionAttribute;
foreach ($insertdata as $k => $v) {
$attributes->$k = $v;
}
$attributes->save();
}
} else {
$attributes = new QuestionAttribute;
foreach ($insertdata as $k => $v) {
$attributes->$k = $v;
}
$attributes->save();
}
$results['question_attributes']++;
}
}
// Import defaultvalues --------------------------------------------------------------
if (isset($xml->defaultvalues)) {
$results['defaultvalues'] = 0;
foreach ($xml->defaultvalues->rows->row as $row) {
$insertdata = array();
foreach ($row as $key=>$value) {
$insertdata[(string) $key] = (string) $value;
}
$insertdata['qid'] = $aQIDReplacements[(int) $insertdata['qid']]; // remap the qid
$insertdata['sqid'] = $aSQIDReplacements[(int) $insertdata['sqid']]; // remap the subquestion id
// now translate any links
$default = new DefaultValue;
foreach ($insertdata as $k => $v) {
$default->$k = $v;
}
$default->save();
$results['defaultvalues']++;
}
}
LimeExpressionManager::SetDirtyFlag(); // so refreshes syntax highlighting
$results['newqid'] = $newqid;
$results['questions'] = 1;
$results['labelsets'] = 0;
$results['labels'] = 0;
return $results;
}
/**
* XMLImportLabelsets()
* Function resp[onsible to import a labelset from XML format.
* @param string $sFullFilePath
* @param mixed $options
* @return
*/
function XMLImportLabelsets($sFullFilePath, $options)
{
$sXMLdata = (string) file_get_contents($sFullFilePath);
$xml = simplexml_load_string($sXMLdata, 'SimpleXMLElement', LIBXML_NONET);
if ($xml->LimeSurveyDocType != 'Label set') {
safeDie('This is not a valid LimeSurvey label set structure XML file.');
}
$csarray = buildLabelSetCheckSumArray();
$aLSIDReplacements = $results = [];
$results['labelsets'] = 0;
$results['labels'] = 0;
$results['warnings'] = array();
// Import label sets table ===================================================================================
foreach ($xml->labelsets->rows->row as $row) {
$insertdata = array();
foreach ($row as $key=>$value) {
$insertdata[(string) $key] = (string) $value;
}
$oldlsid = $insertdata['lid'];
unset($insertdata['lid']); // save the old qid
// Insert the new question
Yii::app()->db->createCommand()->insert('{{labelsets}}', $insertdata);
$results['labelsets']++;
$newlsid = getLastInsertID('{{labelsets}}');
$aLSIDReplacements[$oldlsid] = $newlsid; // add old and new lsid to the mapping array
}
// Import labels table ===================================================================================
if (isset($xml->labels->rows->row)) {
foreach ($xml->labels->rows->row as $row) {
$insertdata = [];
foreach ($row as $key=>$value) {
$insertdata[(string) $key] = (string) $value;
}
$insertdata['lid'] = $aLSIDReplacements[$insertdata['lid']];
Yii::app()->db->createCommand()->insert('{{labels}}', $insertdata);
$results['labels']++;
}
}
//CHECK FOR DUPLICATE LABELSETS
if (isset($_POST['checkforduplicates'])) {
foreach (array_values($aLSIDReplacements) as $newlid) {
$thisset = "";
$query2 = "SELECT code, title, sortorder, language, assessment_value
FROM {{labels}}
WHERE lid=".$newlid."
ORDER BY language, sortorder, code";
$result2 = Yii::app()->db->createCommand($query2)->query();
foreach ($result2->readAll() as $row2) {
$row2 = array_values($row2);
$thisset .= implode('.', $row2);
} // while
$newcs = hash('sha256', $thisset);
unset($lsmatch);
if (isset($csarray) && $options['checkforduplicates'] == 'on') {
foreach ($csarray as $key=>$val) {
if (hash_equals($val,$newcs)) {
$lsmatch = $key;
}
}
}
if (isset($lsmatch)) {
//There is a matching labelset. So, we will delete this one and refer
//to the matched one.
$query = "DELETE FROM {{labels}} WHERE lid=$newlid";
$result = Yii::app()->db->createCommand($query)->execute();
$results['labels'] = $results['labels'] - $result;
$query = "DELETE FROM {{labelsets}} WHERE lid=$newlid";
Yii::app()->db->createCommand($query)->query();
$results['labelsets']--;
$newlid = $lsmatch;
$results['warnings'][] = gT("Label set was not imported because the same label set already exists.")." ".sprintf(gT("Existing LID: %s"), $newlid);
}
}
//END CHECK FOR DUPLICATES
}
return $results;
}
/**
* @param string $sFullFilePath
* @param boolean $bTranslateLinksFields
* @param string $sNewSurveyName
* @param integer $DestSurveyID
*/
function importSurveyFile($sFullFilePath, $bTranslateLinksFields, $sNewSurveyName = null, $DestSurveyID = null)
{
$aPathInfo = pathinfo($sFullFilePath);
if (isset($aPathInfo['extension'])) {
$sExtension = strtolower($aPathInfo['extension']);
} else {
$sExtension = "";
}
switch ($sExtension) {
case 'lss':
$aImportResults = XMLImportSurvey($sFullFilePath, null, $sNewSurveyName, $DestSurveyID, $bTranslateLinksFields);
if (!empty($aImportResults['newsid'])) {
TemplateConfiguration::checkAndcreateSurveyConfig($aImportResults['newsid']);
}
return $aImportResults;
case 'txt':
case 'tsv':
$aImportResults = TSVImportSurvey($sFullFilePath);
if ($aImportResults && $aImportResults['newsid']) {
TemplateConfiguration::checkAndcreateSurveyConfig($aImportResults['newsid']);
}
return $aImportResults;
case 'lsa':
// Import a survey archive
Yii::import("application.libraries.admin.pclzip.pclzip", true);
$pclzip = new PclZip(array('p_zipname' => $sFullFilePath));
$aFiles = $pclzip->listContent();
if ($pclzip->extract(PCLZIP_OPT_PATH, Yii::app()->getConfig('tempdir').DIRECTORY_SEPARATOR, PCLZIP_OPT_BY_EREG, '/(lss|lsr|lsi|lst)$/') == 0) {
unset($pclzip);
}
$aImportResults = [];
// Step 1 - import the LSS file and activate the survey
foreach ($aFiles as $aFile) {
if (pathinfo($aFile['filename'], PATHINFO_EXTENSION) == 'lss') {
//Import the LSS file
$aImportResults = XMLImportSurvey(Yii::app()->getConfig('tempdir').DIRECTORY_SEPARATOR.$aFile['filename'], null, null, null, true, false);
if ($aImportResults && $aImportResults['newsid']) {
TemplateConfiguration::checkAndcreateSurveyConfig($aImportResults['newsid']);
}
// Activate the survey
Yii::app()->loadHelper("admin/activate");
activateSurvey($aImportResults['newsid']);
unlink(Yii::app()->getConfig('tempdir').DIRECTORY_SEPARATOR.$aFile['filename']);
break;
}
}
// Step 2 - import the responses file
foreach ($aFiles as $aFile) {
if (pathinfo($aFile['filename'], PATHINFO_EXTENSION) == 'lsr') {
//Import the LSS file
$aResponseImportResults = XMLImportResponses(Yii::app()->getConfig('tempdir').DIRECTORY_SEPARATOR.$aFile['filename'], $aImportResults['newsid'], $aImportResults['FieldReMap']);
$aImportResults = array_merge($aResponseImportResults, $aImportResults);
unlink(Yii::app()->getConfig('tempdir').DIRECTORY_SEPARATOR.$aFile['filename']);
break;
}
}
// Step 3 - import the tokens file - if exists
foreach ($aFiles as $aFile) {
if (pathinfo($aFile['filename'], PATHINFO_EXTENSION) == 'lst') {
Yii::app()->loadHelper("admin/token");
$aTokenImportResults = [];
if (Token::createTable($aImportResults['newsid'])) {
$aTokenCreateResults = array('tokentablecreated' => true);
$aImportResults = array_merge($aTokenCreateResults, $aImportResults);
$aTokenImportResults = XMLImportTokens(Yii::app()->getConfig('tempdir').DIRECTORY_SEPARATOR.$aFile['filename'], $aImportResults['newsid']);
} else {
$aTokenImportResults['warnings'][] = gT("Unable to create survey participants table");
}
$aImportResults = array_merge_recursive($aTokenImportResults, $aImportResults);
$aImportResults['importwarnings'] = array_merge($aImportResults['importwarnings'], $aImportResults['warnings']);
unlink(Yii::app()->getConfig('tempdir').DIRECTORY_SEPARATOR.$aFile['filename']);
break;
}
}
// Step 4 - import the timings file - if exists
Yii::app()->db->schema->refresh();
foreach ($aFiles as $aFile) {
if (pathinfo($aFile['filename'], PATHINFO_EXTENSION) == 'lsi' && tableExists("survey_{$aImportResults['newsid']}_timings")) {
$aTimingsImportResults = XMLImportTimings(Yii::app()->getConfig('tempdir').DIRECTORY_SEPARATOR.$aFile['filename'], $aImportResults['newsid'], $aImportResults['FieldReMap']);
$aImportResults = array_merge($aTimingsImportResults, $aImportResults);
unlink(Yii::app()->getConfig('tempdir').DIRECTORY_SEPARATOR.$aFile['filename']);
break;
}
}
return $aImportResults;
default:
// Unknow file , return null why not throw error ?
return null;
}
}
/**
* This function imports a LimeSurvey .lss survey XML file
*
* @param string $sFullFilePath The full filepath of the uploaded file
* @param string $sXMLdata
*/
function XMLImportSurvey($sFullFilePath, $sXMLdata = null, $sNewSurveyName = null, $iDesiredSurveyId = null, $bTranslateInsertansTags = true, $bConvertInvalidQuestionCodes = true)
{
$isCopying = ($sNewSurveyName != null);
Yii::app()->loadHelper('database');
$results = [];
$aGIDReplacements = array();
if ($sXMLdata === null) {
$sXMLdata = (string) file_get_contents($sFullFilePath);
}
$xml = @simplexml_load_string($sXMLdata, 'SimpleXMLElement', LIBXML_NONET | LIBXML_PARSEHUGE);
if (!$xml || $xml->LimeSurveyDocType != 'Survey') {
$results['error'] = gT("This is not a valid LimeSurvey survey structure XML file.");
return $results;
}
$iDBVersion = (int) $xml->DBVersion;
$aQIDReplacements = array();
$aQuestionCodeReplacements = array();
$aQuotaReplacements = array();
$results['defaultvalues'] = 0;
$results['answers'] = 0;
$results['surveys'] = 0;
$results['questions'] = 0;
$results['subquestions'] = 0;
$results['question_attributes'] = 0;
$results['groups'] = 0;
$results['assessments'] = 0;
$results['quota'] = 0;
$results['quotals'] = 0;
$results['quotamembers'] = 0;
$results['plugin_settings'] = 0;
$results['themes'] = 0;
$results['survey_url_parameters'] = 0;
$results['importwarnings'] = array();
$results['theme_options_original_data'] = '';
$results['theme_options_differences'] = array();
$sTemplateName = '';
if ($iDBVersion>=400) {
$results['error'] = gT("The file is not compatible with this LimeSurvey version.");
return $results;
}
$aLanguagesSupported = array();
foreach ($xml->languages->language as $language) {
$aLanguagesSupported[] = (string) $language;
}
$results['languages'] = count($aLanguagesSupported);
// Import surveys table ====================================================
foreach ($xml->surveys->rows->row as $row) {
$insertdata = array();
foreach ($row as $key=>$value) {
// Set survey group id to default if not a copy
if ($key == 'gsid' & !$isCopying) {
$value = 1;
}
if ($key == 'template') {
$sTemplateName = (string)$value;
}
$insertdata[(string) $key] = (string) $value;
}
$iOldSID = $results['oldsid'] = $insertdata['sid'];
// Fix#14609 wishSID overwrite sid
if(!is_null($iDesiredSurveyId)) {
$insertdata['sid'] = $iDesiredSurveyId;
}
if ($iDBVersion < 145) {
if (isset($insertdata['private'])) {
$insertdata['anonymized'] = $insertdata['private'];
}
unset($insertdata['private']);
unset($insertdata['notification']);
}
//Make sure it is not set active
$insertdata['active'] = 'N';
//Set current user to be the owner
$insertdata['owner_id'] = Yii::app()->session['loginID'];
if (isset($insertdata['bouncetime']) && $insertdata['bouncetime'] == '') {
$insertdata['bouncetime'] = null;
}
if (isset($insertdata['showXquestions'])) {
$insertdata['showxquestions'] = $insertdata['showXquestions'];
unset($insertdata['showXquestions']);
}
if (isset($insertdata['googleAnalyticsStyle'])) {
$insertdata['googleanalyticsstyle'] = $insertdata['googleAnalyticsStyle'];
unset($insertdata['googleAnalyticsStyle']);
}
if (isset($insertdata['googleAnalyticsAPIKey'])) {
$insertdata['googleanalyticsapikey'] = $insertdata['googleAnalyticsAPIKey'];
unset($insertdata['googleAnalyticsAPIKey']);
}
if (isset($insertdata['allowjumps'])) {
$insertdata['questionindex'] = ($insertdata['allowjumps'] == "Y") ? 1 : 0;
unset($insertdata['allowjumps']);
}
if (isset($insertdata['tokenlength']) && $insertdata['tokenlength']>35) {
$insertdata['tokenlength']=35;
}