function upgrade_tables143() { global $modifyoutput, $dbprefix, $connect; $aQIDReplacements = array(); $answerquery = "select a.*, q.sid, q.gid from {$dbprefix}answers a,{$dbprefix}questions q where a.qid=q.qid and q.type in ('L','O','!') and a.default_value='Y'"; $answerresult = db_execute_assoc($answerquery); if (!$answerresult) { return "Database Error"; } else { while ($row = $answerresult->FetchRow()) { modify_database("", "INSERT INTO {$dbprefix}defaultvalues (qid, scale_id,language,specialtype,defaultvalue) VALUES ({$row['qid']},0," . db_quoteall($row['language']) . ",''," . db_quoteall($row['code']) . ")"); echo $modifyoutput; flush(); ob_flush(); } } // Convert answers to subquestions $answerquery = "select a.*, q.sid, q.gid, q.type from {$dbprefix}answers a,{$dbprefix}questions q where a.qid=q.qid and a.language=q.language and q.type in ('1','A','B','C','E','F','H','K',';',':','M','P','Q')"; $answerresult = db_execute_assoc($answerquery); if (!$answerresult) { return "Database Error"; } else { while ($row = $answerresult->FetchRow()) { $insertarray = array(); if (isset($aQIDReplacements[$row['qid'] . '_' . $row['code']])) { $insertarray['qid'] = $aQIDReplacements[$row['qid'] . '_' . $row['code']]; db_switchIDInsert('questions', true); } $insertarray['sid'] = $row['sid']; $insertarray['gid'] = $row['gid']; $insertarray['parent_qid'] = $row['qid']; $insertarray['type'] = $row['type']; $insertarray['title'] = $row['code']; $insertarray['question'] = $row['answer']; $insertarray['question_order'] = $row['sortorder']; $insertarray['language'] = $row['language']; $tablename = "{$dbprefix}questions"; $query = $connect->GetInsertSQL($tablename, $insertarray); modify_database("", $query); echo $modifyoutput; flush(); ob_flush(); if (!isset($insertarray['qid'])) { $aQIDReplacements[$row['qid'] . '_' . $row['code']] = $connect->Insert_ID("{$dbprefix}questions", "qid"); $iSaveSQID = $aQIDReplacements[$row['qid'] . '_' . $row['code']]; } else { $iSaveSQID = $insertarray['qid']; db_switchIDInsert('questions', false); } if (($row['type'] == 'M' || $row['type'] == 'P') && $row['default_value'] == 'Y') { modify_database("", "INSERT INTO {$dbprefix}defaultvalues (qid, sqid, scale_id,language,specialtype,defaultvalue) VALUES ({$row['qid']},{$iSaveSQID},0," . db_quoteall($row['language']) . ",'','Y')"); echo $modifyoutput; flush(); ob_flush(); } } } modify_database("", "delete {$dbprefix}answers from {$dbprefix}answers LEFT join {$dbprefix}questions ON {$dbprefix}answers.qid={$dbprefix}questions.qid where {$dbprefix}questions.type in ('1','F','H','M','P','W','Z')"); echo $modifyoutput; flush(); ob_flush(); // Convert labels to answers $answerquery = "select qid ,type ,lid ,lid1, language from {$dbprefix}questions where parent_qid=0 and type in ('1','F','H','M','P','W','Z')"; $answerresult = db_execute_assoc($answerquery); if (!$answerresult) { return "Database Error"; } else { while ($row = $answerresult->FetchRow()) { $labelquery = "Select * from {$dbprefix}labels where lid={$row['lid']} and language=" . db_quoteall($row['language']); $labelresult = db_execute_assoc($labelquery); while ($lrow = $labelresult->FetchRow()) { modify_database("", "INSERT INTO {$dbprefix}answers (qid, code, answer, sortorder, language, assessment_value) VALUES ({$row['qid']}," . db_quoteall($lrow['code']) . "," . db_quoteall($lrow['title']) . ",{$lrow['sortorder']}," . db_quoteall($lrow['language']) . ",{$lrow['assessment_value']})"); echo $modifyoutput; flush(); ob_flush(); //$labelids[] } if ($row['type'] == '1') { $labelquery = "Select * from {$dbprefix}labels where lid={$row['lid1']} and language=" . db_quoteall($row['language']); $labelresult = db_execute_assoc($labelquery); while ($lrow = $labelresult->FetchRow()) { modify_database("", "INSERT INTO {$dbprefix}answers (qid, code, answer, sortorder, language, scale_id, assessment_value) VALUES ({$row['qid']}," . db_quoteall($lrow['code']) . "," . db_quoteall($lrow['title']) . ",{$lrow['sortorder']}," . db_quoteall($lrow['language']) . ",1,{$lrow['assessment_value']})"); echo $modifyoutput; flush(); ob_flush(); } } } } // Convert labels to subquestions $answerquery = "select * from {$dbprefix}questions where parent_qid=0 and type in (';',':')"; $answerresult = db_execute_assoc($answerquery); if (!$answerresult) { return "Database Error"; } else { while ($row = $answerresult->FetchRow()) { $labelquery = "Select * from {$dbprefix}labels where lid={$row['lid']} and language=" . db_quoteall($row['language']); $labelresult = db_execute_assoc($labelquery); while ($lrow = $labelresult->FetchRow()) { $insertarray = array(); if (isset($aQIDReplacements[$row['qid'] . '_' . $lrow['code'] . '_1'])) { $insertarray['qid'] = $aQIDReplacements[$row['qid'] . '_' . $lrow['code'] . '_1']; db_switchIDInsert('questions', true); } $insertarray['sid'] = $row['sid']; $insertarray['gid'] = $row['gid']; $insertarray['type'] = $row['type']; $insertarray['parent_qid'] = $row['qid']; $insertarray['title'] = $lrow['code']; $insertarray['question'] = $lrow['title']; $insertarray['question_order'] = $lrow['sortorder']; $insertarray['language'] = $lrow['language']; $insertarray['scale_id'] = 1; $tablename = "{$dbprefix}questions"; $query = $connect->GetInsertSQL($tablename, $insertarray); modify_database("", $query); echo $modifyoutput; flush(); ob_flush(); if (isset($insertarray['qid'])) { $aQIDReplacements[$row['qid'] . '_' . $lrow['code'] . '_1'] = $connect->Insert_ID("{$dbprefix}questions", "qid"); db_switchIDInsert('questions', false); } } } } $updatequery = "update {$dbprefix}questions set type='!' where type='W'"; modify_database("", $updatequery); echo $modifyoutput; flush(); ob_flush(); $updatequery = "update {$dbprefix}questions set type='L' where type='Z'"; modify_database("", $updatequery); echo $modifyoutput; flush(); ob_flush(); // Now move all non-standard templates to the /upload dir global $usertemplaterootdir, $standardtemplates, $standardtemplaterootdir; if (!$usertemplaterootdir) { die("gettemplatelist() no template directory"); } if ($handle = opendir($standardtemplaterootdir)) { while (false !== ($file = readdir($handle))) { if (!is_file("{$standardtemplaterootdir}/{$file}") && $file != "." && $file != ".." && $file != ".svn" && !isStandardTemplate($file)) { if (!rename($standardtemplaterootdir . DIRECTORY_SEPARATOR . $file, $usertemplaterootdir . DIRECTORY_SEPARATOR . $file)) { echo "There was a problem moving directory '" . $standardtemplaterootdir . DIRECTORY_SEPARATOR . $file . "' to '" . $usertemplaterootdir . DIRECTORY_SEPARATOR . $file . "' due to missing permissions. Please do this manually.<br />"; } } } closedir($handle); } }
} } if ($insertstyle == "renumber") { unset($fielddata['id']); } if (isset($fielddata['id'])) { db_switchIDInsert("survey_{$surveyid}", true); } // try again, without the 'id' field. $insert = "INSERT INTO {$surveytable}\n"; $insert .= "(" . implode(", ", array_keys($fielddata)) . ")\n"; $insert .= "VALUES\n"; $insert .= "(" . implode(", ", array_values($fielddata)) . ")"; $result = $connect->Execute($insert); if (isset($fielddata['id'])) { db_switchIDInsert("survey_{$surveyid}", false); } if (!$result) { $vvoutput .= "<div class='warningheader'>\n{$insert}" . "<br />" . sprintf($clang->gT("Import Failed on Record %d because [%s]"), $recordcount, htmlspecialchars(utf8_encode($connect->ErrorMsg()))) . "</div>\n"; } else { $importcount++; } } } if ($noid == "noid" || $insertstyle == "renumber") { $vvoutput .= "<br /><i><strong><font color='red'>" . $clang->gT("Important Note:") . "<br />" . $clang->gT("Do NOT refresh this page, as this will import the file again and produce duplicates") . "</font></strong></i><br /><br />"; } $vvoutput .= $clang->gT("Total records imported:") . " " . $importcount . "<br /><br />"; $vvoutput .= "[<a href='admin.php?action=browse&sid={$surveyid}'>" . $clang->gT("Browse Responses") . "</a>]"; $vvoutput .= "</div><br /> "; }
function modlabelsetanswers($lid) { global $dbprefix, $connect, $clang, $labelsoutput, $databasetype, $filterxsshtml,$postsortorder; $qulabelset = "SELECT * FROM ".db_table_name('labelsets')." WHERE lid='$lid'"; $rslabelset = db_execute_assoc($qulabelset) or safe_die($connect->ErrorMsg()); $rwlabelset=$rslabelset->FetchRow(); $lslanguages=explode(" ", trim($rwlabelset['languages'])); if (!isset($_POST['method'])) { $_POST['method'] = $clang->gT("Save"); } switch($_POST['method']) { case $clang->gT("Add new label", "unescaped"): if (isset($_POST['insertcode']) && $_POST['insertcode']!='') { $_SESSION['nextlabelcode']=getNextCode($_POST['insertcode']); $_POST['insertcode'] = db_quoteall($_POST['insertcode'],true); // check that the code doesn't exist yet $query = "SELECT code FROM ".db_table_name('labels')." WHERE lid='$lid' AND code=".$_POST['insertcode']; $result = $connect->Execute($query); $codeoccurences=$result->RecordCount(); if ($codeoccurences == 0) { $query = "select max(sortorder) as maxorder from ".db_table_name('labels')." where lid='$lid'"; $result = $connect->Execute($query); $newsortorder=sprintf("%05d", $result->fields['maxorder']+1); if ($filterxsshtml) { require_once("../classes/inputfilter/class.inputfilter_clean.php"); $myFilter = new InputFilter('','',1,1,1); $_POST['inserttitle']=$myFilter->process($_POST['inserttitle']); } else { $_POST['inserttitle'] = html_entity_decode($_POST['inserttitle'], ENT_QUOTES, "UTF-8"); } // Fix bug with FCKEditor saving strange BR types $_POST['inserttitle']=fix_FCKeditor_text($_POST['inserttitle']); $_POST['inserttitle'] = db_quoteall($_POST['inserttitle'],true); $_POST['insertassessmentvalue']=(int)$_POST['insertassessmentvalue']; foreach ($lslanguages as $lslanguage) { db_switchIDInsert('labels',true); $query = "INSERT INTO ".db_table_name('labels')." (lid, code, title, sortorder,language, assessment_value) VALUES ($lid, {$_POST['insertcode']}, {$_POST['inserttitle']}, '$newsortorder','$lslanguage',{$_POST['insertassessmentvalue']})"; if (!$result = $connect->Execute($query)) { $labelsoutput.= "<script type=\"text/javascript\">\n<!--\n alert(\"".$clang->gT("Failed to insert label", "js")." - ".$query." - ".$connect->ErrorMsg()."\")\n //-->\n</script>\n"; } db_switchIDInsert('labels',false); } } else { $labelsoutput.= "<script type=\"text/javascript\">\n<!--\n alert(\"".$clang->gT("This label code is already used in this labelset. Please choose another code or rename the existing one.", "js")."\")\n //-->\n</script>\n"; } } break; // Save all labels with one button case $clang->gT("Save Changes", "unescaped"): //Determine autoids by evaluating the hidden field $sortorderids=explode(' ', trim($_POST['sortorderids'])); $codeids=explode(' ', trim($_POST['codeids'])); $count=0; // Quote each code_codeid first foreach ($codeids as $codeid) { $_POST['code_'.$codeid] = db_quoteall($_POST['code_'.$codeid],true); if (isset($_POST['oldcode_'.$codeid])) $_POST['oldcode_'.$codeid] = db_quoteall($_POST['oldcode_'.$codeid],true); // Get the code values to check for duplicates $codevalues[] = $_POST['code_'.$codeid]; } // Check that there is no code duplicate if (count(array_unique($codevalues)) == count($codevalues)) { if ($filterxsshtml) { require_once("../classes/inputfilter/class.inputfilter_clean.php"); $myFilter = new InputFilter('','',1,1,1); } foreach ($sortorderids as $sortorderid) { $orderid=substr($sortorderid,strrpos($sortorderid,'_')+1,20); foreach ($lslanguages as $langid) { $sortorderid = $langid . '_' . $orderid; if ($filterxsshtml) { $_POST['title_'.$sortorderid]=$myFilter->process($_POST['title_'.$sortorderid]); } else { $_POST['title_'.$sortorderid] = html_entity_decode($_POST['title_'.$sortorderid], ENT_QUOTES, "UTF-8"); } // Fix bug with FCKEditor saving strange BR types $_POST['title_'.$sortorderid]=fix_FCKeditor_text($_POST['title_'.$sortorderid]); $_POST['title_'.$sortorderid] = db_quoteall($_POST['title_'.$sortorderid],true); $query = "UPDATE ".db_table_name('labels')." SET code=".$_POST['code_'.$codeids[$count]].", title={$_POST['title_'.$sortorderid]}, assessment_value={$_POST['assessmentvalue_'.$codeids[$count]]} WHERE lid=$lid AND sortorder=$orderid AND language='$langid'"; if (!$result = $connect->Execute($query)) // if update didn't work we assume the label does not exist and insert it { $query = "insert into ".db_table_name('labels')." (code,title,lid,sortorder,language) VALUES (".$_POST['code_'.$codeids[$count]].", {$_POST['title_'.$sortorderid]}, $lid , $orderid , '$langid')"; if (!$result = $connect->Execute($query)) { $labelsoutput.= "<script type=\"text/javascript\">\n<!--\n alert(\"".$clang->gT("Failed to update label","js")." - ".$query." - ".$connect->ErrorMsg()."\")\n //-->\n</script>\n"; } } } $count++; if ($count>count($codeids)-1) {$count=0;} } fixorder($lid); } else { $labelsoutput.= "<script type=\"text/javascript\">\n<!--\n alert(\"".$clang->gT("Can't update labels because you are using duplicated codes","js")."\")\n //-->\n</script>\n"; } break; // Pressing the Up button case $clang->gT("Up", "unescaped"): $newsortorder=$postsortorder-1; $oldsortorder=$postsortorder; $cdquery = "UPDATE ".db_table_name('labels')." SET sortorder=-1 WHERE lid=$lid AND sortorder=$newsortorder"; $cdresult=$connect->Execute($cdquery) or safe_die($connect->ErrorMsg()); $cdquery = "UPDATE ".db_table_name('labels')." SET sortorder=$newsortorder WHERE lid=$lid AND sortorder=$oldsortorder"; $cdresult=$connect->Execute($cdquery) or safe_die($connect->ErrorMsg()); $cdquery = "UPDATE ".db_table_name('labels')." SET sortorder='$oldsortorder' WHERE lid=$lid AND sortorder=-1"; $cdresult=$connect->Execute($cdquery) or safe_die($connect->ErrorMsg()); break; // Pressing the Down button case $clang->gT("Dn", "unescaped"): $newsortorder=$postsortorder+1; $oldsortorder=$postsortorder; $cdquery = "UPDATE ".db_table_name('labels')." SET sortorder=-1 WHERE lid=$lid AND sortorder='$newsortorder'"; $cdresult=$connect->Execute($cdquery) or safe_die($connect->ErrorMsg()); $cdquery = "UPDATE ".db_table_name('labels')." SET sortorder='$newsortorder' WHERE lid=$lid AND sortorder=$oldsortorder"; $cdresult=$connect->Execute($cdquery) or safe_die($connect->ErrorMsg()); $cdquery = "UPDATE ".db_table_name('labels')." SET sortorder=$oldsortorder WHERE lid=$lid AND sortorder=-1"; $cdresult=$connect->Execute($cdquery) or safe_die($connect->ErrorMsg()); break; // Delete Button case $clang->gT("Del", "unescaped"): $query = "DELETE FROM ".db_table_name('labels')." WHERE lid=$lid AND sortorder='{$postsortorder}'"; if (!$result = $connect->Execute($query)) { $labelsoutput.= "<script type=\"text/javascript\">\n<!--\n alert(\"".$clang->gT("Failed to delete label","js")." - ".$query." - ".$connect->ErrorMsg()."\")\n //-->\n</script>\n"; } fixorder($lid); break; } }
function updateset($lid) { global $dbprefix, $connect, $labelsoutput, $databasetype; // Get added and deleted languagesid arrays if (isset($_POST['languageids'])) { $postlanguageids = sanitize_languagecodeS($_POST['languageids']); } if (isset($_POST['label_name'])) { $postlabel_name = sanitize_labelname($_POST['label_name']); } $newlanidarray = explode(" ", trim($postlanguageids)); $postlanguageids = db_quoteall($postlanguageids, true); $postlabel_name = db_quoteall($postlabel_name, true); $oldlangidsarray = array(); $query = "SELECT languages FROM " . db_table_name('labelsets') . " WHERE lid=" . $lid; $result = db_execute_assoc($query); if ($result) { while ($row = $result->FetchRow()) { $oldlangids = $row['languages']; } $oldlangidsarray = explode(" ", trim($oldlangids)); } $addlangidsarray = array_diff($newlanidarray, $oldlangidsarray); $dellangidsarray = array_diff($oldlangidsarray, $newlanidarray); // If new languages are added, create labels' codes and sortorder for the new languages $query = "SELECT code,sortorder,assessment_value FROM " . db_table_name('labels') . " WHERE lid=" . $lid . " GROUP BY code,sortorder,assessment_value"; $result = db_execute_assoc($query); if ($result) { while ($row = $result->FetchRow()) { $oldcodesarray[$row['code']] = array('sortorder' => $row['sortorder'], 'assessment_value' => $row['assessment_value']); } } if (isset($oldcodesarray) && count($oldcodesarray) > 0) { foreach ($addlangidsarray as $addedlangid) { foreach ($oldcodesarray as $oldcode => $olddata) { $sqlvalues[] = " ({$lid}, '{$oldcode}', '{$olddata['sortorder']}', '{$addedlangid}', '{$olddata['assessment_value']}' )"; } } } if (isset($sqlvalues)) { db_switchIDInsert('labels', true); foreach ($sqlvalues as $sqlline) { $query = "INSERT INTO " . db_table_name('labels') . " (lid,code,sortorder,language,assessment_value) VALUES " . $sqlline; $result = db_execute_assoc($query); if (!$result) { $labelsoutput .= "<script type=\"text/javascript\">\n<!--\n alert(\"" . $clang->gT("Failed to Copy already defined labels to added languages", "js") . " - " . $query . " - " . $connect->ErrorMsg() . "\")\n //-->\n</script>\n"; } } db_switchIDInsert('labels', false); } // If languages are removed, delete labels for these languages $sqlwherelang = ''; foreach ($dellangidsarray as $dellangid) { $sqlwherelang .= " OR language='" . $dellangid . "'"; } if ($sqlwherelang) { $query = "DELETE FROM " . db_table_name('labels') . " WHERE lid={$lid} AND (" . trim($sqlwherelang, ' OR') . ")"; $result = db_execute_assoc($query); if (!$result) { $labelsoutput .= "<script type=\"text/javascript\">\n<!--\n alert(\"" . $clang->gT("Failed to delete labels for removed languages", "js") . " - " . $query . " - " . $connect->ErrorMsg() . "\")\n //-->\n</script>\n"; } } // Update the label set itself $query = "UPDATE " . db_table_name('labelsets') . " SET label_name={$postlabel_name}, languages={$postlanguageids} WHERE lid={$lid}"; if (!($result = $connect->Execute($query))) { $labelsoutput .= "<script type=\"text/javascript\">\n<!--\n alert(\"" . $clang->gT("Update of Label Set failed", "js") . " - " . $query . " - " . $connect->ErrorMsg() . "\")\n //-->\n</script>\n"; } }
if (isset($oldcodes[$scale_id][$position]) && $codes[$scale_id][$position] !== $oldcodes[$scale_id][$position]) { $query = 'UPDATE ' . db_table_name('conditions') . ' SET cfieldname="+' . $surveyid . 'X' . $gid . 'X' . $qid . db_quote($codes[$scale_id][$position]) . '" WHERE cqid=' . $qid . ' AND cfieldname="+' . $surveyid . 'X' . $gid . 'X' . $qid . db_quote($oldcodes[$scale_id][$position]) . '"'; $connect->execute($query); $query = 'UPDATE ' . db_table_name('conditions') . ' SET value="' . db_quote($codes[$scale_id][$position]) . '" WHERE cqid=' . $qid . ' AND cfieldname="' . $surveyid . 'X' . $gid . 'X' . $qid . '" AND value="' . $oldcodes[$scale_id][$position] . '"'; $connect->execute($query); } } else { if (!isset($insertqid[$scale_id][$position])) { $query = 'INSERT into ' . db_table_name('questions') . ' (sid, gid, question_order, title, question, parent_qid, language, scale_id) values (' . $surveyid . ',' . $gid . ',' . ($position + 1) . ',' . db_quoteall($codes[$scale_id][$position]) . ',' . db_quoteall($subquestionvalue) . ',' . $qid . ',' . db_quoteall($language) . ',' . $scale_id . ')'; $connect->execute($query); $insertqid[$scale_id][$position] = $connect->Insert_Id(db_table_name_nq('questions'), "qid"); } else { db_switchIDInsert('questions', true); $query = 'INSERT into ' . db_table_name('questions') . ' (qid, sid, gid, question_order, title, question, parent_qid, language, scale_id) values (' . $insertqid[$scale_id][$position] . ',' . $surveyid . ',' . $gid . ',' . ($position + 1) . ',' . db_quoteall($codes[$scale_id][$position]) . ',' . db_quoteall($subquestionvalue) . ',' . $qid . ',' . db_quoteall($language) . ',' . $scale_id . ')'; $connect->execute($query); db_switchIDInsert('questions', false); } } $position++; } } } LimeExpressionManager::UpgradeConditionsToRelevance($surveyid); //include("surveytable_functions.php"); //surveyFixColumns($surveyid); $_SESSION['flashmessage'] = $clang->gT("Subquestions were successfully saved."); $action = 'editsubquestions'; } elseif (($action == "updatesurveysettingsandeditlocalesettings" || $action == "updatesurveysettings") && bHasSurveyPermission($surveyid, 'surveysettings', 'update')) { $formatdata = getDateFormatData($_SESSION['dateformat']); if (trim($_POST['expires']) == "") { $_POST['expires'] = null;
/** * function to import surveys, based on new importsurvey.php 6979 2009-05-30 11:59:03Z c_schmitz $ * * @param unknown_type $iVid * @param unknown_type $sVtit * @param unknown_type $sVbes * @return boolean */ function importSurvey($iVid, $sVtit, $sVbes, $sVwel, $sUbes, $sVtyp) { global $connect; global $dbprefix; global $clang; include "lsrc.config.php"; $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC; $this->debugLsrc("wir sind in " . __FUNCTION__ . " Line " . __LINE__ . ", OK "); // HINT FOR IMPORTERS: go to Line 714 to manipulate the Survey, while it's imported $the_full_file_path = $coreDir . $sVtyp . ".csv"; $this->debugLsrc("wir sind in " . __FUNCTION__ . " Line " . __LINE__ . ",the_full_file_path ='{$the_full_file_path}' OK "); //$_SERVER['SERVER_NAME'] = ""; // just to avoid notices //$_SERVER['SERVER_SOFTWARE'] = ""; // just to avoid notices //require_once(dirname(__FILE__).'/../config-defaults.php'); //require_once(dirname(__FILE__).'/../common.php'); $handle = fopen($the_full_file_path, "r"); while (!feof($handle)) { //To allow for very long survey lines (up to 64k) $buffer = fgets($handle, 56550); $bigarray[] = $buffer; } fclose($handle); // foreach($bigarray as $ba) // $this->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", OK ".$ba); if (isset($bigarray[0])) { $bigarray[0] = $this->removeBOM($bigarray[0]); } // Now we try to determine the dataformat of the survey file. if (isset($bigarray[1]) && isset($bigarray[4]) && substr($bigarray[1], 0, 22) == "# SURVEYOR SURVEY DUMP" && substr($bigarray[4], 0, 29) == "# http://www.phpsurveyor.org/") { $importversion = 100; // version 1.0 file } elseif (isset($bigarray[1]) && isset($bigarray[4]) && substr($bigarray[1], 0, 22) == "# SURVEYOR SURVEY DUMP" && substr($bigarray[4], 0, 37) == "# http://phpsurveyor.sourceforge.net/") { $importversion = 99; // Version 0.99 file or older - carries a different URL } elseif (substr($bigarray[0], 0, 24) == "# LimeSurvey Survey Dump" || substr($bigarray[0], 0, 25) == "# PHPSurveyor Survey Dump") { // Wow.. this seems to be a >1.0 version file - these files carry the version information to read in line two $importversion = substr($bigarray[1], 12, 3); } else { if ($importingfrom == "http") { // $importsurvey .= "<strong><font color='red'>".("Error")."</font></strong>\n"; // $importsurvey .= ("This file is not a LimeSurvey survey file. Import failed.")."\n"; // $importsurvey .= "</font></td></tr></table>\n"; // $importsurvey .= "</body>\n</html>\n"; //unlink($the_full_file_path); return false; } else { //echo ("This file is not a LimeSurvey survey file. Import failed.")."\n"; return false; } } // okay.. now lets drop the first 9 lines and get to the data // This works for all versions for ($i = 0; $i < 9; $i++) { unset($bigarray[$i]); } $bigarray = array_values($bigarray); //$this->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", OK ".print_r($bigarray)); //SURVEYS if (array_search("# GROUPS TABLE\n", $bigarray)) { $stoppoint = array_search("# GROUPS TABLE\n", $bigarray); } elseif (array_search("# GROUPS TABLE\r\n", $bigarray)) { $stoppoint = array_search("# GROUPS TABLE\r\n", $bigarray); } for ($i = 0; $i <= $stoppoint + 1; $i++) { if ($i < $stoppoint - 2) { $surveyarray[] = $bigarray[$i]; } unset($bigarray[$i]); } $bigarray = array_values($bigarray); //GROUPS if (array_search("# QUESTIONS TABLE\n", $bigarray)) { $stoppoint = array_search("# QUESTIONS TABLE\n", $bigarray); } elseif (array_search("# QUESTIONS TABLE\r\n", $bigarray)) { $stoppoint = array_search("# QUESTIONS TABLE\r\n", $bigarray); } else { $stoppoint = count($bigarray) - 1; } for ($i = 0; $i <= $stoppoint + 1; $i++) { if ($i < $stoppoint - 2) { $grouparray[] = $bigarray[$i]; } unset($bigarray[$i]); } $bigarray = array_values($bigarray); //QUESTIONS if (array_search("# ANSWERS TABLE\n", $bigarray)) { $stoppoint = array_search("# ANSWERS TABLE\n", $bigarray); } elseif (array_search("# ANSWERS TABLE\r\n", $bigarray)) { $stoppoint = array_search("# ANSWERS TABLE\r\n", $bigarray); } else { $stoppoint = count($bigarray) - 1; } for ($i = 0; $i <= $stoppoint + 1; $i++) { if ($i < $stoppoint - 2) { $questionarray[] = $bigarray[$i]; } unset($bigarray[$i]); } $bigarray = array_values($bigarray); //ANSWERS if (array_search("# CONDITIONS TABLE\n", $bigarray)) { $stoppoint = array_search("# CONDITIONS TABLE\n", $bigarray); } elseif (array_search("# CONDITIONS TABLE\r\n", $bigarray)) { $stoppoint = array_search("# CONDITIONS TABLE\r\n", $bigarray); } else { $stoppoint = count($bigarray) - 1; } for ($i = 0; $i <= $stoppoint + 1; $i++) { if ($i < $stoppoint - 2) { $answerarray[] = str_replace("`default`", "`default_value`", $bigarray[$i]); } unset($bigarray[$i]); } $bigarray = array_values($bigarray); //CONDITIONS if (array_search("# LABELSETS TABLE\n", $bigarray)) { $stoppoint = array_search("# LABELSETS TABLE\n", $bigarray); } elseif (array_search("# LABELSETS TABLE\r\n", $bigarray)) { $stoppoint = array_search("# LABELSETS TABLE\r\n", $bigarray); } else { //There is no labelsets information, so presumably this is a pre-0.98rc3 survey. $stoppoint = count($bigarray); } for ($i = 0; $i <= $stoppoint + 1; $i++) { if ($i < $stoppoint - 2) { $conditionsarray[] = $bigarray[$i]; } unset($bigarray[$i]); } $bigarray = array_values($bigarray); //LABELSETS if (array_search("# LABELS TABLE\n", $bigarray)) { $stoppoint = array_search("# LABELS TABLE\n", $bigarray); } elseif (array_search("# LABELS TABLE\r\n", $bigarray)) { $stoppoint = array_search("# LABELS TABLE\r\n", $bigarray); } else { $stoppoint = count($bigarray) - 1; } for ($i = 0; $i <= $stoppoint + 1; $i++) { if ($i < $stoppoint - 2) { $labelsetsarray[] = $bigarray[$i]; } unset($bigarray[$i]); } $bigarray = array_values($bigarray); //LABELS if (array_search("# QUESTION_ATTRIBUTES TABLE\n", $bigarray)) { $stoppoint = array_search("# QUESTION_ATTRIBUTES TABLE\n", $bigarray); } elseif (array_search("# QUESTION_ATTRIBUTES TABLE\r\n", $bigarray)) { $stoppoint = array_search("# QUESTION_ATTRIBUTES TABLE\r\n", $bigarray); } else { $stoppoint = count($bigarray) - 1; } for ($i = 0; $i <= $stoppoint + 1; $i++) { if ($i < $stoppoint - 2) { $labelsarray[] = $bigarray[$i]; } unset($bigarray[$i]); } $bigarray = array_values($bigarray); //QUESTION_ATTRIBUTES if (array_search("# ASSESSMENTS TABLE\n", $bigarray)) { $stoppoint = array_search("# ASSESSMENTS TABLE\n", $bigarray); } elseif (array_search("# ASSESSMENTS TABLE\r\n", $bigarray)) { $stoppoint = array_search("# ASSESSMENTS TABLE\r\n", $bigarray); } else { $stoppoint = count($bigarray) - 1; } for ($i = 0; $i <= $stoppoint + 1; $i++) { if ($i < $stoppoint - 2) { $question_attributesarray[] = $bigarray[$i]; } unset($bigarray[$i]); } $bigarray = array_values($bigarray); //ASSESSMENTS if (array_search("# SURVEYS_LANGUAGESETTINGS TABLE\n", $bigarray)) { $stoppoint = array_search("# SURVEYS_LANGUAGESETTINGS TABLE\n", $bigarray); } elseif (array_search("# SURVEYS_LANGUAGESETTINGS TABLE\r\n", $bigarray)) { $stoppoint = array_search("# SURVEYS_LANGUAGESETTINGS TABLE\r\n", $bigarray); } else { $stoppoint = count($bigarray) - 1; } for ($i = 0; $i <= $stoppoint + 1; $i++) { // if ($i<$stoppoint-2 || $i==count($bigarray)-1) if ($i < $stoppoint - 2) { $assessmentsarray[] = $bigarray[$i]; } unset($bigarray[$i]); } $bigarray = array_values($bigarray); //LANGAUGE SETTINGS if (array_search("# QUOTA TABLE\n", $bigarray)) { $stoppoint = array_search("# QUOTA TABLE\n", $bigarray); } elseif (array_search("# QUOTA TABLE\r\n", $bigarray)) { $stoppoint = array_search("# QUOTA TABLE\r\n", $bigarray); } else { $stoppoint = count($bigarray) - 1; } for ($i = 0; $i <= $stoppoint + 1; $i++) { // if ($i<$stoppoint-2 || $i==count($bigarray)-1) //$bigarray[$i]= trim($bigarray[$i]); if (isset($bigarray[$i]) && trim($bigarray[$i]) != '') { if (strpos($bigarray[$i], "#") === 0) { unset($bigarray[$i]); unset($bigarray[$i + 1]); unset($bigarray[$i + 2]); break; } else { $surveylsarray[] = $bigarray[$i]; } } unset($bigarray[$i]); } $bigarray = array_values($bigarray); //QUOTA if (array_search("# QUOTA_MEMBERS TABLE\n", $bigarray)) { $stoppoint = array_search("# QUOTA_MEMBERS TABLE\n", $bigarray); } elseif (array_search("# QUOTA_MEMBERS TABLE\r\n", $bigarray)) { $stoppoint = array_search("# QUOTA_MEMBERS TABLE\r\n", $bigarray); } else { $stoppoint = count($bigarray) - 1; } for ($i = 0; $i <= $stoppoint + 1; $i++) { // if ($i<$stoppoint-2 || $i==count($bigarray)-1) if ($i < $stoppoint - 2) { $quotaarray[] = $bigarray[$i]; } unset($bigarray[$i]); } $bigarray = array_values($bigarray); //Survey Language Settings $stoppoint = count($bigarray) - 1; for ($i = 0; $i < $stoppoint - 1; $i++) { if ($i <= $stoppoint) { $quotamembersarray[] = $bigarray[$i]; } unset($bigarray[$i]); } $bigarray = array_values($bigarray); if (isset($surveyarray)) { $countsurveys = count($surveyarray); } else { $countsurveys = 0; } if (isset($surveylsarray)) { $countlanguages = count($surveylsarray) - 1; } else { $countlanguages = 1; } if (isset($grouparray)) { $countgroups = count($grouparray); } else { $countgroups = 0; } if (isset($questionarray)) { $countquestions = count($questionarray); } else { $countquestions = 0; } if (isset($answerarray)) { $countanswers = count($answerarray); } else { $countanswers = 0; } if (isset($conditionsarray)) { $countconditions = count($conditionsarray); } else { $countconditions = 0; } if (isset($labelsetsarray)) { $countlabelsets = count($labelsetsarray); } else { $countlabelsets = 0; } if (isset($question_attributesarray)) { $countquestion_attributes = count($question_attributesarray); } else { $countquestion_attributes = 0; } if (isset($assessmentsarray)) { $countassessments = count($assessmentsarray); } else { $countassessments = 0; } if (isset($quotaarray)) { $countquota = count($quotaarray); } else { $countquota = 0; } // CREATE SURVEY if ($countsurveys > 0) { $countsurveys--; } if ($countanswers > 0) { $countanswers = ($countanswers - 1) / $countlanguages; } if ($countgroups > 0) { $countgroups = ($countgroups - 1) / $countlanguages; } if ($countquestions > 0) { $countquestions = ($countquestions - 1) / $countlanguages; } if ($countassessments > 0) { $countassessments--; } if ($countconditions > 0) { $countconditions--; } if ($countlabelsets > 0) { $countlabelsets--; } if ($countquestion_attributes > 0) { $countquestion_attributes--; } if ($countquota > 0) { $countquota--; } $sfieldorders = convertCSVRowToArray($surveyarray[0], ',', '"'); $sfieldcontents = convertCSVRowToArray($surveyarray[1], ',', '"'); $surveyrowdata = array_combine($sfieldorders, $sfieldcontents); $surveyid = $surveyrowdata["sid"]; if (!$surveyid) { if ($importingfrom == "http") { // $importsurvey .= "<strong><font color='red'>".("Error")."</strong></font>\n"; // $importsurvey .= ("Import of this survey file failed")."\n"; // $importsurvey .= ("File does not contain LimeSurvey data in the correct format.")."\n"; //Couldn't find the SID - cannot continue // $importsurvey .= "</font></td></tr></table>\n"; // $importsurvey .= "</body>\n</html>\n"; // unlink($the_full_file_path); //Delete the uploaded file return false; } else { //echo ("Import of this survey file failed")."\n".("File does not contain LimeSurvey data in the correct format.")."\n"; return false; } } // Use the existing surveyid if it does not already exists // This allows the URL links to the survey to keep working because the sid did not change $newsid = $iVid; //XXX Changed from $surveyid --> $iVid $isquery = "SELECT sid FROM {$dbprefix}surveys WHERE sid={$newsid}"; $isresult = db_execute_assoc($isquery); if ($isresult->RecordCount() > 0) { // Get new random ids until one is found that is not used do { $newsid = getRandomID(); $isquery = "SELECT sid FROM {$dbprefix}surveys WHERE sid={$newsid}"; $isresult = db_execute_assoc($isquery); } while ($isresult->RecordCount() > 0); } $insert = $surveyarray[0]; $sfieldorders = convertCSVRowToArray($surveyarray[0], ',', '"'); $sfieldcontents = convertCSVRowToArray($surveyarray[1], ',', '"'); $surveyrowdata = array_combine($sfieldorders, $sfieldcontents); // Set new owner ID $surveyrowdata['owner_id'] = $_SESSION['loginID']; // Set new survey ID $surveyrowdata['sid'] = $newsid; $surveyrowdata['active'] = 'N'; if ($importversion <= 100) { $oldlanguage = $surveyrowdata['language']; $newlanguage = 'en'; //Default switch ($oldlanguage) { case "bulgarian": $newlanguage = 'bg'; break; case "chinese-simplified": $newlanguage = 'zh-Hans'; break; case "chinese-traditional": $newlanguage = 'zh-Hant-HK'; break; case "croatian": $newlanguage = 'hr'; break; case "danish": $newlanguage = 'da'; break; case "dutch": $newlanguage = 'nl'; break; case "english": $newlanguage = 'en'; break; case "french": $newlanguage = 'fr'; break; case "german-informal": $newlanguage = 'de-informal'; break; case "german": $newlanguage = 'de'; break; case "greek": $newlanguage = 'el'; break; case "hungarian": $newlanguage = 'hu'; break; case "italian": $newlanguage = 'it'; break; case "japanese": $newlanguage = 'ja'; break; case "lithuanian": $newlanguage = 'lt'; break; case "norwegian": $newlanguage = 'nb'; break; case "portuguese": $newlanguage = 'pt'; break; case "romanian": $newlanguage = 'ro'; break; case "russian": $newlanguage = 'ru'; break; case "slovenian": $newlanguage = 'sl'; break; case "spanish": $newlanguage = 'es'; break; case "swedish": $newlanguage = 'sv'; break; } $surveyrowdata['language'] = $newlanguage; // copy the survey row data // now prepare the languagesettings table and drop according values from the survey array $surveylsrowdata = array(); $surveylsrowdata['surveyls_survey_id'] = $newsid; $surveylsrowdata['surveyls_language'] = $newlanguage; $surveylsrowdata['surveyls_title'] = $surveyrowdata['short_title']; $surveylsrowdata['surveyls_description'] = $surveyrowdata['description']; $surveylsrowdata['surveyls_welcometext'] = $surveyrowdata['welcome']; $surveylsrowdata['surveyls_urldescription'] = $surveyrowdata['urldescrip']; $surveylsrowdata['surveyls_email_invite_subj'] = $surveyrowdata['email_invite_subj']; $surveylsrowdata['surveyls_email_invite'] = $surveyrowdata['email_invite']; $surveylsrowdata['surveyls_email_remind_subj'] = $surveyrowdata['email_remind_subj']; $surveylsrowdata['surveyls_email_remind'] = $surveyrowdata['email_remind']; $surveylsrowdata['surveyls_email_register_subj'] = $surveyrowdata['email_register_subj']; $surveylsrowdata['surveyls_email_register'] = $surveyrowdata['email_register']; $surveylsrowdata['surveyls_email_confirm_subj'] = $surveyrowdata['email_confirm_subj']; $surveylsrowdata['surveyls_email_confirm'] = $surveyrowdata['email_confirm']; unset($surveyrowdata['short_title']); unset($surveyrowdata['description']); unset($surveyrowdata['welcome']); unset($surveyrowdata['urldescrip']); unset($surveyrowdata['email_invite_subj']); unset($surveyrowdata['email_invite']); unset($surveyrowdata['email_remind_subj']); unset($surveyrowdata['email_remind']); unset($surveyrowdata['email_register_subj']); unset($surveyrowdata['email_register']); unset($surveyrowdata['email_confirm_subj']); unset($surveyrowdata['email_confirm']); // translate internal links $surveylsrowdata['surveyls_title'] = translink('survey', $surveyid, $newsid, $surveylsrowdata['surveyls_title']); $surveylsrowdata['surveyls_description'] = translink('survey', $surveyid, $newsid, $surveylsrowdata['surveyls_description']); $surveylsrowdata['surveyls_welcometext'] = translink('survey', $surveyid, $newsid, $surveylsrowdata['surveyls_welcometext']); $surveylsrowdata['surveyls_urldescription'] = translink('survey', $surveyid, $newsid, $surveylsrowdata['surveyls_urldescription']); $surveylsrowdata['surveyls_email_invite'] = translink('survey', $surveyid, $newsid, $surveylsrowdata['surveyls_email_invite']); $surveylsrowdata['surveyls_email_remind'] = translink('survey', $surveyid, $newsid, $surveylsrowdata['surveyls_email_remind']); $surveylsrowdata['surveyls_email_register'] = translink('survey', $surveyid, $newsid, $surveylsrowdata['surveyls_email_register']); $surveylsrowdata['surveyls_email_confirm'] = translink('survey', $surveyid, $newsid, $surveylsrowdata['surveyls_email_confirm']); // import the survey language-specific settings $values = array_values($surveylsrowdata); $values = array_map(array(&$connect, "qstr"), $values); // quote everything accordingly $insert = "insert INTO {$dbprefix}surveys_languagesettings (" . implode(',', array_keys($surveylsrowdata)) . ") VALUES (" . implode(',', $values) . ")"; //handle db prefix try { $iresult = $connect->Execute($insert) or $this->debugLsrc("" . "Import of this survey file failed" . "\n[{$insert}]{$surveyarray[0]}\n" . $connect->ErrorMsg()); } catch (exception $e) { throw new SoapFault("Server: ", "{$e} : {$connect->ErrorMsg}()"); exit; } } if (isset($surveyrowdata['datecreated'])) { $surveyrowdata['datecreated'] = $connect->BindTimeStamp($surveyrowdata['datecreated']); } unset($surveyrowdata['expires']); unset($surveyrowdata['attribute1']); unset($surveyrowdata['attribute2']); unset($surveyrowdata['usestartdate']); unset($surveyrowdata['useexpiry']); unset($surveyrowdata['url']); if (isset($surveyrowdata['startdate'])) { unset($surveyrowdata['startdate']); } $surveyrowdata['bounce_email'] = $surveyrowdata['adminemail']; 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)); } $values = array_values($surveyrowdata); $values = array_map(array(&$connect, "qstr"), $values); // quote everything accordingly $insert = "INSERT INTO {$dbprefix}surveys (" . implode(',', array_keys($surveyrowdata)) . ") VALUES (" . implode(',', $values) . ")"; //handle db prefix try { $iresult = $connect->Execute($insert) or $this->debugLsrc("" . "Import of this survey file failed on Line: " . __LINE__ . "\n[{$insert}]{$surveyarray[0]}\n" . $connect->ErrorMsg()) and exit; } catch (exception $e) { throw new SoapFault("Server: ", "{$e} : {$connect->ErrorMsg}()"); exit; } $oldsid = $surveyid; // Now import the survey language settings if ($importversion >= 111) { $fieldorders = convertCSVRowToArray($surveylsarray[0], ',', '"'); unset($surveylsarray[0]); foreach ($surveylsarray as $slsrow) { $fieldcontents = convertCSVRowToArray($slsrow, ',', '"'); $surveylsrowdata = array_combine($fieldorders, $fieldcontents); // convert back the '\'.'n' cahr from the CSV file to true return char "\n" $surveylsrowdata = array_map('convertCsvreturn2return', $surveylsrowdata); // Convert the \n return char from welcometext to // XXX Change values while Importing here //done by rakete $surveylsrowdata['surveyls_title'] = $sVtit; $surveylsrowdata['surveyls_description'] = $sVbes; $surveylsrowdata['surveyls_welcometext'] = $sVwel; $surveylsrowdata['surveyls_urldescription'] = $sUbes; // translate internal links $surveylsrowdata['surveyls_title'] = translink('survey', $surveyid, $newsid, $surveylsrowdata['surveyls_title']); $surveylsrowdata['surveyls_description'] = translink('survey', $surveyid, $newsid, $surveylsrowdata['surveyls_description']); $surveylsrowdata['surveyls_welcometext'] = translink('survey', $surveyid, $newsid, $surveylsrowdata['surveyls_welcometext']); $surveylsrowdata['surveyls_urldescription'] = translink('survey', $surveyid, $newsid, $surveylsrowdata['surveyls_urldescription']); $surveylsrowdata['surveyls_email_invite'] = translink('survey', $surveyid, $newsid, $surveylsrowdata['surveyls_email_invite']); $surveylsrowdata['surveyls_email_remind'] = translink('survey', $surveyid, $newsid, $surveylsrowdata['surveyls_email_remind']); $surveylsrowdata['surveyls_email_register'] = translink('survey', $surveyid, $newsid, $surveylsrowdata['surveyls_email_register']); $surveylsrowdata['surveyls_email_confirm'] = translink('survey', $surveyid, $newsid, $surveylsrowdata['surveyls_email_confirm']); $surveylsrowdata['surveyls_survey_id'] = $newsid; $newvalues = array_values($surveylsrowdata); $newvalues = array_map(array(&$connect, "qstr"), $newvalues); // quote everything accordingly $lsainsert = "INSERT INTO {$dbprefix}surveys_languagesettings (" . implode(',', array_keys($surveylsrowdata)) . ") VALUES (" . implode(',', $newvalues) . ")"; //handle db prefix $lsiresult = $connect->Execute($lsainsert) or $this->debugLsrc("Import of this survey file failed on Line " . __LINE__ . "") and exit; } } // DO SURVEY_RIGHTS $isrquery = "INSERT INTO {$dbprefix}surveys_rights VALUES({$newsid}," . $_SESSION['loginID'] . ",1,1,1,1,1,1)"; @($isrresult = $connect->Execute($isrquery)); $deniedcountlabelsets = 0; //DO ANY LABELSETS FIRST, SO WE CAN KNOW WHAT THEIR NEW LID IS FOR THE QUESTIONS if (isset($labelsetsarray) && $labelsetsarray) { $csarray = buildLabelSetCheckSumArray(); // build checksums over all existing labelsets $count = 0; foreach ($labelsetsarray as $lsa) { $fieldorders = convertCSVRowToArray($labelsetsarray[0], ',', '"'); $fieldcontents = convertCSVRowToArray($lsa, ',', '"'); if ($count == 0) { $count++; continue; } $labelsetrowdata = array_combine($fieldorders, $fieldcontents); // Save old labelid $oldlid = $labelsetrowdata['lid']; // set the new language if ($importversion <= 100) { $labelsetrowdata['languages'] = $newlanguage; } unset($labelsetrowdata['lid']); $newvalues = array_values($labelsetrowdata); $newvalues = array_map(array(&$connect, "qstr"), $newvalues); // quote everything accordingly $lsainsert = "insert INTO {$dbprefix}labelsets (" . implode(',', array_keys($labelsetrowdata)) . ") VALUES (" . implode(',', $newvalues) . ")"; //handle db prefix $lsiresult = $connect->Execute($lsainsert); // Get the new insert id for the labels inside this labelset $newlid = $connect->Insert_ID("{$dbprefix}labelsets", "lid"); // $importsurvey .= "OLDLID: $oldlid NEWLID: $newlid"; // For debugging label import if ($labelsarray) { $count = 0; foreach ($labelsarray as $la) { if ($importversion >= 111) { $lfieldorders = convertCSVRowToArray($labelsarray[0], ',', '"'); } $lfieldcontents = convertCSVRowToArray($la, ',', '"'); if ($count == 0) { $count++; continue; } // Combine into one array with keys and values since its easier to handle $labelrowdata = array_combine($lfieldorders, $lfieldcontents); if ($importversion <= 132) { $labelrowdata["assessment_value"] = (int) $labelrowdata["code"]; } $labellid = $labelrowdata['lid']; if ($importversion <= 100) { $labelrowdata['language'] = $newlanguage; } if ($labellid == $oldlid) { $labelrowdata['lid'] = $newlid; // translate internal links $labelrowdata['title'] = translink('label', $oldlid, $newlid, $labelrowdata['title']); $newvalues = array_values($labelrowdata); $newvalues = array_map(array(&$connect, "qstr"), $newvalues); // quote everything accordingly $lainsert = "insert INTO {$dbprefix}labels (" . implode(',', array_keys($labelrowdata)) . ") VALUES (" . implode(',', $newvalues) . ")"; //handle db prefix $liresult = $connect->Execute($lainsert); } } } //CHECK FOR DUPLICATE LABELSETS $thisset = ""; $query2 = "SELECT code, title, sortorder, language\r\n\t\t FROM {$dbprefix}labels\r\n\t\t WHERE lid=" . $newlid . "\r\n\t\t ORDER BY language, sortorder, code"; $result2 = db_execute_num($query2) or $this->debugLsrc("Import of this survey file failed on Line " . __LINE__ . "| " . $connect->ErrorMsg()); while ($row2 = $result2->FetchRow()) { $thisset .= implode('.', $row2); } // while $newcs = dechex(crc32($thisset) * 1); unset($lsmatch); if (isset($csarray)) { foreach ($csarray as $key => $val) { if ($val == $newcs) { $lsmatch = $key; } } } if (isset($lsmatch) || $_SESSION['USER_RIGHT_MANAGE_LABEL'] != 1) { //There is a matching labelset or the user is not allowed to edit labels - // So, we will delete this one and refer to the matched one. $query = "DELETE FROM {$dbprefix}labels WHERE lid={$newlid}"; $result = $connect->Execute($query) or $this->debugLsrc("Import of this survey file failed on Line " . __LINE__ . "| " . $connect->ErrorMsg()); $query = "DELETE FROM {$dbprefix}labelsets WHERE lid={$newlid}"; $result = $connect->Execute($query) or $this->debugLsrc("Import of this survey file failed on Line " . __LINE__ . "| " . $connect->ErrorMsg()); if (isset($lsmatch)) { $newlid = $lsmatch; } else { ++$deniedcountlabelsets; --$countlabelsets; } } else { //There isn't a matching labelset, add this checksum to the $csarray array $csarray[$newlid] = $newcs; } //END CHECK FOR DUPLICATES $labelreplacements[] = array($oldlid, $newlid); } } $this->debugLsrc("wir sind in " . __FUNCTION__ . " Line " . __LINE__ . ", OK "); $importwarning = ""; // used to save the warnings while processing questions $qtypes = $this->getqtypelist("", "array"); foreach ($qtypes as $type) { //XXX FIXME $this->debugLsrc("wir sind in " . __FUNCTION__ . " Line " . __LINE__ . ", OK " . $type); } // DO GROUPS, QUESTIONS FOR GROUPS, THEN ANSWERS FOR QUESTIONS IN A NESTED FORMAT! if (isset($grouparray) && $grouparray) { $count = 0; $currentgid = ''; foreach ($grouparray as $ga) { $gafieldorders = convertCSVRowToArray($grouparray[0], ',', '"'); $gacfieldcontents = convertCSVRowToArray($ga, ',', '"'); if ($count == 0) { $count++; continue; } $grouprowdata = array_combine($gafieldorders, $gacfieldcontents); // remember group id if ($currentgid == '' || $currentgid != $grouprowdata['gid']) { $currentgid = $grouprowdata['gid']; $newgroup = true; } else { if ($currentgid == $grouprowdata['gid']) { $newgroup = false; } } $gid = $grouprowdata['gid']; $gsid = $grouprowdata['sid']; //Now an additional integrity check if there are any groups not belonging into this survey if ($gsid != $surveyid) { if ($importingfrom == "http") { // $importsurvey .= "\n<font color='red'><strong>".("Error")."</strong></font>" // ."\n".("A group in the CSV/SQL file is not part of the same survey. The import of the survey was stopped.")."\n"; } else { //echo ("Error").": A group in the CSV/SQL file is not part of the same Survey. The import of the survey was stopped.\n"; } return false; } $this->debugLsrc("wir sind in " . __FUNCTION__ . " Line " . __LINE__ . ", OK "); //remove the old group id if ($newgroup) { unset($grouprowdata['gid']); } else { $grouprowdata['gid'] = $newgid; } //replace old surveyid by new surveyid $grouprowdata['sid'] = $newsid; // Version <=100 dont have a language field yet so we set it now if ($importversion <= 100) { $grouprowdata['language'] = $newlanguage; } $oldgid = $gid; // save it for later $grouprowdata = array_map('convertCsvreturn2return', $grouprowdata); // translate internal links $grouprowdata['group_name'] = translink('survey', $surveyid, $newsid, $grouprowdata['group_name']); $grouprowdata['description'] = translink('survey', $surveyid, $newsid, $grouprowdata['description']); $newvalues = array_values($grouprowdata); $newvalues = array_map(array(&$connect, "qstr"), $newvalues); // quote everything accordingly db_switchIDInsert('groups', true); $ginsert = 'insert INTO ' . db_table_name('groups') . ' (' . implode(',', array_keys($grouprowdata)) . ') VALUES (' . implode(',', $newvalues) . ')'; $gres = $connect->Execute($ginsert) or $this->debugLsrc("Import of this survey file failed on Line " . __LINE__ . "| " . $connect->ErrorMsg()); db_switchIDInsert('groups', false); //GET NEW GID if ($newgroup) { $newgid = $connect->Insert_ID("{$dbprefix}groups", "gid"); } //NOW DO NESTED QUESTIONS FOR THIS GID //$this->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", OK ".var_dump($questionarray)); if (isset($questionarray) && $questionarray && $newgroup) { $count = 0; $currentqid = ''; foreach ($questionarray as $qa) { //$this->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", OK ".$qa); $qafieldorders = convertCSVRowToArray($questionarray[0], ',', '"'); $qacfieldcontents = convertCSVRowToArray($qa, ',', '"'); if ($count == 0) { $count++; continue; } $questionrowdata = array_combine($qafieldorders, $qacfieldcontents); $questionrowdata = array_map('convertCsvreturn2return', $questionrowdata); if ($currentqid == '' || $currentqid != $questionrowdata['qid']) { $currentqid = $questionrowdata['qid']; $newquestion = true; } else { if ($currentqid == $questionrowdata['qid']) { $newquestion = false; } } if (!array_key_exists($questionrowdata["type"], $qtypes)) { $questionrowdata["type"] = strtoupper($questionrowdata["type"]); if (!array_key_exists($questionrowdata["type"], $qtypes)) { //$importwarning .= "<li>" . sprintf(("Question \"%s - %s\" was NOT imported because the question type is unknown."), $questionrowdata["title"], $questionrowdata["question"]) . "</li>"; $countquestions--; $this->debugLsrc("wir sind in " . __FUNCTION__ . " Line " . __LINE__ . ", OK " . $countquestions); continue; } else { //$importwarning .= "<li>" . sprintf(("Question \"%s - %s\" was imported but the type was set to '%s' because it is the most similiar one."), $questionrowdata["title"], $questionrowdata["question"], $qtypes[$questionrowdata["type"]]) . "</li>"; } } $this->debugLsrc("wir sind in " . __FUNCTION__ . " Line " . __LINE__ . ", OK "); $thisgid = $questionrowdata['gid']; $this->debugLsrc("wir sind in " . __FUNCTION__ . " Line " . __LINE__ . ", OK " . $thisgid . " == " . $gid); if ($thisgid == $gid) { $qid = $questionrowdata['qid']; // Remove qid field if ($newquestion) { unset($questionrowdata['qid']); } else { $questionrowdata['qid'] = $newqid; } $questionrowdata["sid"] = $newsid; $questionrowdata["gid"] = $newgid; // Version <=100 doesn't have a language field yet so we set it now if ($importversion <= 100) { $questionrowdata['language'] = $newlanguage; } $oldqid = $qid; if (!isset($questionrowdata["lid1"])) { $questionrowdata["lid1"] = 0; } // Now we will fix up the label id $type = $questionrowdata["type"]; //Get the type if ($type == "F" || $type == "H" || $type == "W" || $type == "Z" || $type == "1" || $type == ":" || $type == ";") { //IF this is a flexible label array, update the lid entry if (isset($labelreplacements)) { // We only replace once in each question label // otherwise could lead to double substitution // if a new lid collides with an older one $already_replaced_label = false; $already_replaced_label1 = false; foreach ($labelreplacements as $lrp) { if ($lrp[0] == $questionrowdata["lid"]) { if (!$already_replaced_label) { $questionrowdata["lid"] = $lrp[1]; $already_replaced_label = true; } } if ($lrp[0] == $questionrowdata["lid1"]) { if (!$already_replaced_label1) { $questionrowdata["lid1"] = $lrp[1]; $already_replaced_label1 = true; } } } } } if (!isset($questionrowdata["question_order"]) || $questionrowdata["question_order"] == '') { $questionrowdata["question_order"] = 0; } $other = $questionrowdata["other"]; //Get 'other' field value // translate internal links $questionrowdata['title'] = translink('survey', $surveyid, $newsid, $questionrowdata['title']); $questionrowdata['question'] = translink('survey', $surveyid, $newsid, $questionrowdata['question']); $questionrowdata['help'] = translink('survey', $surveyid, $newsid, $questionrowdata['help']); $newvalues = array_values($questionrowdata); db_switchIDInsert('questions', true); //foreach($questionrowdata as $qrd) //$this->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", OK ".$qrd); $newvalues = array_map(array(&$connect, "qstr"), $newvalues); // quote everything accordingly $qinsert = "insert INTO {$dbprefix}questions (" . implode(',', array_keys($questionrowdata)) . ") VALUES (" . implode(',', $newvalues) . ")"; $this->debugLsrc("wir sind in " . __FUNCTION__ . " Line " . __LINE__ . ", OK | " . $qinsert); $qres = $connect->Execute($qinsert) or $this->debugLsrc("Import of this survey file failed on Line " . __LINE__ . "| " . $connect->ErrorMsg()); db_switchIDInsert('questions', false); if ($newquestion) { $newqid = $connect->Insert_ID("{$dbprefix}questions", "qid"); } $newrank = 0; $substitutions[] = array($oldsid, $oldgid, $oldqid, $newsid, $newgid, $newqid); //$this->debugLsrc("HALLO?!:"); //NOW DO NESTED ANSWERS FOR THIS QID if (isset($answerarray) && $answerarray && $newquestion) { $count = 0; foreach ($answerarray as $aa) { $aafieldorders = convertCSVRowToArray($answerarray[0], ',', '"'); $aacfieldcontents = convertCSVRowToArray($aa, ',', '"'); if ($count == 0) { $count++; continue; } $answerrowdata = array_combine($aafieldorders, $aacfieldcontents); if ($importversion <= 132) { $answerrowdata["assessment_value"] = (int) $answerrowdata["code"]; } $code = $answerrowdata["code"]; $thisqid = $answerrowdata["qid"]; if ($thisqid == $qid) { $answerrowdata["qid"] = $newqid; // Version <=100 doesn't have a language field yet so we set it now if ($importversion <= 100) { $answerrowdata['language'] = $newlanguage; } // translate internal links $answerrowdata['answer'] = translink('survey', $surveyid, $newsid, $answerrowdata['answer']); $newvalues = array_values($answerrowdata); $newvalues = array_map(array(&$connect, "qstr"), $newvalues); // quote everything accordingly $ainsert = "insert INTO {$dbprefix}answers (" . implode(',', array_keys($answerrowdata)) . ") VALUES (" . implode(',', $newvalues) . ")"; $ares = $connect->Execute($ainsert) or $this->debugLsrc("Import of this survey file failed on Line " . __LINE__ . "| " . $connect->ErrorMsg()); if ($type == "M" || $type == "P") { $fieldnames[] = array("oldcfieldname" => $oldsid . "X" . $oldgid . "X" . $oldqid, "newcfieldname" => $newsid . "X" . $newgid . "X" . $newqid, "oldfieldname" => $oldsid . "X" . $oldgid . "X" . $oldqid . $code, "newfieldname" => $newsid . "X" . $newgid . "X" . $newqid . $code); if ($type == "P") { $fieldnames[] = array("oldcfieldname" => $oldsid . "X" . $oldgid . "X" . $oldqid . "comment", "newcfieldname" => $newsid . "X" . $newgid . "X" . $newqid . $code . "comment", "oldfieldname" => $oldsid . "X" . $oldgid . "X" . $oldqid . $code . "comment", "newfieldname" => $newsid . "X" . $newgid . "X" . $newqid . $code . "comment"); } } elseif ($type == "A" || $type == "B" || $type == "C" || $type == "F" || $type == "H" || $type == "E" || $type == "Q" || $type == "K" || $type == "1") { $fieldnames[] = array("oldcfieldname" => $oldsid . "X" . $oldgid . "X" . $oldqid . $code, "newcfieldname" => $newsid . "X" . $newgid . "X" . $newqid . $code, "oldfieldname" => $oldsid . "X" . $oldgid . "X" . $oldqid . $code, "newfieldname" => $newsid . "X" . $newgid . "X" . $newqid . $code); } elseif ($type == ":" || $type == ";") { // read all label codes from $questionrowdata["lid"] // for each one (as L) set SGQA_L $labelq = "SELECT DISTINCT code FROM {$dbprefix}labels WHERE lid=" . $questionrowdata["lid"]; $labelqresult = db_execute_num($labelq) or safe_die("Died querying labelset {$lid}<br />{$query2}<br />" . $connect->ErrorMsg()); while ($labelqrow = $labelqresult->FetchRow()) { $fieldnames[] = array("oldcfieldname" => $oldsid . "X" . $oldgid . "X" . $oldqid . $code . "_" . $labelqrow[0], "newcfieldname" => $newsid . "X" . $newgid . "X" . $newqid . $code . "_" . $labelqrow[0], "oldfieldname" => $oldsid . "X" . $oldgid . "X" . $oldqid . $code . "_" . $labelqrow[0], "newfieldname" => $newsid . "X" . $newgid . "X" . $newqid . $code . "_" . $labelqrow[0]); } } elseif ($type == "R") { $newrank++; } } } if (($type == "A" || $type == "B" || $type == "C" || $type == "M" || $type == "P" || $type == "L") && $other == "Y") { $fieldnames[] = array("oldcfieldname" => $oldsid . "X" . $oldgid . "X" . $oldqid . "other", "newcfieldname" => $newsid . "X" . $newgid . "X" . $newqid . "other", "oldfieldname" => $oldsid . "X" . $oldgid . "X" . $oldqid . "other", "newfieldname" => $newsid . "X" . $newgid . "X" . $newqid . "other"); if ($type == "P") { $fieldnames[] = array("oldcfieldname" => $oldsid . "X" . $oldgid . "X" . $oldqid . "othercomment", "newcfieldname" => $newsid . "X" . $newgid . "X" . $newqid . "othercomment", "oldfieldname" => $oldsid . "X" . $oldgid . "X" . $oldqid . "othercomment", "newfieldname" => $newsid . "X" . $newgid . "X" . $newqid . "othercomment"); } } if ($type == "R" && $newrank > 0) { for ($i = 1; $i <= $newrank; $i++) { $fieldnames[] = array("oldcfieldname" => $oldsid . "X" . $oldgid . "X" . $oldqid . $i, "newcfieldname" => $newsid . "X" . $newgid . "X" . $newqid . $i, "oldfieldname" => $oldsid . "X" . $oldgid . "X" . $oldqid . $i, "newfieldname" => $newsid . "X" . $newgid . "X" . $newqid . $i); } } if ($type != "A" && $type != "B" && $type != "C" && $type != "R" && $type != "M" && $type != "P") { $fieldnames[] = array("oldcfieldname" => $oldsid . "X" . $oldgid . "X" . $oldqid, "newcfieldname" => $newsid . "X" . $newgid . "X" . $newqid, "oldfieldname" => $oldsid . "X" . $oldgid . "X" . $oldqid, "newfieldname" => $newsid . "X" . $newgid . "X" . $newqid); if ($type == "O") { $fieldnames[] = array("oldcfieldname" => $oldsid . "X" . $oldgid . "X" . $oldqid . "comment", "newcfieldname" => $newsid . "X" . $newgid . "X" . $newqid . "comment", "oldfieldname" => $oldsid . "X" . $oldgid . "X" . $oldqid . "comment", "newfieldname" => $newsid . "X" . $newgid . "X" . $newqid . "comment"); } } } else { $fieldnames[] = array("oldcfieldname" => $oldsid . "X" . $oldgid . "X" . $oldqid, "newcfieldname" => $newsid . "X" . $newgid . "X" . $newqid, "oldfieldname" => $oldsid . "X" . $oldgid . "X" . $oldqid, "newfieldname" => $newsid . "X" . $newgid . "X" . $newqid); } } } } } } $this->debugLsrc("wir sind in " . __FUNCTION__ . " Line " . __LINE__ . ", OK "); // Fix sortorder of the groups - if users removed groups manually from the csv file there would be gaps fixSortOrderGroups($surveyid); $baselang = GetBaseLanguageFromSurveyID($iVid); $cdresult = db_execute_assoc("SELECT gid FROM " . db_table_name('groups') . " WHERE sid='{$surveyid}' AND language='{$baselang}' ORDER BY group_order, group_name"); $position = 0; while ($cdrow = $cdresult->FetchRow()) { $cd2query = "UPDATE " . db_table_name('groups') . " SET group_order='{$position}' WHERE gid='{$cdrow['gid']}' "; $cd2result = $connect->Execute($cd2query) or $this->debugLsrc("Import of this survey file failed on Line " . __LINE__ . "| " . $connect->ErrorMsg()); //Checked $position++; } $this->debugLsrc("wir sind in " . __FUNCTION__ . " Line " . __LINE__ . ", OK "); //... and for the questions inside the groups // get all group ids and fix questions inside each group $gquery = "SELECT gid FROM {$dbprefix}groups where sid={$newsid} group by gid ORDER BY gid"; //Get last question added (finds new qid) $gres = db_execute_assoc($gquery); while ($grow = $gres->FetchRow()) { //fixsortorderQuestions(0,$grow['gid']); //XXX changed: commented out // and fully written out: $qid = sanitize_int(0); $gid = sanitize_int($grow['gid']); $baselang = GetBaseLanguageFromSurveyID($iVid); if ($gid == 0) { $result = db_execute_assoc("SELECT gid FROM " . db_table_name('questions') . " WHERE qid='{$qid}' and language='{$baselang}'"); //Checked $row = $result->FetchRow(); $gid = $row['gid']; } $cdresult = db_execute_assoc("SELECT qid FROM " . db_table_name('questions') . " WHERE gid='{$gid}' and language='{$baselang}' ORDER BY question_order, title ASC"); //Checked $position = 0; while ($cdrow = $cdresult->FetchRow()) { $cd2query = "UPDATE " . db_table_name('questions') . " SET question_order='{$position}' WHERE qid='{$cdrow['qid']}' "; $cd2result = $connect->Execute($cd2query) or $this->debugLsrc("Import of this survey file failed on Line " . __LINE__ . "| " . $connect->ErrorMsg()); $position++; } } $this->debugLsrc("wir sind in " . __FUNCTION__ . " Line " . __LINE__ . ", OK "); //We've built two arrays along the way - one containing the old SID, GID and QIDs - and their NEW equivalents //and one containing the old 'extended fieldname' and its new equivalent. These are needed to import conditions and question_attributes. if (isset($question_attributesarray) && $question_attributesarray) { //ONLY DO THIS IF THERE ARE QUESTION_ATTRIBUES $count = 0; foreach ($question_attributesarray as $qar) { $fieldorders = convertCSVRowToArray($question_attributesarray[0], ',', '"'); $fieldcontents = convertCSVRowToArray($qar, ',', '"'); if ($count == 0) { $count++; continue; } $qarowdata = array_combine($fieldorders, $fieldcontents); $newqid = ""; $oldqid = $qarowdata['qid']; foreach ($substitutions as $subs) { if ($oldqid == $subs[2]) { $newqid = $subs[5]; } } $qarowdata["qid"] = $newqid; unset($qarowdata["qaid"]); $newvalues = array_values($qarowdata); $newvalues = array_map(array(&$connect, "qstr"), $newvalues); // quote everything accordingly $qainsert = "insert INTO {$dbprefix}question_attributes (" . implode(',', array_keys($qarowdata)) . ") VALUES (" . implode(',', $newvalues) . ")"; $result = $connect->Execute($qainsert) or $this->debugLsrc("Import of this survey file failed on Line " . __LINE__ . "| {$qainsert} |" . $connect->ErrorMsg()); } } if (isset($assessmentsarray) && $assessmentsarray) { //ONLY DO THIS IF THERE ARE QUESTION_ATTRIBUES $count = 0; foreach ($assessmentsarray as $qar) { $fieldorders = convertCSVRowToArray($assessmentsarray[0], ',', '"'); $fieldcontents = convertCSVRowToArray($qar, ',', '"'); if ($count == 0) { $count++; continue; } $asrowdata = array_combine($fieldorders, $fieldcontents); if (isset($asrowdata['link'])) { if (trim($asrowdata['link']) != '') { $asrowdata['message'] = $asrowdata['message'] . '<br /><a href="' . $asrowdata['link'] . '">' . $asrowdata['link'] . '</a>'; } unset($asrowdata['link']); } $oldsid = $asrowdata["sid"]; $oldgid = $asrowdata["gid"]; if ($oldgid > 0) { foreach ($substitutions as $subs) { if ($oldsid == $subs[0]) { $newsid = $subs[3]; } if ($oldgid == $subs[1]) { $newgid = $subs[4]; } } } else { $newgid = 0; } $asrowdata["sid"] = $newsid; $asrowdata["gid"] = $newgid; unset($asrowdata["id"]); $newvalues = array_values($asrowdata); $newvalues = array_map(array(&$connect, "qstr"), $newvalues); // quote everything accordingly $asinsert = "insert INTO {$dbprefix}assessments (" . implode(',', array_keys($asrowdata)) . ") VALUES (" . implode(',', $newvalues) . ")"; $result = $connect->Execute($asinsert) or $this->debugLsrc("Import of this survey file failed on Line " . __LINE__ . "| " . $connect->ErrorMsg()); unset($newgid); } } if (isset($quotaarray) && $quotaarray) { //ONLY DO THIS IF THERE ARE QUOTAS $count = 0; foreach ($quotaarray as $qar) { $fieldorders = convertCSVRowToArray($quotaarray[0], ',', '"'); $fieldcontents = convertCSVRowToArray($qar, ',', '"'); if ($count == 0) { $count++; continue; } $asrowdata = array_combine($fieldorders, $fieldcontents); $oldsid = $asrowdata["sid"]; foreach ($substitutions as $subs) { if ($oldsid == $subs[0]) { $newsid = $subs[3]; } } $asrowdata["sid"] = $newsid; $oldid = $asrowdata["id"]; unset($asrowdata["id"]); $newvalues = array_values($asrowdata); $newvalues = array_map(array(&$connect, "qstr"), $newvalues); // quote everything accordingly $asinsert = "insert INTO {$dbprefix}quota (" . implode(',', array_keys($asrowdata)) . ") VALUES (" . implode(',', $newvalues) . ")"; $result = $connect->Execute($asinsert) or $this->debugLsrc("Import of this survey file failed on Line " . __LINE__ . "| " . $connect->ErrorMsg()); $quotaids[] = array($oldid, $connect->Insert_ID(db_table_name_nq('quota'), "id")); } } if (isset($quotamembersarray) && $quotamembersarray) { //ONLY DO THIS IF THERE ARE QUOTAS $count = 0; foreach ($quotamembersarray as $qar) { $fieldorders = convertCSVRowToArray($quotamembersarray[0], ',', '"'); $fieldcontents = convertCSVRowToArray($qar, ',', '"'); if ($count == 0) { $count++; continue; } $asrowdata = array_combine($fieldorders, $fieldcontents); $oldsid = $asrowdata["sid"]; $newqid = ""; $newquotaid = ""; $oldqid = $asrowdata['qid']; $oldquotaid = $asrowdata['quota_id']; foreach ($substitutions as $subs) { if ($oldsid == $subs[0]) { $newsid = $subs[3]; } if ($oldqid == $subs[2]) { $newqid = $subs[5]; } } foreach ($quotaids as $quotaid) { if ($oldquotaid == $quotaid[0]) { $newquotaid = $quotaid[1]; } } $asrowdata["sid"] = $newsid; $asrowdata["qid"] = $newqid; $asrowdata["quota_id"] = $newquotaid; unset($asrowdata["id"]); $newvalues = array_values($asrowdata); $newvalues = array_map(array(&$connect, "qstr"), $newvalues); // quote everything accordingly $asinsert = "insert INTO {$dbprefix}quota_members (" . implode(',', array_keys($asrowdata)) . ") VALUES (" . implode(',', $newvalues) . ")"; $result = $connect->Execute($asinsert) or $this->debugLsrc("Import of this survey file failed on Line " . __LINE__ . "| " . $connect->ErrorMsg()); } } if (isset($conditionsarray) && $conditionsarray) { //ONLY DO THIS IF THERE ARE CONDITIONS! $count = '0'; foreach ($conditionsarray as $car) { $fieldorders = convertCSVRowToArray($conditionsarray[0], ',', '"'); $fieldcontents = convertCSVRowToArray($car, ',', '"'); if ($count == 0) { $count++; continue; } $conditionrowdata = array_combine($fieldorders, $fieldcontents); $oldcid = $conditionrowdata["cid"]; $oldqid = $conditionrowdata["qid"]; $oldcfieldname = $conditionrowdata["cfieldname"]; $oldcqid = $conditionrowdata["cqid"]; $thisvalue = $conditionrowdata["value"]; $newvalue = $thisvalue; foreach ($substitutions as $subs) { if ($oldqid == $subs[2]) { $newqid = $subs[5]; } if ($oldcqid == $subs[2]) { $newcqid = $subs[5]; } } if (ereg('^@([0-9]+)X([0-9]+)X([^@]+)@', $thisvalue, $targetcfieldname)) { foreach ($substitutions as $subs) { if ($targetcfieldname[1] == $subs[0]) { $targetcfieldname[1] = $subs[3]; } if ($targetcfieldname[2] == $subs[1]) { $targetcfieldname[2] = $subs[4]; } if ($targetcfieldname[3] == $subs[2]) { $targetcfieldname[3] = $subs[5]; } } $newvalue = '@' . $targetcfieldname[1] . 'X' . $targetcfieldname[2] . 'X' . $targetcfieldname[3] . '@'; } foreach ($fieldnames as $fns) { //if the $fns['oldcfieldname'] is not the same as $fns['oldfieldname'] then this is a multiple type question if ($fns['oldcfieldname'] == $fns['oldfieldname']) { //The normal method - non multiples if ($oldcfieldname == $fns['oldcfieldname']) { $newcfieldname = $fns['newcfieldname']; } } else { if ($oldcfieldname == $fns['oldcfieldname'] && $oldcfieldname . $thisvalue == $fns['oldfieldname']) { $newcfieldname = $fns['newcfieldname']; } } } if (!isset($newcfieldname)) { $newcfieldname = ""; } unset($conditionrowdata["cid"]); $conditionrowdata["qid"] = $newqid; $conditionrowdata["cfieldname"] = $newcfieldname; $conditionrowdata["value"] = $newvalue; if (isset($newcqid)) { $conditionrowdata["cqid"] = $newcqid; if (!isset($conditionrowdata["method"]) || trim($conditionrowdata["method"]) == '') { $conditionrowdata["method"] = '=='; } if (!isset($conditionrowdata["scenario"]) || trim($conditionrowdata["scenario"]) == '') { $conditionrowdata["scenario"] = 1; } $newvalues = array_values($conditionrowdata); $newvalues = array_map(array(&$connect, "qstr"), $newvalues); // quote everything accordingly $conditioninsert = "insert INTO {$dbprefix}conditions (" . implode(',', array_keys($conditionrowdata)) . ") VALUES (" . implode(',', $newvalues) . ")"; $result = $connect->Execute($conditioninsert) or $this->debugLsrc("Import of this survey file failed on Line " . __LINE__ . "| " . $connect->ErrorMsg()); } else { $importsurvey .= "<font size=1>Condition for {$oldqid} skipped ({$oldcqid} does not exist)</font>"; //if ($importingfrom != "http") echo "Condition for $oldqid skipped ($oldcqid does not exist)\n"; //return; //XXX changed: comment the upper line, returning } unset($newcqid); } } // Translate INSERTANS codes if (isset($fieldnames)) { TranslateInsertansTags($newsid, $oldsid, $fieldnames); } $surveyid = $newsid; return true; }
/** * This function imports a LimeSurvey .lss survey XML file * * @param mixed $sFullFilepath The full filepath of the uploaded file */ function XMLImportSurvey($sFullFilepath,$sXMLdata=NULL,$sNewSurveyName=NULL,$iDesiredSurveyId=NULL, $bTranslateInsertansTags=true) { global $connect, $dbprefix, $clang, $timeadjust; $results['error']=false; if ($sXMLdata == NULL) { $xml = simplexml_load_file($sFullFilepath); } else { $xml = simplexml_load_string($sXMLdata); } if ($xml->LimeSurveyDocType!='Survey') { $results['error'] = $clang->gT("This is not a valid LimeSurvey survey structure XML file."); return $results; } else { //$results['error'] = $clang->gT("This is VALID LimeSurvey survey structure XML file."); //echo $clang->gT("This is VALID LimeSurvey survey structure XML file."); //return $results; } $dbversion = (int) $xml->DBVersion; $aQIDReplacements=array(); $aQuotaReplacements=array(); $results['defaultvalues']=0; $results['answers']=0; $results['surveys']=0; $results['questions']=0; $results['subquestions']=0; $results['question_attributes']=0; $results['groups']=0; $results['assessments']=0; $results['quota']=0; $results['quotals']=0; $results['quotamembers']=0; $results['importwarnings']=array(); $aLanguagesSupported=array(); foreach ($xml->languages->language as $language) { $aLanguagesSupported[]=(string)$language; } $results['languages']=count($aLanguagesSupported); // First get an overview of fieldnames - it's not useful for the moment but might be with newer versions /* $fieldnames=array(); foreach ($xml->questions->fields->fieldname as $fieldname ) { $fieldnames[]=(string)$fieldname; };*/ // Import surveys table =================================================================================== $tablename=$dbprefix.'surveys'; foreach ($xml->surveys->rows->row as $row) { $insertdata=array(); foreach ($row as $key=>$value) { $insertdata[(string)$key]=(string)$value; } $oldsid=$insertdata['sid']; if($iDesiredSurveyId!=NULL) { $newsid=GetNewSurveyID($iDesiredSurveyId); } else { $newsid=GetNewSurveyID($oldsid); } if ($dbversion<=143) { $insertdata['anonymized']=$insertdata['private']; unset($insertdata['private']); unset($insertdata['notification']); } $insertdata['startdate']=NULL; //Now insert the new SID and change some values $insertdata['sid']=$newsid; //Make sure it is not set active $insertdata['active']='N'; //Set current user to be the owner $insertdata['owner_id']=$_SESSION['loginID']; //Change creation date to import date $insertdata['datecreated']=$connect->BindTimeStamp(date_shift(date("Y-m-d H:i:s"), "Y-m-d", $timeadjust)); db_switchIDInsert('surveys',true); $query=$connect->GetInsertSQL($tablename,$insertdata); $result = $connect->Execute($query) or safe_die ($clang->gT("Error").": Failed to insert data<br />{$query}<br />\n".$connect->ErrorMsg()); $results['surveys']++; db_switchIDInsert('surveys',false); } $results['newsid']=$newsid; // Import survey languagesettings table =================================================================================== $tablename=$dbprefix.'surveys_languagesettings'; foreach ($xml->surveys_languagesettings->rows->row as $row) { $insertdata=array(); foreach ($row as $key=>$value) { $insertdata[(string)$key]=(string)$value; } $insertdata['surveyls_survey_id']=$newsid; if ($sNewSurveyName == NULL) { $insertdata['surveyls_title']=translink('survey', $oldsid, $newsid, $insertdata['surveyls_title']); } else { $insertdata['surveyls_title']=translink('survey', $oldsid, $newsid, $sNewSurveyName); } $insertdata['surveyls_description']=translink('survey', $oldsid, $newsid, $insertdata['surveyls_description']); $insertdata['surveyls_welcometext']=translink('survey', $oldsid, $newsid, $insertdata['surveyls_welcometext']); $insertdata['surveyls_urldescription']=translink('survey', $oldsid, $newsid, $insertdata['surveyls_urldescription']); $insertdata['surveyls_email_invite']=translink('survey', $oldsid, $newsid, $insertdata['surveyls_email_invite']); $insertdata['surveyls_email_remind']=translink('survey', $oldsid, $newsid, $insertdata['surveyls_email_remind']); $insertdata['surveyls_email_register']=translink('survey', $oldsid, $newsid, $insertdata['surveyls_email_register']); $insertdata['surveyls_email_confirm']=translink('survey', $oldsid, $newsid, $insertdata['surveyls_email_confirm']); $query=$connect->GetInsertSQL($tablename,$insertdata); $result = $connect->Execute($query) or safe_die ($clang->gT("Error").": Failed to insert data<br />{$query}<br />\n".$connect->ErrorMsg()); } // Import groups table =================================================================================== $tablename=$dbprefix.'groups'; foreach ($xml->groups->rows->row as $row) { $insertdata=array(); foreach ($row as $key=>$value) { $insertdata[(string)$key]=(string)$value; } $oldsid=$insertdata['sid']; $insertdata['sid']=$newsid; $oldgid=$insertdata['gid']; unset($insertdata['gid']); // save the old qid // now translate any links $insertdata['group_name']=translink('survey', $oldsid, $newsid, $insertdata['group_name']); $insertdata['description']=translink('survey', $oldsid, $newsid, $insertdata['description']); // Insert the new group if (isset($aGIDReplacements[$oldgid])) { db_switchIDInsert('groups',true); $insertdata['gid']=$aGIDReplacements[$oldgid]; } $query=$connect->GetInsertSQL($tablename,$insertdata); $result = $connect->Execute($query) or safe_die ($clang->gT("Error").": Failed to insert data<br />{$query}<br />\n".$connect->ErrorMsg()); $results['groups']++; if (!isset($aGIDReplacements[$oldgid])) { $newgid=$connect->Insert_ID($tablename,"gid"); // save this for later $aGIDReplacements[$oldgid]=$newgid; // add old and new qid to the mapping array } else { db_switchIDInsert('groups',false); } } // Import questions table =================================================================================== // We have to run the question table data two times - first to find all main questions // then for subquestions (because we need to determine the new qids for the main questions first) if(isset($xml->questions)) // there could be surveys without a any questions { $tablename=$dbprefix.'questions'; foreach ($xml->questions->rows->row as $row) { $insertdata=array(); foreach ($row as $key=>$value) { $insertdata[(string)$key]=(string)$value; } $oldsid=$insertdata['sid']; $insertdata['sid']=$newsid; $insertdata['gid']=$aGIDReplacements[$insertdata['gid']]; $oldqid=$insertdata['qid']; unset($insertdata['qid']); // save the old qid // now translate any links $insertdata['title']=translink('survey', $oldsid, $newsid, $insertdata['title']); $insertdata['question']=translink('survey', $oldsid, $newsid, $insertdata['question']); $insertdata['help']=translink('survey', $oldsid, $newsid, $insertdata['help']); // Insert the new question if (isset($aQIDReplacements[$oldqid])) { $insertdata['qid']=$aQIDReplacements[$oldqid]; db_switchIDInsert('questions',true); } $query=$connect->GetInsertSQL($tablename,$insertdata); $result = $connect->Execute($query) or safe_die ($clang->gT("Error").": Failed to insert data<br />{$query}<br />\n".$connect->ErrorMsg()); if (!isset($aQIDReplacements[$oldqid])) { $newqid=$connect->Insert_ID($tablename,"qid"); // save this for later $aQIDReplacements[$oldqid]=$newqid; // add old and new qid to the mapping array $results['questions']++; } else { db_switchIDInsert('questions',false); } } } // Import subquestions -------------------------------------------------------------- if(isset($xml->subquestions)) { $tablename=$dbprefix.'questions'; foreach ($xml->subquestions->rows->row as $row) { $insertdata=array(); foreach ($row as $key=>$value) { $insertdata[(string)$key]=(string)$value; } $insertdata['sid']=$newsid; $insertdata['gid']=$aGIDReplacements[(int)$insertdata['gid']];; $oldsqid=(int)$insertdata['qid']; unset($insertdata['qid']); // save the old qid $insertdata['parent_qid']=$aQIDReplacements[(int)$insertdata['parent_qid']]; // remap the parent_qid // now translate any links $insertdata['title']=translink('survey', $oldsid, $newsid, $insertdata['title']); $insertdata['question']=translink('survey', $oldsid, $newsid, $insertdata['question']); $insertdata['help']=translink('survey', $oldsid, $newsid, $insertdata['help']); if (isset($aQIDReplacements[$oldsqid])){ $insertdata['qid']=$aQIDReplacements[$oldsqid]; db_switchIDInsert('questions',true); } $query=$connect->GetInsertSQL($tablename,$insertdata); $result = $connect->Execute($query) or safe_die ($clang->gT("Error").": Failed to insert data<br />{$query}<br />\n".$connect->ErrorMsg()); $newsqid=$connect->Insert_ID($tablename,"qid"); // save this for later if (!isset($insertdata['qid'])) { $aQIDReplacements[$oldsqid]=$newsqid; // add old and new qid to the mapping array } else { db_switchIDInsert('questions',false); } $results['subquestions']++; } } // Import answers -------------------------------------------------------------- if(isset($xml->answers)) { $tablename=$dbprefix.'answers'; foreach ($xml->answers->rows->row as $row) { $insertdata=array(); foreach ($row as $key=>$value) { $insertdata[(string)$key]=(string)$value; } $insertdata['qid']=$aQIDReplacements[(int)$insertdata['qid']]; // remap the parent_qid // now translate any links $insertdata['answer']=translink('survey', $oldsid, $newsid, $insertdata['answer']); $query=$connect->GetInsertSQL($tablename,$insertdata); $result=$connect->Execute($query) or safe_die ($clang->gT("Error").": Failed to insert data<br />{$query}<br />\n".$connect->ErrorMsg()); $results['answers']++; } } // Import questionattributes -------------------------------------------------------------- if(isset($xml->question_attributes)) { $tablename=$dbprefix.'question_attributes'; foreach ($xml->question_attributes->rows->row as $row) { $insertdata=array(); foreach ($row as $key=>$value) { $insertdata[(string)$key]=(string)$value; } unset($insertdata['qaid']); $insertdata['qid']=$aQIDReplacements[(integer)$insertdata['qid']]; // remap the parent_qid // now translate any links $query=$connect->GetInsertSQL($tablename,$insertdata); $result=$connect->Execute($query) or safe_die ($clang->gT("Error").": Failed to insert data<br />{$query}<br />\n".$connect->ErrorMsg()); $results['question_attributes']++; } } // Import defaultvalues -------------------------------------------------------------- if(isset($xml->defaultvalues)) { $tablename=$dbprefix.'defaultvalues'; $results['defaultvalues']=0; foreach ($xml->defaultvalues->rows->row as $row) { $insertdata=array(); foreach ($row as $key=>$value) { $insertdata[(string)$key]=(string)$value; } $insertdata['qid']=$aQIDReplacements[(int)$insertdata['qid']]; // remap the qid if (isset($aQIDReplacements[(int)$insertdata['sqid']])) $insertdata['sqid']=$aQIDReplacements[(int)$insertdata['sqid']]; // remap the subquestion id // now translate any links $query=$connect->GetInsertSQL($tablename,$insertdata); $result=$connect->Execute($query) or safe_die ($clang->gT("Error").": Failed to insert data<br />\$query<br />\n".$connect->ErrorMsg()); $results['defaultvalues']++; } } // Import conditions -------------------------------------------------------------- if(isset($xml->conditions)) { $tablename=$dbprefix.'conditions'; $results['conditions']=0; foreach ($xml->conditions->rows->row as $row) { $insertdata=array(); foreach ($row as $key=>$value) { $insertdata[(string)$key]=(string)$value; } // replace the qid for the new one (if there is no new qid in the $aQIDReplacements array it mean that this condition is orphan -> error, skip this record) if (isset($aQIDReplacements[$insertdata['qid']])) { $insertdata['qid']=$aQIDReplacements[$insertdata['qid']]; // remap the qid } else continue; // a problem with this answer record -> don't consider if ($insertdata['cqid'] != 0) { if (isset($aQIDReplacements[$insertdata['cqid']])) { $insertdata['cqid']=$aQIDReplacements[$insertdata['cqid']]; // remap the qid } else continue; // a problem with this answer record -> don't consider list($oldcsid, $oldcgid, $oldqidanscode) = explode("X",$insertdata["cfieldname"],3); // replace the gid for the new one in the cfieldname(if there is no new gid in the $aGIDReplacements array it means that this condition is orphan -> error, skip this record) if (!isset($aGIDReplacements[$oldcgid])) continue; } unset($insertdata["cid"]); // recreate the cfieldname with the new IDs if ($insertdata['cqid'] != 0) { if (preg_match("/^\+/",$oldcsid)) { $newcfieldname = '+'.$newsid . "X" . $aGIDReplacements[$oldcgid] . "X" . $insertdata["cqid"] .substr($oldqidanscode,strlen($oldqid)); } else { $newcfieldname = $newsid . "X" . $aGIDReplacements[$oldcgid] . "X" . $insertdata["cqid"] .substr($oldqidanscode,strlen($oldqid)); } } else { // The cfieldname is a not a previous question cfield but a {XXXX} replacement field $newcfieldname = $insertdata["cfieldname"]; } $insertdata["cfieldname"] = $newcfieldname; if (trim($insertdata["method"])=='') { $insertdata["method"]='=='; } // now translate any links $query=$connect->GetInsertSQL($tablename,$insertdata); $result=$connect->Execute($query) or safe_die ($clang->gT("Error").": Failed to insert data<br />\$query<br />\n".$connect->ErrorMsg()); $results['conditions']++; } } // Import assessments -------------------------------------------------------------- if(isset($xml->assessments)) { $tablename=$dbprefix.'assessments'; foreach ($xml->assessments->rows->row as $row) { $insertdata=array(); foreach ($row as $key=>$value) { $insertdata[(string)$key]=(string)$value; } if ($insertdata['gid']>0) { $insertdata['gid']=$aGIDReplacements[(int)$insertdata['gid']]; // remap the qid } $insertdata['sid']=$newsid; // remap the survey id // now translate any links $query=$connect->GetInsertSQL($tablename,$insertdata); $result=$connect->Execute($query) or safe_die ($clang->gT("Error").": Failed to insert data<br />\$query<br />\n".$connect->ErrorMsg()); $results['assessments']++; } } // Import quota -------------------------------------------------------------- if(isset($xml->quota)) { $tablename=$dbprefix.'quota'; foreach ($xml->quota->rows->row as $row) { $insertdata=array(); foreach ($row as $key=>$value) { $insertdata[(string)$key]=(string)$value; } $insertdata['sid']=$newsid; // remap the survey id $oldid=$insertdata['id']; unset($insertdata['id']); // now translate any links $query=$connect->GetInsertSQL($tablename,$insertdata); $result=$connect->Execute($query) or safe_die ($clang->gT("Error").": Failed to insert data<br />\$query<br />\n".$connect->ErrorMsg()); $aQuotaReplacements[$oldid] = $connect->Insert_ID(db_table_name_nq('quota'),"id"); $results['quota']++; } } // Import quota_members -------------------------------------------------------------- if(isset($xml->quota_members)) { $tablename=$dbprefix.'quota_members'; foreach ($xml->quota_members->rows->row as $row) { $insertdata=array(); foreach ($row as $key=>$value) { $insertdata[(string)$key]=(string)$value; } $insertdata['sid']=$newsid; // remap the survey id $insertdata['qid']=$aQIDReplacements[(int)$insertdata['qid']]; // remap the qid $insertdata['quota_id']=$aQuotaReplacements[(int)$insertdata['quota_id']]; // remap the qid unset($insertdata['id']); // now translate any links $query=$connect->GetInsertSQL($tablename,$insertdata); $result=$connect->Execute($query) or safe_die ($clang->gT("Error").": Failed to insert data<br />\$query<br />\n".$connect->ErrorMsg()); $results['quotamembers']++; } } // Import quota_languagesettings -------------------------------------------------------------- if(isset($xml->quota_languagesettings)) { $tablename=$dbprefix.'quota_languagesettings'; foreach ($xml->quota_languagesettings->rows->row as $row) { $insertdata=array(); foreach ($row as $key=>$value) { $insertdata[(string)$key]=(string)$value; } $insertdata['quotals_quota_id']=$aQuotaReplacements[(int)$insertdata['quotals_quota_id']]; // remap the qid unset($insertdata['quotals_id']); // now translate any links $query=$connect->GetInsertSQL($tablename,$insertdata); $result=$connect->Execute($query) or safe_die ($clang->gT("Error").": Failed to insert data<br />\$query<br />\n".$connect->ErrorMsg()); $results['quotals']++; } } // Set survey rights GiveAllSurveyPermissions($_SESSION['loginID'],$newsid); if ($bTranslateInsertansTags) { $aOldNewFieldmap=aReverseTranslateFieldnames($oldsid,$newsid,$aGIDReplacements,$aQIDReplacements); TranslateInsertansTags($newsid,$oldsid,$aOldNewFieldmap); } return $results; }
/** * FixLanguageConsistency() fixes missing groups,questions,answers & assessments for languages on a survey * @param string $sid - the currently selected survey * @param string $availlangs - space seperated list of additional languages in survey - if empty all additional languages of a survey are checked against the base language * @return bool - always returns true */ function FixLanguageConsistency($sid, $availlangs = '') { global $connect, $databasetype; if (trim($availlangs) != '') { $availlangs = sanitize_languagecodeS($availlangs); $langs = explode(" ", $availlangs); if ($langs[count($langs) - 1] == "") { array_pop($langs); } } else { $langs = GetAdditionalLanguagesFromSurveyID($sid); } $baselang = GetBaseLanguageFromSurveyID($sid); $sid = sanitize_int($sid); $query = "SELECT * FROM " . db_table_name('groups') . " WHERE sid='{$sid}' AND language='{$baselang}' ORDER BY group_order"; $result = db_execute_assoc($query) or safe_die($connect->ErrorMsg()); //Checked if ($result->RecordCount() > 0) { while ($group = $result->FetchRow()) { foreach ($langs as $lang) { $query = "SELECT gid FROM " . db_table_name('groups') . " WHERE sid='{$sid}' AND gid='{$group['gid']}' AND language='{$lang}'"; $gresult = db_execute_assoc($query) or safe_die($connect->ErrorMsg()); //Checked if ($gresult->RecordCount() < 1) { db_switchIDInsert('groups', true); $query = "INSERT INTO " . db_table_name('groups') . " (gid,sid,group_name,group_order,description,language) VALUES('{$group['gid']}','{$group['sid']}'," . db_quoteall($group['group_name']) . ",'{$group['group_order']}'," . db_quoteall($group['description']) . ",'{$lang}')"; $connect->Execute($query) or safe_die($connect->ErrorMsg()); //Checked db_switchIDInsert('groups', false); } } reset($langs); } } $quests = array(); $query = "SELECT * FROM " . db_table_name('questions') . " WHERE sid='{$sid}' AND language='{$baselang}' ORDER BY question_order"; $result = db_execute_assoc($query) or safe_die($connect->ErrorMsg()); //Checked if ($result->RecordCount() > 0) { while ($question = $result->FetchRow()) { array_push($quests, $question['qid']); foreach ($langs as $lang) { $query = "SELECT qid FROM " . db_table_name('questions') . " WHERE sid='{$sid}' AND qid='{$question['qid']}' AND language='{$lang}'"; $gresult = db_execute_assoc($query) or safe_die($connect->ErrorMsg()); //Checked if ($gresult->RecordCount() < 1) { db_switchIDInsert('questions', true); $query = "INSERT INTO " . db_table_name('questions') . " (qid,sid,gid,type,title,question,preg,help,other,mandatory,question_order,language, scale_id,parent_qid) VALUES('{$question['qid']}','{$question['sid']}','{$question['gid']}','{$question['type']}'," . db_quoteall($question['title']) . "," . db_quoteall($question['question']) . "," . db_quoteall($question['preg']) . "," . db_quoteall($question['help']) . ",'{$question['other']}','{$question['mandatory']}','{$question['question_order']}','{$lang}',{$question['scale_id']},{$question['parent_qid']})"; $connect->Execute($query) or safe_die($query . "<br />" . $connect->ErrorMsg()); //Checked db_switchIDInsert('questions', false); } } reset($langs); } $sqlans = ""; foreach ($quests as $quest) { $sqlans .= " OR qid = '" . $quest . "' "; } $query = "SELECT * FROM " . db_table_name('answers') . " WHERE language='{$baselang}' and (" . trim($sqlans, ' OR') . ") ORDER BY qid, code"; $result = db_execute_assoc($query) or safe_die($connect->ErrorMsg()); //Checked if ($result->RecordCount() > 0) { while ($answer = $result->FetchRow()) { foreach ($langs as $lang) { $query = "SELECT qid FROM " . db_table_name('answers') . " WHERE code='{$answer['code']}' AND qid='{$answer['qid']}' AND language='{$lang}'"; $gresult = db_execute_assoc($query) or safe_die($connect->ErrorMsg()); //Checked if ($gresult->RecordCount() < 1) { db_switchIDInsert('answers', true); $query = "INSERT INTO " . db_table_name('answers') . " (qid,code,answer,scale_id,sortorder,language,assessment_value) VALUES('{$answer['qid']}'," . db_quoteall($answer['code']) . "," . db_quoteall($answer['answer']) . ",{$answer['scale_id']},'{$answer['sortorder']}','{$lang}',{$answer['assessment_value']})"; $connect->Execute($query) or safe_die($connect->ErrorMsg()); //Checked db_switchIDInsert('answers', false); } } reset($langs); } } } $query = "SELECT * FROM " . db_table_name('assessments') . " WHERE sid='{$sid}' AND language='{$baselang}'"; $result = db_execute_assoc($query) or safe_die($connect->ErrorMsg()); //Checked if ($result->RecordCount() > 0) { while ($assessment = $result->FetchRow()) { foreach ($langs as $lang) { $query = "SELECT id FROM " . db_table_name('assessments') . " WHERE sid='{$sid}' AND id='{$assessment['id']}' AND language='{$lang}'"; $gresult = db_execute_assoc($query) or safe_die($connect->ErrorMsg()); //Checked if ($gresult->RecordCount() < 1) { db_switchIDInsert('assessments', true); $query = "INSERT INTO " . db_table_name('assessments') . " (id,sid,scope,gid,name,minimum,maximum,message,language) " . "VALUES('{$assessment['id']}','{$assessment['sid']}'," . db_quoteall($assessment['scope']) . "," . db_quoteall($assessment['gid']) . "," . db_quoteall($assessment['name']) . "," . db_quoteall($assessment['minimum']) . "," . db_quoteall($assessment['maximum']) . "," . db_quoteall($assessment['message']) . ",'{$lang}')"; $connect->Execute($query) or safe_die($connect->ErrorMsg()); //Checked db_switchIDInsert('assessments', false); } } reset($langs); } } return true; }
/** * This function imports a LimeSurvey .lsg question group XML file * * @param mixed $sFullFilepath The full filepath of the uploaded file * @param mixed $newsid The new survey id - the group will always be added after the last group in the survey */ function XMLImportGroup($sFullFilepath, $newsid) { global $connect, $dbprefix, $clang; $aLanguagesSupported = array(); // this array will keep all the languages supported for the survey $sBaseLanguage = GetBaseLanguageFromSurveyID($newsid); $aLanguagesSupported[] = $sBaseLanguage; // adds the base language to the list of supported languages $aLanguagesSupported = array_merge($aLanguagesSupported, GetAdditionalLanguagesFromSurveyID($newsid)); $xml = @simplexml_load_file($sFullFilepath); if ($xml == false || $xml->LimeSurveyDocType != 'Group') { safe_die('This is not a valid LimeSurvey group structure XML file.'); } $dbversion = (double) $xml->DBVersion; $aQIDReplacements = array(); $results['defaultvalues'] = 0; $results['answers'] = 0; $results['question_attributes'] = 0; $results['subquestions'] = 0; $results['conditions'] = 0; $results['groups'] = 0; $importlanguages = array(); foreach ($xml->languages->language as $language) { $importlanguages[] = (string) $language; } if (!in_array($sBaseLanguage, $importlanguages)) { $results['fatalerror'] = $clang->gT("The languages of the imported group file must at least include the base language of this survey."); return $results; } // First get an overview of fieldnames - it's not useful for the moment but might be with newer versions /* $fieldnames=array(); foreach ($xml->questions->fields->fieldname as $fieldname ) { $fieldnames[]=(string)$fieldname; };*/ // Import group table =================================================================================== $tablename = $dbprefix . 'groups'; $newgrouporder = $connect->GetOne("SELECT MAX(group_order) AS maxqo FROM " . db_table_name('groups') . " WHERE sid={$newsid}"); if (is_null($newgrouporder)) { $newgrouporder = 0; } else { $newgrouporder++; } foreach ($xml->groups->rows->row as $row) { $insertdata = array(); foreach ($row as $key => $value) { $insertdata[(string) $key] = (string) $value; } $oldsid = $insertdata['sid']; $insertdata['sid'] = $newsid; $insertdata['group_order'] = $newgrouporder; $oldgid = $insertdata['gid']; unset($insertdata['gid']); // save the old qid // now translate any links $insertdata['group_name'] = translink('survey', $oldsid, $newsid, $insertdata['group_name']); $insertdata['description'] = translink('survey', $oldsid, $newsid, $insertdata['description']); // Insert the new question if (isset($aGIDReplacements[$oldgid])) { $insertdata['gid'] = $aGIDReplacements[$oldgid]; db_switchIDInsert('groups', true); } $query = $connect->GetInsertSQL($tablename, $insertdata); $result = $connect->Execute($query) or safe_die($clang->gT("Error") . ": Failed to insert data<br />{$query}<br />\n" . $connect->ErrorMsg()); $results['groups']++; if (!isset($aGIDReplacements[$oldgid])) { $newgid = $connect->Insert_ID($tablename, "gid"); // save this for later $aGIDReplacements[$oldgid] = $newgid; // add old and new qid to the mapping array } else { db_switchIDInsert('groups', false); } } // Import questions table =================================================================================== // We have to run the question table data two times - first to find all main questions // then for subquestions (because we need to determine the new qids for the main questions first) $tablename = $dbprefix . 'questions'; $results['questions'] = 0; if (isset($xml->questions)) { foreach ($xml->questions->rows->row as $row) { $insertdata = array(); foreach ($row as $key => $value) { $insertdata[(string) $key] = (string) $value; } $oldsid = $insertdata['sid']; $insertdata['sid'] = $newsid; if (!isset($aGIDReplacements[$insertdata['gid']]) || trim($insertdata['title']) == '') { continue; } // Skip questions with invalid group id $insertdata['gid'] = $aGIDReplacements[$insertdata['gid']]; $oldqid = $insertdata['qid']; unset($insertdata['qid']); // save the old qid // now translate any links $insertdata['title'] = translink('survey', $oldsid, $newsid, $insertdata['title']); $insertdata['question'] = translink('survey', $oldsid, $newsid, $insertdata['question']); $insertdata['help'] = translink('survey', $oldsid, $newsid, $insertdata['help']); // Insert the new question if (isset($aQIDReplacements[$oldqid])) { $insertdata['qid'] = $aQIDReplacements[$oldqid]; db_switchIDInsert('questions', true); } $query = $connect->GetInsertSQL($tablename, $insertdata); $result = $connect->Execute($query) or safe_die($clang->gT("Error") . ": Failed to insert data<br />{$query}<br />\n" . $connect->ErrorMsg()); if (!isset($aQIDReplacements[$oldqid])) { $newqid = $connect->Insert_ID($tablename, "qid"); // save this for later $aQIDReplacements[$oldqid] = $newqid; // add old and new qid to the mapping array $results['questions']++; } else { db_switchIDInsert('questions', false); } } } // Import subquestions -------------------------------------------------------------- if (isset($xml->subquestions)) { foreach ($xml->subquestions->rows->row as $row) { $insertdata = array(); foreach ($row as $key => $value) { $insertdata[(string) $key] = (string) $value; } $insertdata['sid'] = $newsid; if (!isset($aGIDReplacements[$insertdata['gid']])) { continue; } // Skip questions with invalid group id $insertdata['gid'] = $aGIDReplacements[(int) $insertdata['gid']]; $oldsqid = (int) $insertdata['qid']; unset($insertdata['qid']); // save the old qid if (!isset($aQIDReplacements[(int) $insertdata['parent_qid']])) { continue; } // Skip subquestions with invalid parent_qids $insertdata['parent_qid'] = $aQIDReplacements[(int) $insertdata['parent_qid']]; // remap the parent_qid // now translate any links $insertdata['title'] = translink('survey', $oldsid, $newsid, $insertdata['title']); $insertdata['question'] = translink('survey', $oldsid, $newsid, $insertdata['question']); $insertdata['help'] = isset($insertdata['help']) ? translink('survey', $oldsid, $newsid, $insertdata['help']) : ''; if (isset($aQIDReplacements[$oldsqid])) { $insertdata['qid'] = $aQIDReplacements[$oldsqid]; db_switchIDInsert('questions', true); } $query = $connect->GetInsertSQL($tablename, $insertdata); $result = $connect->Execute($query) or safe_die($clang->gT("Error") . ": Failed to insert data<br />{$query}<br />\n" . $connect->ErrorMsg()); $newsqid = $connect->Insert_ID($tablename, "qid"); // save this for later if (!isset($insertdata['qid'])) { $aQIDReplacements[$oldsqid] = $newsqid; // add old and new qid to the mapping array } else { db_switchIDInsert('questions', false); } $results['subquestions']++; } } // Import answers -------------------------------------------------------------- if (isset($xml->answers)) { $tablename = $dbprefix . 'answers'; foreach ($xml->answers->rows->row as $row) { $insertdata = array(); foreach ($row as $key => $value) { $insertdata[(string) $key] = (string) $value; } if (!isset($aQIDReplacements[(int) $insertdata['qid']])) { continue; } // Skip questions with invalid group id $insertdata['qid'] = $aQIDReplacements[(int) $insertdata['qid']]; // remap the parent_qid // now translate any links $query = $connect->GetInsertSQL($tablename, $insertdata); $result = $connect->Execute($query) or safe_die($clang->gT("Error") . ": Failed to insert data<br />{$query}<br />\n" . $connect->ErrorMsg()); $results['answers']++; } } // Import questionattributes -------------------------------------------------------------- if (isset($xml->question_attributes)) { $tablename = $dbprefix . 'question_attributes'; foreach ($xml->question_attributes->rows->row as $row) { $insertdata = array(); foreach ($row as $key => $value) { $insertdata[(string) $key] = (string) $value; } unset($insertdata['qaid']); if (!isset($aQIDReplacements[(int) $insertdata['qid']])) { continue; } // Skip questions with invalid group id $insertdata['qid'] = $aQIDReplacements[(int) $insertdata['qid']]; // remap the parent_qid // now translate any links $query = $connect->GetInsertSQL($tablename, $insertdata); $result = $connect->Execute($query) or safe_die($clang->gT("Error") . ": Failed to insert data<br />{$query}<br />\n" . $connect->ErrorMsg()); $results['question_attributes']++; } } // Import defaultvalues -------------------------------------------------------------- if (isset($xml->defaultvalues)) { $tablename = $dbprefix . 'defaultvalues'; $results['defaultvalues'] = 0; foreach ($xml->defaultvalues->rows->row as $row) { $insertdata = array(); foreach ($row as $key => $value) { $insertdata[(string) $key] = (string) $value; } $insertdata['qid'] = $aQIDReplacements[(int) $insertdata['qid']]; // remap the qid if (!isset($aQIDReplacements[(int) $insertdata['sqid']]) || is_null($aQIDReplacements[(int) $insertdata['sqid']])) { $insertdata['sqid'] = 0; // defaults for non-array types } else { $insertdata['sqid'] = $aQIDReplacements[(int) $insertdata['sqid']]; // remap the subqeustion id } // now translate any links $query = $connect->GetInsertSQL($tablename, $insertdata); $result = $connect->Execute($query) or safe_die($clang->gT("Error") . ": Failed to insert data<br />" . $query . "<br />\n" . $connect->ErrorMsg()); $results['defaultvalues']++; } } // Import conditions -------------------------------------------------------------- if (isset($xml->conditions)) { $tablename = $dbprefix . 'conditions'; foreach ($xml->conditions->rows->row as $row) { $insertdata = array(); foreach ($row as $key => $value) { $insertdata[(string) $key] = (string) $value; } // replace the qid for the new one (if there is no new qid in the $aQIDReplacements array it mean that this condition is orphan -> error, skip this record) if (isset($aQIDReplacements[$insertdata['qid']])) { $insertdata['qid'] = $aQIDReplacements[$insertdata['qid']]; // remap the qid } else { continue; } // a problem with this answer record -> don't consider if (isset($aQIDReplacements[$insertdata['cqid']])) { $insertdata['cqid'] = $aQIDReplacements[$insertdata['cqid']]; // remap the qid } else { continue; } // a problem with this answer record -> don't consider list($oldcsid, $oldcgid, $oldqidanscode) = explode("X", $insertdata["cfieldname"], 3); if ($oldcgid != $oldgid) { // this means that the condition is in another group (so it should not have to be been exported -> skip it continue; } unset($insertdata["cid"]); // recreate the cfieldname with the new IDs if (preg_match("/^\\+/", $oldcsid)) { $newcfieldname = '+' . $newsid . "X" . $newgid . "X" . $insertdata["cqid"] . substr($oldqidanscode, strlen($oldqid)); } else { $newcfieldname = $newsid . "X" . $newgid . "X" . $insertdata["cqid"] . substr($oldqidanscode, strlen($oldqid)); } $insertdata["cfieldname"] = $newcfieldname; if (trim($insertdata["method"]) == '') { $insertdata["method"] = '=='; } // now translate any links $query = $connect->GetInsertSQL($tablename, $insertdata); $result = $connect->Execute($query) or safe_die($clang->gT("Error") . ": Failed to insert data<br />\$query<br />\n" . $connect->ErrorMsg()); $results['conditions']++; } } LimeExpressionManager::RevertUpgradeConditionsToRelevance($newsid); LimeExpressionManager::UpgradeConditionsToRelevance($newsid); $results['newgid'] = $newgid; $results['labelsets'] = 0; $results['labels'] = 0; return $results; }
if (isset($oldcodes[$scale_id][$position]) && $codes[$scale_id][$position] !== $oldcodes[$scale_id][$position]) { $query = 'UPDATE ' . db_table_name('conditions') . ' SET cfieldname="+' . $surveyid . 'X' . $gid . 'X' . $qid . db_quote($codes[$scale_id][$position]) . '" WHERE cqid=' . $qid . ' AND cfieldname="+' . $surveyid . 'X' . $gid . 'X' . $qid . db_quote($oldcodes[$scale_id][$position]) . '"'; $connect->execute($query); $query = 'UPDATE ' . db_table_name('conditions') . ' SET value="' . db_quote($codes[$scale_id][$position]) . '" WHERE cqid=' . $qid . ' AND cfieldname="' . $surveyid . 'X' . $gid . 'X' . $qid . '" AND value="' . $oldcodes[$scale_id][$position] . '"'; $connect->execute($query); } } else { if (!isset($insertqid[$scale_id][$position])) { $query = 'INSERT into ' . db_table_name('questions') . ' (sid, gid, question_order, title, question, parent_qid, language, scale_id) values (' . $surveyid . ',' . $gid . ',' . ($position + 1) . ',' . db_quoteall($codes[$scale_id][$position]) . ',' . db_quoteall($subquestionvalue) . ',' . $qid . ',' . db_quoteall($language) . ',' . $scale_id . ')'; $connect->execute($query); $insertqid[$scale_id][$position] = $connect->Insert_Id(db_table_name_nq('questions'), "qid"); } else { db_switchIDInsert('questions', true); $query = 'INSERT into ' . db_table_name('questions') . ' (qid, sid, gid, question_order, title, question, parent_qid, language, scale_id) values (' . $insertqid[$scale_id][$position] . ',' . $surveyid . ',' . $gid . ',' . ($position + 1) . ',' . db_quoteall($codes[$scale_id][$position]) . ',' . db_quoteall($subquestionvalue) . ',' . $qid . ',' . db_quoteall($language) . ',' . $scale_id . ')'; $connect->execute($query); db_switchIDInsert('questions', true); } } $position++; } } } LimeExpressionManager::UpgradeConditionsToRelevance($surveyid); //include("surveytable_functions.php"); //surveyFixColumns($surveyid); $_SESSION['flashmessage'] = $clang->gT("Subquestions were successfully saved."); $action = 'editsubquestions'; } elseif (($action == "updatesurveysettingsandeditlocalesettings" || $action == "updatesurveysettings") && bHasSurveyPermission($surveyid, 'surveysettings', 'update')) { $formatdata = getDateFormatData($_SESSION['dateformat']); if (trim($_POST['expires']) == "") { $_POST['expires'] = null;
/** * This function imports a LimeSurvey .lsq question XML file * * @param mixed $sFullFilepath The full filepath of the uploaded file * @param mixed $newsid The new survey id * @param mixed $newgid The new question group id -the question will always be added after the last question in the group */ function XMLImportQuestion($sFullFilepath, $newsid, $newgid) { global $connect, $dbprefix, $clang; $aLanguagesSupported = array(); // this array will keep all the languages supported for the survey $sBaseLanguage = GetBaseLanguageFromSurveyID($newsid); $aLanguagesSupported[] = $sBaseLanguage; // adds the base language to the list of supported languages $aLanguagesSupported = array_merge($aLanguagesSupported, GetAdditionalLanguagesFromSurveyID($newsid)); $xml = simplexml_load_file($sFullFilepath); if ($xml->LimeSurveyDocType != 'Question') { safe_die('This is not a valid LimeSurvey question structure XML file.'); } $dbversion = (double) $xml->DBVersion; $aQIDReplacements = array(); $aSQIDReplacements = array(0 => 0); $results['defaultvalues'] = 0; $results['answers'] = 0; $results['question_attributes'] = 0; $results['subquestions'] = 0; $importlanguages = array(); foreach ($xml->languages->language as $language) { $importlanguages[] = (string) $language; } if (!in_array($sBaseLanguage, $importlanguages)) { $results['fatalerror'] = $clang->gT("The languages of the imported question file must at least include the base language of this survey."); return $results; } // First get an overview of fieldnames - it's not useful for the moment but might be with newer versions /* $fieldnames=array(); foreach ($xml->questions->fields->fieldname as $fieldname ) { $fieldnames[]=(string)$fieldname; };*/ // Import questions table =================================================================================== // We have to run the question table data two times - first to find all main questions // then for subquestions (because we need to determine the new qids for the main questions first) $tablename = $dbprefix . 'questions'; $newquestionorder = $connect->GetOne("SELECT MAX(question_order) AS maxqo FROM " . db_table_name('questions') . " WHERE sid={$newsid} AND gid={$newgid}") + 1; if (is_null($newquestionorder)) { $newquestionorder = 0; } else { $newquestionorder++; } foreach ($xml->questions->rows->row as $row) { $insertdata = array(); foreach ($row as $key => $value) { $insertdata[(string) $key] = (string) $value; } $oldsid = $insertdata['sid']; $insertdata['sid'] = $newsid; $insertdata['gid'] = $newgid; $insertdata['question_order'] = $newquestionorder; $oldqid = $insertdata['qid']; unset($insertdata['qid']); // save the old qid // now translate any links $insertdata['title'] = translink('survey', $oldsid, $newsid, $insertdata['title']); $insertdata['question'] = translink('survey', $oldsid, $newsid, $insertdata['question']); $insertdata['help'] = translink('survey', $oldsid, $newsid, $insertdata['help']); // Insert the new question if (isset($aQIDReplacements[$oldqid])) { $insertdata['qid'] = $aQIDReplacements[$oldqid]; db_switchIDInsert('questions', true); } $query = $connect->GetInsertSQL($tablename, $insertdata); $result = $connect->Execute($query) or safe_die($clang->gT("Error") . ": Failed to insert data<br />{$query}<br />\n" . $connect->ErrorMsg()); if (!isset($aQIDReplacements[$oldqid])) { $newqid = $connect->Insert_ID($tablename, "qid"); // save this for later $aQIDReplacements[$oldqid] = $newqid; // add old and new qid to the mapping array } else { db_switchIDInsert('questions', false); } } // Import subquestions -------------------------------------------------------------- if (isset($xml->subquestions)) { foreach ($xml->subquestions->rows->row as $row) { $insertdata = array(); foreach ($row as $key => $value) { $insertdata[(string) $key] = (string) $value; } $insertdata['sid'] = $newsid; $insertdata['gid'] = $newgid; $oldsqid = (int) $insertdata['qid']; unset($insertdata['qid']); // save the old qid $insertdata['parent_qid'] = $aQIDReplacements[(int) $insertdata['parent_qid']]; // remap the parent_qid // now translate any links $insertdata['title'] = translink('survey', $oldsid, $newsid, $insertdata['title']); $insertdata['question'] = translink('survey', $oldsid, $newsid, $insertdata['question']); $insertdata['help'] = translink('survey', $oldsid, $newsid, $insertdata['help']); if (isset($aQIDReplacements[$oldsqid])) { $insertdata['qid'] = $aQIDReplacements[$oldsqid]; db_switchIDInsert('questions', true); } $query = $connect->GetInsertSQL($tablename, $insertdata); $result = $connect->Execute($query) or safe_die($clang->gT("Error") . ": Failed to insert data<br />{$query}<br />\n" . $connect->ErrorMsg()); $newsqid = $connect->Insert_ID($tablename, "qid"); // save this for later if (!isset($insertdata['qid'])) { $aQIDReplacements[$oldsqid] = $newsqid; // add old and new qid to the mapping array } else { db_switchIDInsert('questions', false); } $results['subquestions']++; } } // Import answers -------------------------------------------------------------- if (isset($xml->answers)) { $tablename = $dbprefix . 'answers'; foreach ($xml->answers->rows->row as $row) { $insertdata = array(); foreach ($row as $key => $value) { $insertdata[(string) $key] = (string) $value; } $insertdata['qid'] = $aQIDReplacements[(int) $insertdata['qid']]; // remap the parent_qid // now translate any links $query = $connect->GetInsertSQL($tablename, $insertdata); $result = $connect->Execute($query) or safe_die($clang->gT("Error") . ": Failed to insert data<br />{$query}<br />\n" . $connect->ErrorMsg()); $results['answers']++; } } // Import questionattributes -------------------------------------------------------------- if (isset($xml->question_attributes)) { $tablename = $dbprefix . 'question_attributes'; foreach ($xml->question_attributes->rows->row as $row) { $insertdata = array(); foreach ($row as $key => $value) { $insertdata[(string) $key] = (string) $value; } unset($insertdata['qaid']); $insertdata['qid'] = $aQIDReplacements[(int) $insertdata['qid']]; // remap the parent_qid // now translate any links $query = $connect->GetInsertSQL($tablename, $insertdata); $result = $connect->Execute($query) or safe_die($clang->gT("Error") . ": Failed to insert data<br />{$query}<br />\n" . $connect->ErrorMsg()); $results['question_attributes']++; } } // Import defaultvalues -------------------------------------------------------------- if (isset($xml->defaultvalues)) { $tablename = $dbprefix . 'defaultvalues'; $results['defaultvalues'] = 0; foreach ($xml->defaultvalues->rows->row as $row) { $insertdata = array(); foreach ($row as $key => $value) { $insertdata[(string) $key] = (string) $value; } $insertdata['qid'] = $aQIDReplacements[(int) $insertdata['qid']]; // remap the qid $insertdata['sqid'] = $aSQIDReplacements[(int) $insertdata['sqid']]; // remap the subquestion id // now translate any links $query = $connect->GetInsertSQL($tablename, $insertdata); $result = $connect->Execute($query) or safe_die($clang->gT("Error") . ": Failed to insert data<br />\$query<br />\n" . $connect->ErrorMsg()); $results['defaultvalues']++; } } LimeExpressionManager::SetDirtyFlag(); // so refreshes syntax highlighting $results['newqid'] = $newqid; $results['questions'] = 1; $results['labelsets'] = 0; $results['labels'] = 0; return $results; }
/** * This function imports a LimeSurvey .lss survey XML file * * @param mixed $sFullFilepath The full filepath of the uploaded file * @param string $sXMLdata Alternatively you can specify XML data to import in this variable - $sFullFilepath is then ignored - default NULL * @param string $sNewSurveyName Name of the to be imported survey (optional) - default NULL * @param boolean $bTranslateInsertansTags If INSERTANS tags should be translated - defaults to true */ function XMLImportSurvey($sFullFilepath, $sXMLdata = NULL, $sNewSurveyName = NULL, $bTranslateInsertansTags = true) { global $connect, $dbprefix, $clang, $timeadjust; if ($sXMLdata == NULL) { $xml = simplexml_load_file($sFullFilepath); } else { $xml = simplexml_load_string($sXMLdata); } if ($xml->LimeSurveyDocType != 'Survey') { safe_die('This is not a valid LimeSurvey survey structure XML file.'); } $dbversion = (int) $xml->DBVersion; $aQIDReplacements = array(); $aQuotaReplacements = array(); $results['defaultvalues'] = 0; $results['answers'] = 0; $results['surveys'] = 0; $results['questions'] = 0; $results['subquestions'] = 0; $results['question_attributes'] = 0; $results['groups'] = 0; $results['assessments'] = 0; $results['quota'] = 0; $results['quotals'] = 0; $results['quotamembers'] = 0; $results['importwarnings'] = array(); $aLanguagesSupported = array(); foreach ($xml->languages->language as $language) { $aLanguagesSupported[] = (string) $language; } $results['languages'] = count($aLanguagesSupported); // First get an overview of fieldnames - it's not useful for the moment but might be with newer versions /* $fieldnames=array(); foreach ($xml->questions->fields->fieldname as $fieldname ) { $fieldnames[]=(string)$fieldname; };*/ // Import surveys table =================================================================================== $tablename = $dbprefix . 'surveys'; foreach ($xml->surveys->rows->row as $row) { $insertdata = array(); foreach ($row as $key => $value) { $insertdata[(string) $key] = (string) $value; } $oldsid = $insertdata['sid']; $newsid = GetNewSurveyID($oldsid); //Now insert the new SID and change some values $insertdata['sid'] = $newsid; //Make sure it is not set active $insertdata['active'] = 'N'; //Set current user to be the owner $insertdata['owner_id'] = $_SESSION['loginID']; //Change creation date to import date $insertdata['datecreated'] = $connect->BindTimeStamp(date_shift(date("Y-m-d H:i:s"), "Y-m-d", $timeadjust)); db_switchIDInsert('surveys', true); $query = $connect->GetInsertSQL($tablename, $insertdata); $result = $connect->Execute($query) or safe_die($clang->gT("Error") . ": Failed to insert data<br />{$query}<br />\n" . $connect->ErrorMsg()); $results['surveys']++; db_switchIDInsert('surveys', false); } $results['newsid'] = $newsid; // Import survey languagesettings table =================================================================================== $tablename = $dbprefix . 'surveys_languagesettings'; foreach ($xml->surveys_languagesettings->rows->row as $row) { $insertdata = array(); foreach ($row as $key => $value) { $insertdata[(string) $key] = (string) $value; } $insertdata['surveyls_survey_id'] = $newsid; if ($sNewSurveyName == NULL) { $insertdata['surveyls_title'] = translink('survey', $oldsid, $newsid, $insertdata['surveyls_title']); } else { $insertdata['surveyls_title'] = translink('survey', $oldsid, $newsid, $sNewSurveyName); } $insertdata['surveyls_description'] = translink('survey', $oldsid, $newsid, $insertdata['surveyls_description']); $insertdata['surveyls_welcometext'] = translink('survey', $oldsid, $newsid, $insertdata['surveyls_welcometext']); $insertdata['surveyls_urldescription'] = translink('survey', $oldsid, $newsid, $insertdata['surveyls_urldescription']); $insertdata['surveyls_email_invite'] = translink('survey', $oldsid, $newsid, $insertdata['surveyls_email_invite']); $insertdata['surveyls_email_remind'] = translink('survey', $oldsid, $newsid, $insertdata['surveyls_email_remind']); $insertdata['surveyls_email_register'] = translink('survey', $oldsid, $newsid, $insertdata['surveyls_email_register']); $insertdata['surveyls_email_confirm'] = translink('survey', $oldsid, $newsid, $insertdata['surveyls_email_confirm']); $query = $connect->GetInsertSQL($tablename, $insertdata); $result = $connect->Execute($query) or safe_die($clang->gT("Error") . ": Failed to insert data<br />{$query}<br />\n" . $connect->ErrorMsg()); } // Import groups table =================================================================================== $tablename = $dbprefix . 'groups'; foreach ($xml->groups->rows->row as $row) { $insertdata = array(); foreach ($row as $key => $value) { $insertdata[(string) $key] = (string) $value; } $oldsid = $insertdata['sid']; $insertdata['sid'] = $newsid; $oldgid = $insertdata['gid']; unset($insertdata['gid']); // save the old qid // now translate any links $insertdata['group_name'] = translink('survey', $oldsid, $newsid, $insertdata['group_name']); $insertdata['description'] = translink('survey', $oldsid, $newsid, $insertdata['description']); // Insert the new group if (isset($aGIDReplacements[$oldgid])) { db_switchIDInsert('groups', true); $insertdata['gid'] = $aGIDReplacements[$oldgid]; } $query = $connect->GetInsertSQL($tablename, $insertdata); $result = $connect->Execute($query) or safe_die($clang->gT("Error") . ": Failed to insert data<br />{$query}<br />\n" . $connect->ErrorMsg()); $results['groups']++; if (!isset($aGIDReplacements[$oldgid])) { $newgid = $connect->Insert_ID($tablename, "gid"); // save this for later $aGIDReplacements[$oldgid] = $newgid; // add old and new qid to the mapping array } else { db_switchIDInsert('groups', false); } } // Import questions table =================================================================================== // We have to run the question table data two times - first to find all main questions // then for subquestions (because we need to determine the new qids for the main questions first) if (isset($xml->questions)) { $tablename = $dbprefix . 'questions'; foreach ($xml->questions->rows->row as $row) { $insertdata = array(); foreach ($row as $key => $value) { $insertdata[(string) $key] = (string) $value; } $oldsid = $insertdata['sid']; $insertdata['sid'] = $newsid; if (!isset($aGIDReplacements[$insertdata['gid']]) || trim($insertdata['title']) == '') { continue; } // Skip questions with invalid group id $insertdata['gid'] = $aGIDReplacements[$insertdata['gid']]; $oldqid = $insertdata['qid']; unset($insertdata['qid']); // save the old qid // now translate any links $insertdata['title'] = translink('survey', $oldsid, $newsid, $insertdata['title']); $insertdata['question'] = translink('survey', $oldsid, $newsid, $insertdata['question']); $insertdata['help'] = translink('survey', $oldsid, $newsid, $insertdata['help']); // Insert the new question if (isset($aQIDReplacements[$oldqid])) { $insertdata['qid'] = $aQIDReplacements[$oldqid]; db_switchIDInsert('questions', true); } $query = $connect->GetInsertSQL($tablename, $insertdata); $result = $connect->Execute($query) or safe_die($clang->gT("Error") . ": Failed to insert data<br />{$query}<br />\n" . $connect->ErrorMsg()); if (!isset($aQIDReplacements[$oldqid])) { $newqid = $connect->Insert_ID($tablename, "qid"); // save this for later $aQIDReplacements[$oldqid] = $newqid; // add old and new qid to the mapping array $results['questions']++; } else { db_switchIDInsert('questions', false); } } } // Import subquestions -------------------------------------------------------------- if (isset($xml->subquestions)) { $tablename = $dbprefix . 'questions'; foreach ($xml->subquestions->rows->row as $row) { $insertdata = array(); foreach ($row as $key => $value) { $insertdata[(string) $key] = (string) $value; } $insertdata['sid'] = $newsid; if (!isset($aGIDReplacements[$insertdata['gid']])) { continue; } // Skip questions with invalid group id $insertdata['gid'] = $aGIDReplacements[(int) $insertdata['gid']]; $oldsqid = (int) $insertdata['qid']; unset($insertdata['qid']); // save the old qid $insertdata['parent_qid'] = $aQIDReplacements[(int) $insertdata['parent_qid']]; // remap the parent_qid // now translate any links $insertdata['title'] = translink('survey', $oldsid, $newsid, $insertdata['title']); $insertdata['question'] = translink('survey', $oldsid, $newsid, $insertdata['question']); $insertdata['help'] = translink('survey', $oldsid, $newsid, $insertdata['help']); if (isset($aQIDReplacements[$oldsqid])) { $insertdata['qid'] = $aQIDReplacements[$oldsqid]; db_switchIDInsert('questions', true); } $query = $connect->GetInsertSQL($tablename, $insertdata); $result = $connect->Execute($query) or safe_die($clang->gT("Error") . ": Failed to insert data<br />{$query}<br />\n" . $connect->ErrorMsg()); $newsqid = $connect->Insert_ID($tablename, "qid"); // save this for later if (!isset($insertdata['qid'])) { $aQIDReplacements[$oldsqid] = $newsqid; // add old and new qid to the mapping array } else { db_switchIDInsert('questions', false); } $results['subquestions']++; } } // Import answers -------------------------------------------------------------- if (isset($xml->answers)) { $tablename = $dbprefix . 'answers'; foreach ($xml->answers->rows->row as $row) { $insertdata = array(); foreach ($row as $key => $value) { $insertdata[(string) $key] = (string) $value; } if (!isset($aQIDReplacements[(int) $insertdata['qid']])) { continue; } // Skip questions with invalid group id $insertdata['qid'] = $aQIDReplacements[(int) $insertdata['qid']]; // remap the parent_qid // now translate any links $query = $connect->GetInsertSQL($tablename, $insertdata); $result = $connect->Execute($query) or safe_die($clang->gT("Error") . ": Failed to insert data<br />{$query}<br />\n" . $connect->ErrorMsg()); $results['answers']++; } } // Import questionattributes -------------------------------------------------------------- if (isset($xml->question_attributes)) { $tablename = $dbprefix . 'question_attributes'; foreach ($xml->question_attributes->rows->row as $row) { $insertdata = array(); foreach ($row as $key => $value) { $insertdata[(string) $key] = (string) $value; } unset($insertdata['qaid']); if (!isset($aQIDReplacements[(int) $insertdata['qid']])) { continue; } // Skip questions with invalid group id $insertdata['qid'] = $aQIDReplacements[(int) $insertdata['qid']]; // remap the parent_qid // now translate any links $query = $connect->GetInsertSQL($tablename, $insertdata); $result = $connect->Execute($query); $results['question_attributes']++; } } // Import defaultvalues -------------------------------------------------------------- if (isset($xml->defaultvalues)) { $tablename = $dbprefix . 'defaultvalues'; $results['defaultvalues'] = 0; foreach ($xml->defaultvalues->rows->row as $row) { $insertdata = array(); foreach ($row as $key => $value) { $insertdata[(string) $key] = (string) $value; } $insertdata['qid'] = $aQIDReplacements[(int) $insertdata['qid']]; // remap the qid if (isset($aQIDReplacements[(int) $insertdata['sqid']])) { $insertdata['sqid'] = $aQIDReplacements[(int) $insertdata['sqid']]; } // remap the subquestion id // now translate any links $query = $connect->GetInsertSQL($tablename, $insertdata); $result = $connect->Execute($query) or safe_die($clang->gT("Error") . ": Failed to insert data<br />\$query<br />\n" . $connect->ErrorMsg()); $results['defaultvalues']++; } } // At this point we know the new/old SID, GIDs, QIDs and we are able to build // the aray mapping old and new fieldnames // this will be usefull in order to translate conditions cfieldname and @SGQA@ codes, as well as INSERTANS links. $aOldNewFieldmap = aReverseTranslateFieldnames($oldsid, $newsid, $aGIDReplacements, $aQIDReplacements); // Import conditions -------------------------------------------------------------- if (isset($xml->conditions)) { $tablename = $dbprefix . 'conditions'; $results['conditions'] = 0; foreach ($xml->conditions->rows->row as $row) { $insertdata = array(); foreach ($row as $key => $value) { $insertdata[(string) $key] = (string) $value; } // replace the qid for the new one (if there is no new qid in the $aQIDReplacements array it mean that this condition is orphan -> error, skip this record) if (isset($aQIDReplacements[$insertdata['qid']])) { $insertdata['qid'] = $aQIDReplacements[$insertdata['qid']]; // remap the qid } else { continue; } // a problem with this answer record -> don't consider if (isset($aQIDReplacements[$insertdata['cqid']])) { $oldcqid = $insertdata['cqid']; $insertdata['cqid'] = $aQIDReplacements[$insertdata['cqid']]; // remap the qid } else { continue; } // a problem with this answer record -> don't consider // replace the old cfieldname by the new one // first get the cfieldname without optionnal leading Meta-character // (see Multiple-options (single checkbox) preg_match("/^(\\+{0,1})(.*)\$/", $insertdata["cfieldname"], $insertedCfieldname); if (isset($aOldNewFieldmap[$insertedCfieldname[2]])) { if ($insertedCfieldname[1] == "+") { // this is a single-checkbox cfieldname in the form +SGQA $newcfieldname = '+' . $aOldNewFieldmap[$insertedCfieldname[2]]; } else { // this is a normal cfieldname in the form SGQ or SGQA // in the case of Multiple-options, this can be a virtual global // cfieldname grouping all checkboxes (in the form SGQ) $newcfieldname = $aOldNewFieldmap[$insertdata["cfieldname"]]; } $insertdata["cfieldname"] = $newcfieldname; } else { //error_log("TIBO: oldcfieldname={$insertdata["cfieldname"]}//{$insertedCfieldname[2]} can't be found in aOldNewFieldmap"); continue; // a problem with cfieldname mapping -> don't consider } if (preg_match("/^@(.*)@\$/", $insertdata["value"], $cfieldnameInCondValue)) { if (isset($aOldNewFieldmap[$cfieldnameInCondValue[1]])) { $newvalue = '@' . $aOldNewFieldmap[$cfieldnameInCondValue[1]] . '@'; $insertdata["value"] = $newvalue; } else { //error_log("TIBO2: oldvalue=@..{$cfieldnameInCondValue[1]}..@ can't be found in aOldNewFieldmap"); continue; // a problem with cfieldname mapping -> don't consider } } if (trim($insertdata["method"]) == '') { $insertdata["method"] = '=='; } unset($insertdata["cid"]); $query = $connect->GetInsertSQL($tablename, $insertdata); $result = $connect->Execute($query) or safe_die($clang->gT("Error") . ": Failed to insert data<br />\$query<br />\n" . $connect->ErrorMsg()); $results['conditions']++; } } // Import assessments -------------------------------------------------------------- if (isset($xml->assessments)) { $tablename = $dbprefix . 'assessments'; foreach ($xml->assessments->rows->row as $row) { $insertdata = array(); foreach ($row as $key => $value) { $insertdata[(string) $key] = (string) $value; } if ($insertdata['gid'] > 0) { $insertdata['gid'] = $aGIDReplacements[(int) $insertdata['gid']]; // remap the qid } $insertdata['sid'] = $newsid; // remap the survey id // now translate any links $query = $connect->GetInsertSQL($tablename, $insertdata); $result = $connect->Execute($query) or safe_die($clang->gT("Error") . ": Failed to insert data<br />\$query<br />\n" . $connect->ErrorMsg()); $results['assessments']++; } } // Import quota -------------------------------------------------------------- if (isset($xml->quota)) { $tablename = $dbprefix . 'quota'; foreach ($xml->quota->rows->row as $row) { $insertdata = array(); foreach ($row as $key => $value) { $insertdata[(string) $key] = (string) $value; } $insertdata['sid'] = $newsid; // remap the survey id $oldid = $insertdata['id']; unset($insertdata['id']); // now translate any links $query = $connect->GetInsertSQL($tablename, $insertdata); $result = $connect->Execute($query) or safe_die($clang->gT("Error") . ": Failed to insert data<br />\$query<br />\n" . $connect->ErrorMsg()); $aQuotaReplacements[$oldid] = $connect->Insert_ID(db_table_name_nq('quota'), "id"); $results['quota']++; } } // Import quota_members -------------------------------------------------------------- if (isset($xml->quota_members)) { $tablename = $dbprefix . 'quota_members'; foreach ($xml->quota_members->rows->row as $row) { $insertdata = array(); foreach ($row as $key => $value) { $insertdata[(string) $key] = (string) $value; } $insertdata['sid'] = $newsid; // remap the survey id $insertdata['qid'] = $aQIDReplacements[(int) $insertdata['qid']]; // remap the qid $insertdata['quota_id'] = $aQuotaReplacements[(int) $insertdata['quota_id']]; // remap the qid unset($insertdata['id']); // now translate any links $query = $connect->GetInsertSQL($tablename, $insertdata); $result = $connect->Execute($query) or safe_die($clang->gT("Error") . ": Failed to insert data<br />\$query<br />\n" . $connect->ErrorMsg()); $results['quotamembers']++; } } // Import quota_languagesettings -------------------------------------------------------------- if (isset($xml->quota_languagesettings)) { $tablename = $dbprefix . 'quota_languagesettings'; foreach ($xml->quota_languagesettings->rows->row as $row) { $insertdata = array(); foreach ($row as $key => $value) { $insertdata[(string) $key] = (string) $value; } $insertdata['quotals_quota_id'] = $aQuotaReplacements[(int) $insertdata['quotals_quota_id']]; // remap the qid unset($insertdata['quotals_id']); // now translate any links $query = $connect->GetInsertSQL($tablename, $insertdata); $result = $connect->Execute($query) or safe_die($clang->gT("Error") . ": Failed to insert data<br />\$query<br />\n" . $connect->ErrorMsg()); $results['quotals']++; } } // Set survey rights $sQuery = "INSERT INTO {$dbprefix}surveys_rights (sid, uid, edit_survey_property, define_questions, browse_response, export, delete_survey, activate_survey) VALUES({$newsid}," . $_SESSION['loginID'] . ",1,1,1,1,1,1)"; $connect->Execute($sQuery); if ($bTranslateInsertansTags) { if (isset($aOldNewFieldmap)) { // It should be set anyway ! TranslateInsertansTags($newsid, $oldsid, $aOldNewFieldmap); } } return $results; }