PageRenderTime 56ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 0ms

/sondage/admin/importgroup.php

https://bitbucket.org/bontiv/insomnia
PHP | 1182 lines | 945 code | 133 blank | 104 comment | 151 complexity | 194c181af83c5677529faba413d99321 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: importgroup.php 10925 2011-09-02 14:12:02Z c_schmitz $
  14. */
  15. //Ensure script is not run directly, avoid path disclosure
  16. include_once("login_check.php");
  17. $importgroup = "<div class='header ui-widget-header'>".$clang->gT("Import question group")."</div>\n";
  18. $importgroup .= "<div class='messagebox ui-corner-all'>\n";
  19. $sFullFilepath = $tempdir . DIRECTORY_SEPARATOR . $_FILES['the_file']['name'];
  20. $aPathInfo = pathinfo($sFullFilepath);
  21. $sExtension = $aPathInfo['extension'];
  22. if (!@move_uploaded_file($_FILES['the_file']['tmp_name'], $sFullFilepath))
  23. {
  24. $fatalerror = sprintf ($clang->gT("An error occurred uploading your file. This may be caused by incorrect permissions in your %s folder."),$tempdir);
  25. }
  26. // validate that we have a SID
  27. if (!returnglobal('sid'))
  28. {
  29. $fatalerror .= $clang->gT("No SID (Survey) has been provided. Cannot import question.");
  30. }
  31. else
  32. {
  33. $surveyid=returnglobal('sid');
  34. }
  35. if (isset($fatalerror))
  36. {
  37. $importgroup .= "<div class='warningheader'>".$clang->gT("Error")."</div><br />\n";
  38. $importgroup .= $fatalerror."<br /><br />\n";
  39. $importgroup .= "<input type='submit' value='".$clang->gT("Main Admin Screen")."' onclick=\"window.open('$scriptname', '_top')\" /><br /><br />\n";
  40. $importgroup .= "</div>\n";
  41. @unlink($sFullFilepath);
  42. return;
  43. }
  44. // IF WE GOT THIS FAR, THEN THE FILE HAS BEEN UPLOADED SUCCESFULLY
  45. $importgroup .= "<div class='successheader'>".$clang->gT("Success")."</div>&nbsp;<br />\n"
  46. .$clang->gT("File upload succeeded.")."<br /><br />\n"
  47. .$clang->gT("Reading file..")."<br /><br />\n";
  48. if (strtolower($sExtension)=='csv')
  49. {
  50. $aImportResults=CSVImportGroup($sFullFilepath, $surveyid);
  51. }
  52. elseif (strtolower($sExtension)=='lsg')
  53. {
  54. $aImportResults=XMLImportGroup($sFullFilepath, $surveyid);
  55. }
  56. else die('Unknown file extension');
  57. FixLanguageConsistency($surveyid);
  58. if (isset($aImportResults['fatalerror']))
  59. {
  60. $importgroup .= "<div class='warningheader'>".$clang->gT("Error")."</div><br />\n";
  61. $importgroup .= $aImportResults['fatalerror']."<br /><br />\n";
  62. $importgroup .= "<input type='submit' value='".$clang->gT("Main Admin Screen")."' onclick=\"window.open('$scriptname', '_top')\" />\n";
  63. $importgroup .= "</div>\n";
  64. unlink($sFullFilepath);
  65. return;
  66. }
  67. $importgroup .= "<div class='successheader'>".$clang->gT("Success")."</div><br />\n"
  68. ."<strong><u>".$clang->gT("Question group import summary")."</u></strong><br />\n"
  69. ."<ul style=\"text-align:left;\">\n"
  70. ."\t<li>".$clang->gT("Groups").": ".$aImportResults['groups']."</li>\n"
  71. ."\t<li>".$clang->gT("Questions").": ".$aImportResults['questions']."</li>\n"
  72. ."\t<li>".$clang->gT("Subquestions").": ".$aImportResults['subquestions']."</li>\n"
  73. ."\t<li>".$clang->gT("Answers").": ".$aImportResults['answers']."</li>\n"
  74. ."\t<li>".$clang->gT("Conditions").": ".$aImportResults['conditions']."</li>\n";
  75. if (strtolower($sExtension)=='csv') {
  76. $importgroup.="\t<li>".$clang->gT("Label sets").": ".$aImportResults['labelsets']." (".$aImportResults['labels'].")</li>\n";
  77. }
  78. $importgroup.="\t<li>".$clang->gT("Question attributes:").$aImportResults['question_attributes']."</li>"
  79. ."</ul>\n";
  80. $importgroup .= "<strong>".$clang->gT("Question group import is complete.")."</strong><br />&nbsp;\n";
  81. $importgroup .= "<input type='submit' value='".$clang->gT("Go to question group")."' onclick=\"window.open('$scriptname?sid=$surveyid&amp;gid={$aImportResults['newgid']}', '_top')\" />\n";
  82. $importgroup .= "</div><br />\n";
  83. unlink($sFullFilepath);
  84. /**
  85. * This function imports an old-school question group file (*.csv,*.sql)
  86. *
  87. * @param mixed $sFullFilepath Full file patch to the import file
  88. * @param mixed $newsid Survey ID to which the question is attached
  89. */
  90. function CSVImportGroup($sFullFilepath, $newsid)
  91. {
  92. global $dbprefix, $connect, $clang;
  93. $aLIDReplacements=array();
  94. $aQIDReplacements = array(); // this array will have the "new qid" for the questions, the key will be the "old qid"
  95. $aGIDReplacements = array();
  96. $handle = fopen($sFullFilepath, "r");
  97. while (!feof($handle))
  98. {
  99. $buffer = fgets($handle);
  100. $bigarray[] = $buffer;
  101. }
  102. fclose($handle);
  103. if (substr($bigarray[0], 0, 23) != "# LimeSurvey Group Dump")
  104. {
  105. $results['fatalerror'] = $clang->gT("This file is not a LimeSurvey question file. Import failed.");
  106. $importversion=0;
  107. }
  108. else
  109. {
  110. $importversion=(int)trim(substr($bigarray[1],12));
  111. }
  112. if ((int)$importversion<112)
  113. {
  114. $results['fatalerror'] = $clang->gT("This file is too old. Only files from LimeSurvey version 1.50 (DBVersion 112) and newer are supported.");
  115. }
  116. for ($i=0; $i<9; $i++) //skipping the first lines that are not needed
  117. {
  118. unset($bigarray[$i]);
  119. }
  120. $bigarray = array_values($bigarray);
  121. //GROUPS
  122. if (array_search("# QUESTIONS TABLE\n", $bigarray))
  123. {
  124. $stoppoint = array_search("# QUESTIONS TABLE\n", $bigarray);
  125. }
  126. elseif (array_search("# QUESTIONS TABLE\r\n", $bigarray))
  127. {
  128. $stoppoint = array_search("# QUESTIONS TABLE\r\n", $bigarray);
  129. }
  130. else
  131. {
  132. $stoppoint = count($bigarray)-1;
  133. }
  134. for ($i=0; $i<=$stoppoint+1; $i++)
  135. {
  136. if ($i<$stoppoint-2) {$grouparray[] = $bigarray[$i];}
  137. unset($bigarray[$i]);
  138. }
  139. $bigarray = array_values($bigarray);
  140. //QUESTIONS
  141. if (array_search("# ANSWERS TABLE\n", $bigarray))
  142. {
  143. $stoppoint = array_search("# ANSWERS TABLE\n", $bigarray);
  144. }
  145. elseif (array_search("# ANSWERS TABLE\r\n", $bigarray))
  146. {
  147. $stoppoint = array_search("# ANSWERS TABLE\r\n", $bigarray);
  148. }
  149. else
  150. {
  151. $stoppoint = count($bigarray)-1;
  152. }
  153. for ($i=0; $i<=$stoppoint+1; $i++)
  154. {
  155. if ($i<$stoppoint-2)
  156. {
  157. $questionarray[] = $bigarray[$i];
  158. }
  159. unset($bigarray[$i]);
  160. }
  161. $bigarray = array_values($bigarray);
  162. //ANSWERS
  163. if (array_search("# CONDITIONS TABLE\n", $bigarray))
  164. {
  165. $stoppoint = array_search("# CONDITIONS TABLE\n", $bigarray);
  166. }
  167. elseif (array_search("# CONDITIONS TABLE\r\n", $bigarray))
  168. {
  169. $stoppoint = array_search("# CONDITIONS TABLE\r\n", $bigarray);
  170. }
  171. else
  172. {
  173. $stoppoint = count($bigarray)-1;
  174. }
  175. for ($i=0; $i<=$stoppoint+1; $i++)
  176. {
  177. if ($i<$stoppoint-2)
  178. {
  179. $answerarray[] = str_replace("`default`", "`default_value`", $bigarray[$i]);
  180. }
  181. unset($bigarray[$i]);
  182. }
  183. $bigarray = array_values($bigarray);
  184. //CONDITIONS
  185. if (array_search("# LABELSETS TABLE\n", $bigarray))
  186. {
  187. $stoppoint = array_search("# LABELSETS TABLE\n", $bigarray);
  188. }
  189. elseif (array_search("# LABELSETS TABLE\r\n", $bigarray))
  190. {
  191. $stoppoint = array_search("# LABELSETS TABLE\r\n", $bigarray);
  192. }
  193. for ($i=0; $i<=$stoppoint+1; $i++)
  194. {
  195. if ($i<$stoppoint-2) {$conditionsarray[] = $bigarray[$i];}
  196. unset($bigarray[$i]);
  197. }
  198. $bigarray = array_values($bigarray);
  199. //LABELSETS
  200. if (array_search("# LABELS TABLE\n", $bigarray))
  201. {
  202. $stoppoint = array_search("# LABELS TABLE\n", $bigarray);
  203. }
  204. elseif (array_search("# LABELS TABLE\r\n", $bigarray))
  205. {
  206. $stoppoint = array_search("# LABELS TABLE\r\n", $bigarray);
  207. }
  208. else
  209. {
  210. $stoppoint = count($bigarray)-1;
  211. }
  212. for ($i=0; $i<=$stoppoint+1; $i++)
  213. {
  214. if ($i<$stoppoint-2) {$labelsetsarray[] = $bigarray[$i];}
  215. unset($bigarray[$i]);
  216. }
  217. $bigarray = array_values($bigarray);
  218. //LABELS
  219. if (array_search("# QUESTION_ATTRIBUTES TABLE\n", $bigarray))
  220. {
  221. $stoppoint = array_search("# QUESTION_ATTRIBUTES TABLE\n", $bigarray);
  222. }
  223. elseif (array_search("# QUESTION_ATTRIBUTES TABLE\r\n", $bigarray))
  224. {
  225. $stoppoint = array_search("# QUESTION_ATTRIBUTES TABLE\r\n", $bigarray);
  226. }
  227. else
  228. {
  229. $stoppoint = count($bigarray)-1;
  230. }
  231. for ($i=0; $i<=$stoppoint+1; $i++)
  232. {
  233. if ($i<$stoppoint-2) {$labelsarray[] = $bigarray[$i];}
  234. unset($bigarray[$i]);
  235. }
  236. $bigarray = array_values($bigarray);
  237. //Question attributes
  238. if (!isset($noconditions) || $noconditions != "Y")
  239. {
  240. // stoppoint is the last line number
  241. // this is an empty line after the QA CSV lines
  242. $stoppoint = count($bigarray)-1;
  243. for ($i=0; $i<=$stoppoint+1; $i++)
  244. {
  245. if ($i<=$stoppoint-1) {$question_attributesarray[] = $bigarray[$i];}
  246. unset($bigarray[$i]);
  247. }
  248. }
  249. $bigarray = array_values($bigarray);
  250. $countgroups=0;
  251. if (isset($questionarray))
  252. {
  253. $questionfieldnames=convertCSVRowToArray($questionarray[0],',','"');
  254. unset($questionarray[0]);
  255. $countquestions = 0;
  256. }
  257. if (isset($answerarray))
  258. {
  259. $answerfieldnames=convertCSVRowToArray($answerarray[0],',','"');
  260. unset($answerarray[0]);
  261. $countanswers = count($answerarray);
  262. }
  263. else {$countanswers=0;}
  264. $aLanguagesSupported = array(); // this array will keep all the languages supported for the survey
  265. $sBaseLanguage = GetBaseLanguageFromSurveyID($newsid);
  266. $aLanguagesSupported[]=$sBaseLanguage; // adds the base language to the list of supported languages
  267. $aLanguagesSupported=array_merge($aLanguagesSupported,GetAdditionalLanguagesFromSurveyID($newsid));
  268. // Let's check that imported objects support at least the survey's baselang
  269. $langcode = GetBaseLanguageFromSurveyID($newsid);
  270. if (isset($grouparray))
  271. {
  272. $groupfieldnames = convertCSVRowToArray($grouparray[0],',','"');
  273. $langfieldnum = array_search("language", $groupfieldnames);
  274. $gidfieldnum = array_search("gid", $groupfieldnames);
  275. $groupssupportbaselang = bDoesImportarraySupportsLanguage($grouparray,Array($gidfieldnum),$langfieldnum,$sBaseLanguage,true);
  276. if (!$groupssupportbaselang)
  277. {
  278. $results['fatalerror']=$clang->gT("You can't import a group which doesn't support at least the survey base language.");
  279. return $results;
  280. }
  281. }
  282. if (isset($questionarray))
  283. {
  284. $langfieldnum = array_search("language", $questionfieldnames);
  285. $qidfieldnum = array_search("qid", $questionfieldnames);
  286. $questionssupportbaselang = bDoesImportarraySupportsLanguage($questionarray,Array($qidfieldnum), $langfieldnum,$sBaseLanguage,true);
  287. if (!$questionssupportbaselang)
  288. {
  289. $results['fatalerror']=$clang->gT("You can't import a question which doesn't support at least the survey base language.");
  290. return $results;
  291. }
  292. }
  293. if ($countanswers > 0)
  294. {
  295. $langfieldnum = array_search("language", $answerfieldnames);
  296. $answercodefilednum1 = array_search("qid", $answerfieldnames);
  297. $answercodefilednum2 = array_search("code", $answerfieldnames);
  298. $answercodekeysarr = Array($answercodefilednum1,$answercodefilednum2);
  299. $answerssupportbaselang = bDoesImportarraySupportsLanguage($answerarray,$answercodekeysarr,$langfieldnum,$sBaseLanguage);
  300. if (!$answerssupportbaselang)
  301. {
  302. $results['fatalerror']=$clang->gT("You can't import answers which doesn't support at least the survey base language.");
  303. return $results;
  304. }
  305. }
  306. if (count($labelsetsarray) > 1)
  307. {
  308. $labelsetfieldname = convertCSVRowToArray($labelsetsarray[0],',','"');
  309. $langfieldnum = array_search("languages", $labelsetfieldname);
  310. $lidfilednum = array_search("lid", $labelsetfieldname);
  311. $labelsetssupportbaselang = bDoesImportarraySupportsLanguage($labelsetsarray,Array($lidfilednum),$langfieldnum,$sBaseLanguage,true);
  312. if (!$labelsetssupportbaselang)
  313. {
  314. $results['fatalerror']=$clang->gT("You can't import label sets which don't support the current survey's base language");
  315. return $results;
  316. }
  317. }
  318. // I assume that if a labelset supports the survey's baselang,
  319. // then it's labels do support it as well
  320. //DO ANY LABELSETS FIRST, SO WE CAN KNOW WHAT THEIR NEW LID IS FOR THE QUESTIONS
  321. $results['labelsets']=0;
  322. $qtypes = getqtypelist("" ,"array");
  323. $results['labels']=0;
  324. $results['labelsets']=0;
  325. $results['answers']=0;
  326. $results['subquestions']=0;
  327. //Do label sets
  328. if (isset($labelsetsarray) && $labelsetsarray)
  329. {
  330. $csarray=buildLabelSetCheckSumArray(); // build checksums over all existing labelsets
  331. $count=0;
  332. foreach ($labelsetsarray as $lsa) {
  333. $fieldorders =convertCSVRowToArray($labelsetsarray[0],',','"');
  334. $fieldcontents=convertCSVRowToArray($lsa,',','"');
  335. if ($count==0) {$count++; continue;}
  336. $labelsetrowdata=array_combine($fieldorders,$fieldcontents);
  337. // Save old labelid
  338. $oldlid=$labelsetrowdata['lid'];
  339. unset($labelsetrowdata['lid']);
  340. $newvalues=array_values($labelsetrowdata);
  341. $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly
  342. $lsainsert = "INSERT INTO {$dbprefix}labelsets (".implode(',',array_keys($labelsetrowdata)).") VALUES (".implode(',',$newvalues).")"; //handle db prefix
  343. $lsiresult=$connect->Execute($lsainsert);
  344. $results['labelsets']++;
  345. // Get the new insert id for the labels inside this labelset
  346. $newlid=$connect->Insert_ID("{$dbprefix}labelsets",'lid');
  347. if ($labelsarray) {
  348. $count=0;
  349. foreach ($labelsarray as $la) {
  350. $lfieldorders =convertCSVRowToArray($labelsarray[0],',','"');
  351. $lfieldcontents=convertCSVRowToArray($la,',','"');
  352. if ($count==0) {$count++; continue;}
  353. // Combine into one array with keys and values since its easier to handle
  354. $labelrowdata=array_combine($lfieldorders,$lfieldcontents);
  355. $labellid=$labelrowdata['lid'];
  356. if ($importversion<=132)
  357. {
  358. $labelrowdata["assessment_value"]=(int)$labelrowdata["code"];
  359. }
  360. if ($labellid == $oldlid) {
  361. $labelrowdata['lid']=$newlid;
  362. // translate internal links
  363. $labelrowdata['title']=translink('label', $oldlid, $newlid, $labelrowdata['title']);
  364. $newvalues=array_values($labelrowdata);
  365. $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly
  366. $lainsert = "INSERT INTO {$dbprefix}labels (".implode(',',array_keys($labelrowdata)).") VALUES (".implode(',',$newvalues).")"; //handle db prefix
  367. $liresult=$connect->Execute($lainsert);
  368. if ($liresult!==false) $results['labels']++;
  369. }
  370. }
  371. }
  372. //CHECK FOR DUPLICATE LABELSETS
  373. $thisset="";
  374. $query2 = "SELECT code, title, sortorder, language, assessment_value
  375. FROM {$dbprefix}labels
  376. WHERE lid=".$newlid."
  377. ORDER BY language, sortorder, code";
  378. $result2 = db_execute_num($query2) or safe_die("Died querying labelset $lid<br />$query2<br />".$connect->ErrorMsg());
  379. while($row2=$result2->FetchRow())
  380. {
  381. $thisset .= implode('.', $row2);
  382. } // while
  383. $newcs=dechex(crc32($thisset)*1);
  384. unset($lsmatch);
  385. if (isset($csarray))
  386. {
  387. foreach($csarray as $key=>$val)
  388. {
  389. if ($val == $newcs)
  390. {
  391. $lsmatch=$key;
  392. }
  393. }
  394. }
  395. if (isset($lsmatch) || ($_SESSION['USER_RIGHT_MANAGE_LABEL'] != 1))
  396. {
  397. //There is a matching labelset or the user is not allowed to edit labels -
  398. // So, we will delete this one and refer to the matched one.
  399. $query = "DELETE FROM {$dbprefix}labels WHERE lid=$newlid";
  400. $result=$connect->Execute($query) or safe_die("Couldn't delete labels<br />$query<br />".$connect->ErrorMsg());
  401. $results['labels']=$results['labels']-$connect->Affected_Rows();
  402. $query = "DELETE FROM {$dbprefix}labelsets WHERE lid=$newlid";
  403. $result=$connect->Execute($query) or safe_die("Couldn't delete labelset<br />$query<br />".$connect->ErrorMsg());
  404. $results['labelsets']=$results['labelsets']-$connect->Affected_Rows();
  405. $newlid=$lsmatch;
  406. }
  407. else
  408. {
  409. //There isn't a matching labelset, add this checksum to the $csarray array
  410. $csarray[$newlid]=$newcs;
  411. }
  412. //END CHECK FOR DUPLICATES
  413. $aLIDReplacements[$oldlid]=$newlid;
  414. }
  415. }
  416. // Import groups
  417. if (isset($grouparray) && $grouparray)
  418. {
  419. // do GROUPS
  420. $gafieldorders=convertCSVRowToArray($grouparray[0],',','"');
  421. unset($grouparray[0]);
  422. $newgid = 0;
  423. $group_order = 0; // just to initialize this variable
  424. foreach ($grouparray as $ga)
  425. {
  426. $gacfieldcontents=convertCSVRowToArray($ga,',','"');
  427. $grouprowdata=array_combine($gafieldorders,$gacfieldcontents);
  428. // Skip not supported languages
  429. if (!in_array($grouprowdata['language'],$aLanguagesSupported))
  430. {
  431. $skippedlanguages[]=$grouprowdata['language']; // this is for the message in the end.
  432. continue;
  433. }
  434. // replace the sid
  435. $oldsid=$grouprowdata['sid'];
  436. $grouprowdata['sid']=$newsid;
  437. // replace the gid or remove it if needed (it also will calculate the group order if is a new group)
  438. $oldgid=$grouprowdata['gid'];
  439. if ($newgid == 0)
  440. {
  441. unset($grouprowdata['gid']);
  442. // find the maximum group order and use this grouporder+1 to assign it to the new group
  443. $qmaxgo = "select max(group_order) as maxgo from ".db_table_name('groups')." where sid=$newsid";
  444. $gres = db_execute_assoc($qmaxgo) or safe_die ($clang->gT("Error")." Failed to find out maximum group order value<br />\n$qmaxqo<br />\n".$connect->ErrorMsg());
  445. $grow=$gres->FetchRow();
  446. $group_order = $grow['maxgo']+1;
  447. }
  448. else
  449. $grouprowdata['gid'] = $newgid;
  450. $grouprowdata["group_order"]= $group_order;
  451. // Everything set - now insert it
  452. $grouprowdata=array_map('convertCsvreturn2return', $grouprowdata);
  453. // translate internal links
  454. $grouprowdata['group_name']=translink('survey', $oldsid, $newsid, $grouprowdata['group_name']);
  455. $grouprowdata['description']=translink('survey', $oldsid, $newsid, $grouprowdata['description']);
  456. db_switchIDInsert('groups',true);
  457. $tablename=$dbprefix.'groups';
  458. $ginsert = $connect->GetinsertSQL($tablename,$grouprowdata);
  459. $gres = $connect->Execute($ginsert) or safe_die($clang->gT('Error').": Failed to insert group<br />\n$ginsert<br />\n".$connect->ErrorMsg());
  460. db_switchIDInsert('groups',false);
  461. //GET NEW GID .... if is not done before and we count a group if a new gid is required
  462. if ($newgid == 0)
  463. {
  464. $newgid = $connect->Insert_ID("{$dbprefix}groups",'gid');
  465. $countgroups++;
  466. }
  467. }
  468. // GROUPS is DONE
  469. // Import questions
  470. if (isset($questionarray) && $questionarray)
  471. {
  472. foreach ($questionarray as $qa)
  473. {
  474. $qacfieldcontents=convertCSVRowToArray($qa,',','"');
  475. $questionrowdata=array_combine($questionfieldnames,$qacfieldcontents);
  476. $questionrowdata=array_map('convertCsvreturn2return', $questionrowdata);
  477. $questionrowdata["type"]=strtoupper($questionrowdata["type"]);
  478. // Skip not supported languages
  479. if (!in_array($questionrowdata['language'],$aLanguagesSupported))
  480. continue;
  481. // replace the sid
  482. $questionrowdata["sid"] = $newsid;
  483. // replace the gid (if the gid is not in the oldgid it means there is a problem with the exported record, so skip it)
  484. if ($questionrowdata['gid'] == $oldgid)
  485. $questionrowdata['gid'] = $newgid;
  486. else
  487. continue; // a problem with this question record -> don't consider
  488. if (isset($aQIDReplacements[$questionrowdata['qid']]))
  489. {
  490. $questionrowdata['qid']=$aQIDReplacements[$questionrowdata['qid']];
  491. }
  492. else
  493. {
  494. $oldqid = $questionrowdata['qid'];
  495. unset($questionrowdata['qid']);
  496. }
  497. // Save the following values - will need them for proper conversion later if ((int)$questionrowdata['lid']>0)
  498. unset($oldlid1); unset($oldlid2);
  499. if ((isset($questionrowdata['lid']) && $questionrowdata['lid']>0))
  500. {
  501. $oldlid1=$questionrowdata['lid'];
  502. }
  503. if ((isset($questionrowdata['lid1']) && $questionrowdata['lid1']>0))
  504. {
  505. $oldlid2=$questionrowdata['lid1'];
  506. }
  507. unset($questionrowdata['lid']);
  508. unset($questionrowdata['lid1']);
  509. if ($questionrowdata['type']=='W')
  510. {
  511. $questionrowdata['type']='!';
  512. }
  513. elseif ($questionrowdata['type']=='Z')
  514. {
  515. $questionrowdata['type']='L';
  516. }
  517. if (!isset($questionrowdata["question_order"]) || $questionrowdata["question_order"]=='') {$questionrowdata["question_order"]=0;}
  518. $questionrowdata=array_map('convertCsvreturn2return', $questionrowdata);
  519. // translate internal links
  520. $questionrowdata['title']=translink('survey', $oldsid, $newsid, $questionrowdata['title']);
  521. $questionrowdata['question']=translink('survey', $oldsid, $newsid, $questionrowdata['question']);
  522. $questionrowdata['help']=translink('survey', $oldsid, $newsid, $questionrowdata['help']);
  523. $newvalues=array_values($questionrowdata);
  524. $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly
  525. if (isset($questionrowdata['qid']))
  526. {
  527. db_switchIDInsert('questions',true);
  528. }
  529. $tablename=$dbprefix.'questions';
  530. $qinsert = $connect->GetInsertSQL($tablename,$questionrowdata);
  531. $qres = $connect->Execute($qinsert) or safe_die ($clang->gT("Error").": Failed to insert question<br />\n$qinsert<br />\n".$connect->ErrorMsg());
  532. $results['questions']++;
  533. //GET NEW QID .... if is not done before and we count a question if a new qid is required
  534. if (isset($questionrowdata['qid']))
  535. {
  536. $saveqid=$questionrowdata['qid'];
  537. }
  538. else
  539. {
  540. $aQIDReplacements[$oldqid]=$connect->Insert_ID("{$dbprefix}questions",'qid');
  541. $saveqid=$aQIDReplacements[$oldqid];
  542. }
  543. $qtypes = getqtypelist("" ,"array");
  544. $aSQIDReplacements=array();
  545. db_switchIDInsert('questions',false);
  546. // Now we will fix up old label sets where they are used as answers
  547. if ((isset($oldlid1) || isset($oldlid2)) && ($qtypes[$questionrowdata['type']]['answerscales']>0 || $qtypes[$questionrowdata['type']]['subquestions']>1))
  548. {
  549. $query="select * from ".db_table_name('labels')." where lid={$aLIDReplacements[$oldlid1]} and language='{$questionrowdata['language']}'";
  550. $oldlabelsresult=db_execute_assoc($query);
  551. while($labelrow=$oldlabelsresult->FetchRow())
  552. {
  553. if (in_array($labelrow['language'],$aLanguagesSupported))
  554. {
  555. if ($qtypes[$questionrowdata['type']]['subquestions']<2)
  556. {
  557. $qinsert = "insert INTO ".db_table_name('answers')." (qid,code,answer,sortorder,language,assessment_value)
  558. VALUES ({$aQIDReplacements[$oldqid]},".db_quoteall($labelrow['code']).",".db_quoteall($labelrow['title']).",".db_quoteall($labelrow['sortorder']).",".db_quoteall($labelrow['language']).",".db_quoteall($labelrow['assessment_value']).")";
  559. $qres = $connect->Execute($qinsert) or safe_die ($clang->gT("Error").": Failed to insert answer (lid1) <br />\n$qinsert<br />\n".$connect->ErrorMsg());
  560. }
  561. else
  562. {
  563. if (isset($aSQIDReplacements[$labelrow['code'].'_'.$saveqid])){
  564. $fieldname='qid,';
  565. $data=$aSQIDReplacements[$labelrow['code'].'_'.$saveqid].',';
  566. }
  567. else
  568. {
  569. $fieldname='' ;
  570. $data='';
  571. }
  572. $qinsert = "insert INTO ".db_table_name('questions')." ($fieldname parent_qid,title,question,question_order,language,scale_id,type, sid, gid)
  573. 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']})";
  574. $qres = $connect->Execute($qinsert) or safe_die ($clang->gT("Error").": Failed to insert question <br />\n$qinsert<br />\n".$connect->ErrorMsg());
  575. if ($fieldname=='')
  576. {
  577. $aSQIDReplacements[$labelrow['code'].'_'.$saveqid]=$connect->Insert_ID("{$dbprefix}questions","qid");
  578. }
  579. }
  580. }
  581. }
  582. if (isset($oldlid2) && $qtypes[$questionrowdata['type']]['answerscales']>1)
  583. {
  584. $query="select * from ".db_table_name('labels')." where lid={$aLIDReplacements[$oldlid2]} and language='{$questionrowdata['language']}'";
  585. $oldlabelsresult=db_execute_assoc($query);
  586. while($labelrow=$oldlabelsresult->FetchRow())
  587. {
  588. $qinsert = "insert INTO ".db_table_name('answers')." (qid,code,answer,sortorder,language,assessment_value,scale_id)
  589. 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)";
  590. $qres = $connect->Execute($qinsert) or safe_die ($clang->gT("Error").": Failed to insert answer (lid2)<br />\n$qinsert<br />\n".$connect->ErrorMsg());
  591. }
  592. }
  593. }
  594. }
  595. }
  596. //Do answers
  597. $results['subquestions']=0;
  598. if (isset($answerarray) && $answerarray)
  599. {
  600. foreach ($answerarray as $aa)
  601. {
  602. $answerfieldcontents=convertCSVRowToArray($aa,',','"');
  603. $answerrowdata=array_combine($answerfieldnames,$answerfieldcontents);
  604. if ($answerrowdata===false)
  605. {
  606. $importquestion.='<br />'.$clang->gT("Faulty line in import - fields and data don't match").":".implode(',',$answerfieldcontents);
  607. }
  608. // Skip not supported languages
  609. if (!in_array($answerrowdata['language'],$aLanguagesSupported))
  610. continue;
  611. // 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)
  612. if (isset($aQIDReplacements[$answerrowdata["qid"]]))
  613. $answerrowdata["qid"] = $aQIDReplacements[$answerrowdata["qid"]];
  614. else
  615. continue; // a problem with this answer record -> don't consider
  616. if ($importversion<=132)
  617. {
  618. $answerrowdata["assessment_value"]=(int)$answerrowdata["code"];
  619. }
  620. // Convert default values for single select questions
  621. $questiontemp=$connect->GetRow('select type,gid from '.db_table_name('questions').' where qid='.$answerrowdata["qid"]);
  622. $oldquestion['newtype']=$questiontemp['type'];
  623. $oldquestion['gid']=$questiontemp['gid'];
  624. if ($answerrowdata['default_value']=='Y' && ($oldquestion['newtype']=='L' || $oldquestion['newtype']=='O' || $oldquestion['newtype']=='!'))
  625. {
  626. $insertdata=array();
  627. $insertdata['qid']=$newqid;
  628. $insertdata['language']=$answerrowdata['language'];
  629. $insertdata['defaultvalue']=$answerrowdata['answer'];
  630. $query=$connect->GetInsertSQL($dbprefix.'defaultvalues',$insertdata);
  631. $qres = $connect->Execute($query) or safe_die ("Error: Failed to insert defaultvalue <br />{$query}<br />\n".$connect->ErrorMsg());
  632. }
  633. // translate internal links
  634. $answerrowdata['answer']=translink('survey', $oldsid, $newsid, $answerrowdata['answer']);
  635. // Everything set - now insert it
  636. $answerrowdata = array_map('convertCsvreturn2return', $answerrowdata);
  637. if ($qtypes[$oldquestion['newtype']]['subquestions']>0) //hmmm.. this is really a subquestion
  638. {
  639. $questionrowdata=array();
  640. if (isset($aSQIDReplacements[$answerrowdata['code'].$answerrowdata['qid']])){
  641. $questionrowdata['qid']=$aSQIDReplacements[$answerrowdata['code'].$answerrowdata['qid']];
  642. }
  643. $questionrowdata['parent_qid']=$answerrowdata['qid'];;
  644. $questionrowdata['sid']=$newsid;
  645. $questionrowdata['gid']=$oldquestion['gid'];
  646. $questionrowdata['title']=$answerrowdata['code'];
  647. $questionrowdata['question']=$answerrowdata['answer'];
  648. $questionrowdata['question_order']=$answerrowdata['sortorder'];
  649. $questionrowdata['language']=$answerrowdata['language'];
  650. $questionrowdata['type']=$oldquestion['newtype'];
  651. $tablename=$dbprefix.'questions';
  652. $query=$connect->GetInsertSQL($tablename,$questionrowdata);
  653. if (isset($questionrowdata['qid'])) db_switchIDInsert('questions',true);
  654. $qres = $connect->Execute($query) or safe_die ("Error: Failed to insert subquestion <br />{$query}<br />".$connect->ErrorMsg());
  655. if (!isset($questionrowdata['qid']))
  656. {
  657. $aSQIDReplacements[$answerrowdata['code'].$answerrowdata['qid']]=$connect->Insert_ID("{$dbprefix}questions","qid");
  658. }
  659. else
  660. {
  661. db_switchIDInsert('questions',false);
  662. }
  663. $results['subquestions']++;
  664. // also convert default values subquestions for multiple choice
  665. if ($answerrowdata['default_value']=='Y' && ($oldquestion['newtype']=='M' || $oldquestion['newtype']=='P'))
  666. {
  667. $insertdata=array();
  668. $insertdata['qid']=$newqid;
  669. $insertdata['sqid']=$aSQIDReplacements[$answerrowdata['code']];
  670. $insertdata['language']=$answerrowdata['language'];
  671. $insertdata['defaultvalue']='Y';
  672. $tablename=$dbprefix.'defaultvalues';
  673. $query=$connect->GetInsertSQL($tablename,$insertdata);
  674. $qres = $connect->Execute($query) or safe_die ("Error: Failed to insert defaultvalue <br />{$query}<br />\n".$connect->ErrorMsg());
  675. }
  676. }
  677. else // insert answers
  678. {
  679. unset($answerrowdata['default_value']);
  680. $tablename=$dbprefix.'answers';
  681. $query=$connect->GetInsertSQL($tablename,$answerrowdata);
  682. $ares = $connect->Execute($query) or safe_die ("Error: Failed to insert answer<br />{$query}<br />\n".$connect->ErrorMsg());
  683. $results['answers']++;
  684. }
  685. }
  686. }
  687. // ANSWERS is DONE
  688. // Fix sortorder of the groups - if users removed groups manually from the csv file there would be gaps
  689. fixSortOrderGroups($surveyid);
  690. //... and for the questions inside the groups
  691. // get all group ids and fix questions inside each group
  692. $gquery = "SELECT gid FROM {$dbprefix}groups where sid=$newsid group by gid ORDER BY gid"; //Get last question added (finds new qid)
  693. $gres = db_execute_assoc($gquery);
  694. while ($grow = $gres->FetchRow())
  695. {
  696. fixsortorderQuestions($grow['gid'], $newsid);
  697. }
  698. }
  699. $results['question_attributes']=0;
  700. // Finally the question attributes - it is called just once and only if there was a question
  701. if (isset($question_attributesarray) && $question_attributesarray)
  702. {//ONLY DO THIS IF THERE ARE QUESTION_ATTRIBUES
  703. $fieldorders=convertCSVRowToArray($question_attributesarray[0],',','"');
  704. unset($question_attributesarray[0]);
  705. foreach ($question_attributesarray as $qar) {
  706. $fieldcontents=convertCSVRowToArray($qar,',','"');
  707. $qarowdata=array_combine($fieldorders,$fieldcontents);
  708. // replace the qid for the new one (if there is no new qid in the $aQIDReplacements array it mean that this attribute is orphan -> error, skip this record)
  709. if (isset($aQIDReplacements[$qarowdata["qid"]]))
  710. $qarowdata["qid"] = $aQIDReplacements[$qarowdata["qid"]];
  711. else
  712. continue; // a problem with this answer record -> don't consider
  713. unset($qarowdata["qaid"]);
  714. $tablename="{$dbprefix}question_attributes";
  715. $qainsert=$connect->GetInsertSQL($tablename,$qarowdata);
  716. $result=$connect->Execute($qainsert);
  717. if ($result!==false) $results['question_attributes']++;
  718. }
  719. }
  720. // ATTRIBUTES is DONE
  721. // do CONDITIONS
  722. $results['conditions']=0;
  723. if (isset($conditionsarray) && $conditionsarray)
  724. {
  725. $fieldorders=convertCSVRowToArray($conditionsarray[0],',','"');
  726. unset($conditionsarray[0]);
  727. foreach ($conditionsarray as $car) {
  728. $fieldcontents=convertCSVRowToArray($car,',','"');
  729. $conditionrowdata=array_combine($fieldorders,$fieldcontents);
  730. $oldqid = $conditionrowdata["qid"];
  731. $oldcqid = $conditionrowdata["cqid"];
  732. // replace the qid for the new one (if there is no new qid in the $aQIDReplacements array it mean that this condition is orphan -> error, skip this record)
  733. if (isset($aQIDReplacements[$oldqid]))
  734. $conditionrowdata["qid"] = $aQIDReplacements[$oldqid];
  735. else
  736. continue; // a problem with this answer record -> don't consider
  737. // replace the cqid for the new one (if there is no new qid in the $aQIDReplacements array it mean that this condition is orphan -> error, skip this record)
  738. if (isset($aQIDReplacements[$oldcqid]))
  739. $conditionrowdata["cqid"] = $aQIDReplacements[$oldcqid];
  740. else
  741. continue; // a problem with this answer record -> don't consider
  742. list($oldcsid, $oldcgid, $oldqidanscode) = explode("X",$conditionrowdata["cfieldname"],3);
  743. if ($oldcgid != $oldgid) // this means that the condition is in another group (so it should not have to be been exported -> skip it
  744. continue;
  745. unset($conditionrowdata["cid"]);
  746. // recreate the cfieldname with the new IDs
  747. if (preg_match("/^\+/",$oldcsid))
  748. {
  749. $newcfieldname = '+'.$newsid . "X" . $newgid . "X" . $conditionrowdata["cqid"] .substr($oldqidanscode,strlen($oldqid));
  750. }
  751. else
  752. {
  753. $newcfieldname = $newsid . "X" . $newgid . "X" . $conditionrowdata["cqid"] .substr($oldqidanscode,strlen($oldqid));
  754. }
  755. $conditionrowdata["cfieldname"] = $newcfieldname;
  756. if (!isset($conditionrowdata["method"]) || trim($conditionrowdata["method"])=='')
  757. {
  758. $conditionrowdata["method"]='==';
  759. }
  760. $newvalues=array_values($conditionrowdata);
  761. $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly
  762. $conditioninsert = "insert INTO {$dbprefix}conditions (".implode(',',array_keys($conditionrowdata)).") VALUES (".implode(',',$newvalues).")";
  763. $result=$connect->Execute($conditioninsert) or safe_die ("Couldn't insert condition<br />$conditioninsert<br />".$connect->ErrorMsg());
  764. $results['conditions']++;
  765. }
  766. }
  767. $results['groups']=1;
  768. $results['newgid']=$newgid;
  769. return $results;
  770. }
  771. /**
  772. * This function imports a LimeSurvey .lsg question group XML file
  773. *
  774. * @param mixed $sFullFilepath The full filepath of the uploaded file
  775. * @param mixed $newsid The new survey id - the group will always be added after the last group in the survey
  776. */
  777. function XMLImportGroup($sFullFilepath, $newsid)
  778. {
  779. global $connect, $dbprefix, $clang;
  780. $aLanguagesSupported = array(); // this array will keep all the languages supported for the survey
  781. $sBaseLanguage = GetBaseLanguageFromSurveyID($newsid);
  782. $aLanguagesSupported[]=$sBaseLanguage; // adds the base language to the list of supported languages
  783. $aLanguagesSupported=array_merge($aLanguagesSupported,GetAdditionalLanguagesFromSurveyID($newsid));
  784. $xml = @simplexml_load_file($sFullFilepath);
  785. if ($xml==false || $xml->LimeSurveyDocType!='Group') safe_die('This is not a valid LimeSurvey group structure XML file.');
  786. $dbversion = (int) $xml->DBVersion;
  787. $aQIDReplacements=array();
  788. $results['defaultvalues']=0;
  789. $results['answers']=0;
  790. $results['question_attributes']=0;
  791. $results['subquestions']=0;
  792. $results['conditions']=0;
  793. $results['groups']=0;
  794. $importlanguages=array();
  795. foreach ($xml->languages->language as $language)
  796. {
  797. $importlanguages[]=(string)$language;
  798. }
  799. if (!in_array($sBaseLanguage,$importlanguages))
  800. {
  801. $results['fatalerror'] = $clang->gT("The languages of the imported group file must at least include the base language of this survey.");
  802. return;
  803. }
  804. // First get an overview of fieldnames - it's not useful for the moment but might be with newer versions
  805. /*
  806. $fieldnames=array();
  807. foreach ($xml->questions->fields->fieldname as $fieldname )
  808. {
  809. $fieldnames[]=(string)$fieldname;
  810. };*/
  811. // Import group table ===================================================================================
  812. $tablename=$dbprefix.'groups';
  813. $newgrouporder=$connect->GetOne("SELECT MAX(group_order) AS maxqo FROM ".db_table_name('groups')." WHERE sid=$newsid");
  814. if (is_null($newgrouporder))
  815. {
  816. $newgrouporder=0;
  817. }
  818. else {
  819. $newgrouporder++;
  820. }
  821. foreach ($xml->groups->rows->row as $row)
  822. {
  823. $insertdata=array();
  824. foreach ($row as $key=>$value)
  825. {
  826. $insertdata[(string)$key]=(string)$value;
  827. }
  828. $oldsid=$insertdata['sid'];
  829. $insertdata['sid']=$newsid;
  830. $insertdata['group_order']=$newgrouporder;
  831. $oldgid=$insertdata['gid']; unset($insertdata['gid']); // save the old qid
  832. // now translate any links
  833. $insertdata['group_name']=translink('survey', $oldsid, $newsid, $insertdata['group_name']);
  834. $insertdata['description']=translink('survey', $oldsid, $newsid, $insertdata['description']);
  835. // Insert the new question
  836. if (isset($aGIDReplacements[$oldgid]))
  837. {
  838. $insertdata['gid']=$aGIDReplacements[$oldgid];
  839. db_switchIDInsert('groups',true);
  840. }
  841. $query=$connect->GetInsertSQL($tablename,$insertdata);
  842. $result = $connect->Execute($query) or safe_die ($clang->gT("Error").": Failed to insert data<br />{$query}<br />\n".$connect->ErrorMsg());
  843. $results['groups']++;
  844. if (!isset($aGIDReplacements[$oldgid]))
  845. {
  846. $newgid=$connect->Insert_ID($tablename,"gid"); // save this for later
  847. $aGIDReplacements[$oldgid]=$newgid; // add old and new qid to the mapping array
  848. }
  849. else
  850. {
  851. db_switchIDInsert('groups',false);
  852. }
  853. }
  854. // Import questions table ===================================================================================
  855. // We have to run the question table data two times - first to find all main questions
  856. // then for subquestions (because we need to determine the new qids for the main questions first)
  857. $tablename=$dbprefix.'questions';
  858. $results['questions']=0;
  859. foreach ($xml->questions->rows->row as $row)
  860. {
  861. $insertdata=array();
  862. foreach ($row as $key=>$value)
  863. {
  864. $insertdata[(string)$key]=(string)$value;
  865. }
  866. $oldsid=$insertdata['sid'];
  867. $insertdata['sid']=$newsid;
  868. if (!isset($aGIDReplacements[$insertdata['gid']]) || trim($insertdata['title'])=='') continue; // Skip questions with invalid group id
  869. $insertdata['gid']=$aGIDReplacements[$insertdata['gid']];
  870. $oldqid=$insertdata['qid']; unset($insertdata['qid']); // save the old qid
  871. // now translate any links
  872. $insertdata['title']=translink('survey', $oldsid, $newsid, $insertdata['title']);
  873. $insertdata['question']=translink('survey', $oldsid, $newsid, $insertdata['question']);
  874. $insertdata['help']=translink('survey', $oldsid, $newsid, $insertdata['help']);
  875. // Insert the new question
  876. if (isset($aQIDReplacements[$oldqid]))
  877. {
  878. $insertdata['qid']=$aQIDReplacements[$oldqid];
  879. db_switchIDInsert('questions',true);
  880. }
  881. $query=$connect->GetInsertSQL($tablename,$insertdata);
  882. $result = $connect->Execute($query) or safe_die ($clang->gT("Error").": Failed to insert data<br />{$query}<br />\n".$connect->ErrorMsg());
  883. if (!isset($aQIDReplacements[$oldqid]))
  884. {
  885. $newqid=$connect->Insert_ID($tablename,"qid"); // save this for later
  886. $aQIDReplacements[$oldqid]=$newqid; // add old and new qid to the mapping array
  887. $results['questions']++;
  888. }
  889. else
  890. {
  891. db_switchIDInsert('questions',false);
  892. }
  893. }
  894. // Import subquestions --------------------------------------------------------------
  895. if (isset($xml->subquestions))
  896. {
  897. foreach ($xml->subquestions->rows->row as $row)
  898. {
  899. $insertdata=array();
  900. foreach ($row as $key=>$value)
  901. {
  902. $insertdata[(string)$key]=(string)$value;
  903. }
  904. $insertdata['sid']=$newsid;
  905. if (!isset($aGIDReplacements[$insertdata['gid']])) continue; // Skip questions with invalid group id
  906. $insertdata['gid']=$aGIDReplacements[(int)$insertdata['gid']];;
  907. $oldsqid=(int)$insertdata['qid']; unset($insertdata['qid']); // save the old qid
  908. if (!isset($aQIDReplacements[(int)$insertdata['parent_qid']])) continue; // Skip subquestions with invalid parent_qids
  909. $insertdata['parent_qid']=$aQIDReplacements[(int)$insertdata['parent_qid']]; // remap the parent_qid
  910. // now translate any links
  911. $insertdata['title']=translink('survey', $oldsid, $newsid, $insertdata['title']);
  912. $insertdata['question']=translink('survey', $oldsid, $newsid, $insertdata['question']);
  913. $insertdata['help']=translink('survey', $oldsid, $newsid, $insertdata['help']);
  914. if (isset($aQIDReplacements[$oldsqid])){
  915. $insertdata['qid']=$aQIDReplacements[$oldsqid];
  916. db_switchIDInsert('questions',true);
  917. }
  918. $query=$connect->GetInsertSQL($tablename,$insertdata);
  919. $result = $connect->Execute($query) or safe_die ($clang->gT("Error").": Failed to insert data<br />{$query}<br />\n".$connect->ErrorMsg());
  920. $newsqid=$connect->Insert_ID($tablename,"qid"); // save this for later
  921. if (!isset($insertdata['qid']))
  922. {
  923. $aQIDReplacements[$oldsqid]=$newsqid; // add old and new qid to the mapping array
  924. }
  925. else
  926. {
  927. db_switchIDInsert('questions',false);
  928. }
  929. $results['subquestions']++;
  930. }
  931. }
  932. // Import answers --------------------------------------------------------------
  933. if(isset($xml->answers))
  934. {
  935. $tablename=$dbprefix.'answers';
  936. foreach ($xml->answers->rows->row as $row)
  937. {
  938. $insertdata=array();
  939. foreach ($row as $key=>$value)
  940. {
  941. $insertdata[(string)$key]=(string)$value;
  942. }
  943. if (!isset($aQIDReplacements[(int)$insertdata['qid']])) continue; // Skip questions with invalid group id
  944. $insertdata['qid']=$aQIDReplacements[(int)$insertdata['qid']]; // remap the parent_qid
  945. // now translate any links
  946. $query=$connect->GetInsertSQL($tablename,$insertdata);
  947. $result=$connect->Execute($query) or safe_die ($clang->gT("Error").": Failed to insert data<br />{$query}<br />\n".$connect->ErrorMsg());
  948. $results['answers']++;
  949. }
  950. }
  951. // Import questionattributes --------------------------------------------------------------
  952. if(isset($xml->question_attributes))
  953. {
  954. $tablename=$dbprefix.'question_attributes';
  955. foreach ($xml->question_attributes->rows->row as $row)
  956. {
  957. $insertdata=array();
  958. foreach ($row as $key=>$value)
  959. {
  960. $insertdata[(string)$key]=(string)$value;
  961. }
  962. unset($insertdata['qaid']);
  963. if (!isset($aQIDReplacements[(int)$insertdata['qid']])) continue; // Skip questions with invalid group id
  964. $insertdata['qid']=$aQIDReplacements[(int)$insertdata['qid']]; // remap the parent_qid
  965. // now translate any links
  966. $query=$connect->GetInsertSQL($tablename,$insertdata);
  967. $result=$connect->Execute($query) or safe_die ($clang->gT("Error").": Failed to insert data<br />{$query}<br />\n".$connect->ErrorMsg());
  968. $results['question_attributes']++;
  969. }
  970. }
  971. // Import defaultvalues --------------------------------------------------------------
  972. if(isset($xml->defaultvalues))
  973. {
  974. $tablename=$dbprefix.'defaultvalues';
  975. $results['defaultvalues']=0;
  976. foreach ($xml->defaultvalues->rows->row as $row)
  977. {
  978. $insertdata=array();
  979. foreach ($row as $key=>$value)
  980. {
  981. $insertdata[(string)$key]=

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