PageRenderTime 77ms CodeModel.GetById 39ms RepoModel.GetById 0ms app.codeStats 0ms

/sondage/admin/import_functions.php

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

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