PageRenderTime 61ms CodeModel.GetById 27ms RepoModel.GetById 1ms app.codeStats 0ms

/limesurvey/admin/import_functions.php

https://github.com/tacman/citrus
PHP | 1578 lines | 1277 code | 158 blank | 143 comment | 211 complexity | d0851a062926dcf4274332e576026833 MD5 | raw file
Possible License(s): GPL-3.0, BSD-3-Clause, LGPL-2.1, LGPL-3.0, GPL-2.0, Apache-2.0

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. /*
  3. * LimeSurvey
  4. * Copyright (C) 2007 The LimeSurvey Project Team / Carsten Schmitz
  5. * All rights reserved.
  6. * License: GNU/GPL License v2 or later, see LICENSE.php
  7. * LimeSurvey is free software. This version may have been modified pursuant
  8. * to the GNU General Public License, and as distributed it includes or
  9. * is derivative of works licensed under the GNU General Public License or
  10. * other free or open source software licenses.
  11. * See COPYRIGHT.php for copyright notices and details.
  12. *
  13. * $Id: import_functions.php 9586 2010-12-06 03:08:07Z c_schmitz $
  14. * Files Purpose:
  15. */
  16. /**
  17. * This function imports the old CSV data from 1.50 to 1.87 or older. Starting with 1.90 (DBVersion 143) there is an XML format instead
  18. *
  19. * @param array $sFullFilepath
  20. * @returns array Information of imported questions/answers/etc.
  21. */
  22. function CSVImportSurvey($sFullFilepath,$iDesiredSurveyId=NULL)
  23. {
  24. global $dbprefix, $connect, $timeadjust, $clang;
  25. $handle = fopen($sFullFilepath, "r");
  26. while (!feof($handle))
  27. {
  28. $buffer = fgets($handle);
  29. $bigarray[] = $buffer;
  30. }
  31. fclose($handle);
  32. $aIgnoredAnswers=array();
  33. $aSQIDReplacements=array();
  34. $aLIDReplacements=array();
  35. $aGIDReplacements=array();
  36. $substitutions=array();
  37. $aQuotaReplacements=array();
  38. $importresults['importwarnings']=array();
  39. $importresults['question_attributes']=0;
  40. if (isset($bigarray[0])) $bigarray[0]=removeBOM($bigarray[0]);
  41. // Now we try to determine the dataformat of the survey file.
  42. $importversion=0;
  43. if (isset($bigarray[1]) && isset($bigarray[4])&& (substr($bigarray[1], 0, 22) == "# SURVEYOR SURVEY DUMP"))
  44. {
  45. $importversion = 100; // Version 0.99 or 1.0 file
  46. }
  47. elseif
  48. (substr($bigarray[0], 0, 24) == "# LimeSurvey Survey Dump" || substr($bigarray[0], 0, 25) == "# PHPSurveyor Survey Dump")
  49. { // Seems to be a >1.0 version file - these files carry the version information to read in line two
  50. $importversion=substr($bigarray[1], 12, 3);
  51. }
  52. else // unknown file - show error message
  53. {
  54. if ($importingfrom == "http")
  55. {
  56. $importsurvey .= "<div class='warningheader'>".$clang->gT("Error")."</div><br />\n";
  57. $importsurvey .= $clang->gT("This file is not a LimeSurvey survey file. Import failed.")."<br /><br />\n";
  58. $importsurvey .= "<input type='submit' value='".$clang->gT("Main Admin Screen")."' onclick=\"window.open('$scriptname', '_top')\" />\n";
  59. $importsurvey .= "</div>\n";
  60. unlink($sFullFilepath);
  61. return;
  62. }
  63. else
  64. {
  65. echo $clang->gT("This file is not a LimeSurvey survey file. Import failed.")."\n";
  66. return;
  67. }
  68. }
  69. if ((int)$importversion<112)
  70. {
  71. $results['fatalerror'] = $clang->gT("This file is too old. Only files from LimeSurvey version 1.50 (DBVersion 112) and newer are supported.");
  72. }
  73. // okay.. now lets drop the first 9 lines and get to the data
  74. // This works for all versions
  75. for ($i=0; $i<9; $i++)
  76. {
  77. unset($bigarray[$i]);
  78. }
  79. $bigarray = array_values($bigarray);
  80. //SURVEYS
  81. if (array_search("# GROUPS TABLE\n", $bigarray))
  82. {
  83. $stoppoint = array_search("# GROUPS TABLE\n", $bigarray);
  84. }
  85. elseif (array_search("# GROUPS TABLE\r\n", $bigarray))
  86. {
  87. $stoppoint = array_search("# GROUPS TABLE\r\n", $bigarray);
  88. }
  89. for ($i=0; $i<=$stoppoint+1; $i++)
  90. {
  91. if ($i<$stoppoint-2) {$surveyarray[] = $bigarray[$i];}
  92. unset($bigarray[$i]);
  93. }
  94. $bigarray = array_values($bigarray);
  95. //GROUPS
  96. if (array_search("# QUESTIONS TABLE\n", $bigarray))
  97. {
  98. $stoppoint = array_search("# QUESTIONS TABLE\n", $bigarray);
  99. }
  100. elseif (array_search("# QUESTIONS TABLE\r\n", $bigarray))
  101. {
  102. $stoppoint = array_search("# QUESTIONS TABLE\r\n", $bigarray);
  103. }
  104. else
  105. {
  106. $stoppoint = count($bigarray)-1;
  107. }
  108. for ($i=0; $i<=$stoppoint+1; $i++)
  109. {
  110. if ($i<$stoppoint-2) {$grouparray[] = $bigarray[$i];}
  111. unset($bigarray[$i]);
  112. }
  113. $bigarray = array_values($bigarray);
  114. //QUESTIONS
  115. if (array_search("# ANSWERS TABLE\n", $bigarray))
  116. {
  117. $stoppoint = array_search("# ANSWERS TABLE\n", $bigarray);
  118. }
  119. elseif (array_search("# ANSWERS TABLE\r\n", $bigarray))
  120. {
  121. $stoppoint = array_search("# ANSWERS TABLE\r\n", $bigarray);
  122. }
  123. else
  124. {
  125. $stoppoint = count($bigarray)-1;
  126. }
  127. for ($i=0; $i<=$stoppoint+1; $i++)
  128. {
  129. if ($i<$stoppoint-2)
  130. {
  131. $questionarray[] = $bigarray[$i];
  132. }
  133. unset($bigarray[$i]);
  134. }
  135. $bigarray = array_values($bigarray);
  136. //ANSWERS
  137. if (array_search("# CONDITIONS TABLE\n", $bigarray))
  138. {
  139. $stoppoint = array_search("# CONDITIONS TABLE\n", $bigarray);
  140. }
  141. elseif (array_search("# CONDITIONS TABLE\r\n", $bigarray))
  142. {
  143. $stoppoint = array_search("# CONDITIONS TABLE\r\n", $bigarray);
  144. }
  145. else
  146. {
  147. $stoppoint = count($bigarray)-1;
  148. }
  149. for ($i=0; $i<=$stoppoint+1; $i++)
  150. {
  151. if ($i<$stoppoint-2)
  152. {
  153. $answerarray[] = str_replace("`default`", "`default_value`", $bigarray[$i]);
  154. }
  155. unset($bigarray[$i]);
  156. }
  157. $bigarray = array_values($bigarray);
  158. //CONDITIONS
  159. if (array_search("# LABELSETS TABLE\n", $bigarray))
  160. {
  161. $stoppoint = array_search("# LABELSETS TABLE\n", $bigarray);
  162. }
  163. elseif (array_search("# LABELSETS TABLE\r\n", $bigarray))
  164. {
  165. $stoppoint = array_search("# LABELSETS TABLE\r\n", $bigarray);
  166. }
  167. for ($i=0; $i<=$stoppoint+1; $i++)
  168. {
  169. if ($i<$stoppoint-2) {$conditionsarray[] = $bigarray[$i];}
  170. unset($bigarray[$i]);
  171. }
  172. $bigarray = array_values($bigarray);
  173. //LABELSETS
  174. if (array_search("# LABELS TABLE\n", $bigarray))
  175. {
  176. $stoppoint = array_search("# LABELS TABLE\n", $bigarray);
  177. }
  178. elseif (array_search("# LABELS TABLE\r\n", $bigarray))
  179. {
  180. $stoppoint = array_search("# LABELS TABLE\r\n", $bigarray);
  181. }
  182. else
  183. {
  184. $stoppoint = count($bigarray)-1;
  185. }
  186. for ($i=0; $i<=$stoppoint+1; $i++)
  187. {
  188. if ($i<$stoppoint-2) {$labelsetsarray[] = $bigarray[$i];}
  189. unset($bigarray[$i]);
  190. }
  191. $bigarray = array_values($bigarray);
  192. //LABELS
  193. if (array_search("# QUESTION_ATTRIBUTES TABLE\n", $bigarray))
  194. {
  195. $stoppoint = array_search("# QUESTION_ATTRIBUTES TABLE\n", $bigarray);
  196. }
  197. elseif (array_search("# QUESTION_ATTRIBUTES TABLE\r\n", $bigarray))
  198. {
  199. $stoppoint = array_search("# QUESTION_ATTRIBUTES TABLE\r\n", $bigarray);
  200. }
  201. else
  202. {
  203. $stoppoint = count($bigarray)-1;
  204. }
  205. for ($i=0; $i<=$stoppoint+1; $i++)
  206. {
  207. if ($i<$stoppoint-2) {$labelsarray[] = $bigarray[$i];}
  208. unset($bigarray[$i]);
  209. }
  210. $bigarray = array_values($bigarray);
  211. //Question attributes
  212. if (array_search("# ASSESSMENTS TABLE\n", $bigarray))
  213. {
  214. $stoppoint = array_search("# ASSESSMENTS TABLE\n", $bigarray);
  215. }
  216. elseif (array_search("# ASSESSMENTS TABLE\r\n", $bigarray))
  217. {
  218. $stoppoint = array_search("# ASSESSMENTS TABLE\r\n", $bigarray);
  219. }
  220. else
  221. {
  222. $stoppoint = count($bigarray)-1;
  223. }
  224. for ($i=0; $i<=$stoppoint+1; $i++)
  225. {
  226. if ($i<$stoppoint-2) {$question_attributesarray[] = $bigarray[$i];}
  227. unset($bigarray[$i]);
  228. }
  229. $bigarray = array_values($bigarray);
  230. //ASSESSMENTS
  231. if (array_search("# SURVEYS_LANGUAGESETTINGS TABLE\n", $bigarray))
  232. {
  233. $stoppoint = array_search("# SURVEYS_LANGUAGESETTINGS TABLE\n", $bigarray);
  234. }
  235. elseif (array_search("# SURVEYS_LANGUAGESETTINGS TABLE\r\n", $bigarray))
  236. {
  237. $stoppoint = array_search("# SURVEYS_LANGUAGESETTINGS TABLE\r\n", $bigarray);
  238. }
  239. else
  240. {
  241. $stoppoint = count($bigarray)-1;
  242. }
  243. for ($i=0; $i<=$stoppoint+1; $i++)
  244. {
  245. // if ($i<$stoppoint-2 || $i==count($bigarray)-1)
  246. if ($i<$stoppoint-2)
  247. {
  248. $assessmentsarray[] = $bigarray[$i];
  249. }
  250. unset($bigarray[$i]);
  251. }
  252. $bigarray = array_values($bigarray);
  253. //LANGAUGE SETTINGS
  254. if (array_search("# QUOTA TABLE\n", $bigarray))
  255. {
  256. $stoppoint = array_search("# QUOTA TABLE\n", $bigarray);
  257. }
  258. elseif (array_search("# QUOTA TABLE\r\n", $bigarray))
  259. {
  260. $stoppoint = array_search("# QUOTA TABLE\r\n", $bigarray);
  261. }
  262. else
  263. {
  264. $stoppoint = count($bigarray)-1;
  265. }
  266. for ($i=0; $i<=$stoppoint+1; $i++)
  267. {
  268. // if ($i<$stoppoint-2 || $i==count($bigarray)-1)
  269. //$bigarray[$i]= trim($bigarray[$i]);
  270. if (isset($bigarray[$i]) && (trim($bigarray[$i])!=''))
  271. {
  272. if (strpos($bigarray[$i],"#")===0)
  273. {
  274. unset($bigarray[$i]);
  275. unset($bigarray[$i+1]);
  276. unset($bigarray[$i+2]);
  277. break ;
  278. }
  279. else
  280. {
  281. $surveylsarray[] = $bigarray[$i];
  282. }
  283. }
  284. unset($bigarray[$i]);
  285. }
  286. $bigarray = array_values($bigarray);
  287. //QUOTA
  288. if (array_search("# QUOTA_MEMBERS TABLE\n", $bigarray))
  289. {
  290. $stoppoint = array_search("# QUOTA_MEMBERS TABLE\n", $bigarray);
  291. }
  292. elseif (array_search("# QUOTA_MEMBERS TABLE\r\n", $bigarray))
  293. {
  294. $stoppoint = array_search("# QUOTA_MEMBERS TABLE\r\n", $bigarray);
  295. }
  296. else
  297. {
  298. $stoppoint = count($bigarray)-1;
  299. }
  300. for ($i=0; $i<=$stoppoint+1; $i++)
  301. {
  302. // if ($i<$stoppoint-2 || $i==count($bigarray)-1)
  303. if ($i<$stoppoint-2)
  304. {
  305. $quotaarray[] = $bigarray[$i];
  306. }
  307. unset($bigarray[$i]);
  308. }
  309. $bigarray = array_values($bigarray);
  310. //QUOTA MEMBERS
  311. if (array_search("# QUOTA_LANGUAGESETTINGS TABLE\n", $bigarray))
  312. {
  313. $stoppoint = array_search("# QUOTA_LANGUAGESETTINGS TABLE\n", $bigarray);
  314. }
  315. elseif (array_search("# QUOTA_LANGUAGESETTINGS TABLE\r\n", $bigarray))
  316. {
  317. $stoppoint = array_search("# QUOTA_LANGUAGESETTINGS TABLE\r\n", $bigarray);
  318. }
  319. else
  320. {
  321. $stoppoint = count($bigarray)-1;
  322. }
  323. for ($i=0; $i<=$stoppoint+1; $i++)
  324. {
  325. // if ($i<$stoppoint-2 || $i==count($bigarray)-1)
  326. if ($i<$stoppoint-2)
  327. {
  328. $quotamembersarray[] = $bigarray[$i];
  329. }
  330. unset($bigarray[$i]);
  331. }
  332. $bigarray = array_values($bigarray);
  333. //Whatever is the last table - currently
  334. //QUOTA LANGUAGE SETTINGS
  335. $stoppoint = count($bigarray)-1;
  336. for ($i=0; $i<$stoppoint-1; $i++)
  337. {
  338. if ($i<=$stoppoint) {$quotalsarray[] = $bigarray[$i];}
  339. unset($bigarray[$i]);
  340. }
  341. $bigarray = array_values($bigarray);
  342. if (isset($surveyarray)) {$importresults['surveys'] = count($surveyarray);} else {$importresults['surveys'] = 0;}
  343. if (isset($surveylsarray)) {$importresults['languages'] = count($surveylsarray)-1;} else {$importresults['languages'] = 1;}
  344. if (isset($grouparray)) {$importresults['groups'] = count($grouparray)-1;} else {$importresults['groups'] = 0;}
  345. if (isset($questionarray)) {$importresults['questions'] = count($questionarray);} else {$importresults['questions']=0;}
  346. if (isset($answerarray)) {$importresults['answers'] = count($answerarray);} else {$importresults['answers']=0;}
  347. if (isset($conditionsarray)) {$importresults['conditions'] = count($conditionsarray);} else {$importresults['conditions']=0;}
  348. if (isset($labelsetsarray)) {$importresults['labelsets'] = count($labelsetsarray);} else {$importresults['labelsets']=0;}
  349. if (isset($assessmentsarray)) {$importresults['assessments']=count($assessmentsarray);} else {$importresults['assessments']=0;}
  350. if (isset($quotaarray)) {$importresults['quota']=count($quotaarray);} else {$importresults['quota']=0;}
  351. if (isset($quotamembersarray)) {$importresults['quotamembers']=count($quotamembersarray);} else {$importresults['quotamembers']=0;}
  352. if (isset($quotalsarray)) {$importresults['quotals']=count($quotalsarray);} else {$importresults['quotals']=0;}
  353. // CREATE SURVEY
  354. if ($importresults['surveys']>0){$importresults['surveys']--;};
  355. if ($importresults['answers']>0){$importresults['answers']=($importresults['answers']-1)/$importresults['languages'];};
  356. if ($importresults['groups']>0){$countgroups=($importresults['groups']-1)/$importresults['languages'];};
  357. if ($importresults['questions']>0){$importresults['questions']=($importresults['questions']-1)/$importresults['languages'];};
  358. if ($importresults['assessments']>0){$importresults['assessments']--;};
  359. if ($importresults['conditions']>0){$importresults['conditions']--;};
  360. if ($importresults['labelsets']>0){$importresults['labelsets']--;};
  361. if ($importresults['quota']>0){$importresults['quota']--;};
  362. $sfieldorders =convertCSVRowToArray($surveyarray[0],',','"');
  363. $sfieldcontents=convertCSVRowToArray($surveyarray[1],',','"');
  364. $surveyrowdata=array_combine($sfieldorders,$sfieldcontents);
  365. $oldsid=$surveyrowdata["sid"];
  366. if($iDesiredSurveyId!=NULL)
  367. $oldsid = $iDesiredSurveyId;
  368. if (!$oldsid)
  369. {
  370. if ($importingfrom == "http")
  371. {
  372. $importsurvey .= "<br /><div class='warningheader'>".$clang->gT("Error")."</div><br />\n";
  373. $importsurvey .= $clang->gT("Import of this survey file failed")."<br />\n";
  374. $importsurvey .= $clang->gT("File does not contain LimeSurvey data in the correct format.")."<br /><br />\n"; //Couldn't find the SID - cannot continue
  375. $importsurvey .= "<input type='submit' value='".$clang->gT("Main Admin Screen")."' onclick=\"window.open('$scriptname', '_top')\" />\n";
  376. $importsurvey .= "</div>\n";
  377. unlink($sFullFilepath); //Delete the uploaded file
  378. return;
  379. }
  380. else
  381. {
  382. echo $clang->gT("Import of this survey file failed")."\n".$clang->gT("File does not contain LimeSurvey data in the correct format.")."\n";
  383. return;
  384. }
  385. }
  386. $newsid = GetNewSurveyID($oldsid);
  387. $insert=$surveyarray[0];
  388. $sfieldorders =convertCSVRowToArray($surveyarray[0],',','"');
  389. $sfieldcontents=convertCSVRowToArray($surveyarray[1],',','"');
  390. $surveyrowdata=array_combine($sfieldorders,$sfieldcontents);
  391. // Set new owner ID
  392. $surveyrowdata['owner_id']=$_SESSION['loginID'];
  393. // Set new survey ID
  394. $surveyrowdata['sid']=$newsid;
  395. $surveyrowdata['active']='N';
  396. if (validate_templatedir($surveyrowdata['template'])!==$surveyrowdata['template']) $importresults['importwarnings'][] = sprintf($clang->gT('Template %s not found, please review when activating.'),$surveyrowdata['template']);
  397. if (isset($surveyrowdata['datecreated'])) {$surveyrowdata['datecreated']=$connect->BindTimeStamp($surveyrowdata['datecreated']);}
  398. unset($surveyrowdata['expires']);
  399. unset($surveyrowdata['attribute1']);
  400. unset($surveyrowdata['attribute2']);
  401. unset($surveyrowdata['usestartdate']);
  402. unset($surveyrowdata['notification']);
  403. unset($surveyrowdata['useexpiry']);
  404. unset($surveyrowdata['url']);
  405. unset($surveyrowdata['lastpage']);
  406. if (isset($surveyrowdata['private'])){
  407. $surveyrowdata['anonymized']=$surveyrowdata['private'];
  408. unset($surveyrowdata['private']);
  409. }
  410. if (isset($surveyrowdata['startdate'])) {unset($surveyrowdata['startdate']);}
  411. $surveyrowdata['bounce_email']=$surveyrowdata['adminemail'];
  412. if (!isset($surveyrowdata['datecreated']) || $surveyrowdata['datecreated']=='' || $surveyrowdata['datecreated']=='null') {$surveyrowdata['datecreated']=$connect->BindTimeStamp(date_shift(date("Y-m-d H:i:s"), "Y-m-d", $timeadjust));}
  413. $values=array_values($surveyrowdata);
  414. $values=array_map(array(&$connect, "qstr"),$values); // quote everything accordingly
  415. $insert = "INSERT INTO {$dbprefix}surveys (".implode(',',array_keys($surveyrowdata)).") VALUES (".implode(',',$values).")"; //handle db prefix
  416. $iresult = $connect->Execute($insert) or safe_die("<br />".$clang->gT("Import of this survey file failed")."<br />\n[$insert]<br />{$surveyarray[0]}<br /><br />\n" . $connect->ErrorMsg());
  417. // Now import the survey language settings
  418. $fieldorders=convertCSVRowToArray($surveylsarray[0],',','"');
  419. unset($surveylsarray[0]);
  420. foreach ($surveylsarray as $slsrow) {
  421. $fieldcontents=convertCSVRowToArray($slsrow,',','"');
  422. $surveylsrowdata=array_combine($fieldorders,$fieldcontents);
  423. // convert back the '\'.'n' char from the CSV file to true return char "\n"
  424. $surveylsrowdata=array_map('convertCsvreturn2return', $surveylsrowdata);
  425. // Convert the \n return char from welcometext to <br />
  426. // translate internal links
  427. $surveylsrowdata['surveyls_title']=translink('survey', $oldsid, $newsid, $surveylsrowdata['surveyls_title']);
  428. $surveylsrowdata['surveyls_description']=translink('survey', $oldsid, $newsid, $surveylsrowdata['surveyls_description']);
  429. $surveylsrowdata['surveyls_welcometext']=translink('survey', $oldsid, $newsid, $surveylsrowdata['surveyls_welcometext']);
  430. $surveylsrowdata['surveyls_urldescription']=translink('survey', $oldsid, $newsid, $surveylsrowdata['surveyls_urldescription']);
  431. $surveylsrowdata['surveyls_email_invite']=translink('survey', $oldsid, $newsid, $surveylsrowdata['surveyls_email_invite']);
  432. $surveylsrowdata['surveyls_email_remind']=translink('survey', $oldsid, $newsid, $surveylsrowdata['surveyls_email_remind']);
  433. $surveylsrowdata['surveyls_email_register']=translink('survey', $oldsid, $newsid, $surveylsrowdata['surveyls_email_register']);
  434. $surveylsrowdata['surveyls_email_confirm']=translink('survey', $oldsid, $newsid, $surveylsrowdata['surveyls_email_confirm']);
  435. unset($surveylsrowdata['lastpage']);
  436. $surveylsrowdata['surveyls_survey_id']=$newsid;
  437. $newvalues=array_values($surveylsrowdata);
  438. $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly
  439. $lsainsert = "INSERT INTO {$dbprefix}surveys_languagesettings (".implode(',',array_keys($surveylsrowdata)).") VALUES (".implode(',',$newvalues).")"; //handle db prefix
  440. $lsiresult=$connect->Execute($lsainsert) or safe_die("<br />".$clang->gT("Import of this survey file failed")."<br />\n[$lsainsert]<br />\n" . $connect->ErrorMsg() );
  441. }
  442. // The survey languagesettings are imported now
  443. $aLanguagesSupported = array(); // this array will keep all the languages supported for the survey
  444. $sBaseLanguage = GetBaseLanguageFromSurveyID($newsid);
  445. $aLanguagesSupported[]=$sBaseLanguage; // adds the base language to the list of supported languages
  446. $aLanguagesSupported=array_merge($aLanguagesSupported,GetAdditionalLanguagesFromSurveyID($newsid));
  447. // DO SURVEY_RIGHTS
  448. GiveAllSurveyPermissions($_SESSION['loginID'],$newsid);
  449. $importresults['deniedcountls'] =0;
  450. $qtypes = getqtypelist("" ,"array");
  451. $results['labels']=0;
  452. $results['labelsets']=0;
  453. $results['answers']=0;
  454. $results['subquestions']=0;
  455. //Do label sets
  456. if (isset($labelsetsarray) && $labelsetsarray)
  457. {
  458. $csarray=buildLabelSetCheckSumArray(); // build checksums over all existing labelsets
  459. $count=0;
  460. foreach ($labelsetsarray as $lsa) {
  461. $fieldorders =convertCSVRowToArray($labelsetsarray[0],',','"');
  462. $fieldcontents=convertCSVRowToArray($lsa,',','"');
  463. if ($count==0) {$count++; continue;}
  464. $labelsetrowdata=array_combine($fieldorders,$fieldcontents);
  465. // Save old labelid
  466. $oldlid=$labelsetrowdata['lid'];
  467. unset($labelsetrowdata['lid']);
  468. $newvalues=array_values($labelsetrowdata);
  469. $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly
  470. $lsainsert = "INSERT INTO {$dbprefix}labelsets (".implode(',',array_keys($labelsetrowdata)).") VALUES (".implode(',',$newvalues).")"; //handle db prefix
  471. $lsiresult=$connect->Execute($lsainsert);
  472. $results['labelsets']++;
  473. // Get the new insert id for the labels inside this labelset
  474. $newlid=$connect->Insert_ID("{$dbprefix}labelsets",'lid');
  475. if ($labelsarray) {
  476. $count=0;
  477. foreach ($labelsarray as $la) {
  478. $lfieldorders =convertCSVRowToArray($labelsarray[0],',','"');
  479. $lfieldcontents=convertCSVRowToArray($la,',','"');
  480. if ($count==0) {$count++; continue;}
  481. // Combine into one array with keys and values since its easier to handle
  482. $labelrowdata=array_combine($lfieldorders,$lfieldcontents);
  483. $labellid=$labelrowdata['lid'];
  484. if ($importversion<=132)
  485. {
  486. $labelrowdata["assessment_value"]=(int)$labelrowdata["code"];
  487. }
  488. if ($labellid == $oldlid) {
  489. $labelrowdata['lid']=$newlid;
  490. // translate internal links
  491. $labelrowdata['title']=translink('label', $oldlid, $newlid, $labelrowdata['title']);
  492. $newvalues=array_values($labelrowdata);
  493. $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly
  494. $lainsert = "INSERT INTO {$dbprefix}labels (".implode(',',array_keys($labelrowdata)).") VALUES (".implode(',',$newvalues).")"; //handle db prefix
  495. $liresult=$connect->Execute($lainsert);
  496. if ($liresult!==false) $results['labels']++;
  497. }
  498. }
  499. }
  500. //CHECK FOR DUPLICATE LABELSETS
  501. $thisset="";
  502. $query2 = "SELECT code, title, sortorder, language, assessment_value
  503. FROM {$dbprefix}labels
  504. WHERE lid=".$newlid."
  505. ORDER BY language, sortorder, code";
  506. $result2 = db_execute_num($query2) or safe_die("Died querying labelset $lid<br />$query2<br />".$connect->ErrorMsg());
  507. while($row2=$result2->FetchRow())
  508. {
  509. $thisset .= implode('.', $row2);
  510. } // while
  511. $newcs=dechex(crc32($thisset)*1);
  512. unset($lsmatch);
  513. if (isset($csarray))
  514. {
  515. foreach($csarray as $key=>$val)
  516. {
  517. if ($val == $newcs)
  518. {
  519. $lsmatch=$key;
  520. }
  521. }
  522. }
  523. if (isset($lsmatch) || ($_SESSION['USER_RIGHT_MANAGE_LABEL'] != 1))
  524. {
  525. //There is a matching labelset or the user is not allowed to edit labels -
  526. // So, we will delete this one and refer to the matched one.
  527. $query = "DELETE FROM {$dbprefix}labels WHERE lid=$newlid";
  528. $result=$connect->Execute($query) or safe_die("Couldn't delete labels<br />$query<br />".$connect->ErrorMsg());
  529. $results['labels']=$results['labels']-$connect->Affected_Rows();
  530. $query = "DELETE FROM {$dbprefix}labelsets WHERE lid=$newlid";
  531. $result=$connect->Execute($query) or safe_die("Couldn't delete labelset<br />$query<br />".$connect->ErrorMsg());
  532. $results['labelsets']=$results['labelsets']-$connect->Affected_Rows();
  533. $newlid=$lsmatch;
  534. }
  535. else
  536. {
  537. //There isn't a matching labelset, add this checksum to the $csarray array
  538. $csarray[$newlid]=$newcs;
  539. }
  540. //END CHECK FOR DUPLICATES
  541. $aLIDReplacements[$oldlid]=$newlid;
  542. }
  543. }
  544. // Import groups
  545. if (isset($grouparray) && $grouparray)
  546. {
  547. // do GROUPS
  548. $gafieldorders=convertCSVRowToArray($grouparray[0],',','"');
  549. unset($grouparray[0]);
  550. foreach ($grouparray as $ga)
  551. {
  552. $gacfieldcontents=convertCSVRowToArray($ga,',','"');
  553. $grouprowdata=array_combine($gafieldorders,$gacfieldcontents);
  554. //Now an additional integrity check if there are any groups not belonging into this survey
  555. if ($grouprowdata['sid'] != $oldsid)
  556. {
  557. $results['fatalerror'] = $clang->gT("A group in the CSV/SQL file is not part of the same survey. The import of the survey was stopped.")."<br />\n";
  558. return $results;
  559. }
  560. $grouprowdata['sid']=$newsid;
  561. // remember group id
  562. $oldgid=$grouprowdata['gid'];
  563. //update/remove the old group id
  564. if (isset($aGIDReplacements[$oldgid]))
  565. $grouprowdata['gid'] = $aGIDReplacements[$oldgid];
  566. else
  567. unset($grouprowdata['gid']);
  568. // Everything set - now insert it
  569. $grouprowdata=array_map('convertCsvreturn2return', $grouprowdata);
  570. // translate internal links
  571. $grouprowdata['group_name']=translink('survey', $oldsid, $newsid, $grouprowdata['group_name']);
  572. $grouprowdata['description']=translink('survey', $oldsid, $newsid, $grouprowdata['description']);
  573. if (isset($grouprowdata['gid'])) db_switchIDInsert('groups',true);
  574. $tablename=$dbprefix.'groups';
  575. $ginsert = $connect->GetinsertSQL($tablename,$grouprowdata);
  576. $gres = $connect->Execute($ginsert) or safe_die($clang->gT('Error').": Failed to insert group<br />\n$ginsert<br />\n".$connect->ErrorMsg());
  577. if (isset($grouprowdata['gid'])) db_switchIDInsert('groups',false);
  578. //GET NEW GID
  579. if (!isset($grouprowdata['gid'])) {$aGIDReplacements[$oldgid]=$connect->Insert_ID("{$dbprefix}groups","gid");}
  580. }
  581. // Fix sortorder of the groups - if users removed groups manually from the csv file there would be gaps
  582. fixSortOrderGroups($newsid);
  583. }
  584. // GROUPS is DONE
  585. // Import questions
  586. if (isset($questionarray) && $questionarray)
  587. {
  588. $qafieldorders=convertCSVRowToArray($questionarray[0],',','"');
  589. unset($questionarray[0]);
  590. foreach ($questionarray as $qa)
  591. {
  592. $qacfieldcontents=convertCSVRowToArray($qa,',','"');
  593. $questionrowdata=array_combine($qafieldorders,$qacfieldcontents);
  594. $questionrowdata=array_map('convertCsvreturn2return', $questionrowdata);
  595. $questionrowdata["type"]=strtoupper($questionrowdata["type"]);
  596. // Skip not supported languages
  597. if (!in_array($questionrowdata['language'],$aLanguagesSupported))
  598. continue;
  599. // replace the sid
  600. $questionrowdata["sid"] = $newsid;
  601. // Skip if gid is invalid
  602. if (!isset($aGIDReplacements[$questionrowdata['gid']])) continue;
  603. $questionrowdata["gid"] = $aGIDReplacements[$questionrowdata['gid']];
  604. if (isset($aQIDReplacements[$questionrowdata['qid']]))
  605. {
  606. $questionrowdata['qid']=$aQIDReplacements[$questionrowdata['qid']];
  607. }
  608. else
  609. {
  610. $oldqid=$questionrowdata['qid'];
  611. unset($questionrowdata['qid']);
  612. }
  613. unset($oldlid1); unset($oldlid2);
  614. if ((isset($questionrowdata['lid']) && $questionrowdata['lid']>0))
  615. {
  616. $oldlid1=$questionrowdata['lid'];
  617. }
  618. if ((isset($questionrowdata['lid1']) && $questionrowdata['lid1']>0))
  619. {
  620. $oldlid2=$questionrowdata['lid1'];
  621. }
  622. unset($questionrowdata['lid']);
  623. unset($questionrowdata['lid1']);
  624. if ($questionrowdata['type']=='W')
  625. {
  626. $questionrowdata['type']='!';
  627. }
  628. elseif ($questionrowdata['type']=='Z')
  629. {
  630. $questionrowdata['type']='L';
  631. $aIgnoredAnswers[]=$oldqid;
  632. }
  633. if (!isset($questionrowdata["question_order"]) || $questionrowdata["question_order"]=='') {$questionrowdata["question_order"]=0;}
  634. // translate internal links
  635. $questionrowdata['title']=translink('survey', $oldsid, $newsid, $questionrowdata['title']);
  636. $questionrowdata['question']=translink('survey', $oldsid, $newsid, $questionrowdata['question']);
  637. $questionrowdata['help']=translink('survey', $oldsid, $newsid, $questionrowdata['help']);
  638. if (isset($questionrowdata['qid'])) {
  639. db_switchIDInsert('questions',true);
  640. }
  641. $tablename=$dbprefix.'questions';
  642. $qinsert = $connect->GetInsertSQL($tablename,$questionrowdata);
  643. $qres = $connect->Execute($qinsert) or safe_die ($clang->gT("Error").": Failed to insert question<br />\n$qinsert<br />\n".$connect->ErrorMsg());
  644. if (isset($questionrowdata['qid'])) {
  645. db_switchIDInsert('questions',false);
  646. $saveqid=$questionrowdata['qid'];
  647. }
  648. else
  649. {
  650. $aQIDReplacements[$oldqid]=$connect->Insert_ID("{$dbprefix}questions",'qid');
  651. $saveqid=$aQIDReplacements[$oldqid];
  652. }
  653. // Now we will fix up old label sets where they are used as answers
  654. if (((isset($oldlid1) && isset($aLIDReplacements[$oldlid1])) || (isset($oldlid2) && isset($aLIDReplacements[$oldlid2]))) && ($qtypes[$questionrowdata['type']]['answerscales']>0 || $qtypes[$questionrowdata['type']]['subquestions']>1))
  655. {
  656. $query="select * from ".db_table_name('labels')." where lid={$aLIDReplacements[$oldlid1]} and language='{$questionrowdata['language']}'";
  657. $oldlabelsresult=db_execute_assoc($query);
  658. while($labelrow=$oldlabelsresult->FetchRow())
  659. {
  660. if (in_array($labelrow['language'],$aLanguagesSupported))
  661. {
  662. if ($qtypes[$questionrowdata['type']]['subquestions']<2)
  663. {
  664. $qinsert = "insert INTO ".db_table_name('answers')." (qid,code,answer,sortorder,language,assessment_value)
  665. VALUES ({$aQIDReplacements[$oldqid]},".db_quoteall($labelrow['code']).",".db_quoteall($labelrow['title']).",".db_quoteall($labelrow['sortorder']).",".db_quoteall($labelrow['language']).",".db_quoteall($labelrow['assessment_value']).")";
  666. $qres = $connect->Execute($qinsert) or safe_die ($clang->gT("Error").": Failed to insert answer (lid1) <br />\n$qinsert<br />\n".$connect->ErrorMsg());
  667. }
  668. else
  669. {
  670. if (isset($aSQIDReplacements[$labelrow['code'].'_'.$saveqid])){
  671. $fieldname='qid,';
  672. $data=$aSQIDReplacements[$labelrow['code'].'_'.$saveqid].',';
  673. }
  674. else{
  675. $fieldname='' ;
  676. $data='';
  677. }
  678. $qinsert = "insert INTO ".db_table_name('questions')." ($fieldname parent_qid,title,question,question_order,language,scale_id,type, sid, gid)
  679. VALUES ($data{$aQIDReplacements[$oldqid]},".db_quoteall($labelrow['code']).",".db_quoteall($labelrow['title']).",".db_quoteall($labelrow['sortorder']).",".db_quoteall($labelrow['language']).",1,'{$questionrowdata['type']}',{$questionrowdata['sid']},{$questionrowdata['gid']})";
  680. $qres = $connect->Execute($qinsert) or safe_die ($clang->gT("Error").": Failed to insert question <br />\n$qinsert<br />\n".$connect->ErrorMsg());
  681. if ($fieldname=='')
  682. {
  683. $aSQIDReplacements[$labelrow['code'].'_'.$saveqid]=$connect->Insert_ID("{$dbprefix}questions","qid");
  684. }
  685. }
  686. }
  687. }
  688. if (isset($oldlid2) && $qtypes[$questionrowdata['type']]['answerscales']>1)
  689. {
  690. $query="select * from ".db_table_name('labels')." where lid={$aLIDReplacements[$oldlid2]} and language='{$questionrowdata['language']}'";
  691. $oldlabelsresult=db_execute_assoc($query);
  692. while($labelrow=$oldlabelsresult->FetchRow())
  693. {
  694. $qinsert = "insert INTO ".db_table_name('answers')." (qid,code,answer,sortorder,language,assessment_value,scale_id)
  695. VALUES ({$aQIDReplacements[$oldqid]},".db_quoteall($labelrow['code']).",".db_quoteall($labelrow['title']).",".db_quoteall($labelrow['sortorder']).",".db_quoteall($labelrow['language']).",".db_quoteall($labelrow['assessment_value']).",1)";
  696. $qres = $connect->Execute($qinsert) or safe_die ($clang->gT("Error").": Failed to insert answer (lid2)<br />\n$qinsert<br />\n".$connect->ErrorMsg());
  697. }
  698. }
  699. }
  700. }
  701. }
  702. //Do answers
  703. if (isset($answerarray) && $answerarray)
  704. {
  705. $answerfieldnames = convertCSVRowToArray($answerarray[0],',','"');
  706. unset($answerarray[0]);
  707. foreach ($answerarray as $aa)
  708. {
  709. $answerfieldcontents = convertCSVRowToArray($aa,',','"');
  710. $answerrowdata = array_combine($answerfieldnames,$answerfieldcontents);
  711. if (in_array($answerrowdata['qid'],$aIgnoredAnswers))
  712. {
  713. // Due to a bug in previous LS versions there may be orphaned answers with question type Z (which is now L)
  714. // this way they are ignored
  715. continue;
  716. }
  717. if ($answerrowdata===false)
  718. {
  719. $importquestion.='<br />'.$clang->gT("Faulty line in import - fields and data don't match").":".implode(',',$answerfieldcontents);
  720. }
  721. // Skip not supported languages
  722. if (!in_array($answerrowdata['language'],$aLanguagesSupported))
  723. continue;
  724. // replace the qid for the new one (if there is no new qid in the $aQIDReplacements array it mean that this answer is orphan -> error, skip this record)
  725. if (isset($aQIDReplacements[$answerrowdata["qid"]]))
  726. $answerrowdata["qid"] = $aQIDReplacements[$answerrowdata["qid"]];
  727. else
  728. continue; // a problem with this answer record -> don't consider
  729. if ($importversion<=132)
  730. {
  731. $answerrowdata["assessment_value"]=(int)$answerrowdata["code"];
  732. }
  733. // Convert default values for single select questions
  734. $questiontemp=$connect->GetRow('select type,gid from '.db_table_name('questions').' where qid='.$answerrowdata["qid"]);
  735. $oldquestion['newtype']=$questiontemp['type'];
  736. $oldquestion['gid']=$questiontemp['gid'];
  737. if ($answerrowdata['default_value']=='Y' && ($oldquestion['newtype']=='L' || $oldquestion['newtype']=='O' || $oldquestion['newtype']=='!'))
  738. {
  739. $insertdata=array();
  740. $insertdata['qid']=$newqid;
  741. $insertdata['language']=$answerrowdata['language'];
  742. $insertdata['defaultvalue']=$answerrowdata['answer'];
  743. $query=$connect->GetInsertSQL($dbprefix.'defaultvalues',$insertdata);
  744. $qres = $connect->Execute($query) or safe_die ("Error: Failed to insert defaultvalue <br />{$query}<br />\n".$connect->ErrorMsg());
  745. }
  746. // translate internal links
  747. $answerrowdata['answer']=translink('survey', $oldsid, $newsid, $answerrowdata['answer']);
  748. // Everything set - now insert it
  749. $answerrowdata = array_map('convertCsvreturn2return', $answerrowdata);
  750. if ($qtypes[$oldquestion['newtype']]['subquestions']>0) //hmmm.. this is really a subquestion
  751. {
  752. $questionrowdata=array();
  753. if (isset($aSQIDReplacements[$answerrowdata['code'].$answerrowdata['qid']])){
  754. $questionrowdata['qid']=$aSQIDReplacements[$answerrowdata['code'].$answerrowdata['qid']];
  755. }
  756. $questionrowdata['parent_qid']=$answerrowdata['qid'];;
  757. $questionrowdata['sid']=$newsid;
  758. $questionrowdata['gid']=$oldquestion['gid'];
  759. $questionrowdata['title']=$answerrowdata['code'];
  760. $questionrowdata['question']=$answerrowdata['answer'];
  761. $questionrowdata['question_order']=$answerrowdata['sortorder'];
  762. $questionrowdata['language']=$answerrowdata['language'];
  763. $questionrowdata['type']=$oldquestion['newtype'];
  764. $tablename=$dbprefix.'questions';
  765. $query=$connect->GetInsertSQL($tablename,$questionrowdata);
  766. if (isset($questionrowdata['qid'])) db_switchIDInsert('questions',true);
  767. $qres = $connect->Execute($query) or safe_die ("Error: Failed to insert subquestion <br />{$query}<br />".$connect->ErrorMsg());
  768. if (!isset($questionrowdata['qid']))
  769. {
  770. $aSQIDReplacements[$answerrowdata['code'].$answerrowdata['qid']]=$connect->Insert_ID("{$dbprefix}questions","qid");
  771. }
  772. else
  773. {
  774. db_switchIDInsert('questions',false);
  775. }
  776. $results['subquestions']++;
  777. // also convert default values subquestions for multiple choice
  778. if ($answerrowdata['default_value']=='Y' && ($oldquestion['newtype']=='M' || $oldquestion['newtype']=='P'))
  779. {
  780. $insertdata=array();
  781. $insertdata['qid']=$newqid;
  782. $insertdata['sqid']=$aSQIDReplacements[$answerrowdata['code']];
  783. $insertdata['language']=$answerrowdata['language'];
  784. $insertdata['defaultvalue']='Y';
  785. $tablename=$dbprefix.'defaultvalues';
  786. $query=$connect->GetInsertSQL($tablename,$insertdata);
  787. $qres = $connect->Execute($query) or safe_die ("Error: Failed to insert defaultvalue <br />{$query}<br />\n".$connect->ErrorMsg());
  788. }
  789. }
  790. else // insert answers
  791. {
  792. unset($answerrowdata['default_value']);
  793. $tablename=$dbprefix.'answers';
  794. $query=$connect->GetInsertSQL($tablename,$answerrowdata);
  795. $ares = $connect->Execute($query) or safe_die ("Error: Failed to insert answer<br />{$query}<br />\n".$connect->ErrorMsg());
  796. $results['answers']++;
  797. }
  798. }
  799. }
  800. // get all group ids and fix questions inside each group
  801. $gquery = "SELECT gid FROM {$dbprefix}groups where sid=$newsid group by gid ORDER BY gid"; //Get last question added (finds new qid)
  802. $gres = db_execute_assoc($gquery);
  803. while ($grow = $gres->FetchRow())
  804. {
  805. fixsortorderQuestions($grow['gid'], $newsid);
  806. }
  807. //We've built two arrays along the way - one containing the old SID, GID and QIDs - and their NEW equivalents
  808. //and one containing the old 'extended fieldname' and its new equivalent. These are needed to import conditions and question_attributes.
  809. if (isset($question_attributesarray) && $question_attributesarray) {//ONLY DO THIS IF THERE ARE QUESTION_ATTRIBUES
  810. $fieldorders =convertCSVRowToArray($question_attributesarray[0],',','"');
  811. unset($question_attributesarray[0]);
  812. foreach ($question_attributesarray as $qar) {
  813. $fieldcontents=convertCSVRowToArray($qar,',','"');
  814. $qarowdata=array_combine($fieldorders,$fieldcontents);
  815. $newqid="";
  816. $qarowdata["qid"]=$aQIDReplacements[$qarowdata["qid"]];
  817. unset($qarowdata["qaid"]);
  818. $newvalues=array_values($qarowdata);
  819. $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly
  820. $qainsert = "insert INTO {$dbprefix}question_attributes (".implode(',',array_keys($qarowdata)).") VALUES (".implode(',',$newvalues).")";
  821. $result=$connect->Execute($qainsert); // no safe_die since some LimeSurvey version export duplicate question attributes - these are just ignored
  822. if ($connect->Affected_Rows()>0) {$importresults['question_attributes']++;}
  823. }
  824. }
  825. if (isset($assessmentsarray) && $assessmentsarray) {//ONLY DO THIS IF THERE ARE QUESTION_ATTRIBUTES
  826. $fieldorders=convertCSVRowToArray($assessmentsarray[0],',','"');
  827. unset($assessmentsarray[0]);
  828. foreach ($assessmentsarray as $qar)
  829. {
  830. $fieldcontents=convertCSVRowToArray($qar,',','"');
  831. $asrowdata=array_combine($fieldorders,$fieldcontents);
  832. if (isset($asrowdata['link']))
  833. {
  834. if (trim($asrowdata['link'])!='') $asrowdata['message']=$asrowdata['message'].'<br /><a href="'.$asrowdata['link'].'">'.$asrowdata['link'].'</a>';
  835. unset($asrowdata['link']);
  836. }
  837. if ($asrowdata["gid"]>0)
  838. {
  839. $asrowdata["gid"]=$aGIDReplacements[$asrowdata["gid"]];
  840. }
  841. $asrowdata["sid"]=$newsid;
  842. unset($asrowdata["id"]);
  843. $tablename=$dbprefix.'assessments';
  844. $asinsert = $connect->GetInsertSQL($tablename,$asrowdata);
  845. $result=$connect->Execute($asinsert) or safe_die ("Couldn't insert assessment<br />$asinsert<br />".$connect->ErrorMsg());
  846. unset($newgid);
  847. }
  848. }
  849. if (isset($quotaarray) && $quotaarray) {//ONLY DO THIS IF THERE ARE QUOTAS
  850. $fieldorders=convertCSVRowToArray($quotaarray[0],',','"');
  851. unset($quotaarray[0]);
  852. foreach ($quotaarray as $qar)
  853. {
  854. $fieldcontents=convertCSVRowToArray($qar,',','"');
  855. $asrowdata=array_combine($fieldorders,$fieldcontents);
  856. $oldsid=$asrowdata["sid"];
  857. foreach ($substitutions as $subs) {
  858. if ($oldsid==$subs[0]) {$newsid=$subs[3];}
  859. }
  860. $asrowdata["sid"]=$newsid;
  861. $oldid = $asrowdata["id"];
  862. unset($asrowdata["id"]);
  863. $quotadata[]=$asrowdata; //For use later if needed
  864. $tablename=$dbprefix.'quota';
  865. $asinsert = $connect->getInsertSQL($tablename,$asrowdata);
  866. $result=$connect->Execute($asinsert) or safe_die ("Couldn't insert quota<br />$asinsert<br />".$connect->ErrorMsg());
  867. $aQuotaReplacements[$oldid] = $connect->Insert_ID(db_table_name_nq('quota'),"id");
  868. }
  869. }
  870. if (isset($quotamembersarray) && $quotamembersarray) {//ONLY DO THIS IF THERE ARE QUOTA MEMBERS
  871. $count=0;
  872. foreach ($quotamembersarray as $qar) {
  873. $fieldorders =convertCSVRowToArray($quotamembersarray[0],',','"');
  874. $fieldcontents=convertCSVRowToArray($qar,',','"');
  875. if ($count==0) {$count++; continue;}
  876. $asrowdata=array_combine($fieldorders,$fieldcontents);
  877. $oldsid=$asrowdata["sid"];
  878. $newqid="";
  879. $newquotaid="";
  880. $oldqid=$asrowdata['qid'];
  881. $oldquotaid=$asrowdata['quota_id'];
  882. foreach ($substitutions as $subs) {
  883. if ($oldsid==$subs[0]) {$newsid=$subs[3];}
  884. if ($oldqid==$subs[2]) {$newqid=$subs[5];}
  885. }
  886. $newquotaid=$aQuotaReplacements[$oldquotaid];
  887. $asrowdata["sid"]=$newsid;
  888. $asrowdata["qid"]=$newqid;
  889. $asrowdata["quota_id"]=$newquotaid;
  890. unset($asrowdata["id"]);
  891. $tablename=$dbprefix.'quota_members';
  892. $asinsert = $connect->getInsertSQL($tablename,$asrowdata);
  893. $result=$connect->Execute($asinsert) or safe_die ("Couldn't insert quota<br />$asinsert<br />".$connect->ErrorMsg());
  894. }
  895. }
  896. if (isset($quotalsarray) && $quotalsarray) {//ONLY DO THIS IF THERE ARE QUOTA LANGUAGE SETTINGS
  897. $count=0;
  898. foreach ($quotalsarray as $qar) {
  899. $fieldorders =convertCSVRowToArray($quotalsarray[0],',','"');
  900. $fieldcontents=convertCSVRowToArray($qar,',','"');
  901. if ($count==0) {$count++; continue;}
  902. $asrowdata=array_combine($fieldorders,$fieldcontents);
  903. $newquotaid="";
  904. $oldquotaid=$asrowdata['quotals_quota_id'];
  905. $newquotaid=$aQuotaReplacements[$oldquotaid];
  906. $asrowdata["quotals_quota_id"]=$newquotaid;
  907. unset($asrowdata["quotals_id"]);
  908. $tablename=$dbprefix.'quota_languagesettings';
  909. $asinsert = $connect->getInsertSQL($tablename,$asrowdata);
  910. $result=$connect->Execute($asinsert) or safe_die ("Couldn't insert quota<br />$asinsert<br />".$connect->ErrorMsg());
  911. }
  912. }
  913. //if there are quotas, but no quotals, then we need to create default dummy for each quota (this handles exports from pre-language quota surveys)
  914. if ($importresults['quota'] > 0 && (!isset($importresults['quotals']) || $importresults['quotals'] == 0)) {
  915. $i=0;
  916. $defaultsurveylanguage=isset($defaultsurveylanguage) ? $defaultsurveylanguage : "en";
  917. foreach($aQuotaReplacements as $oldquotaid=>$newquotaid) {
  918. $asrowdata=array("quotals_quota_id" => $newquotaid,
  919. "quotals_language" => $defaultsurveylanguage,
  920. "quotals_name" => $quotadata[$i]["name"],
  921. "quotals_message" => $clang->gT("Sorry your responses have exceeded a quota on this survey."),
  922. "quotals_url" => "",
  923. "quotals_urldescrip" => "");
  924. $i++;
  925. }
  926. $tablename=$dbprefix.'quota_languagesettings';
  927. $asinsert = $connect->getInsertSQL($tablename,$asrowdata);
  928. $result=$connect->Execute($asinsert) or safe_die ("Couldn't insert quota<br />$asinsert<br />".$connect->ErrorMsg());
  929. $countquotals=$i;
  930. }
  931. // Do conditions
  932. if (isset($conditionsarray) && $conditionsarray) {//ONLY DO THIS IF THERE ARE CONDITIONS!
  933. $fieldorders =convertCSVRowToArray($conditionsarray[0],',','"');
  934. unset($conditionsarray[0]);
  935. // Exception for conditions based on attributes
  936. $aQIDReplacements[0]=0;
  937. foreach ($conditionsarray as $car) {
  938. $fieldcontents=convertCSVRowToArray($car,',','"');
  939. $conditionrowdata=array_combine($fieldorders,$fieldcontents);
  940. unset($conditionrowdata["cid"]);
  941. if (!isset($conditionrowdata["method"]) || trim($conditionrowdata["method"])=='')
  942. {
  943. $conditionrowdata["method"]='==';
  944. }
  945. if (!isset($conditionrowdata["scenario"]) || trim($conditionrowdata["scenario"])=='')
  946. {
  947. $conditionrowdata["scenario"]=1;
  948. }
  949. $oldcqid=$conditionrowdata["cqid"];
  950. $oldgid=array_search($connect->GetOne('select gid from '.db_table_name('questions').' where qid='.$aQIDReplacements[$conditionrowdata["cqid"]]),$aGIDReplacements);
  951. $conditionrowdata["qid"]=$aQIDReplacements[$conditionrowdata["qid"]];
  952. $conditionrowdata["cqid"]=$aQIDReplacements[$conditionrowdata["cqid"]];
  953. $oldcfieldname=$conditionrowdata["cfieldname"];
  954. $conditionrowdata["cfieldname"]=str_replace($oldsid.'X'.$oldgid.'X'.$oldcqid,$newsid.'X'.$aGIDReplacements[$oldgid].'X'.$conditionrowdata["cqid"],$conditionrowdata["cfieldname"]);
  955. $tablename=$dbprefix.'conditions';
  956. $conditioninsert = $connect->getInsertSQL($tablename,$conditionrowdata);
  957. $result=$connect->Execute($conditioninsert) or safe_die ("Couldn't insert condition<br />$conditioninsert<br />".$connect->ErrorMsg());
  958. }
  959. }
  960. $importresults['importversion']=$importversion;
  961. $importresults['newsid']=$newsid;
  962. $importresults['oldsid']=$oldsid;
  963. return $importresults;
  964. }
  965. /**
  966. * This function imports a LimeSurvey .lss survey XML file
  967. *
  968. * @param mixed $sFullFilepath The full filepath of the uploaded file
  969. */
  970. function XMLImportSurvey($sFullFilepath,$sXMLdata=NULL,$sNewSurveyName=NULL,$iDesiredSurveyId=NULL, $bTranslateInsertansTags=true)
  971. {
  972. global $connect, $dbprefix, $clang, $timeadjust;
  973. if ($sXMLdata == NULL)
  974. {
  975. $xml = simplexml_load_file($sFullFilepath);
  976. } else
  977. {
  978. $xml = simplexml_load_string($sXMLdata);
  979. }
  980. if ($xml->LimeSurveyDocType!='Survey') safe_die('This is not a valid LimeSurvey survey structure XML file.');
  981. $dbversion = (int) $xml->DBVersion;
  982. $aQIDReplacements=array();
  983. $aQuotaReplacements=array();
  984. $results['defaultvalues']=0;
  985. $results['answers']=0;
  986. $results['surveys']=0;
  987. $results['questions']=0;
  988. $results['subquestions']=0;
  989. $results['question_attributes']=0;
  990. $results['groups']=0;
  991. $results['assessments']=0;
  992. $results['quota']=0;
  993. $results['quotals']=0;
  994. $results['quotamembers']=0;
  995. $results['importwarnings']=array();
  996. $aLanguagesSupported=array();
  997. foreach ($xml->languages->language as $language)
  998. {
  999. $aLanguagesSupported[]=(string)$language;
  1000. }
  1001. $results['languages']=co

Large files files are truncated, but you can click here to view the full file