/**
  * Execute the console command.
  *
  * @return void
  */
 public function fire()
 {
     //
     $tutorials = objectToArray(DB::select(DB::raw('select id from tutorials')));
     $tutorials = array_dot($tutorials);
     $students = array_dot(objectToArray(DB::select(DB::raw('SELECT `user_id` as `id`  from `students`'))));
     $teachers = array_dot(objectToArray(DB::select(DB::raw('SELECT `user_id` as `id`  from `teachers`'))));
     $subjects = array_dot(objectToArray(DB::select(DB::raw('SELECT id from subjects'))));
     $minimum = $this->option('minimum');
     $assessmenttitle = "This is a {title|heading|header} for Assessment.";
     $assessmentdesc = "This is a sample {data|words|description} for Assessment.";
     for ($i = 1; $i <= $minimum; $i++) {
         $assessment = new Assessments();
         $assessment->title = self::spintax($assessmenttitle);
         $assessment->description = self::spintax($assessmentdesc);
         $assessment->assessmenttype = "presentation";
         $assessment->tutorialid = rand(1, 100);
         $assessment->teacherid = array_rand($teachers);
         $assessment->subjectid = rand(1, 55);
         $assessment->studentid = array_rand($students);
         $assessment->marks = rand(75, 100);
         $assessment->created_at = self::randDate('10th January 2013', date('jS F o'));
         $assessment->save();
     }
 }
Esempio n. 2
0
 public function assessmentupdateget($dash, $id)
 {
     $assessment = Assessments::find($id);
     $user = User::find($assessment->teacherid);
     if (Sentry::getUser()->id == $user->id) {
         $theme = Theme::uses('dashboard')->layout('default');
         $view = array('name' => 'Dashboard Assessment Update', 'id' => $id);
         $theme->breadcrumb()->add([['label' => 'Dashboard', 'url' => Setting::get('system.dashurl')], ['label' => 'Assessments', 'url' => Setting::get('system.dashurl') . '/assessments'], ['label' => $id, 'url' => Setting::get('system.dashurl') . '/assessment/' . $id]]);
         $theme->appendTitle(' - Assessment Update');
         $theme->asset()->container('datatable')->writeScript('inline-script', '$(document).ready(function(){
             $(\'#attachments\').dataTable({
                 "sDom": "<\'row\'<\'col-xs-5 col-sm-5 col-md-5\'l><\'col-xs-5 col-sm-5 col-md-5\'f>r>t<\'row\'<\'col-xs-5 col-sm-5 col-md-5\'i><\'col-xs-5 col-sm-5 col-md-5\'p>>",
                     "oLanguage": {
                     "sLengthMenu": "_MENU_ ' . ' Attachments per page"
                     },
                     "sPagination":"bootstrap"
                
             });
         });$(document).ready(function(){
             $(\'#questionfail\').dataTable({
                 "sDom": "<\'row\'<\'col-xs-5 col-sm-5 col-md-5\'l><\'col-xs-5 col-sm-5 col-md-5\'f>r>t<\'row\'<\'col-xs-5 col-sm-5 col-md-5\'i><\'col-xs-5 col-sm-5 col-md-5\'p>>",
                     "oLanguage": {
                     "sLengthMenu": "_MENU_ ' . ' Failures per page"
                     },
                     "sPagination":"bootstrap"
                
             });
         });');
         $theme->asset()->container('footer')->writeScript('inline-script', '$(document).ready(function(){
             $("#examsheader").hide();
             $("div#exams").hide();
             $("div#examslock").hide();
             $(".hidequestions").hide();
             $(".hidequestions").click(function(){
                 $("div#exams").hide(2000);
                  $(\'html, body\').animate({
                     scrollTop: $("#top").offset().top
                 }, 2000);
                 $("#examsheader").hide(1200);
                 $("#examslock").hide(1200);
                 $(".hidequestions").hide(1000);
                 $("#showquestions").show(1000);
             });
             $("#showquestions").click(function(){
                 $("div#exams").show(2000);
                 $("div#examslock").show(100);
                 $(\'html, body\').animate({
                     scrollTop: $("#examslock").offset().top
                 }, 2000);
                 $("#examsheader").show(1000);
                 $(".hidequestions").show(1000);
                 $("#showquestions").hide(1000);
             });
         });');
         return $theme->scope('assessment.update', $view)->render();
         // return View::make('dashboard.assessments.update')->with('id',$id);
     } else {
         return "UPDATE NOT AUTHORISED";
     }
 }
