示例#1
0
/**
* This function imports an old-school question group file (*.csv,*.sql)
*
* @param mixed $sFullFilepath Full file patch to the import file
* @param mixed $iNewSID  Survey ID to which the question is attached
*/
function CSVImportGroup($sFullFilepath, $iNewSID)
{
    $clang = Yii::app()->lang;
    $aLIDReplacements = array();
    $aQIDReplacements = array();
    // this array will have the "new qid" for the questions, the key will be the "old qid"
    $aGIDReplacements = array();
    $handle = fopen($sFullFilepath, "r");
    while (!feof($handle)) {
        $buffer = fgets($handle);
        $bigarray[] = $buffer;
    }
    fclose($handle);
    if (substr($bigarray[0], 0, 23) != "# LimeSurvey Group Dump") {
        $results['fatalerror'] = $clang->gT("This file is not a LimeSurvey question file. Import failed.");
        $importversion = 0;
    } else {
        $importversion = (int) trim(substr($bigarray[1], 12));
    }
    if ((int) $importversion < 112) {
        $results['fatalerror'] = $clang->gT("This file is too old. Only files from LimeSurvey version 1.50 (DBVersion 112) and newer are supported.");
    }
    for ($i = 0; $i < 9; $i++) {
        unset($bigarray[$i]);
    }
    $bigarray = array_values($bigarray);
    //GROUPS
    if (array_search("# QUESTIONS TABLE\n", $bigarray)) {
        $stoppoint = array_search("# QUESTIONS TABLE\n", $bigarray);
    } elseif (array_search("# QUESTIONS TABLE\r\n", $bigarray)) {
        $stoppoint = array_search("# QUESTIONS TABLE\r\n", $bigarray);
    } else {
        $stoppoint = count($bigarray) - 1;
    }
    for ($i = 0; $i <= $stoppoint + 1; $i++) {
        if ($i < $stoppoint - 2) {
            $grouparray[] = $bigarray[$i];
        }
        unset($bigarray[$i]);
    }
    $bigarray = array_values($bigarray);
    //QUESTIONS
    if (array_search("# ANSWERS TABLE\n", $bigarray)) {
        $stoppoint = array_search("# ANSWERS TABLE\n", $bigarray);
    } elseif (array_search("# ANSWERS TABLE\r\n", $bigarray)) {
        $stoppoint = array_search("# ANSWERS TABLE\r\n", $bigarray);
    } else {
        $stoppoint = count($bigarray) - 1;
    }
    for ($i = 0; $i <= $stoppoint + 1; $i++) {
        if ($i < $stoppoint - 2) {
            $questionarray[] = $bigarray[$i];
        }
        unset($bigarray[$i]);
    }
    $bigarray = array_values($bigarray);
    //ANSWERS
    if (array_search("# CONDITIONS TABLE\n", $bigarray)) {
        $stoppoint = array_search("# CONDITIONS TABLE\n", $bigarray);
    } elseif (array_search("# CONDITIONS TABLE\r\n", $bigarray)) {
        $stoppoint = array_search("# CONDITIONS TABLE\r\n", $bigarray);
    } else {
        $stoppoint = count($bigarray) - 1;
    }
    for ($i = 0; $i <= $stoppoint + 1; $i++) {
        if ($i < $stoppoint - 2) {
            $answerarray[] = str_replace("`default`", "`default_value`", $bigarray[$i]);
        }
        unset($bigarray[$i]);
    }
    $bigarray = array_values($bigarray);
    //CONDITIONS
    if (array_search("# LABELSETS TABLE\n", $bigarray)) {
        $stoppoint = array_search("# LABELSETS TABLE\n", $bigarray);
    } elseif (array_search("# LABELSETS TABLE\r\n", $bigarray)) {
        $stoppoint = array_search("# LABELSETS TABLE\r\n", $bigarray);
    }
    for ($i = 0; $i <= $stoppoint + 1; $i++) {
        if ($i < $stoppoint - 2) {
            $conditionsarray[] = $bigarray[$i];
        }
        unset($bigarray[$i]);
    }
    $bigarray = array_values($bigarray);
    //LABELSETS
    if (array_search("# LABELS TABLE\n", $bigarray)) {
        $stoppoint = array_search("# LABELS TABLE\n", $bigarray);
    } elseif (array_search("# LABELS TABLE\r\n", $bigarray)) {
        $stoppoint = array_search("# LABELS TABLE\r\n", $bigarray);
    } else {
        $stoppoint = count($bigarray) - 1;
    }
    for ($i = 0; $i <= $stoppoint + 1; $i++) {
        if ($i < $stoppoint - 2) {
            $labelsetsarray[] = $bigarray[$i];
        }
        unset($bigarray[$i]);
    }
    $bigarray = array_values($bigarray);
    //LABELS
    if (array_search("# QUESTION_ATTRIBUTES TABLE\n", $bigarray)) {
        $stoppoint = array_search("# QUESTION_ATTRIBUTES TABLE\n", $bigarray);
    } elseif (array_search("# QUESTION_ATTRIBUTES TABLE\r\n", $bigarray)) {
        $stoppoint = array_search("# QUESTION_ATTRIBUTES TABLE\r\n", $bigarray);
    } else {
        $stoppoint = count($bigarray) - 1;
    }
    for ($i = 0; $i <= $stoppoint + 1; $i++) {
        if ($i < $stoppoint - 2) {
            $labelsarray[] = $bigarray[$i];
        }
        unset($bigarray[$i]);
    }
    $bigarray = array_values($bigarray);
    //Question attributes
    if (!isset($noconditions) || $noconditions != "Y") {
        // stoppoint is the last line number
        // this is an empty line after the QA CSV lines
        $stoppoint = count($bigarray) - 1;
        for ($i = 0; $i <= $stoppoint + 1; $i++) {
            if ($i <= $stoppoint - 1) {
                $question_attributesarray[] = $bigarray[$i];
            }
            unset($bigarray[$i]);
        }
    }
    $bigarray = array_values($bigarray);
    $countgroups = 0;
    if (isset($questionarray)) {
        $questionfieldnames = convertCSVRowToArray($questionarray[0], ',', '"');
        unset($questionarray[0]);
        $countquestions = 0;
    }
    if (isset($answerarray)) {
        $answerfieldnames = convertCSVRowToArray($answerarray[0], ',', '"');
        unset($answerarray[0]);
        $countanswers = count($answerarray);
    } else {
        $countanswers = 0;
    }
    $aLanguagesSupported = array();
    // this array will keep all the languages supported for the survey
    $sBaseLanguage = Survey::model()->findByPk($iNewSID)->language;
    $aLanguagesSupported[] = $sBaseLanguage;
    // adds the base language to the list of supported languages
    $aLanguagesSupported = array_merge($aLanguagesSupported, Survey::model()->findByPk($iNewSID)->additionalLanguages);
    // Let's check that imported objects support at least the survey's baselang
    $langcode = Survey::model()->findByPk($iNewSID)->language;
    if (isset($grouparray)) {
        $groupfieldnames = convertCSVRowToArray($grouparray[0], ',', '"');
        $langfieldnum = array_search("language", $groupfieldnames);
        $gidfieldnum = array_search("gid", $groupfieldnames);
        $groupssupportbaselang = doesImportArraySupportLanguage($grouparray, array($gidfieldnum), $langfieldnum, $sBaseLanguage, true);
        if (!$groupssupportbaselang) {
            $results['fatalerror'] = $clang->gT("You can't import a group which doesn't support at least the survey base language.");
            return $results;
        }
    }
    if (isset($questionarray)) {
        $langfieldnum = array_search("language", $questionfieldnames);
        $qidfieldnum = array_search("qid", $questionfieldnames);
        $questionssupportbaselang = doesImportArraySupportLanguage($questionarray, array($qidfieldnum), $langfieldnum, $sBaseLanguage, true);
        if (!$questionssupportbaselang) {
            $results['fatalerror'] = $clang->gT("You can't import a question which doesn't support at least the survey base language.");
            return $results;
        }
    }
    if ($countanswers > 0) {
        $langfieldnum = array_search("language", $answerfieldnames);
        $answercodefilednum1 = array_search("qid", $answerfieldnames);
        $answercodefilednum2 = array_search("code", $answerfieldnames);
        $answercodekeysarr = array($answercodefilednum1, $answercodefilednum2);
        $answerssupportbaselang = doesImportArraySupportLanguage($answerarray, $answercodekeysarr, $langfieldnum, $sBaseLanguage);
        if (!$answerssupportbaselang) {
            $results['fatalerror'] = $clang->gT("You can't import answers which doesn't support at least the survey base language.");
            return $results;
        }
    }
    if (count($labelsetsarray) > 1) {
        $labelsetfieldname = convertCSVRowToArray($labelsetsarray[0], ',', '"');
        $langfieldnum = array_search("languages", $labelsetfieldname);
        $lidfilednum = array_search("lid", $labelsetfieldname);
        $labelsetssupportbaselang = doesImportArraySupportLanguage($labelsetsarray, array($lidfilednum), $langfieldnum, $sBaseLanguage, true);
        if (!$labelsetssupportbaselang) {
            $results['fatalerror'] = $clang->gT("You can't import label sets which don't support the current survey's base language");
            return $results;
        }
    }
    // I assume that if a labelset supports the survey's baselang,
    // then it's labels do support it as well
    //DO ANY LABELSETS FIRST, SO WE CAN KNOW WHAT THEIR NEW LID IS FOR THE QUESTIONS
    $results['labelsets'] = 0;
    $qtypes = getQuestionTypeList("", "array");
    $results['labels'] = 0;
    $results['labelsets'] = 0;
    $results['answers'] = 0;
    $results['subquestions'] = 0;
    //Do label sets
    if (isset($labelsetsarray) && $labelsetsarray) {
        $csarray = buildLabelSetCheckSumArray();
        // build checksums over all existing labelsets
        $count = 0;
        foreach ($labelsetsarray as $lsa) {
            $fieldorders = convertCSVRowToArray($labelsetsarray[0], ',', '"');
            $fieldcontents = convertCSVRowToArray($lsa, ',', '"');
            if ($count == 0) {
                $count++;
                continue;
            }
            $labelsetrowdata = array_combine($fieldorders, $fieldcontents);
            // Save old labelid
            $oldlid = $labelsetrowdata['lid'];
            unset($labelsetrowdata['lid']);
            $newvalues = array_values($labelsetrowdata);
            $lsainsert = "INSERT INTO {{labelsets}} (" . implode(',', array_keys($labelsetrowdata)) . ") VALUES (" . implode(',', $newvalues) . ")";
            //handle db prefix
            $lsiresult = Yii::app()->db->createCommand($lsainsert)->query();
            $results['labelsets']++;
            // Get the new insert id for the labels inside this labelset
            $newlid = Yii::app()->db->getCommandBuilder()->getLastInsertID('{{labelsets}}');
            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 ($importversion <= 132) {
                        $labelrowdata["assessment_value"] = (int) $labelrowdata["code"];
                    }
                    if ($labellid == $oldlid) {
                        $labelrowdata['lid'] = $newlid;
                        // translate internal links
                        $labelrowdata['title'] = translateLinks('label', $oldlid, $newlid, $labelrowdata['title']);
                        $newvalues = array_values($labelrowdata);
                        $lainsert = "INSERT INTO {{labels}} (" . implode(',', array_keys($labelrowdata)) . ") VALUES (" . implode(',', $newvalues) . ")";
                        //handle db prefix
                        $liresult = Yii::app()->db->createCommand($lainsert)->query();
                        if ($liresult !== false) {
                            $results['labels']++;
                        }
                    }
                }
            }
            //CHECK FOR DUPLICATE LABELSETS
            $thisset = "";
            $query2 = "SELECT code, title, sortorder, language, assessment_value\n            FROM {{labels}}\n            WHERE lid=" . $newlid . "\n            ORDER BY language, sortorder, code";
            $result2 = Yii::app()->db->createCommand($query2);
            foreach ($result2->readAll() as $row2) {
                $row2 = array_values($row2);
                $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) || Yii::app()->session['USER_RIGHT_MANAGE_LABEL'] != 1) {
                //There is a matching labelset or the user is not allowed to edit labels -
                // So, we will delete this one and refer to the matched one.
                $query = "DELETE FROM {{labels}} WHERE lid={$newlid}";
                $result = Yii::app()->db->createCommand($query)->execute();
                $results['labels'] = $results['labels'] - $result;
                $query = "DELETE FROM {{labelsets}} WHERE lid={$newlid}";
                $result = Yii::app()->db->createCommand($query)->execute();
                $results['labelsets'] = $results['labelsets'] - $result;
                $newlid = $lsmatch;
            } else {
                //There isn't a matching labelset, add this checksum to the $csarray array
                $csarray[$newlid] = $newcs;
            }
            //END CHECK FOR DUPLICATES
            $aLIDReplacements[$oldlid] = $newlid;
        }
    }
    // Import groups
    if (isset($grouparray) && $grouparray) {
        // do GROUPS
        $gafieldorders = convertCSVRowToArray($grouparray[0], ',', '"');
        unset($grouparray[0]);
        $newgid = 0;
        $group_order = 0;
        // just to initialize this variable
        foreach ($grouparray as $ga) {
            $gacfieldcontents = convertCSVRowToArray($ga, ',', '"');
            $grouprowdata = array_combine($gafieldorders, $gacfieldcontents);
            // Skip not supported languages
            if (!in_array($grouprowdata['language'], $aLanguagesSupported)) {
                $skippedlanguages[] = $grouprowdata['language'];
                // this is for the message in the end.
                continue;
            }
            // replace the sid
            $iOldSID = $grouprowdata['sid'];
            $grouprowdata['sid'] = $iNewSID;
            // replace the gid  or remove it if needed (it also will calculate the group order if is a new group)
            $oldgid = $grouprowdata['gid'];
            if ($newgid == 0) {
                unset($grouprowdata['gid']);
                // find the maximum group order and use this grouporder+1 to assign it to the new group
                $qmaxgo = "select max(group_order) as maxgo from {{groups}} where sid={$iNewSID}";
                $gres = Yii::app()->db->createCommand($qmaxgo)->query();
                $grow = $gres->read();
                $group_order = $grow['maxgo'] + 1;
            } else {
                $grouprowdata['gid'] = $newgid;
            }
            $grouprowdata["group_order"] = $group_order;
            // Everything set - now insert it
            $grouprowdata = array_map('convertCSVReturnToReturn', $grouprowdata);
            // translate internal links
            $grouprowdata['group_name'] = translateLinks('survey', $iOldSID, $iNewSID, $grouprowdata['group_name']);
            $grouprowdata['description'] = translateLinks('survey', $iOldSID, $iNewSID, $grouprowdata['description']);
            $gres = Yii::app()->db->createCommand()->insert('{{groups}}', $grouprowdata);
            //GET NEW GID  .... if is not done before and we count a group if a new gid is required
            if ($newgid == 0) {
                $newgid = Yii::apps()->db->getCommandBuilder()->getLastInsertID('{{groups}}');
                $countgroups++;
            }
        }
        // GROUPS is DONE
        // Import questions
        if (isset($questionarray) && $questionarray) {
            foreach ($questionarray as $qa) {
                $qacfieldcontents = convertCSVRowToArray($qa, ',', '"');
                $questionrowdata = array_combine($questionfieldnames, $qacfieldcontents);
                $questionrowdata = array_map('convertCSVReturnToReturn', $questionrowdata);
                $questionrowdata["type"] = strtoupper($questionrowdata["type"]);
                // Skip not supported languages
                if (!in_array($questionrowdata['language'], $aLanguagesSupported)) {
                    continue;
                }
                // replace the sid
                $questionrowdata["sid"] = $iNewSID;
                // replace the gid (if the gid is not in the oldgid it means there is a problem with the exported record, so skip it)
                if ($questionrowdata['gid'] == $oldgid) {
                    $questionrowdata['gid'] = $newgid;
                } else {
                    continue;
                }
                // a problem with this question record -> don't consider
                if (isset($aQIDReplacements[$questionrowdata['qid']])) {
                    $questionrowdata['qid'] = $aQIDReplacements[$questionrowdata['qid']];
                } else {
                    $oldqid = $questionrowdata['qid'];
                    unset($questionrowdata['qid']);
                }
                // Save the following values - will need them for proper conversion later                if ((int)$questionrowdata['lid']>0)
                unset($oldlid1);
                unset($oldlid2);
                if (isset($questionrowdata['lid']) && $questionrowdata['lid'] > 0) {
                    $oldlid1 = $questionrowdata['lid'];
                }
                if (isset($questionrowdata['lid1']) && $questionrowdata['lid1'] > 0) {
                    $oldlid2 = $questionrowdata['lid1'];
                }
                unset($questionrowdata['lid']);
                unset($questionrowdata['lid1']);
                if ($questionrowdata['type'] == 'W') {
                    $questionrowdata['type'] = '!';
                } elseif ($questionrowdata['type'] == 'Z') {
                    $questionrowdata['type'] = 'L';
                }
                if (!isset($questionrowdata["question_order"]) || $questionrowdata["question_order"] == '') {
                    $questionrowdata["question_order"] = 0;
                }
                $questionrowdata = array_map('convertCSVReturnToReturn', $questionrowdata);
                // translate internal links
                $questionrowdata['title'] = translateLinks('survey', $iOldSID, $iNewSID, $questionrowdata['title']);
                $questionrowdata['question'] = translateLinks('survey', $iOldSID, $iNewSID, $questionrowdata['question']);
                $questionrowdata['help'] = translateLinks('survey', $iOldSID, $iNewSID, $questionrowdata['help']);
                $newvalues = array_values($questionrowdata);
                $qres = Yii::app()->db->createCommand()->insert('{{questions}}', $questionrowdata);
                $results['questions']++;
                //GET NEW QID  .... if is not done before and we count a question if a new qid is required
                if (isset($questionrowdata['qid'])) {
                    $saveqid = $questionrowdata['qid'];
                } else {
                    $aQIDReplacements[$oldqid] = Yii::app()->db->getCommandBuilder()->getLastInsertID('{{questions}}');
                    $saveqid = $aQIDReplacements[$oldqid];
                }
                $qtypes = getQuestionTypeList("", "array");
                $aSQIDReplacements = array();
                // Now we will fix up old label sets where they are used as answers
                if ((isset($oldlid1) || isset($oldlid2)) && ($qtypes[$questionrowdata['type']]['answerscales'] > 0 || $qtypes[$questionrowdata['type']]['subquestions'] > 1)) {
                    $query = "select * from {{labels}} where lid={$aLIDReplacements[$oldlid1]} and language='{$questionrowdata['language']}'";
                    $oldlabelsresult = Yii::app()->db->createCommand($query)->query();
                    foreach ($oldlabelsresult->readAll() as $labelrow) {
                        if (in_array($labelrow['language'], $aLanguagesSupported)) {
                            if ($qtypes[$questionrowdata['type']]['subquestions'] < 2) {
                                $qinsert = "insert INTO {{answers}} (qid,code,answer,sortorder,language,assessment_value)\n                                VALUES ({$aQIDReplacements[$oldqid]},'" . $labelrow['code'] . "','" . $labelrow['title'] . "','" . $labelrow['sortorder'] . "','" . $labelrow['language'] . "','" . $labelrow['assessment_value'] . "')";
                                $qres = Yii::app()->db->createCommand($qinsert)->query() or safeDie($clang->gT("Error") . ": Failed to insert answer (lid1) <br />\n{$qinsert}<br />\n");
                            } else {
                                if (isset($aSQIDReplacements[$labelrow['code'] . '_' . $saveqid])) {
                                    $fieldname = 'qid,';
                                    $data = $aSQIDReplacements[$labelrow['code'] . '_' . $saveqid] . ',';
                                } else {
                                    $fieldname = '';
                                    $data = '';
                                }
                                $qinsert = "insert INTO {{questions}} ({$fieldname} parent_qid,title,question,question_order,language,scale_id,type, sid, gid)\n                                VALUES ({$data}{$aQIDReplacements[$oldqid]},'" . $labelrow['code'] . "','" . $labelrow['title'] . "','" . $labelrow['sortorder'] . "','" . $labelrow['language'] . "',1,'{$questionrowdata['type']}',{$questionrowdata['sid']},{$questionrowdata['gid']})";
                                $qres = Yii::app()->db->createCommand($qinsert)->query() or safeDie($clang->gT("Error") . ": Failed to insert question <br />\n{$qinsert}<br />\n");
                                if ($fieldname == '') {
                                    $aSQIDReplacements[$labelrow['code'] . '_' . $saveqid] = Yii::app()->db->getCommandBuilder()->getLastInsertID('{{questions}}');
                                }
                            }
                        }
                    }
                    if (isset($oldlid2) && $qtypes[$questionrowdata['type']]['answerscales'] > 1) {
                        $query = "select * from {{labels}} where lid={$aLIDReplacements[$oldlid2]} and language='{$questionrowdata['language']}'";
                        $oldlabelsresult = Yii::app()->db->createCommand($query)->query();
                        foreach ($oldlabelsresult->readAll() as $labelrow) {
                            $qinsert = "insert INTO {{answers}} (qid,code,answer,sortorder,language,assessment_value,scale_id)\n                            VALUES ({$aQIDReplacements[$oldqid]},'" . $labelrow['code'] . "','" . $labelrow['title'] . "','" . $labelrow['sortorder'] . "','" . $labelrow['language'] . "','" . $labelrow['assessment_value'] . "',1)";
                            $qres = Yii::app()->db->createCommand($qinsert)->query() or safeDie($clang->gT("Error") . ": Failed to insert answer (lid2)<br />\n{$qinsert}<br />\n");
                        }
                    }
                }
            }
        }
        //Do answers
        $results['subquestions'] = 0;
        if (isset($answerarray) && $answerarray) {
            foreach ($answerarray as $aa) {
                $answerfieldcontents = convertCSVRowToArray($aa, ',', '"');
                $answerrowdata = array_combine($answerfieldnames, $answerfieldcontents);
                if ($answerrowdata === false) {
                    $importquestion .= '<br />' . $clang->gT("Faulty line in import - fields and data don't match") . ":" . implode(',', $answerfieldcontents);
                }
                // Skip not supported languages
                if (!in_array($answerrowdata['language'], $aLanguagesSupported)) {
                    continue;
                }
                // replace the qid for the new one (if there is no new qid in the $aQIDReplacements array it mean that this answer is orphan -> error, skip this record)
                if (isset($aQIDReplacements[$answerrowdata["qid"]])) {
                    $answerrowdata["qid"] = $aQIDReplacements[$answerrowdata["qid"]];
                } else {
                    continue;
                }
                // a problem with this answer record -> don't consider
                if ($importversion <= 132) {
                    $answerrowdata["assessment_value"] = (int) $answerrowdata["code"];
                }
                // Convert default values for single select questions
                $query = 'select type,gid from {{questions}} where qid=' . $answerrowdata["qid"];
                $res = Yii::app()->db->createCommand($query)->query();
                $questiontemp = $res->read();
                $oldquestion['newtype'] = $questiontemp['type'];
                $oldquestion['gid'] = $questiontemp['gid'];
                if ($answerrowdata['default_value'] == 'Y' && ($oldquestion['newtype'] == 'L' || $oldquestion['newtype'] == 'O' || $oldquestion['newtype'] == '!')) {
                    $insertdata = array();
                    $insertdata['qid'] = $newqid;
                    $insertdata['language'] = $answerrowdata['language'];
                    $insertdata['defaultvalue'] = $answerrowdata['answer'];
                    $qres = Yii::app()->db->createCommand()->insert('{{defaultvalues}}', $insertdata);
                }
                // translate internal links
                $answerrowdata['answer'] = translateLinks('survey', $iOldSID, $iNewSID, $answerrowdata['answer']);
                // Everything set - now insert it
                $answerrowdata = array_map('convertCSVReturnToReturn', $answerrowdata);
                if ($qtypes[$oldquestion['newtype']]['subquestions'] > 0) {
                    $questionrowdata = array();
                    if (isset($aSQIDReplacements[$answerrowdata['code'] . $answerrowdata['qid']])) {
                        $questionrowdata['qid'] = $aSQIDReplacements[$answerrowdata['code'] . $answerrowdata['qid']];
                    }
                    $questionrowdata['parent_qid'] = $answerrowdata['qid'];
                    $questionrowdata['sid'] = $iNewSID;
                    $questionrowdata['gid'] = $oldquestion['gid'];
                    $questionrowdata['title'] = $answerrowdata['code'];
                    $questionrowdata['question'] = $answerrowdata['answer'];
                    $questionrowdata['question_order'] = $answerrowdata['sortorder'];
                    $questionrowdata['language'] = $answerrowdata['language'];
                    $questionrowdata['type'] = $oldquestion['newtype'];
                    $qres = Yii::app()->db->createCommand()->insert('{{questions}}', $questionrowdata);
                    if (!isset($questionrowdata['qid'])) {
                        $aSQIDReplacements[$answerrowdata['code'] . $answerrowdata['qid']] = Yii::app()->db->getCommandBuilder()->getLastInsertID('{{questions}}');
                    }
                    $results['subquestions']++;
                    // also convert default values subquestions for multiple choice
                    if ($answerrowdata['default_value'] == 'Y' && ($oldquestion['newtype'] == 'M' || $oldquestion['newtype'] == 'P')) {
                        $insertdata = array();
                        $insertdata['qid'] = $newqid;
                        $insertdata['sqid'] = $aSQIDReplacements[$answerrowdata['code']];
                        $insertdata['language'] = $answerrowdata['language'];
                        $insertdata['defaultvalue'] = 'Y';
                        $qres = Yii::app()->db->createCommand()->insert('{{defaultvalues}}', $insertdata);
                    }
                } else {
                    unset($answerrowdata['default_value']);
                    $ares = Yii::app()->db->createCommand()->insert('{{answers}}', $answerrowdata);
                    $results['answers']++;
                }
            }
        }
        // ANSWERS is DONE
        // Fix sortorder of the groups  - if users removed groups manually from the csv file there would be gaps
        fixSortOrderGroups($surveyid);
        //... and for the questions inside the groups
        // get all group ids and fix questions inside each group
        $gquery = "SELECT gid FROM {{groups}} where sid={$iNewSID} group by gid ORDER BY gid";
        //Get last question added (finds new qid)
        $gres = Yii::app()->db->createCommand($gquery)->query();
        foreach ($gres->readAll() as $grow) {
            Questions::model()->updateQuestionOrder($grow['gid'], $iNewSID);
        }
    }
    $results['question_attributes'] = 0;
    // Finally the question attributes - it 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);
            // replace the qid for the new one (if there is no new qid in the $aQIDReplacements array it mean that this attribute is orphan -> error, skip this record)
            if (isset($aQIDReplacements[$qarowdata["qid"]])) {
                $qarowdata["qid"] = $aQIDReplacements[$qarowdata["qid"]];
            } else {
                continue;
            }
            // a problem with this answer record -> don't consider
            unset($qarowdata["qaid"]);
            $result = Yii::app()->db->createCommand()->insert('{{question_attributes}}', $qarowdata);
            if ($result !== false) {
                $results['question_attributes']++;
            }
        }
    }
    // ATTRIBUTES is DONE
    // TMSW Conditions->Relevance:  Anything needed here, other than call to LEM->ConvertConditionsToRelevance() when done?
    // do CONDITIONS
    $results['conditions'] = 0;
    if (isset($conditionsarray) && $conditionsarray) {
        $fieldorders = convertCSVRowToArray($conditionsarray[0], ',', '"');
        unset($conditionsarray[0]);
        foreach ($conditionsarray as $car) {
            $fieldcontents = convertCSVRowToArray($car, ',', '"');
            $conditionrowdata = array_combine($fieldorders, $fieldcontents);
            $oldqid = $conditionrowdata["qid"];
            $oldcqid = $conditionrowdata["cqid"];
            // 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[$oldqid])) {
                $conditionrowdata["qid"] = $aQIDReplacements[$oldqid];
            } else {
                continue;
            }
            // a problem with this answer record -> don't consider
            // replace the cqid for the new one (if there is no new qid in the $aQIDReplacements array it mean that this condition is orphan -> error, skip this record)
            if (isset($aQIDReplacements[$oldcqid])) {
                $conditionrowdata["cqid"] = $aQIDReplacements[$oldcqid];
            } else {
                continue;
            }
            // a problem with this answer record -> don't consider
            list($oldcsid, $oldcgid, $oldqidanscode) = explode("X", $conditionrowdata["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($conditionrowdata["cid"]);
            // recreate the cfieldname with the new IDs
            if (preg_match("/^\\+/", $oldcsid)) {
                $newcfieldname = '+' . $iNewSID . "X" . $newgid . "X" . $conditionrowdata["cqid"] . substr($oldqidanscode, strlen($oldqid));
            } else {
                $newcfieldname = $iNewSID . "X" . $newgid . "X" . $conditionrowdata["cqid"] . substr($oldqidanscode, strlen($oldqid));
            }
            $conditionrowdata["cfieldname"] = $newcfieldname;
            if (!isset($conditionrowdata["method"]) || trim($conditionrowdata["method"]) == '') {
                $conditionrowdata["method"] = '==';
            }
            $newvalues = array_values($conditionrowdata);
            $conditioninsert = "insert INTO {{conditions}} (" . implode(',', array_keys($conditionrowdata)) . ") VALUES (" . implode(',', $newvalues) . ")";
            $result = Yii::app()->db->createCommand($conditioninsert)->query() or safeDie("Couldn't insert condition<br />{$conditioninsert}<br />");
            $results['conditions']++;
        }
    }
    LimeExpressionManager::RevertUpgradeConditionsToRelevance($iNewSID);
    LimeExpressionManager::UpgradeConditionsToRelevance($iNewSID);
    $results['groups'] = 1;
    $results['newgid'] = $newgid;
    return $results;
}