Ejemplo n.º 1
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;
}
Ejemplo n.º 2
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;
}