Esempio n. 3
0
/**
* This function imports the old CSV data from 1.50 to 1.87 or older. Starting with 1.90 (DBVersion 143) there is an XML format instead
*
* @param array $sFullFilepath
* @returns array Information of imported questions/answers/etc.
*/
function CSVImportSurvey($sFullFilepath, $iDesiredSurveyId = NULL, $bTranslateLinks = true)
{
    Yii::app()->loadHelper('database');
    $clang = Yii::app()->lang;
    $handle = fopen($sFullFilepath, "r");
    while (!feof($handle)) {
        $buffer = fgets($handle);
        $bigarray[] = $buffer;
    }
    fclose($handle);
    $aIgnoredAnswers = array();
    $aSQIDReplacements = array();
    $aLIDReplacements = array();
    $aGIDReplacements = array();
    $substitutions = array();
    $aQuotaReplacements = array();
    $importresults['error'] = false;
    $importresults['importwarnings'] = array();
    $importresults['question_attributes'] = 0;
    if (isset($bigarray[0])) {
        $bigarray[0] = removeBOM($bigarray[0]);
    }
    // Now we try to determine the dataformat of the survey file.
    $importversion = 0;
    if (isset($bigarray[1]) && isset($bigarray[4]) && substr($bigarray[1], 0, 22) == "# SURVEYOR SURVEY DUMP") {
        $importversion = 100;
        // Version 0.99 or  1.0 file
    } elseif (substr($bigarray[0], 0, 24) == "# LimeSurvey Survey Dump" || substr($bigarray[0], 0, 25) == "# PHPSurveyor Survey Dump") {
        // 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 {
        $importresults['error'] = $clang->gT("This file is not a LimeSurvey survey file. Import failed.") . "\n";
        return $importresults;
    }
    if ((int) $importversion < 112) {
        $importresults['error'] = $clang->gT("This file is too old. Only files from LimeSurvey version 1.50 (DBVersion 112) and newer are supported.");
        return $importresults;
    }
    // okay.. now lets drop the first 9 lines and get to the data
    // This works for all versions
    for ($i = 0; $i < 9; $i++) {
        unset($bigarray[$i]);
    }
    $bigarray = array_values($bigarray);
    //SURVEYS
    if (array_search("# GROUPS TABLE\n", $bigarray)) {
        $stoppoint = array_search("# GROUPS TABLE\n", $bigarray);
    } elseif (array_search("# GROUPS TABLE\r\n", $bigarray)) {
        $stoppoint = array_search("# GROUPS TABLE\r\n", $bigarray);
    }
    for ($i = 0; $i <= $stoppoint + 1; $i++) {
        if ($i < $stoppoint - 2) {
            $surveyarray[] = $bigarray[$i];
        }
        unset($bigarray[$i]);
    }
    $bigarray = array_values($bigarray);
    //GROUPS
    if (array_search("# QUESTIONS TABLE\n", $bigarray)) {
        $stoppoint = array_search("# QUESTIONS TABLE\n", $bigarray);
    } elseif (array_search("# QUESTIONS TABLE\r\n", $bigarray)) {
        $stoppoint = array_search("# QUESTIONS TABLE\r\n", $bigarray);
    } else {
        $stoppoint = count($bigarray) - 1;
    }
    for ($i = 0; $i <= $stoppoint + 1; $i++) {
        if ($i < $stoppoint - 2) {
            $grouparray[] = $bigarray[$i];
        }
        unset($bigarray[$i]);
    }
    $bigarray = array_values($bigarray);
    //QUESTIONS
    if (array_search("# ANSWERS TABLE\n", $bigarray)) {
        $stoppoint = array_search("# ANSWERS TABLE\n", $bigarray);
    } elseif (array_search("# ANSWERS TABLE\r\n", $bigarray)) {
        $stoppoint = array_search("# ANSWERS TABLE\r\n", $bigarray);
    } else {
        $stoppoint = count($bigarray) - 1;
    }
    for ($i = 0; $i <= $stoppoint + 1; $i++) {
        if ($i < $stoppoint - 2) {
            $questionarray[] = $bigarray[$i];
        }
        unset($bigarray[$i]);
    }
    $bigarray = array_values($bigarray);
    //ANSWERS
    if (array_search("# CONDITIONS TABLE\n", $bigarray)) {
        $stoppoint = array_search("# CONDITIONS TABLE\n", $bigarray);
    } elseif (array_search("# CONDITIONS TABLE\r\n", $bigarray)) {
        $stoppoint = array_search("# CONDITIONS TABLE\r\n", $bigarray);
    } else {
        $stoppoint = count($bigarray) - 1;
    }
    for ($i = 0; $i <= $stoppoint + 1; $i++) {
        if ($i < $stoppoint - 2) {
            $answerarray[] = str_replace("`default`", "`default_value`", $bigarray[$i]);
        }
        unset($bigarray[$i]);
    }
    $bigarray = array_values($bigarray);
    //CONDITIONS
    if (array_search("# LABELSETS TABLE\n", $bigarray)) {
        $stoppoint = array_search("# LABELSETS TABLE\n", $bigarray);
    } elseif (array_search("# LABELSETS TABLE\r\n", $bigarray)) {
        $stoppoint = array_search("# LABELSETS TABLE\r\n", $bigarray);
    }
    for ($i = 0; $i <= $stoppoint + 1; $i++) {
        if ($i < $stoppoint - 2) {
            $conditionsarray[] = $bigarray[$i];
        }
        unset($bigarray[$i]);
    }
    $bigarray = array_values($bigarray);
    //LABELSETS
    if (array_search("# LABELS TABLE\n", $bigarray)) {
        $stoppoint = array_search("# LABELS TABLE\n", $bigarray);
    } elseif (array_search("# LABELS TABLE\r\n", $bigarray)) {
        $stoppoint = array_search("# LABELS TABLE\r\n", $bigarray);
    } else {
        $stoppoint = count($bigarray) - 1;
    }
    for ($i = 0; $i <= $stoppoint + 1; $i++) {
        if ($i < $stoppoint - 2) {
            $labelsetsarray[] = $bigarray[$i];
        }
        unset($bigarray[$i]);
    }
    $bigarray = array_values($bigarray);
    //LABELS
    if (array_search("# QUESTION_ATTRIBUTES TABLE\n", $bigarray)) {
        $stoppoint = array_search("# QUESTION_ATTRIBUTES TABLE\n", $bigarray);
    } elseif (array_search("# QUESTION_ATTRIBUTES TABLE\r\n", $bigarray)) {
        $stoppoint = array_search("# QUESTION_ATTRIBUTES TABLE\r\n", $bigarray);
    } else {
        $stoppoint = count($bigarray) - 1;
    }
    for ($i = 0; $i <= $stoppoint + 1; $i++) {
        if ($i < $stoppoint - 2) {
            $labelsarray[] = $bigarray[$i];
        }
        unset($bigarray[$i]);
    }
    $bigarray = array_values($bigarray);
    //Question attributes
    if (array_search("# ASSESSMENTS TABLE\n", $bigarray)) {
        $stoppoint = array_search("# ASSESSMENTS TABLE\n", $bigarray);
    } elseif (array_search("# ASSESSMENTS TABLE\r\n", $bigarray)) {
        $stoppoint = array_search("# ASSESSMENTS TABLE\r\n", $bigarray);
    } else {
        $stoppoint = count($bigarray) - 1;
    }
    for ($i = 0; $i <= $stoppoint + 1; $i++) {
        if ($i < $stoppoint - 2) {
            $question_attributesarray[] = $bigarray[$i];
        }
        unset($bigarray[$i]);
    }
    $bigarray = array_values($bigarray);
    //ASSESSMENTS
    if (array_search("# SURVEYS_LANGUAGESETTINGS TABLE\n", $bigarray)) {
        $stoppoint = array_search("# SURVEYS_LANGUAGESETTINGS TABLE\n", $bigarray);
    } elseif (array_search("# SURVEYS_LANGUAGESETTINGS TABLE\r\n", $bigarray)) {
        $stoppoint = array_search("# SURVEYS_LANGUAGESETTINGS TABLE\r\n", $bigarray);
    } else {
        $stoppoint = count($bigarray) - 1;
    }
    for ($i = 0; $i <= $stoppoint + 1; $i++) {
        //    if ($i<$stoppoint-2 || $i==count($bigarray)-1)
        if ($i < $stoppoint - 2) {
            $assessmentsarray[] = $bigarray[$i];
        }
        unset($bigarray[$i]);
    }
    $bigarray = array_values($bigarray);
    //LANGAUGE SETTINGS
    if (array_search("# QUOTA TABLE\n", $bigarray)) {
        $stoppoint = array_search("# QUOTA TABLE\n", $bigarray);
    } elseif (array_search("# QUOTA TABLE\r\n", $bigarray)) {
        $stoppoint = array_search("# QUOTA TABLE\r\n", $bigarray);
    } else {
        $stoppoint = count($bigarray) - 1;
    }
    for ($i = 0; $i <= $stoppoint + 1; $i++) {
        //    if ($i<$stoppoint-2 || $i==count($bigarray)-1)
        //$bigarray[$i]=        trim($bigarray[$i]);
        if (isset($bigarray[$i]) && trim($bigarray[$i]) != '') {
            if (strpos($bigarray[$i], "#") === 0) {
                unset($bigarray[$i]);
                unset($bigarray[$i + 1]);
                unset($bigarray[$i + 2]);
                break;
            } else {
                $surveylsarray[] = $bigarray[$i];
            }
        }
        unset($bigarray[$i]);
    }
    $bigarray = array_values($bigarray);
    //QUOTA
    if (array_search("# QUOTA_MEMBERS TABLE\n", $bigarray)) {
        $stoppoint = array_search("# QUOTA_MEMBERS TABLE\n", $bigarray);
    } elseif (array_search("# QUOTA_MEMBERS TABLE\r\n", $bigarray)) {
        $stoppoint = array_search("# QUOTA_MEMBERS TABLE\r\n", $bigarray);
    } else {
        $stoppoint = count($bigarray) - 1;
    }
    for ($i = 0; $i <= $stoppoint + 1; $i++) {
        //    if ($i<$stoppoint-2 || $i==count($bigarray)-1)
        if ($i < $stoppoint - 2) {
            $quotaarray[] = $bigarray[$i];
        }
        unset($bigarray[$i]);
    }
    $bigarray = array_values($bigarray);
    //QUOTA MEMBERS
    if (array_search("# QUOTA_LANGUAGESETTINGS TABLE\n", $bigarray)) {
        $stoppoint = array_search("# QUOTA_LANGUAGESETTINGS TABLE\n", $bigarray);
    } elseif (array_search("# QUOTA_LANGUAGESETTINGS TABLE\r\n", $bigarray)) {
        $stoppoint = array_search("# QUOTA_LANGUAGESETTINGS TABLE\r\n", $bigarray);
    } else {
        $stoppoint = count($bigarray) - 1;
    }
    for ($i = 0; $i <= $stoppoint + 1; $i++) {
        //    if ($i<$stoppoint-2 || $i==count($bigarray)-1)
        if ($i < $stoppoint - 2) {
            $quotamembersarray[] = $bigarray[$i];
        }
        unset($bigarray[$i]);
    }
    $bigarray = array_values($bigarray);
    //Whatever is the last table - currently
    //QUOTA LANGUAGE SETTINGS
    $stoppoint = count($bigarray) - 1;
    for ($i = 0; $i < $stoppoint - 1; $i++) {
        if ($i <= $stoppoint) {
            $quotalsarray[] = $bigarray[$i];
        }
        unset($bigarray[$i]);
    }
    $bigarray = array_values($bigarray);
    if (isset($surveyarray)) {
        $importresults['surveys'] = count($surveyarray);
    } else {
        $importresults['surveys'] = 0;
    }
    if (isset($surveylsarray)) {
        $importresults['languages'] = count($surveylsarray) - 1;
    } else {
        $importresults['languages'] = 1;
    }
    if (isset($grouparray)) {
        $importresults['groups'] = count($grouparray) - 1;
    } else {
        $importresults['groups'] = 0;
    }
    if (isset($questionarray)) {
        $importresults['questions'] = count($questionarray);
    } else {
        $importresults['questions'] = 0;
    }
    if (isset($answerarray)) {
        $importresults['answers'] = count($answerarray);
    } else {
        $importresults['answers'] = 0;
    }
    if (isset($conditionsarray)) {
        $importresults['conditions'] = count($conditionsarray);
    } else {
        $importresults['conditions'] = 0;
    }
    if (isset($labelsetsarray)) {
        $importresults['labelsets'] = count($labelsetsarray);
    } else {
        $importresults['labelsets'] = 0;
    }
    if (isset($assessmentsarray)) {
        $importresults['assessments'] = count($assessmentsarray);
    } else {
        $importresults['assessments'] = 0;
    }
    if (isset($quotaarray)) {
        $importresults['quota'] = count($quotaarray);
    } else {
        $importresults['quota'] = 0;
    }
    if (isset($quotamembersarray)) {
        $importresults['quotamembers'] = count($quotamembersarray);
    } else {
        $importresults['quotamembers'] = 0;
    }
    if (isset($quotalsarray)) {
        $importresults['quotals'] = count($quotalsarray);
    } else {
        $importresults['quotals'] = 0;
    }
    // CREATE SURVEY
    if ($importresults['surveys'] > 0) {
        $importresults['surveys']--;
    }
    if ($importresults['answers'] > 0) {
        $importresults['answers'] = ($importresults['answers'] - 1) / $importresults['languages'];
    }
    if ($importresults['groups'] > 0) {
        $countgroups = ($importresults['groups'] - 1) / $importresults['languages'];
    }
    if ($importresults['questions'] > 0) {
        $importresults['questions'] = ($importresults['questions'] - 1) / $importresults['languages'];
    }
    if ($importresults['assessments'] > 0) {
        $importresults['assessments']--;
    }
    if ($importresults['conditions'] > 0) {
        $importresults['conditions']--;
    }
    if ($importresults['labelsets'] > 0) {
        $importresults['labelsets']--;
    }
    if ($importresults['quota'] > 0) {
        $importresults['quota']--;
    }
    $sfieldorders = convertCSVRowToArray($surveyarray[0], ',', '"');
    $sfieldcontents = convertCSVRowToArray($surveyarray[1], ',', '"');
    $surveyrowdata = array_combine($sfieldorders, $sfieldcontents);
    $iOldSID = $surveyrowdata["sid"];
    if (!$iOldSID) {
        if ($importingfrom == "http") {
            $importsurvey .= "<br /><div class='warningheader'>" . $clang->gT("Error") . "</div><br />\n";
            $importsurvey .= $clang->gT("Import of this survey file failed") . "<br />\n";
            $importsurvey .= $clang->gT("File does not contain LimeSurvey data in the correct format.") . "<br /><br />\n";
            //Couldn't find the SID - cannot continue
            $importsurvey .= "<input type='submit' value='" . $clang->gT("Main Admin Screen") . "' onclick=\"window.open('{$scriptname}', '_top')\" />\n";
            $importsurvey .= "</div>\n";
            unlink($sFullFilepath);
            //Delete the uploaded file
            return;
        } else {
            $clang->eT("Import of this survey file failed") . "\n" . $clang->gT("File does not contain LimeSurvey data in the correct format.") . "\n";
            return;
        }
    }
    if ($iDesiredSurveyId != NULL) {
        $iNewSID = GetNewSurveyID($iDesiredSurveyId);
    } else {
        $iNewSID = GetNewSurveyID($iOldSID);
    }
    $insert = $surveyarray[0];
    $sfieldorders = convertCSVRowToArray($surveyarray[0], ',', '"');
    $sfieldcontents = convertCSVRowToArray($surveyarray[1], ',', '"');
    $surveyrowdata = array_combine($sfieldorders, $sfieldcontents);
    // Set new owner ID
    $surveyrowdata['owner_id'] = Yii::app()->session['loginID'];
    // Set new survey ID
    $surveyrowdata['sid'] = $iNewSID;
    $surveyrowdata['active'] = 'N';
    if (validateTemplateDir($surveyrowdata['template']) !== $surveyrowdata['template']) {
        $importresults['importwarnings'][] = sprintf($clang->gT('Template %s not found, please review when activating.'), $surveyrowdata['template']);
    }
    //if (isset($surveyrowdata['datecreated'])) {$surveyrowdata['datecreated'] = $connect->BindTimeStamp($surveyrowdata['datecreated']);}
    unset($surveyrowdata['expires']);
    unset($surveyrowdata['attribute1']);
    unset($surveyrowdata['attribute2']);
    unset($surveyrowdata['usestartdate']);
    unset($surveyrowdata['notification']);
    unset($surveyrowdata['useexpiry']);
    unset($surveyrowdata['url']);
    unset($surveyrowdata['lastpage']);
    if (isset($surveyrowdata['private'])) {
        $surveyrowdata['anonymized'] = $surveyrowdata['private'];
        unset($surveyrowdata['private']);
    }
    if (isset($surveyrowdata['startdate'])) {
        unset($surveyrowdata['startdate']);
    }
    $surveyrowdata['bounce_email'] = $surveyrowdata['adminemail'];
    if (empty($surveyrowdata['datecreated'])) {
        $surveyrowdata['datecreated'] = new CDbExpression('NOW()');
    }
    $iNewSID = Survey::model()->insertNewSurvey($surveyrowdata) or safeDie("<br />" . $clang->gT("Import of this survey file failed") . "<br />{$surveyarray[0]}<br /><br />\n");
    // Now import the survey language settings
    $fieldorders = convertCSVRowToArray($surveylsarray[0], ',', '"');
    unset($surveylsarray[0]);
    foreach ($surveylsarray as $slsrow) {
        $fieldcontents = convertCSVRowToArray($slsrow, ',', '"');
        $surveylsrowdata = array_combine($fieldorders, $fieldcontents);
        // convert back the '\'.'n' char from the CSV file to true return char "\n"
        $surveylsrowdata = array_map('convertCSVReturnToReturn', $surveylsrowdata);
        // Convert the \n return char from welcometext to <br />
        // translate internal links
        if ($bTranslateLinks) {
            $surveylsrowdata['surveyls_title'] = translateLinks('survey', $iOldSID, $iNewSID, $surveylsrowdata['surveyls_title']);
            $surveylsrowdata['surveyls_description'] = translateLinks('survey', $iOldSID, $iNewSID, $surveylsrowdata['surveyls_description']);
            $surveylsrowdata['surveyls_welcometext'] = translateLinks('survey', $iOldSID, $iNewSID, $surveylsrowdata['surveyls_welcometext']);
            $surveylsrowdata['surveyls_urldescription'] = translateLinks('survey', $iOldSID, $iNewSID, $surveylsrowdata['surveyls_urldescription']);
            $surveylsrowdata['surveyls_email_invite'] = translateLinks('survey', $iOldSID, $iNewSID, $surveylsrowdata['surveyls_email_invite']);
            $surveylsrowdata['surveyls_email_remind'] = translateLinks('survey', $iOldSID, $iNewSID, $surveylsrowdata['surveyls_email_remind']);
            $surveylsrowdata['surveyls_email_register'] = translateLinks('survey', $iOldSID, $iNewSID, $surveylsrowdata['surveyls_email_register']);
            $surveylsrowdata['surveyls_email_confirm'] = translateLinks('survey', $iOldSID, $iNewSID, $surveylsrowdata['surveyls_email_confirm']);
        }
        unset($surveylsrowdata['lastpage']);
        $surveylsrowdata['surveyls_survey_id'] = $iNewSID;
        $lsiresult = Surveys_languagesettings::model()->insertNewSurvey($surveylsrowdata) or safeDie("<br />" . $clang->gT("Import of this survey file failed") . "<br />");
    }
    // The survey languagesettings are imported now
    $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);
    // DO SURVEY_RIGHTS
    Survey_permissions::model()->giveAllSurveyPermissions(Yii::app()->session['loginID'], $iNewSID);
    $importresults['deniedcountls'] = 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']);
            $lblsets = Labelsets::model();
            $lsiresult = $lblsets->insertRecords($labelsetrowdata);
            $results['labelsets']++;
            // Get the new insert id for the labels inside this labelset
            $newlid = Yii::app()->db->createCommand('Select LAST_INSERT_ID()')->query()->read();
            $newlid = $newlid['LAST_INSERT_ID()'];
            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
                        if ($bTranslateLinks) {
                            $labelrowdata['title'] = translateLinks('label', $oldlid, $newlid, $labelrowdata['title']);
                        }
                        $liresult = Label::model()->insertRecords($labelrowdata);
                        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)->query() or die("Died querying labelset {$lid}<br />");
            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]);
        foreach ($grouparray as $ga) {
            $gacfieldcontents = convertCSVRowToArray($ga, ',', '"');
            $grouprowdata = array_combine($gafieldorders, $gacfieldcontents);
            //Now an additional integrity check if there are any groups not belonging into this survey
            if ($grouprowdata['sid'] != $iOldSID) {
                $results['fatalerror'] = $clang->gT("A group in the CSV/SQL file is not part of the same survey. The import of the survey was stopped.") . "<br />\n";
                return $results;
            }
            $grouprowdata['sid'] = $iNewSID;
            // remember group id
            $oldgid = $grouprowdata['gid'];
            //update/remove the old group id
            if (isset($aGIDReplacements[$oldgid])) {
                $grouprowdata['gid'] = $aGIDReplacements[$oldgid];
            } else {
                unset($grouprowdata['gid']);
            }
            // Everything set - now insert it
            $grouprowdata = array_map('convertCSVReturnToReturn', $grouprowdata);
            // translate internal links
            if ($bTranslateLinks) {
                $grouprowdata['group_name'] = translateLinks('survey', $iOldSID, $iNewSID, $grouprowdata['group_name']);
                $grouprowdata['description'] = translateLinks('survey', $iOldSID, $iNewSID, $grouprowdata['description']);
            }
            if (isset($grouprowdata['gid'])) {
                switchMSSQLIdentityInsert('groups', true);
            }
            $gres = Groups::model()->insertRecords($grouprowdata) or safeDie($clang->gT('Error') . ": Failed to insert group<br />\\<br />\n");
            if (isset($grouprowdata['gid'])) {
                switchMSSQLIdentityInsert('groups', false);
            }
            if (!isset($grouprowdata['gid'])) {
                $aGIDReplacements[$oldgid] = Yii::app()->db->createCommand('Select LAST_INSERT_ID()')->query()->read();
                $aGIDReplacements[$oldgid] = $aGIDReplacements[$oldgid]['LAST_INSERT_ID()'];
            }
        }
        // Fix sortorder of the groups  - if users removed groups manually from the csv file there would be gaps
        fixSortOrderGroups($iNewSID);
    }
    // GROUPS is DONE
    // Import questions
    if (isset($questionarray) && $questionarray) {
        $qafieldorders = convertCSVRowToArray($questionarray[0], ',', '"');
        unset($questionarray[0]);
        foreach ($questionarray as $qa) {
            $qacfieldcontents = convertCSVRowToArray($qa, ',', '"');
            $questionrowdata = array_combine($qafieldorders, $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;
            // Skip if gid is invalid
            if (!isset($aGIDReplacements[$questionrowdata['gid']])) {
                continue;
            }
            $questionrowdata["gid"] = $aGIDReplacements[$questionrowdata['gid']];
            if (isset($aQIDReplacements[$questionrowdata['qid']])) {
                $questionrowdata['qid'] = $aQIDReplacements[$questionrowdata['qid']];
            } else {
                $oldqid = $questionrowdata['qid'];
                unset($questionrowdata['qid']);
            }
            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';
                $aIgnoredAnswers[] = $oldqid;
            }
            if (!isset($questionrowdata["question_order"]) || $questionrowdata["question_order"] == '') {
                $questionrowdata["question_order"] = 0;
            }
            // translate internal links
            if ($bTranslateLinks) {
                $questionrowdata['question'] = translateLinks('survey', $iOldSID, $iNewSID, $questionrowdata['question']);
                $questionrowdata['help'] = translateLinks('survey', $iOldSID, $iNewSID, $questionrowdata['help']);
            }
            if (isset($questionrowdata['qid'])) {
                switchMSSQLIdentityInsert('questions', true);
            }
            $qres = Questions::model()->insertRecords($questionrowdata) or safeDie($clang->gT("Error") . ": Failed to insert question<br />");
            if (isset($questionrowdata['qid'])) {
                switchMSSQLIdentityInsert('questions', false);
                $saveqid = $questionrowdata['qid'];
            } else {
                $aQIDReplacements[$oldqid] = Yii::app()->db->createCommand('Select LAST_INSERT_ID()')->query()->read();
                $aQIDReplacements[$oldqid] = $aQIDReplacements[$oldqid]['LAST_INSERT_ID()'];
                $saveqid = $aQIDReplacements[$oldqid];
            }
            // Now we will fix up old label sets where they are used as answers
            if ((isset($oldlid1) && isset($aLIDReplacements[$oldlid1]) || isset($oldlid2) && isset($aLIDReplacements[$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
    if (isset($answerarray) && $answerarray) {
        $answerfieldnames = convertCSVRowToArray($answerarray[0], ',', '"');
        unset($answerarray[0]);
        foreach ($answerarray as $aa) {
            $answerfieldcontents = convertCSVRowToArray($aa, ',', '"');
            $answerrowdata = array_combine($answerfieldnames, $answerfieldcontents);
            if (in_array($answerrowdata['qid'], $aIgnoredAnswers)) {
                // Due to a bug in previous LS versions there may be orphaned answers with question type Z (which is now L)
                // this way they are ignored
                continue;
            }
            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
            $query1 = 'select type,gid from {{questions}} where qid=' . $answerrowdata["qid"];
            $resultquery1 = Yii::app()->db->createCommand($query1)->query();
            $questiontemp = $resultquery1->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 = Defaultvalues::model()->insertRecords($insertdata) or safeDie("Error: Failed to insert defaultvalue <br />");
            }
            // translate internal links
            if ($bTranslateLinks) {
                $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'];
                if (isset($questionrowdata['qid'])) {
                    switchMSSQLIdentityInsert('questions', true);
                }
                if ($questionrowdata) {
                    XSSFilterArray($questionrowdata);
                }
                $qres = Questions::model()->insertRecords($questionrowdata) or safeDie("Error: Failed to insert subquestion <br />");
                if (!isset($questionrowdata['qid'])) {
                    $aSQIDReplacements[$answerrowdata['code'] . $answerrowdata['qid']] = Yii::app()->db->createCommand('Select LAST_INSERT_ID()')->query()->read();
                    $aSQIDReplacements[$answerrowdata['code'] . $answerrowdata['qid']] = $aSQIDReplacements[$answerrowdata['code'] . $answerrowdata['qid']]['LAST_INSERT_ID()'];
                } else {
                    switchMSSQLIdentityInsert('questions', false);
                }
                $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';
                    if ($insertdata) {
                        XSSFilterArray($insertdata);
                    }
                    $qres = Defaultvalues::model()->insertRecords($insertdata) or safeDie("Error: Failed to insert defaultvalue <br />");
                }
            } else {
                unset($answerrowdata['default_value']);
                if ($answerrowdata) {
                    XSSFilterArray($answerrowdata);
                }
                $ares = Answers::model()->insertRecords($answerrowdata) or safeDie("Error: Failed to insert answer<br />");
                $results['answers']++;
            }
        }
    }
    // 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);
    }
    //We've built two arrays along the way - one containing the old SID, GID and QIDs - and their NEW equivalents
    //and one containing the old 'extended fieldname' and its new equivalent.  These are needed to import conditions and question_attributes.
    if (isset($question_attributesarray) && $question_attributesarray) {
        //ONLY DO THIS IF THERE ARE QUESTION_ATTRIBUES
        $fieldorders = convertCSVRowToArray($question_attributesarray[0], ',', '"');
        unset($question_attributesarray[0]);
        foreach ($question_attributesarray as $qar) {
            $fieldcontents = convertCSVRowToArray($qar, ',', '"');
            $qarowdata = array_combine($fieldorders, $fieldcontents);
            $newqid = "";
            $qarowdata["qid"] = $aQIDReplacements[$qarowdata["qid"]];
            unset($qarowdata["qaid"]);
            $result = Question_attributes::model()->insertRecords($qarowdata);
            if ($result > 0) {
                $importresults['question_attributes']++;
            }
        }
    }
    if (isset($assessmentsarray) && $assessmentsarray) {
        //ONLY DO THIS IF THERE ARE QUESTION_ATTRIBUTES
        $fieldorders = convertCSVRowToArray($assessmentsarray[0], ',', '"');
        unset($assessmentsarray[0]);
        foreach ($assessmentsarray as $qar) {
            $fieldcontents = convertCSVRowToArray($qar, ',', '"');
            $asrowdata = array_combine($fieldorders, $fieldcontents);
            if (isset($asrowdata['link'])) {
                if (trim($asrowdata['link']) != '') {
                    $asrowdata['message'] = $asrowdata['message'] . '<br /><a href="' . $asrowdata['link'] . '">' . $asrowdata['link'] . '</a>';
                }
                unset($asrowdata['link']);
            }
            if ($asrowdata["gid"] > 0) {
                $asrowdata["gid"] = $aGIDReplacements[$asrowdata["gid"]];
            }
            $asrowdata["sid"] = $iNewSID;
            unset($asrowdata["id"]);
            $result = Assessments::model()->insertRecords($asrowdata) or safeDie("Couldn't insert assessment<br />");
            unset($newgid);
        }
    }
    if (isset($quotaarray) && $quotaarray) {
        //ONLY DO THIS IF THERE ARE QUOTAS
        $fieldorders = convertCSVRowToArray($quotaarray[0], ',', '"');
        unset($quotaarray[0]);
        foreach ($quotaarray as $qar) {
            $fieldcontents = convertCSVRowToArray($qar, ',', '"');
            $asrowdata = array_combine($fieldorders, $fieldcontents);
            $iOldSID = $asrowdata["sid"];
            foreach ($substitutions as $subs) {
                if ($iOldSID == $subs[0]) {
                    $iNewSID = $subs[3];
                }
            }
            $asrowdata["sid"] = $iNewSID;
            $oldid = $asrowdata["id"];
            unset($asrowdata["id"]);
            $quotadata[] = $asrowdata;
            //For use later if needed
            $result = Quota::model()->insertRecords($asrowdata) or safeDie("Couldn't insert quota<br />");
            $aQuotaReplacements[$oldid] = Yii::app()->db->createCommand('Select LAST_INSERT_ID()')->query()->read();
            $aQuotaReplacements[$oldid] = $aQuotaReplacements[$oldid]['LAST_INSERT_ID()'];
        }
    }
    if (isset($quotamembersarray) && $quotamembersarray) {
        //ONLY DO THIS IF THERE ARE QUOTA MEMBERS
        $count = 0;
        foreach ($quotamembersarray as $qar) {
            $fieldorders = convertCSVRowToArray($quotamembersarray[0], ',', '"');
            $fieldcontents = convertCSVRowToArray($qar, ',', '"');
            if ($count == 0) {
                $count++;
                continue;
            }
            $asrowdata = array_combine($fieldorders, $fieldcontents);
            $iOldSID = $asrowdata["sid"];
            $newqid = "";
            $newquotaid = "";
            $oldqid = $asrowdata['qid'];
            $oldquotaid = $asrowdata['quota_id'];
            foreach ($substitutions as $subs) {
                if ($iOldSID == $subs[0]) {
                    $iNewSID = $subs[3];
                }
                if ($oldqid == $subs[2]) {
                    $newqid = $subs[5];
                }
            }
            $newquotaid = $aQuotaReplacements[$oldquotaid];
            $asrowdata["sid"] = $iNewSID;
            $asrowdata["qid"] = $newqid;
            $asrowdata["quota_id"] = $newquotaid;
            unset($asrowdata["id"]);
            $result = Quota_members::model()->insertRecords($asrowdata) or safeDie("Couldn't insert quota<br />");
        }
    }
    if (isset($quotalsarray) && $quotalsarray) {
        //ONLY DO THIS IF THERE ARE QUOTA LANGUAGE SETTINGS
        $count = 0;
        foreach ($quotalsarray as $qar) {
            $fieldorders = convertCSVRowToArray($quotalsarray[0], ',', '"');
            $fieldcontents = convertCSVRowToArray($qar, ',', '"');
            if ($count == 0) {
                $count++;
                continue;
            }
            $asrowdata = array_combine($fieldorders, $fieldcontents);
            $newquotaid = "";
            $oldquotaid = $asrowdata['quotals_quota_id'];
            $newquotaid = $aQuotaReplacements[$oldquotaid];
            $asrowdata["quotals_quota_id"] = $newquotaid;
            unset($asrowdata["quotals_id"]);
            $result = Quota_languagesettings::model()->insertRecords($asrowdata) or safeDie("Couldn't insert quota<br />");
        }
    }
    //if there are quotas, but no quotals, then we need to create default dummy for each quota (this handles exports from pre-language quota surveys)
    if ($importresults['quota'] > 0 && (!isset($importresults['quotals']) || $importresults['quotals'] == 0)) {
        $i = 0;
        $defaultsurveylanguage = isset($defaultsurveylanguage) ? $defaultsurveylanguage : "en";
        foreach ($aQuotaReplacements as $oldquotaid => $newquotaid) {
            $asrowdata = array("quotals_quota_id" => $newquotaid, "quotals_language" => $defaultsurveylanguage, "quotals_name" => $quotadata[$i]["name"], "quotals_message" => $clang->gT("Sorry your responses have exceeded a quota on this survey."), "quotals_url" => "", "quotals_urldescrip" => "");
            $i++;
        }
        $result = Quota_languagesettings::model()->insertRecords($asrowdata) or safeDie("Couldn't insert quota<br />");
        $countquotals = $i;
    }
    // Do conditions
    if (isset($conditionsarray) && $conditionsarray) {
        //ONLY DO THIS IF THERE ARE CONDITIONS!
        $fieldorders = convertCSVRowToArray($conditionsarray[0], ',', '"');
        unset($conditionsarray[0]);
        // Exception for conditions based on attributes
        $aQIDReplacements[0] = 0;
        foreach ($conditionsarray as $car) {
            $fieldcontents = convertCSVRowToArray($car, ',', '"');
            $conditionrowdata = array_combine($fieldorders, $fieldcontents);
            unset($conditionrowdata["cid"]);
            if (!isset($conditionrowdata["method"]) || trim($conditionrowdata["method"]) == '') {
                $conditionrowdata["method"] = '==';
            }
            if (!isset($conditionrowdata["scenario"]) || trim($conditionrowdata["scenario"]) == '') {
                $conditionrowdata["scenario"] = 1;
            }
            $oldcqid = $conditionrowdata["cqid"];
            $query = 'select gid from {{questions}} where qid=' . $aQIDReplacements[$conditionrowdata["cqid"]];
            $res = Yii::app()->db->createCommand($query)->query();
            $resrow = $res->read();
            $oldgid = array_search($resrow['gid'], $aGIDReplacements);
            $conditionrowdata["qid"] = $aQIDReplacements[$conditionrowdata["qid"]];
            $conditionrowdata["cqid"] = $aQIDReplacements[$conditionrowdata["cqid"]];
            $oldcfieldname = $conditionrowdata["cfieldname"];
            $conditionrowdata["cfieldname"] = str_replace($iOldSID . 'X' . $oldgid . 'X' . $oldcqid, $iNewSID . 'X' . $aGIDReplacements[$oldgid] . 'X' . $conditionrowdata["cqid"], $conditionrowdata["cfieldname"]);
            $result = Conditions::model()->insertRecords($conditionrowdata) or safeDie("Couldn't insert condition<br />");
        }
    }
    LimeExpressionManager::RevertUpgradeConditionsToRelevance($iNewSID);
    LimeExpressionManager::UpgradeConditionsToRelevance($iNewSID);
    LimeExpressionManager::SetSurveyId($iNewSID);
    $importresults['importversion'] = $importversion;
    $importresults['newsid'] = $iNewSID;
    $importresults['oldsid'] = $iOldSID;
    return $importresults;
}
                <thead>
                    <tr>
                        <th>#ID</th>
                        <th>Name</th>
                        <th>Related Tutorial</th>
                        <th>Subject</th>
                        <th>Grade</th>
                        <th>Submitted To</th>
                        <th>Submission Date</th>
                        <th>Score out of 100</th>
                        <th>Submitted By</th>
                    </tr>
                </thead>
                <tbody>
                    <?php 
$assessments = Assessments::all();
foreach ($assessments as $assessment) {
    $tutorialid = $assessment->tutorialid;
    $teacherid = $assessment->teacherid;
    $teacher = User::find($teacherid);
    $admin = Sentry::getUser()->inGroup(Sentry::findGroupByName('admin'));
    if (Sentry::getUser()->id == $teacherid || $admin) {
        $tutorial = DB::select(DB::raw('SELECT * FROM `tutorials` WHERE `id` = ' . $tutorialid));
        $tutorial = array_dot(objectToArray($tutorial));
        $tutorial = Tutorials::find((int) $assessment->tutorialid);
        $studentid = $assessment->studentid;
        $student = User::find($studentid);
        $subject = Subject::find($assessment->subjectid);
        echo "<tr>";
        echo "<td>";
        echo $assessment->id;
        <table id="assessments" class="table table-striped table-bordered bootstrap-datatable datatable">
         <thead>
            <tr>
                <th>#ID</th>
                <th>Title</th>
                <th>Subject</th>
                <th>Submitted To</th>
                <th>Related Tutorial</th>
                <th>Submitted On</th>
                <th>Last Updated</th>
                <th>Marks</th>
            </tr>
        </thead>
        <tbody>
            <?php 
$assessments = Assessments::where('studentid', '=', Sentry::getUser()->id)->get();
foreach ($assessments as $assessment) {
    $subjectid = $assessment->subjectid;
    $subject = Subject::find($subjectid);
    $teacherid = $assessment->teacherid;
    $teacher = User::find($teacherid);
    $tutorialid = $assessment->tutorialid;
    $tutorial = Tutorials::find($tutorialid);
    echo "<tr>";
    echo "<td>";
    echo $assessment->id;
    echo "</td>";
    echo "<td>";
    echo "<a href='/assessment/update/" . $assessment->id . "'>{$assessment->title}";
    echo "</td>";
    echo "<td>";
Esempio n. 6
0
<b>Path(s):</b> 
<? foreach($to_assess as $path => $assess) print "<div style='margin-left:0.5cm;'>$path (" . get_evaluation_img($assess,false,false,true) . " " .  $doc_assessments[$assess]. ")</div>";
 if ($do_siblings == "yes") print " <i>and its siblings</i>"; 
 //print_r($to_assess);
 ?>
</div>
</div>

<div><a href="javascript:window.parent.document.getElementById('assessing').style.visibility = 'hidden'">Hide</a></div>

<?
$header_done = 1;

// (1) Retrieve & add assessment ---------------------------

$doc_assessments = new Assessments($id_pool, "$file", "","");
$f = false;

// if ($do_siblings == "yes") {
// 	if (sizeof($assess) > 1) fatal_error("Sibling mode AND more than one path !");
// 	$r = path2record("$directory/$file","$paths[0]");
// 	if (!$r) fatal_error("No record for $paths[0] in $directory/$file");
// 	if (!preg_match("#^(.*)/[^/]+#", $paths[0], $match)) fatal_error("Can't compute the parent path of $paths[0]");
// 	$ppath = $match[1];
// 	$qh = sql_query("SELECT tag, rank FROM map WHERE parent=$r[parent]");
// 	while ($row = sql_fetch_array($qh)) {
// 		$cpath = "$ppath/$row[0][$row[1]]";
// 		$e = &$doc_assessments->get_element("$ppath/$row[0][$row[1]]");
// 		if ((!$e || ($e->get_assessment() == 'U') || $assess == "U") && $paths[0] != $cpath) {
// 			$paths[] = $cpath;
// 		}
Esempio n. 7
0
echo sizeof($toremove);
?>
 to remove.</div>
<?
   if (!$write_access) {
      ?><script type="text/javascript">
            ref.Message.show("warning","Pool is read-only.");
            ref.XRai.saved(false);
      </script><?
      exit();
   }
?>
</div>
<?

$assessments = Assessments::create($id_pool, $collection, $file);
if (DB::isError($assessments)) {
?><script type="text/javascript">alert("Assessments could not be saved (database error).");</script><?
} else if ($assessments->getVersion() != $aversion) {
?><script type="text/javascript">alert("Assessments could not be saved: the version you assessed has been modified by someone else.");</script><?
   if ($do_debug) print "<div>Current version is " . $assessments->getVersion() . " but base version is $aversion</div>";
} else {
   // Start the transaction
   $xrai_db->autoCommit(false);
   for($aaaa = true; $aaaa; $aaaa = false) { // useful for breaking the process without exceptions
      $res = $assessments->setNextVersion();
      if (DB::isError($res)) break;
      $res = $assessments->setStatus($docstatus);
      if (DB::isError($res)) break;
      $res = $assessments->setHasRelevant($hasrelevant);
      if ($do_debug) print "<div>Relevance status: " . ($hasrelevant ? "true" : "false") . "</div>";
 public function teacherUpdate($dash, $id)
 {
     $assessmentid = $id;
     $assessment = Assessments::findOrFail($assessmentid);
     $userid = $assessment->studentid;
     $validator = Validator::make(Input::all(), ['id' => 'required|exists:assessments,id', 'title' => 'required|max:128|min:5|exists:assessments,title,id,' . $id, 'description' => 'max:1024|exists:assessments,description,id,' . $id, 'related_tutorial' => "required|exists:assessments,tutorialid,studentid," . $userid, 'submitted_to' => 'required|exists:assessments,teacherid,id,' . $id, 'subject' => 'required|exists:assessments,subjectid,id,' . $id, 'marks' => 'required|integer|between:0,100', 'remarks' => 'required|max:1024|min:4']);
     if ($validator->fails()) {
         Input::flash();
         return Redirect::to(URL::previous())->withErrors($validator);
     }
     $user = Sentry::getUser()->id;
     if ($user == $assessment->teacherid) {
         if ($assessment->assessmenttype == 'exam') {
         } else {
             $assessment->marks = Input::get('marks');
         }
         $assessment->result = Input::get('remarks');
         $assessment->save();
     }
     return Redirect::to(URL::previous());
 }
Esempio n. 9
0
$studentquery = DB::select(DB::raw('SELECT COUNT(`dob`) FROM `students` WHERE `created_at` >= CURDATE() - INTERVAL 1 DAY'));
$userquery = DB::select(DB::raw('SELECT COUNT(`email`) FROM `users` WHERE `created_at` >= CURDATE() - INTERVAL 1 DAY'));
$tutorialquery = DB::select(DB::raw('SELECT COUNT(`id`) FROM `tutorials` WHERE `created_at` >= CURDATE() - INTERVAL 1 DAY'));
$assessmentquery = DB::select(DB::raw('SELECT COUNT(`id`) FROM `assessments` WHERE `created_at` >= CURDATE() - INTERVAL 1 DAY'));
$stresult = objectToArray($studentquery);
$usresult = objectToArray($userquery);
$turesult = objectToArray($tutorialquery);
$asresult = objectToArray($assessmentquery);
$todayusercount = $usresult[0]['COUNT(`email`)'];
$usercountall = User::all()->count();
$todaystudentcount = $stresult[0]['COUNT(`dob`)'];
$studentcountall = Student::all()->count();
$todaytutorialcount = $turesult[0]['COUNT(`id`)'];
$tutorialcountall = Tutorials::all()->count();
$todayassessmentcount = $asresult[0]['COUNT(`id`)'];
$assessmentcountall = Assessments::all()->count();
?>
<div class="sortable row-fluid">
                <a data-rel="tooltip" title="{{ $todayusercount }} new members." class="well span3 top-block" href="#">
                    <span class="icon32 icon-red icon-user"></span>
                    <div>Total Members</div>
                    <div>{{ $usercountall }}</div>
                    <span class="notification">{{ $todayusercount }}</span>
                </a>

                <a data-rel="tooltip" title="{{ $todaystudentcount }} new students." class="well span3 top-block" href="#">
                    <span class="icon32 icon-blue icon-user"></span>
                    <div>Total Students</div>
                    <div>{{ $studentcountall }} </div>
                    <span class="notification blue">{{ $todaystudentcount }}</span>
                </a>
Esempio n. 10
0
            <div>
        {{$breadcrumbs}}
            </div>

            <!--TODO: Editing Template  -->
                <div class="box span12">
                    <div class="box-header well">
                        <h2><i class="icon-info-sign"></i>Rate Assessment Submission</h2>
                    </div>
                    <div class="box-content" style="display: block;">
                        <div class="container-fluid">
                        <div class="row-fluid">
                            <div class="span6">
                            <?php 
$assessment = Assessments::findOrFail($id);
echo Form::open(array('url' => '/assessment/' . $id, 'method' => 'POST', 'class' => 'form-horizontal', 'files' => 'true'));
echo "<fieldset>";
echo Form::label('id', 'ID', array('class' => 'pull-left', 'style' => 'margin:10px;'));
echo Form::text('id', $assessment->id, array('class' => 'pull-right disabled uneditable-input', 'style' => 'margin:5px;'));
echo Form::label('title', 'Title', array('class' => 'pull-left', 'style' => 'clear:left;margin:10px;'));
echo Form::text('title', $assessment->title, array('class' => 'pull-right disabled uneditable-input', 'placeholder' => 'Title of the Assessment', 'style' => 'clear:right;margin:5px;'));
echo Form::label('description', 'Description', array('class' => 'pull-left', 'style' => 'margin:10px;clear:left;'));
echo Form::text('description', $assessment->description, array('class' => 'pull-right disabled uneditable-input', 'placeholder' => 'Small Description of the Assessment', 'style' => 'clear:right;margin:5px;'));
echo Form::label('related_tutorial', 'Related Tutorial', array('class' => 'pull-left', 'style' => 'clear:left;margin:10px'));
$tutorialid = $assessment->tutorialid;
$tutoriallist = array();
// $tutorial = Tutorials::where('id','=',$tutorialid);
// var_dump($tutorial);
if ($tutorialid !== NULL) {
    $tutorial = Tutorials::findOrFail($tutorialid);
Esempio n. 11
0
 public function doExam($tid, $eid, $hash)
 {
     $userid = Sentry::getUser()->id;
     $decryptedhash = Crypt::decrypt($hash);
     if ($decryptedhash == 'tutorial-' . $tid) {
         Session::put('halt_tutorial_except', 0);
         Session::put('examid', 0);
         $validator = Validator::make(Input::all(), ['related_tutorial' => "required|unique:assessments,tutorialid,NULL,id,studentid," . $userid, 'submitted_to' => 'required|exists:users,id', 'subject' => 'required|exists:subjects,id']);
         if ($validator->fails()) {
             return "EXAM PAPER HAS BEEN MODIFIED or SUBMITTED AGAIN.Click here to go to <a href='" . Setting::get('app.url') . "'>HOME PAGE</a>. ANSWERS ARE NOT ACCEPTED.";
         }
         $tutorial = Tutorials::findOrFail($tid);
         $exam = Exams::find($eid);
         $data = array();
         $assessment = new Assessments();
         $assessment->title = $tutorial->name . ' Exam For ' . $exam->title;
         $assessment->description = $exam->title . ' exam done for ' . $tutorial->name . ' by ' . Sentry::getUser()->first_name . ' ' . Sentry::getUser()->last_name;
         $assessment->assessmenttype = "exam";
         $assessment->tutorialid = $tid;
         $assessment->studentid = Sentry::getUser()->id;
         $assessment->teacherid = $tutorial->createdby;
         $assessment->subjectid = $tutorial->subjectid;
         $assessment->save();
         $questions = $exam->totalquestions;
         $input = Input::all();
         for ($qc = 1; $qc <= $questions;) {
             Session::put('checkboxcount', 1);
             $data['answers'][$qc][1] = '';
             $data['answers'][$qc][2] = '';
             $data['answers'][$qc][3] = '';
             $data['answers'][$qc][4] = '';
             if (!isset($input['checkbox_' . $qc])) {
                 $qc++;
                 continue;
             }
             foreach ($input['checkbox_' . $qc] as $answer) {
                 // var_dump($answer);
                 $qu = Session::get('checkboxcount', 0);
                 $data['answers'][$qc][$qu] = $answer;
                 Session::put('checkboxcount', ++$qu);
             }
             $qc++;
         }
         $answerdata = json_encode($data);
         $nassessment = DB::table('assessments')->orderby('id', 'desc')->first();
         $encryptedpath = 'questiondata';
         // var_dump(app_path().'/files/assessment/'.$nassessment->id.'/exam-'.$tid.'/');
         File::makeDirectory(app_path() . '/files/assessment/' . $nassessment->id . '/exam-' . $eid, 0777, true);
         file_put_contents(app_path() . '/files/assessment/' . $nassessment->id . '/exam-' . $exam->id . '/' . $encryptedpath . '.json', $answerdata);
         $failedquestions = [];
         file_put_contents(app_path() . '/files/assessment/' . $assessment->id . '/exam-' . $exam->id . '/questionfailed.json', $failedquestions);
         return Redirect::to('/');
         // var_dump($decryptedhash);
     } else {
         return Redirect::to(URL::previous());
     }
 }
Esempio n. 12
0
                        <?php 
$tohash = 'tutorial-' . $tutorial->id;
$encrypted = Crypt::encrypt($tohash);
$encryptionexam = Crypt::encrypt($tohash);
$exams = unserialize($tutorial->exams);
Session::put($tohash, $encrypted);
function checkSubject($subjects, $subject)
{
    foreach ($subjects as $s) {
        if ($s == $subject) {
            return 1;
        }
    }
    return 0;
}
$testcount = Assessments::whereRaw('`tutorialid` = ? and `studentid` = ?', [$tutorial->id, Sentry::getUser()->id])->count();
$usere = Sentry::getUser();
$usergroup = $usere->getGroups();
$usergroupe = json_decode($usergroup, true);
$usergroupe[0]['pivot']['group_id'];
$group = Sentry::findGroupById($usergroupe[0]['pivot']['group_id']);
$truth = 0;
$groupname = $group->name;
if ($groupname == 'teachers') {
    $user = Teacher::findOrFail($usere->id);
    $ssubjects = $user->extra;
    $subjectstodo = unserialize($ssubjects);
    if ($subjectstodo != null) {
        $truth = checkSubject($subjectstodo, $tutorial->subjectid);
    }
} elseif ($groupname == 'students') {