Exemplo n.º 1
0
function CSVImportLabelset($sFullFilepath, $options)
{
    global $dbprefix, $connect, $clang;
    $results['labelsets'] = 0;
    $results['labels'] = 0;
    $results['warnings'] = array();
    $csarray = buildLabelSetCheckSumArray();
    //$csarray is now a keyed array with the Checksum of each of the label sets, and the lid as the key
    $handle = fopen($sFullFilepath, "r");
    while (!feof($handle)) {
        $buffer = fgets($handle);
        //To allow for very long survey welcomes (up to 10k)
        $bigarray[] = $buffer;
    }
    fclose($handle);
    if (substr($bigarray[0], 0, 27) != "# LimeSurvey Label Set Dump" && substr($bigarray[0], 0, 28) != "# PHPSurveyor Label Set Dump") {
        $results['fatalerror'] = $clang->gT("This file is not a LimeSurvey label set file. Import failed.");
        return $results;
    }
    for ($i = 0; $i < 9; $i++) {
        unset($bigarray[$i]);
    }
    $bigarray = array_values($bigarray);
    //LABEL SETS
    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
    $stoppoint = count($bigarray) - 1;
    for ($i = 0; $i < $stoppoint; $i++) {
        // do not import empty lines
        if (trim($bigarray[$i]) != '') {
            $labelsarray[] = $bigarray[$i];
        }
        unset($bigarray[$i]);
    }
    $countlabelsets = count($labelsetsarray) - 1;
    $countlabels = count($labelsarray) - 1;
    if (isset($labelsetsarray) && $labelsetsarray) {
        $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
            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);
            $results['labelsets']++;
            // Get the new insert id for the labels inside this labelset
            $newlid = $connect->Insert_ID("{$dbprefix}labelsets", 'lid');
            if ($labelsarray) {
                $count = 0;
                $lfieldorders = convertCSVRowToArray($labelsarray[0], ',', '"');
                unset($labelsarray[0]);
                foreach ($labelsarray as $la) {
                    $lfieldcontents = convertCSVRowToArray($la, ',', '"');
                    // Combine into one array with keys and values since its easier to handle
                    $labelrowdata = array_combine($lfieldorders, $lfieldcontents);
                    $labellid = $labelrowdata['lid'];
                    if ($labellid == $oldlid) {
                        $labelrowdata['lid'] = $newlid;
                        // translate internal links
                        $labelrowdata['title'] = translink('label', $oldlid, $newlid, $labelrowdata['title']);
                        if (!isset($labelrowdata["assessment_value"])) {
                            $labelrowdata["assessment_value"] = (int) $labelrowdata["code"];
                        }
                        $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);
                        $results['labels']++;
                    }
                }
            }
            //CHECK FOR DUPLICATE LABELSETS
            if (isset($_POST['checkforduplicates'])) {
                $thisset = "";
                $query2 = "SELECT code, title, sortorder, language, assessment_value\n                           FROM " . db_table_name('labels') . "\n                           WHERE lid=" . $newlid . "\n                           ORDER BY language, sortorder, code";
                $result2 = db_execute_num($query2) or safe_die("Died querying labelset {$lid}<br />{$query2}<br />" . $connect->ErrorMsg());
                while ($row2 = $result2->FetchRow()) {
                    $thisset .= implode('.', $row2);
                }
                // while
                $newcs = dechex(crc32($thisset) * 1);
                unset($lsmatch);
                if (isset($csarray) && $options['checkforduplicates'] == 'on') {
                    foreach ($csarray as $key => $val) {
                        //			echo $val."-".$newcs."<br/>";  For debug purposes
                        if ($val == $newcs) {
                            $lsmatch = $key;
                        }
                    }
                }
                if (isset($lsmatch)) {
                    //There is a matching labelset. So, we will delete this one and refer
                    //to the matched one.
                    $query = "DELETE FROM {$dbprefix}labels WHERE lid={$newlid}";
                    $result = $connect->Execute($query) or safe_die("Couldn't delete labels<br />{$query}<br />" . $connect->ErrorMsg());
                    $query = "DELETE FROM {$dbprefix}labelsets WHERE lid={$newlid}";
                    $result = $connect->Execute($query) or safe_die("Couldn't delete labelset<br />{$query}<br />" . $connect->ErrorMsg());
                    $newlid = $lsmatch;
                    $results['warnings'][] = $clang->gT("Label set was not imported because the same label set already exists.") . " " . sprintf($clang->gT("Existing LID: %s"), $newlid);
                }
                //END CHECK FOR DUPLICATES
            }
        }
    }
    return $results;
}
Exemplo n.º 2
0
 /**
  *
  * Enter description here...
  * @param $surveyid
  * @param $sMod
  * @param $newGroup
  * @return unknown_type
  */
 function importQuestion($surveyid, $sMod, $newGroup = false)
 {
     global $connect;
     global $dbprefix;
     $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
     include "lsrc.config.php";
     $newsid = $surveyid;
     $this->debugLsrc("wir sind in " . __FUNCTION__ . " Line " . __LINE__ . ", START OK {$dbprefix} ");
     //$getGidSql = "SELECT gid FROM {$dbprefix}  ";
     $getGidSql = "SELECT gid\r\n\t                   FROM {$dbprefix}groups \r\n\t                   WHERE sid=" . $surveyid . " AND language='" . GetBaseLanguageFromSurveyID($surveyid) . "'\r\n\t                   ORDER BY gid desc ";
     $getGidRs = db_execute_num($getGidSql);
     $gidRow = $getGidRs->FetchRow();
     $gid = $gidRow[0];
     if ($gid == '') {
         $this->debugLsrc("No Group for importing the question, available!");
         return "No Group for importing the question, available! Import failed.";
     }
     if ($newGroup === true) {
         ++$gid;
     }
     $the_full_file_path = $queDir . $sMod . ".csv";
     $this->debugLsrc("wir sind in " . __FILE__ . " - " . __FUNCTION__ . " Line " . __LINE__ . ", OK {$the_full_file_path} ");
     $handle = fopen($the_full_file_path, "r");
     while (!feof($handle)) {
         $buffer = fgets($handle, 10240);
         //To allow for very long survey welcomes (up to 10k)
         $bigarray[] = $buffer;
     }
     fclose($handle);
     // Now we try to determine the dataformat of the survey file.
     if (substr($bigarray[1], 0, 24) == "# SURVEYOR QUESTION DUMP" && substr($bigarray[4], 0, 29) == "# http://www.phpsurveyor.org/") {
         $importversion = 100;
         // version 1.0 file
     } elseif (substr($bigarray[1], 0, 24) == "# SURVEYOR QUESTION 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, 26) == "# LimeSurvey Question Dump" || substr($bigarray[0], 0, 27) == "# PHPSurveyor Question 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 {
         //		      $importquestion .= "<strong><font color='red'>".("Error")."</font></strong>\n";
         //		      $importquestion .= ("This file is not a LimeSurvey question file. Import failed.")."\n";
         //		      $importquestion .= "</font></td></tr></table>\n";
         //		      $importquestion .= "</body>\n</html>\n";
         //		      unlink($the_full_file_path);
         return "This is not a Limesurvey question file. Import failed";
     }
     //		if ($importversion != $dbversionnumber)
     //		{
     ////		    $importquestion .= "<strong><font color='red'>".("Error")."</font></strong>\n";
     ////		    $importquestion .= ("Sorry, importing questions is limited to the same version. Import failed.")."\n";
     ////		    $importquestion .= "</font></td></tr></table>\n";
     ////		    $importquestion .= "</body>\n</html>\n";
     ////		    unlink($the_full_file_path);
     //		    return;
     //		}
     $this->debugLsrc("wir sind in " . __FILE__ . " - " . __FUNCTION__ . " Line " . __LINE__ . ", OK ");
     for ($i = 0; $i < 9; $i++) {
         unset($bigarray[$i]);
     }
     $bigarray = array_values($bigarray);
     $this->debugLsrc("wir sind in " . __FILE__ . " - " . __FUNCTION__ . " Line " . __LINE__ . ", OK ");
     //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);
     $this->debugLsrc("wir sind in " . __FILE__ . " - " . __FUNCTION__ . " Line " . __LINE__ . ", OK ");
     //ANSWERS
     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 {
         $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);
     $this->debugLsrc("wir sind in " . __FILE__ . " - " . __FUNCTION__ . " Line " . __LINE__ . ", OK ");
     //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);
     $this->debugLsrc("wir sind in " . __FILE__ . " - " . __FUNCTION__ . " Line " . __LINE__ . ", OK ");
     //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);
     $this->debugLsrc("wir sind in " . __FILE__ . " - " . __FUNCTION__ . " Line " . __LINE__ . ", OK ");
     //Question_attributes
     if (!isset($noconditions) || $noconditions != "Y") {
         $stoppoint = count($bigarray);
         for ($i = 0; $i <= $stoppoint + 1; $i++) {
             if ($i < $stoppoint - 1) {
                 $question_attributesarray[] = $bigarray[$i];
             }
             unset($bigarray[$i]);
         }
     }
     $bigarray = array_values($bigarray);
     if (isset($questionarray)) {
         $countquestions = count($questionarray) - 1;
     } else {
         $countquestions = 0;
     }
     if (isset($answerarray)) {
         $answerfieldnames = convertCSVRowToArray($answerarray[0], ',', '"');
         unset($answerarray[0]);
         $countanswers = count($answerarray);
     } else {
         $countanswers = 0;
     }
     if (isset($labelsetsarray)) {
         $countlabelsets = count($labelsetsarray) - 1;
     } else {
         $countlabelsets = 0;
     }
     if (isset($labelsarray)) {
         $countlabels = count($labelsarray) - 1;
     } else {
         $countlabels = 0;
     }
     if (isset($question_attributesarray)) {
         $countquestion_attributes = count($question_attributesarray) - 1;
     } else {
         $countquestion_attributes = 0;
     }
     $languagesSupported = array();
     // this array will keep all the languages supported for the survey
     // Let's check that imported objects support at least the survey's baselang
     $langcode = GetBaseLanguageFromSurveyID($surveyid);
     $languagesSupported[$langcode] = 1;
     // adds the base language to the list of supported languages
     $this->debugLsrc("wir sind in " . __FILE__ . " - " . __FUNCTION__ . " Line " . __LINE__ . ", OK ");
     if ($countquestions > 0) {
         $questionfieldnames = convertCSVRowToArray($questionarray[0], ',', '"');
         $langfieldnum = array_search("language", $questionfieldnames);
         $qidfieldnum = array_search("qid", $questionfieldnames);
         $questionssupportbaselang = bDoesImportarraySupportsLanguage($questionarray, array($qidfieldnum), $langfieldnum, $langcode, true);
         if (!$questionssupportbaselang) {
             //				$importquestion .= "<strong><font color='red'>".("Error")."</font></strong>\n"
             //				.("You can't import a question which doesn't support the current survey's base language")."\n"
             //				."</td></tr></table>\n";
             //				unlink($the_full_file_path);
             return "You can't import a question which doesn't support the current survey's base language";
         }
     }
     $this->debugLsrc("wir sind in " . __FILE__ . " - " . __FUNCTION__ . " Line " . __LINE__ . ", OK ");
     foreach (GetAdditionalLanguagesFromSurveyID($surveyid) as $language) {
         $languagesSupported[$language] = 1;
     }
     // Let's assume that if the questions do support tye baselang
     // Then the answers do support it as well.
     // ==> So the following section is commented for now
     //if ($countanswers > 0)
     //{
     //	$langfieldnum = array_search("language", $answerfieldnames);
     //	$answercodefilednum1 =  array_search("qid", $answerfieldnames);
     //	$answercodefilednum2 =  array_search("code", $answerfieldnames);
     //	$answercodekeysarr = Array($answercodefilednum1,$answercodefilednum2);
     //	$answerssupportbaselang = bDoesImportarraySupportsLanguage($answerarray,$answercodekeysarr,$langfieldnum,$langcode);
     //	if (!$answerssupportbaselang)
     //	{
     //		$importquestion .= "<strong><font color='red'>".("Error")."</font></strong>\n"
     //		.("You can't import answers which don't support current survey's base language")."\n"
     //		."</td></tr></table>\n";
     //		return;
     //	}
     //
     //}
     $this->debugLsrc("wir sind in " . __FILE__ . " - " . __FUNCTION__ . " Line " . __LINE__ . ", OK ");
     if ($countlabelsets > 0) {
         $labelsetfieldname = convertCSVRowToArray($labelsetsarray[0], ',', '"');
         $langfieldnum = array_search("languages", $labelsetfieldname);
         $lidfilednum = array_search("lid", $labelsetfieldname);
         $labelsetssupportbaselang = bDoesImportarraySupportsLanguage($labelsetsarray, array($lidfilednum), $langfieldnum, $langcode, true);
         if (!$labelsetssupportbaselang) {
             //				$importquestion .= "<strong><font color='red'>".("Error")."</font></strong>\n"
             //				.("You can't import label sets which don't support the current survey's base language")."\n"
             //				."</td></tr></table>\n";
             //				unlink($the_full_file_path);
             return "You can't import label sets which don't support the current survey's base language";
         }
     }
     // I assume that if a labelset supports the survey's baselang,
     // then it's labels do support it as well
     // GET SURVEY AND GROUP DETAILS
     //$surveyid=$postsid;
     //$gid=$postgid;
     $newsid = $surveyid;
     $newgid = $gid;
     $this->debugLsrc("wir sind in " . __FILE__ . " - " . __FUNCTION__ . " Line " . __LINE__ . ", OK ");
     //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;
         $this->debugLsrc("wir sind in " . __FILE__ . " - " . __FUNCTION__ . " Line " . __LINE__ . ", OK ");
         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
             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");
             if ($labelsarray) {
                 $count = 0;
                 foreach ($labelsarray as $la) {
                     $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);
                     $labellid = $labelrowdata['lid'];
                     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("Died querying labelset {$lid}{$query2}" . $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)) {
                 //There is a matching labelset. 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("Couldn't delete labels{$query}" . $connect->ErrorMsg());
                 $query = "DELETE FROM {$dbprefix}labelsets WHERE lid={$newlid}";
                 $result = $connect->Execute($query) or $this->debugLsrc("Couldn't delete labelset{$query}" . $connect->ErrorMsg());
                 $newlid = $lsmatch;
             } 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 " . __FILE__ . " - " . __FUNCTION__ . " Line " . __LINE__ . ", OK ");
     // QUESTIONS, THEN ANSWERS FOR QUESTIONS IN A NESTED FORMAT!
     if (isset($questionarray) && $questionarray) {
         $qafieldorders = convertCSVRowToArray($questionarray[0], ',', '"');
         unset($questionarray[0]);
         //Assuming we will only import one question at a time we will now find out the maximum question order in this group
         //and save it for later
         $qmaxqo = "SELECT MAX(question_order) AS maxqo FROM " . db_table_name('questions') . " WHERE sid={$newsid} AND gid={$newgid}";
         $qres = db_execute_assoc($qmaxqo) or $this->debugLsrc("Error: " . ": Failed to find out maximum question order value\n{$qmaxqo}\n" . $connect->ErrorMsg());
         $qrow = $qres->FetchRow();
         $newquestionorder = $qrow['maxqo'] + 1;
         $this->debugLsrc("wir sind in " . __FILE__ . " - " . __FUNCTION__ . " Line " . __LINE__ . ", OK ");
         foreach ($questionarray as $qa) {
             $qacfieldcontents = convertCSVRowToArray($qa, ',', '"');
             $newfieldcontents = $qacfieldcontents;
             $questionrowdata = array_combine($qafieldorders, $qacfieldcontents);
             if (isset($languagesSupported[$questionrowdata["language"]])) {
                 $oldqid = $questionrowdata['qid'];
                 $oldsid = $questionrowdata['sid'];
                 $oldgid = $questionrowdata['gid'];
                 // Remove qid field if there is no newqid; and set it to newqid if it's set
                 if (!isset($newqid)) {
                     unset($questionrowdata['qid']);
                 } else {
                     $questionrowdata['qid'] = $newqid;
                 }
                 $questionrowdata["sid"] = $newsid;
                 $questionrowdata["gid"] = $newgid;
                 $questionrowdata["question_order"] = $newquestionorder;
                 $this->debugLsrc("wir sind in " . __FILE__ . " - " . __FUNCTION__ . " Line " . __LINE__ . ", OK ");
                 // Now we will fix up the label id
                 $type = $questionrowdata["type"];
                 //Get the type
                 if ($type == "F" || $type == "H" || $type == "1" || $type == ":" || $type == ";") {
                     //IF this is a flexible label array, update the lid entry
                     $this->debugLsrc("wir sind in " . __FILE__ . " - " . __FUNCTION__ . " Line " . __LINE__ . ", OK ");
                     if (isset($labelreplacements)) {
                         foreach ($labelreplacements as $lrp) {
                             if ($lrp[0] == $questionrowdata["lid"]) {
                                 $questionrowdata["lid"] = $lrp[1];
                             }
                             if ($lrp[0] == $questionrowdata["lid1"]) {
                                 $questionrowdata["lid1"] = $lrp[1];
                             }
                         }
                     }
                 }
                 $other = $questionrowdata["other"];
                 //Get 'other' field value
                 $oldlid = $questionrowdata["lid"];
                 $questionrowdata = array_map('convertCsvreturn2return', $questionrowdata);
                 // translate internal links
                 $questionrowdata['title'] = translink('survey', $oldsid, $newsid, $questionrowdata['title']);
                 $questionrowdata['question'] = translink('survey', $oldsid, $newsid, $questionrowdata['question']);
                 $questionrowdata['help'] = translink('survey', $oldsid, $newsid, $questionrowdata['help']);
                 $newvalues = array_values($questionrowdata);
                 $newvalues = array_map(array(&$connect, "qstr"), $newvalues);
                 // quote everything accordingly
                 $qinsert = "INSERT INTO {$dbprefix}questions (" . implode(',', array_keys($questionrowdata)) . ") VALUES (" . implode(',', $newvalues) . ")";
                 $qres = $connect->Execute($qinsert) or $this->debugLsrc("Error: " . ": Failed to insert question\n{$qinsert}\n" . $connect->ErrorMsg());
                 $this->debugLsrc("wir sind in " . __FILE__ . " - " . __FUNCTION__ . " Line " . __LINE__ . ", OK ");
                 // set the newqid only if is not set
                 if (!isset($newqid)) {
                     $newqid = $connect->Insert_ID("{$dbprefix}questions", "qid");
                 }
             }
         }
         $this->debugLsrc("wir sind in " . __FILE__ . " - " . __FUNCTION__ . " Line " . __LINE__ . ", OK ");
         //NOW DO ANSWERS FOR THIS QID - Is called just once and only if there was a question
         if (isset($answerarray) && $answerarray) {
             foreach ($answerarray as $aa) {
                 $answerfieldcontents = convertCSVRowToArray($aa, ',', '"');
                 $answerrowdata = array_combine($answerfieldnames, $answerfieldcontents);
                 if ($answerrowdata === false) {
                     $importquestion .= '' . "Faulty line in import - fields and data don't match" . ":" . implode(',', $answerfieldcontents);
                 }
                 if (isset($languagesSupported[$answerrowdata["language"]])) {
                     $code = $answerrowdata["code"];
                     $thisqid = $answerrowdata["qid"];
                     $answerrowdata["qid"] = $newqid;
                     // translate internal links
                     $answerrowdata['answer'] = translink('survey', $oldsid, $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("Error: " . ": Failed to insert answer\n{$ainsert}\n" . $connect->ErrorMsg());
                 }
             }
         }
         $this->debugLsrc("wir sind in " . __FILE__ . " - " . __FUNCTION__ . " Line " . __LINE__ . ", OK ");
         // Finally the question attributes - Is called just once and only if there was a question
         if (isset($question_attributesarray) && $question_attributesarray) {
             //ONLY DO THIS IF THERE ARE QUESTION_ATTRIBUES
             $fieldorders = convertCSVRowToArray($question_attributesarray[0], ',', '"');
             unset($question_attributesarray[0]);
             foreach ($question_attributesarray as $qar) {
                 $fieldcontents = convertCSVRowToArray($qar, ',', '"');
                 $qarowdata = array_combine($fieldorders, $fieldcontents);
                 $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("Couldn't insert question_attribute{$qainsert}" . $connect->ErrorMsg());
             }
         }
     }
     $this->debugLsrc("wir sind in - " . __FUNCTION__ . " Line " . __LINE__ . ", FERTIG ");
     // CONDITIONS is DONE
     return array('gid' => $newgid, 'qid' => $newqid);
     //return $newgid;
 }
Exemplo n.º 3
0
/**
* 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;
}
Exemplo n.º 4
0
/**
* 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;
}
Exemplo n.º 5
0
/**
* 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;
}
Exemplo n.º 6
0
/**
* 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;
}