/**
  * Shows admin menu for question
  * @param int Survey id
  * @param int Group id
  * @param int Question id
  * @param string action
  */
 function _questionbar($iSurveyID, $gid, $qid, $action = null)
 {
     $baselang = Survey::model()->findByPk($iSurveyID)->language;
     //Show Question Details
     $qrrow = Question::model()->findByAttributes(array('qid' => $qid, 'gid' => $gid, 'sid' => $iSurveyID, 'language' => $baselang));
     if (is_null($qrrow)) {
         return;
     }
     // Throw 404 ....
     $questionsummary = "<div class='menubar'>\n";
     // Check if other questions in the Survey are dependent upon this question
     $condarray = getQuestDepsForConditions($iSurveyID, "all", "all", $qid, "by-targqid", "outsidegroup");
     $sumresult1 = Survey::model()->findByPk($iSurveyID);
     if (is_null($sumresult1)) {
         Yii::app()->session['flashmessage'] = gT("Invalid survey ID");
         $this->getController()->redirect(array("admin/index"));
     }
     //  if surveyid is invalid then die to prevent errors at a later time
     $surveyinfo = $sumresult1->attributes;
     $surveyinfo = array_map('flattenText', $surveyinfo);
     $aData['activated'] = $surveyinfo['active'];
     $qrrow = $qrrow->attributes;
     $aData['languagelist'] = Survey::model()->findByPk($iSurveyID)->getAllLanguages();
     $aData['qtypes'] = $qtypes = getQuestionTypeList('', 'array');
     // Warning of lack of sub-questions or answers
     $aWarnings = array();
     if ($qtypes[$qrrow['type']]['answerscales'] > 0 && !Answer::model()->count("qid=:qid AND language=:language and scale_id=0", array(':qid' => $qid, ':language' => $baselang))) {
         $aWarnings[] = array('url' => App()->createUrl("admin/questions", array("sa" => "answeroptions", "surveyid" => $iSurveyID, "gid" => $gid, "qid" => $qid)), 'img' => 'answers_20.png', 'text' => gT("You need to add answer options to this question.", 'unescaped'), 'help' => gT("Edit answer options for this question.", 'unescaped'));
     } elseif ($qtypes[$qrrow['type']]['answerscales'] > 1 && !Answer::model()->count("qid=:qid AND language=:language and scale_id=1", array(':qid' => $qid, ':language' => $baselang))) {
         $aWarnings[] = array('url' => App()->createUrl("admin/questions", array("sa" => "answeroptions", "surveyid" => $iSurveyID, "gid" => $gid, "qid" => $qid)), 'img' => 'answers_20.png', 'text' => gT("You need to add answer options to this question.", 'unescaped'), 'help' => gT("Edit answer options for this question.", 'unescaped'));
     }
     if ($qtypes[$qrrow['type']]['subquestions'] > 0 && !Question::model()->count("parent_qid=:qid AND language=:language and scale_id=0", array(':qid' => $qid, ':language' => $baselang))) {
         $aWarnings[] = array('url' => App()->createUrl("admin/questions", array("sa" => "subquestions", "surveyid" => $iSurveyID, "gid" => $gid, "qid" => $qid)), 'img' => $qtypes[$qrrow['type']]['subquestions'] > 1 ? "subquestions2d_20.png" : "subquestions_20.png", 'text' => gT("You need to add subquestions options to this question.", 'unescaped'), 'help' => gT("Edit subquestions options for this question.", 'unescaped'));
     } elseif ($qtypes[$qrrow['type']]['subquestions'] > 1 && !Question::model()->count("parent_qid=:qid AND language=:language and scale_id=1", array(':qid' => $qid, ':language' => $baselang))) {
         $aWarnings[] = array('url' => App()->createUrl("admin/questions", array("sa" => "subquestions", "surveyid" => $iSurveyID, "gid" => $gid, "qid" => $qid)), 'img' => 'subquestions2d_20.png', 'text' => gT("You need to add subquestions to this question.", 'unescaped'), 'help' => gT("Edit subquestions for this question.", 'unescaped'));
     }
     $aData['aWarnings'] = $aWarnings;
     if ($action == 'editansweroptions' || $action == "editsubquestions" || $action == "editquestion" || $action == "editdefaultvalues" || $action == "editdefaultvalues" || $action == "copyquestion") {
         $qshowstyle = "style='display: none'";
     } else {
         $qshowstyle = "";
     }
     $aData['qshowstyle'] = $qshowstyle;
     $aData['action'] = $action;
     $aData['surveyid'] = $iSurveyID;
     $aData['qid'] = $qid;
     $aData['gid'] = $gid;
     $aData['qrrow'] = $qrrow;
     $aData['baselang'] = $baselang;
     $aAttributesWithValues = Question::model()->getAdvancedSettingsWithValues($qid, $qrrow['type'], $iSurveyID, $baselang);
     $DisplayArray = array();
     foreach ($aAttributesWithValues as $aAttribute) {
         if ($aAttribute['i18n'] == false && isset($aAttribute['value']) && $aAttribute['value'] != $aAttribute['default'] || $aAttribute['i18n'] == true && isset($aAttribute['value'][$baselang]) && $aAttribute['value'][$baselang] != $aAttribute['default']) {
             if ($aAttribute['inputtype'] == 'singleselect') {
                 $aAttribute['value'] = $aAttribute['options'][$aAttribute['value']];
             }
             /*
             if ($aAttribute['name']=='relevance')
             {
             $sRelevance = $aAttribute['value'];
             if ($sRelevance !== '' && $sRelevance !== '1' && $sRelevance !== '0')
             {
             LimeExpressionManager::ProcessString("{" . $sRelevance . "}");    // tests Relevance equation so can pretty-print it
             $aAttribute['value']= LimeExpressionManager::GetLastPrettyPrintExpression();
             }
             }
             */
             $DisplayArray[] = $aAttribute;
         }
     }
     $aData['advancedsettings'] = $DisplayArray;
     $aData['condarray'] = $condarray;
     $aData['sImageURL'] = Yii::app()->getConfig('adminimageurl');
     $aData['iIconSize'] = Yii::app()->getConfig('adminthemeiconsize');
     $questionsummary .= $this->getController()->renderPartial('/admin/survey/Question/questionbar_view', $aData, true);
     $finaldata['display'] = $questionsummary;
     $this->getController()->renderPartial('/survey_view', $finaldata);
 }
 /**
  * Database::index()
  *
  * @param mixed $sa
  * @return
  */
 function index($sa = null)
 {
     $sAction = Yii::app()->request->getPost('action');
     $iSurveyID = isset($_POST['sid']) ? $_POST['sid'] : returnGlobal('sid');
     $iQuestionGroupID = returnGlobal('gid');
     $iQuestionID = returnGlobal('qid');
     // TODO: This variable seems to be never set or used in any function call?
     $sDBOutput = '';
     $oFixCKeditor = new LSYii_Validators();
     $oFixCKeditor->fixCKeditor = true;
     $oFixCKeditor->xssfilter = false;
     if ($sAction == "updatedefaultvalues" && Permission::model()->hasSurveyPermission($iSurveyID, 'surveycontent', 'update')) {
         $aSurveyLanguages = Survey::model()->findByPk($iSurveyID)->additionalLanguages;
         $sBaseLanguage = Survey::model()->findByPk($iSurveyID)->language;
         array_unshift($aSurveyLanguages, $sBaseLanguage);
         Question::model()->updateAll(array('same_default' => Yii::app()->request->getPost('samedefault') ? 1 : 0), 'sid=:sid ANd qid=:qid', array(':sid' => $iSurveyID, ':qid' => $iQuestionID));
         $arQuestion = Question::model()->findByAttributes(array('qid' => $iQuestionID));
         $sQuestionType = $arQuestion['type'];
         $aQuestionTypeList = getQuestionTypeList('', 'array');
         if ($aQuestionTypeList[$sQuestionType]['answerscales'] > 0 && $aQuestionTypeList[$sQuestionType]['subquestions'] == 0) {
             for ($iScaleID = 0; $iScaleID < $aQuestionTypeList[$sQuestionType]['answerscales']; $iScaleID++) {
                 foreach ($aSurveyLanguages as $sLanguage) {
                     if (!is_null(Yii::app()->request->getPost('defaultanswerscale_' . $iScaleID . '_' . $sLanguage))) {
                         $this->_updateDefaultValues($iQuestionID, 0, $iScaleID, '', $sLanguage, Yii::app()->request->getPost('defaultanswerscale_' . $iScaleID . '_' . $sLanguage), true);
                     }
                     if (!is_null(Yii::app()->request->getPost('other_' . $iScaleID . '_' . $sLanguage))) {
                         $this->_updateDefaultValues($iQuestionID, 0, $iScaleID, 'other', $sLanguage, Yii::app()->request->getPost('other_' . $iScaleID . '_' . $sLanguage), true);
                     }
                 }
             }
         }
         if ($aQuestionTypeList[$sQuestionType]['subquestions'] > 0) {
             foreach ($aSurveyLanguages as $sLanguage) {
                 $arQuestions = Question::model()->findAllByAttributes(array('sid' => $iSurveyID, 'gid' => $iQuestionGroupID, 'parent_qid' => $iQuestionID, 'language' => $sLanguage, 'scale_id' => 0));
                 for ($iScaleID = 0; $iScaleID < $aQuestionTypeList[$sQuestionType]['subquestions']; $iScaleID++) {
                     foreach ($arQuestions as $aSubquestionrow) {
                         if (!is_null(Yii::app()->request->getPost('defaultanswerscale_' . $iScaleID . '_' . $sLanguage . '_' . $aSubquestionrow['qid']))) {
                             $this->_updateDefaultValues($iQuestionID, $aSubquestionrow['qid'], $iScaleID, '', $sLanguage, Yii::app()->request->getPost('defaultanswerscale_' . $iScaleID . '_' . $sLanguage . '_' . $aSubquestionrow['qid']), true);
                         }
                     }
                 }
             }
         }
         if ($aQuestionTypeList[$sQuestionType]['answerscales'] == 0 && $aQuestionTypeList[$sQuestionType]['subquestions'] == 0) {
             foreach ($aSurveyLanguages as $sLanguage) {
                 // Qick and dirty insert for yes/no defaul value
                 // write the the selectbox option, or if "EM" is slected, this value to table
                 if ($sQuestionType == 'Y') {
                     /// value for all langs
                     if (Yii::app()->request->getPost('samedefault') == 1) {
                         $sLanguage = $aSurveyLanguages[0];
                         // turn
                     } else {
                         $sCurrentLang = $sLanguage;
                         // edit the next lines
                     }
                     if (Yii::app()->request->getPost('defaultanswerscale_0_' . $sLanguage) == 'EM') {
                         // Case EM, write expression to database
                         $this->_updateDefaultValues($iQuestionID, 0, 0, '', $sLanguage, Yii::app()->request->getPost('defaultanswerscale_0_' . $sLanguage . '_EM'), true);
                     } else {
                         // Case "other", write list value to database
                         $this->_updateDefaultValues($iQuestionID, 0, 0, '', $sLanguage, Yii::app()->request->getPost('defaultanswerscale_0_' . $sLanguage), true);
                     }
                     ///// end yes/no
                 } else {
                     if (!is_null(Yii::app()->request->getPost('defaultanswerscale_0_' . $sLanguage . '_0'))) {
                         $this->_updateDefaultValues($iQuestionID, 0, 0, '', $sLanguage, Yii::app()->request->getPost('defaultanswerscale_0_' . $sLanguage . '_0'), true);
                     }
                 }
             }
         }
         Yii::app()->session['flashmessage'] = gT("Default value settings were successfully saved.");
         LimeExpressionManager::SetDirtyFlag();
         if ($sDBOutput != '') {
             echo $sDBOutput;
         } else {
             if (Yii::app()->request->getPost('close-after-save') === 'true') {
                 $this->getController()->redirect(array('admin/questions/sa/view/surveyid/' . $iSurveyID . '/gid/' . $iQuestionGroupID . '/qid/' . $iQuestionID));
             }
             $this->getController()->redirect(array('admin/questions/sa/editdefaultvalues/surveyid/' . $iSurveyID . '/gid/' . $iQuestionGroupID . '/qid/' . $iQuestionID));
         }
     }
     if ($sAction == "updateansweroptions" && Permission::model()->hasSurveyPermission($iSurveyID, 'surveycontent', 'update')) {
         Yii::app()->loadHelper('database');
         $aSurveyLanguages = Survey::model()->findByPk($iSurveyID)->additionalLanguages;
         $sBaseLanguage = Survey::model()->findByPk($iSurveyID)->language;
         array_unshift($aSurveyLanguages, $sBaseLanguage);
         $arQuestion = Question::model()->findByAttributes(array('qid' => $iQuestionID));
         $sQuestionType = $arQuestion['type'];
         // Checked)
         $aQuestionTypeList = getQuestionTypeList('', 'array');
         $iScaleCount = $aQuestionTypeList[$sQuestionType]['answerscales'];
         //First delete all answers
         Answer::model()->deleteAllByAttributes(array('qid' => $iQuestionID));
         LimeExpressionManager::RevertUpgradeConditionsToRelevance($iSurveyID);
         for ($iScaleID = 0; $iScaleID < $iScaleCount; $iScaleID++) {
             $iMaxCount = (int) Yii::app()->request->getPost('answercount_' . $iScaleID);
             for ($iSortOrderID = 1; $iSortOrderID < $iMaxCount; $iSortOrderID++) {
                 $sCode = sanitize_paranoid_string(Yii::app()->request->getPost('code_' . $iSortOrderID . '_' . $iScaleID));
                 $iAssessmentValue = (int) Yii::app()->request->getPost('assessment_' . $iSortOrderID . '_' . $iScaleID);
                 foreach ($aSurveyLanguages as $sLanguage) {
                     $sAnswerText = Yii::app()->request->getPost('answer_' . $sLanguage . '_' . $iSortOrderID . '_' . $iScaleID);
                     // Fix bug with FCKEditor saving strange BR types
                     $sAnswerText = $oFixCKeditor->fixCKeditor($sAnswerText);
                     // Now we insert the answers
                     $iInsertCount = Answer::model()->insertRecords(array('code' => $sCode, 'answer' => $sAnswerText, 'qid' => $iQuestionID, 'sortorder' => $iSortOrderID, 'language' => $sLanguage, 'assessment_value' => $iAssessmentValue, 'scale_id' => $iScaleID));
                     if (!$iInsertCount) {
                         Yii::app()->setFlashMessage(gT("Failed to update answers"), 'error');
                     }
                 }
                 // Updating code (oldcode!==null) => update condition with the new code
                 $sOldCode = Yii::app()->request->getPost('oldcode_' . $iSortOrderID . '_' . $iScaleID);
                 if (isset($sOldCode) && $sCode !== $sOldCode) {
                     Condition::model()->updateAll(array('value' => $sCode), 'cqid=:cqid AND value=:value', array(':cqid' => $iQuestionID, ':value' => $sOldCode));
                 }
             }
             // for ($sortorderid=0;$sortorderid<$maxcount;$sortorderid++)
         }
         //  for ($scale_id=0;
         LimeExpressionManager::UpgradeConditionsToRelevance($iSurveyID);
         if (!Yii::app()->request->getPost('bFullPOST')) {
             Yii::app()->setFlashMessage(gT("Not all answer options were saved. This usually happens due to server limitations ( PHP setting max_input_vars) - please contact your system administrator."));
         } else {
             Yii::app()->session['flashmessage'] = gT("Answer options were successfully saved.");
         }
         LimeExpressionManager::SetDirtyFlag();
         if ($sDBOutput != '') {
             echo $sDBOutput;
         } else {
             if (Yii::app()->request->getPost('close-after-save') === 'true') {
                 $this->getController()->redirect(array('admin/questions/sa/view/surveyid/' . $iSurveyID . '/gid/' . $iQuestionGroupID . '/qid/' . $iQuestionID));
             }
             $this->getController()->redirect(array('/admin/questions/sa/answeroptions/surveyid/' . $iSurveyID . '/gid/' . $iQuestionGroupID . '/qid/' . $iQuestionID));
         }
     }
     if ($sAction == "updatesubquestions" && Permission::model()->hasSurveyPermission($iSurveyID, 'surveycontent', 'update')) {
         Yii::app()->loadHelper('database');
         $aSurveyLanguages = Survey::model()->findByPk($iSurveyID)->additionalLanguages;
         $sBaseLanguage = Survey::model()->findByPk($iSurveyID)->language;
         array_unshift($aSurveyLanguages, $sBaseLanguage);
         $arQuestion = Question::model()->findByAttributes(array('qid' => $iQuestionID));
         $sQuestionType = $arQuestion['type'];
         // Checked
         $aQuestionTypeList = getQuestionTypeList('', 'array');
         $iScaleCount = $aQuestionTypeList[$sQuestionType]['subquestions'];
         // First delete any deleted ids
         $aDeletedQIDs = explode(' ', trim(Yii::app()->request->getPost('deletedqids')));
         LimeExpressionManager::RevertUpgradeConditionsToRelevance($iSurveyID);
         $aDeletedQIDs = array_unique($aDeletedQIDs, SORT_NUMERIC);
         foreach ($aDeletedQIDs as $iDeletedQID) {
             $iDeletedQID = (int) $iDeletedQID;
             if ($iDeletedQID > 0) {
                 // don't remove undefined
                 $iInsertCount = Question::model()->deleteAllByAttributes(array('qid' => $iDeletedQID));
                 if (!$iInsertCount) {
                     Yii::app()->setFlashMessage(gT("Failed to delete answer"), 'error');
                 }
             }
         }
         //Determine ids by evaluating the hidden field
         $aRows = array();
         $aCodes = array();
         $aOldCodes = array();
         $aRelevance = array();
         foreach ($_POST as $sPOSTKey => $sPOSTValue) {
             $sPOSTKey = explode('_', $sPOSTKey);
             if ($sPOSTKey[0] == 'answer') {
                 $aRows[$sPOSTKey[3]][$sPOSTKey[1]][$sPOSTKey[2]] = $sPOSTValue;
             }
             if ($sPOSTKey[0] == 'code') {
                 $aCodes[$sPOSTKey[2]][] = $sPOSTValue;
             }
             if ($sPOSTKey[0] == 'oldcode') {
                 $aOldCodes[$sPOSTKey[2]][] = $sPOSTValue;
             }
             if ($sPOSTKey[0] == 'relevance') {
                 $aRelevance[$sPOSTKey[2]][] = $sPOSTValue;
             }
         }
         $aInsertQID = array();
         for ($iScaleID = 0; $iScaleID < $iScaleCount; $iScaleID++) {
             foreach ($aSurveyLanguages as $sLanguage) {
                 $iPosition = 0;
                 foreach ($aRows[$iScaleID][$sLanguage] as $subquestionkey => $subquestionvalue) {
                     if (substr($subquestionkey, 0, 3) != 'new') {
                         $oSubQuestion = Question::model()->find("qid=:qid AND language=:language", array(":qid" => $subquestionkey, ':language' => $sLanguage));
                         if (!is_object($oSubQuestion)) {
                             throw new CHttpException(502, "could not find subquestion {$subquestionkey} !");
                         }
                         $oSubQuestion->question_order = $iPosition + 1;
                         $oSubQuestion->title = $aCodes[$iScaleID][$iPosition];
                         $oSubQuestion->question = $subquestionvalue;
                         $oSubQuestion->scale_id = $iScaleID;
                         $oSubQuestion->relevance = isset($aRelevance[$iScaleID][$iPosition]) ? $aRelevance[$iScaleID][$iPosition] : "";
                     } else {
                         if (!isset($aInsertQID[$iScaleID][$iPosition])) {
                             $oSubQuestion = new Question();
                             $oSubQuestion->sid = $iSurveyID;
                             $oSubQuestion->gid = $iQuestionGroupID;
                             $oSubQuestion->question_order = $iPosition + 1;
                             $oSubQuestion->title = $aCodes[$iScaleID][$iPosition];
                             $oSubQuestion->question = $subquestionvalue;
                             $oSubQuestion->parent_qid = $iQuestionID;
                             $oSubQuestion->language = $sLanguage;
                             $oSubQuestion->scale_id = $iScaleID;
                             $oSubQuestion->relevance = isset($aRelevance[$iScaleID][$iPosition]) ? $aRelevance[$iScaleID][$iPosition] : "";
                         } else {
                             $oSubQuestion = Question::model()->find("qid=:qid AND language=:language", array(":qid" => $aInsertQID[$iScaleID][$iPosition], ':language' => $sLanguage));
                             if (!$oSubQuestion) {
                                 $oSubQuestion = new Question();
                             }
                             $oSubQuestion->sid = $iSurveyID;
                             $oSubQuestion->qid = $aInsertQID[$iScaleID][$iPosition];
                             $oSubQuestion->gid = $iQuestionGroupID;
                             $oSubQuestion->question_order = $iPosition + 1;
                             $oSubQuestion->title = $aCodes[$iScaleID][$iPosition];
                             $oSubQuestion->question = $subquestionvalue;
                             $oSubQuestion->parent_qid = $iQuestionID;
                             $oSubQuestion->language = $sLanguage;
                             $oSubQuestion->scale_id = $iScaleID;
                             $oSubQuestion->relevance = isset($aRelevance[$iScaleID][$iPosition]) ? $aRelevance[$iScaleID][$iPosition] : "";
                         }
                     }
                     if ($oSubQuestion->qid) {
                         switchMSSQLIdentityInsert('questions', true);
                         $bSubQuestionResult = $oSubQuestion->save();
                         switchMSSQLIdentityInsert('questions', false);
                     } else {
                         $bSubQuestionResult = $oSubQuestion->save();
                     }
                     if ($bSubQuestionResult) {
                         if (substr($subquestionkey, 0, 3) != 'new' && isset($aOldCodes[$iScaleID][$iPosition]) && $aCodes[$iScaleID][$iPosition] !== $aOldCodes[$iScaleID][$iPosition]) {
                             Condition::model()->updateAll(array('cfieldname' => '+' . $iSurveyID . 'X' . $iQuestionGroupID . 'X' . $iQuestionID . $aCodes[$iScaleID][$iPosition], 'value' => $aCodes[$iScaleID][$iPosition]), 'cqid=:cqid AND cfieldname=:cfieldname AND value=:value', array(':cqid' => $iQuestionID, ':cfieldname' => $iSurveyID . 'X' . $iQuestionGroupID . 'X' . $iQuestionID, ':value' => $aOldCodes[$iScaleID][$iPosition]));
                         }
                         if (!isset($aInsertQID[$iScaleID][$iPosition])) {
                             $aInsertQID[$iScaleID][$iPosition] = $oSubQuestion->qid;
                         }
                     } else {
                         $aErrors = $oSubQuestion->getErrors();
                         if (count($aErrors)) {
                             //$sErrorMessage=gT("Question could not be updated with this errors:");
                             foreach ($aErrors as $sAttribute => $aStringErrors) {
                                 foreach ($aStringErrors as $sStringErrors) {
                                     Yii::app()->setFlashMessage(sprintf(gT("Error on %s for subquestion %s: %s"), $sAttribute, $aCodes[$iScaleID][$iPosition], $sStringErrors), 'error');
                                 }
                             }
                         } else {
                             Yii::app()->setFlashMessage(sprintf(gT("Subquestions %s could not be updated."), $aCodes[$iScaleID][$iPosition]), 'error');
                         }
                     }
                     $iPosition++;
                 }
             }
         }
         LimeExpressionManager::UpgradeConditionsToRelevance($iSurveyID);
         // Do it only if there are no error ?
         if (!isset($aErrors) || !count($aErrors)) {
             if (!Yii::app()->request->getPost('bFullPOST')) {
                 Yii::app()->session['flashmessage'] = gT("Not all subquestions were saved. This usually happens due to server limitations ( PHP setting max_input_vars) - please contact your system administrator.");
             } else {
                 Yii::app()->session['flashmessage'] = gT("Subquestions were successfully saved.");
             }
         }
         //$action='editsubquestions';
         LimeExpressionManager::SetDirtyFlag();
         if ($sDBOutput != '') {
             echo 'Problem in database controller: ' . $sDBOutput;
         } else {
             if (Yii::app()->request->getPost('close-after-save') === 'true') {
                 $this->getController()->redirect(array('/admin/questions/sa/view/surveyid/' . $iSurveyID . '/gid/' . $iQuestionGroupID . '/qid/' . $iQuestionID));
             }
             $this->getController()->redirect(array('/admin/questions/sa/subquestions/surveyid/' . $iSurveyID . '/gid/' . $iQuestionGroupID . '/qid/' . $iQuestionID));
         }
     }
     /**
      * Insert / Copy question
      */
     if (in_array($sAction, array('insertquestion', 'copyquestion')) && Permission::model()->hasSurveyPermission($iSurveyID, 'surveycontent', 'create')) {
         $survey = Survey::model()->findByPk($iSurveyID);
         $sBaseLanguage = $survey->language;
         // Abort if survey is active
         if ($survey->active !== 'N') {
             Yii::app()->setFlashMessage(gT("You can't insert a new question when the survey is active."), 'error');
             $this->getController()->redirect(array("/admin/survey/sa/view/surveyid/" . $survey->sid), "refresh");
         }
         if (strlen(Yii::app()->request->getPost('title')) < 1) {
             Yii::app()->setFlashMessage(gT("The question could not be added. You must enter at least a question code."), 'error');
         } else {
             // For Bootstrap Version usin YiiWheels switch :
             $_POST['mandatory'] = Yii::app()->request->getPost('mandatory') == '1' ? 'Y' : 'N';
             $_POST['other'] = Yii::app()->request->getPost('other') == '1' ? 'Y' : 'N';
             if (Yii::app()->request->getPost('questionposition', "") != "") {
                 $iQuestionOrder = intval(Yii::app()->request->getPost('questionposition'));
                 //Need to renumber all questions on or after this
                 $sQuery = "UPDATE {{questions}} SET question_order=question_order+1 WHERE gid=:gid AND question_order >= :order";
                 Yii::app()->db->createCommand($sQuery)->bindValues(array(':gid' => $iQuestionGroupID, ':order' => $iQuestionOrder))->query();
             } else {
                 $iQuestionOrder = getMaxQuestionOrder($iQuestionGroupID, $iSurveyID);
                 $iQuestionOrder++;
             }
             $sQuestionText = Yii::app()->request->getPost('question_' . $sBaseLanguage, '');
             $sQuestionHelp = Yii::app()->request->getPost('help_' . $sBaseLanguage, '');
             // Fix bug with FCKEditor saving strange BR types : in rules ?
             $sQuestionText = $oFixCKeditor->fixCKeditor($sQuestionText);
             $sQuestionHelp = $oFixCKeditor->fixCKeditor($sQuestionHelp);
             $iQuestionID = 0;
             $oQuestion = new Question();
             $oQuestion->sid = $iSurveyID;
             $oQuestion->gid = $iQuestionGroupID;
             $oQuestion->type = Yii::app()->request->getPost('type');
             $oQuestion->title = Yii::app()->request->getPost('title');
             $oQuestion->question = $sQuestionText;
             $oQuestion->preg = Yii::app()->request->getPost('preg');
             $oQuestion->help = $sQuestionHelp;
             $oQuestion->other = Yii::app()->request->getPost('other');
             // For Bootstrap Version usin YiiWheels switch :
             $oQuestion->mandatory = Yii::app()->request->getPost('mandatory');
             $oQuestion->other = Yii::app()->request->getPost('other');
             $oQuestion->relevance = Yii::app()->request->getPost('relevance');
             $oQuestion->question_order = $iQuestionOrder;
             $oQuestion->language = $sBaseLanguage;
             $oQuestion->save();
             if ($oQuestion) {
                 $iQuestionID = $oQuestion->qid;
             }
             $aErrors = $oQuestion->getErrors();
             if (count($aErrors)) {
                 foreach ($aErrors as $sAttribute => $aStringErrors) {
                     foreach ($aStringErrors as $sStringErrors) {
                         Yii::app()->setFlashMessage(sprintf(gT("Question could not be created with error on %s: %s"), $sAttribute, $sStringErrors), 'error');
                     }
                 }
             }
             // Add other languages
             if ($iQuestionID) {
                 $addlangs = Survey::model()->findByPk($iSurveyID)->additionalLanguages;
                 foreach ($addlangs as $alang) {
                     if ($alang != "") {
                         $langqid = 0;
                         $oQuestion = new Question();
                         $oQuestion->qid = $iQuestionID;
                         $oQuestion->sid = $iSurveyID;
                         $oQuestion->gid = $iQuestionGroupID;
                         $oQuestion->type = Yii::app()->request->getPost('type');
                         $oQuestion->title = Yii::app()->request->getPost('title');
                         $oQuestion->question = Yii::app()->request->getPost('question_' . $alang);
                         $oQuestion->preg = Yii::app()->request->getPost('preg');
                         $oQuestion->help = Yii::app()->request->getPost('help_' . $alang);
                         $oQuestion->other = Yii::app()->request->getPost('other');
                         $oQuestion->mandatory = Yii::app()->request->getPost('mandatory');
                         $oQuestion->relevance = Yii::app()->request->getPost('relevance');
                         $oQuestion->question_order = $iQuestionOrder;
                         $oQuestion->language = $alang;
                         switchMSSQLIdentityInsert('questions', true);
                         // Not sure for this one ?
                         $oQuestion->save();
                         switchMSSQLIdentityInsert('questions', false);
                         if ($oQuestion) {
                             $langqid = $oQuestion->qid;
                         }
                         $aErrors = $oQuestion->getErrors();
                         if (count($aErrors)) {
                             foreach ($aErrors as $sAttribute => $aStringErrors) {
                                 foreach ($aStringErrors as $sStringErrors) {
                                     Yii::app()->setFlashMessage(sprintf(gT("Question in language %s could not be created with error on %s: %s"), $alang, $sAttribute, $sStringErrors), 'error');
                                 }
                             }
                         }
                         #                            if (!$langqid)
                         #                            {
                         #                                Yii::app()->setFlashMessage(gT("Question in language %s could not be created."),'error');
                         #                            }
                     }
                 }
             }
             if (!$iQuestionID) {
                 Yii::app()->setFlashMessage(gT("Question could not be created."), 'error');
             } else {
                 /**
                  *
                  * Copy Question
                  *
                  */
                 if ($sAction == 'copyquestion') {
                     if (returnGlobal('copysubquestions') == "Y") {
                         $aSQIDMappings = array();
                         $r1 = Question::model()->getSubQuestions(returnGlobal('oldqid'));
                         $aSubQuestions = $r1->readAll();
                         foreach ($aSubQuestions as $qr1) {
                             $qr1['parent_qid'] = $iQuestionID;
                             if (isset($aSQIDMappings[$qr1['qid']])) {
                                 $qr1['qid'] = $aSQIDMappings[$qr1['qid']];
                             } else {
                                 $oldqid = $qr1['qid'];
                                 unset($qr1['qid']);
                             }
                             $qr1['gid'] = $iQuestionGroupID;
                             $iInsertID = Question::model()->insertRecords($qr1);
                             if (!isset($qr1['qid'])) {
                                 $aSQIDMappings[$oldqid] = $iInsertID;
                             }
                         }
                     }
                     if (returnGlobal('copyanswers') == "Y") {
                         $r1 = Answer::model()->getAnswers(returnGlobal('oldqid'));
                         $aAnswerOptions = $r1->readAll();
                         foreach ($aAnswerOptions as $qr1) {
                             Answer::model()->insertRecords(array('qid' => $iQuestionID, 'code' => $qr1['code'], 'answer' => $qr1['answer'], 'assessment_value' => $qr1['assessment_value'], 'sortorder' => $qr1['sortorder'], 'language' => $qr1['language'], 'scale_id' => $qr1['scale_id']));
                         }
                     }
                     /**
                      * Copy attribute
                      */
                     if (returnGlobal('copyattributes') == "Y") {
                         $oOldAttributes = QuestionAttribute::model()->findAll("qid=:qid", array("qid" => returnGlobal('oldqid')));
                         foreach ($oOldAttributes as $oOldAttribute) {
                             $attribute = new QuestionAttribute();
                             $attribute->qid = $iQuestionID;
                             $attribute->value = $oOldAttribute->value;
                             $attribute->attribute = $oOldAttribute->attribute;
                             $attribute->language = $oOldAttribute->language;
                             $attribute->save();
                         }
                     }
                     // Since 2.5, user can edit attribute while copying
                     $qattributes = questionAttributes();
                     $validAttributes = $qattributes[Yii::app()->request->getPost('type')];
                     $aLanguages = array_merge(array(Survey::model()->findByPk($iSurveyID)->language), Survey::model()->findByPk($iSurveyID)->additionalLanguages);
                     foreach ($validAttributes as $validAttribute) {
                         if ($validAttribute['i18n']) {
                             foreach ($aLanguages as $sLanguage) {
                                 $value = Yii::app()->request->getPost($validAttribute['name'] . '_' . $sLanguage);
                                 $iInsertCount = QuestionAttribute::model()->findAllByAttributes(array('attribute' => $validAttribute['name'], 'qid' => $iQuestionID, 'language' => $sLanguage));
                                 if (count($iInsertCount) > 0) {
                                     if ($value != '') {
                                         QuestionAttribute::model()->updateAll(array('value' => $value), 'attribute=:attribute AND qid=:qid AND language=:language', array(':attribute' => $validAttribute['name'], ':qid' => $iQuestionID, ':language' => $sLanguage));
                                     } else {
                                         QuestionAttribute::model()->deleteAll('attribute=:attribute AND qid=:qid AND language=:language', array(':attribute' => $validAttribute['name'], ':qid' => $iQuestionID, ':language' => $sLanguage));
                                     }
                                 } elseif ($value != '') {
                                     $attribute = new QuestionAttribute();
                                     $attribute->qid = $iQuestionID;
                                     $attribute->value = $value;
                                     $attribute->attribute = $validAttribute['name'];
                                     $attribute->language = $sLanguage;
                                     $attribute->save();
                                 }
                             }
                         } else {
                             $value = Yii::app()->request->getPost($validAttribute['name']);
                             if ($validAttribute['name'] == 'multiflexible_step' && trim($value) != '') {
                                 $value = floatval($value);
                                 if ($value == 0) {
                                     $value = 1;
                                 }
                             }
                             $iInsertCount = QuestionAttribute::model()->findAllByAttributes(array('attribute' => $validAttribute['name'], 'qid' => $iQuestionID));
                             if (count($iInsertCount) > 0) {
                                 if ($value != $validAttribute['default'] && trim($value) != "") {
                                     QuestionAttribute::model()->updateAll(array('value' => $value), 'attribute=:attribute AND qid=:qid', array(':attribute' => $validAttribute['name'], ':qid' => $iQuestionID));
                                 } else {
                                     QuestionAttribute::model()->deleteAll('attribute=:attribute AND qid=:qid', array(':attribute' => $validAttribute['name'], ':qid' => $iQuestionID));
                                 }
                             } elseif ($value != $validAttribute['default'] && trim($value) != "") {
                                 $attribute = new QuestionAttribute();
                                 $attribute->qid = $iQuestionID;
                                 $attribute->value = $value;
                                 $attribute->attribute = $validAttribute['name'];
                                 $attribute->save();
                             }
                         }
                     }
                 } else {
                     $qattributes = questionAttributes();
                     $validAttributes = $qattributes[Yii::app()->request->getPost('type')];
                     $aLanguages = array_merge(array(Survey::model()->findByPk($iSurveyID)->language), Survey::model()->findByPk($iSurveyID)->additionalLanguages);
                     foreach ($validAttributes as $validAttribute) {
                         if ($validAttribute['i18n']) {
                             foreach ($aLanguages as $sLanguage) {
                                 $value = Yii::app()->request->getPost($validAttribute['name'] . '_' . $sLanguage);
                                 $iInsertCount = QuestionAttribute::model()->findAllByAttributes(array('attribute' => $validAttribute['name'], 'qid' => $iQuestionID, 'language' => $sLanguage));
                                 if (count($iInsertCount) > 0) {
                                     if ($value != '') {
                                         QuestionAttribute::model()->updateAll(array('value' => $value), 'attribute=:attribute AND qid=:qid AND language=:language', array(':attribute' => $validAttribute['name'], ':qid' => $iQuestionID, ':language' => $sLanguage));
                                     } else {
                                         QuestionAttribute::model()->deleteAll('attribute=:attribute AND qid=:qid AND language=:language', array(':attribute' => $validAttribute['name'], ':qid' => $iQuestionID, ':language' => $sLanguage));
                                     }
                                 } elseif ($value != '') {
                                     $attribute = new QuestionAttribute();
                                     $attribute->qid = $iQuestionID;
                                     $attribute->value = $value;
                                     $attribute->attribute = $validAttribute['name'];
                                     $attribute->language = $sLanguage;
                                     $attribute->save();
                                 }
                             }
                         } else {
                             $value = Yii::app()->request->getPost($validAttribute['name']);
                             if ($validAttribute['name'] == 'multiflexible_step' && trim($value) != '') {
                                 $value = floatval($value);
                                 if ($value == 0) {
                                     $value = 1;
                                 }
                             }
                             $iInsertCount = QuestionAttribute::model()->findAllByAttributes(array('attribute' => $validAttribute['name'], 'qid' => $iQuestionID));
                             if (count($iInsertCount) > 0) {
                                 if ($value != $validAttribute['default'] && trim($value) != "") {
                                     QuestionAttribute::model()->updateAll(array('value' => $value), 'attribute=:attribute AND qid=:qid', array(':attribute' => $validAttribute['name'], ':qid' => $iQuestionID));
                                 } else {
                                     QuestionAttribute::model()->deleteAll('attribute=:attribute AND qid=:qid', array(':attribute' => $validAttribute['name'], ':qid' => $iQuestionID));
                                 }
                             } elseif ($value != $validAttribute['default'] && trim($value) != "") {
                                 $attribute = new QuestionAttribute();
                                 $attribute->qid = $iQuestionID;
                                 $attribute->value = $value;
                                 $attribute->attribute = $validAttribute['name'];
                                 $attribute->save();
                             }
                         }
                     }
                 }
                 Question::model()->updateQuestionOrder($iQuestionGroupID, $iSurveyID);
                 Yii::app()->session['flashmessage'] = gT("Question was successfully added.");
             }
         }
         LimeExpressionManager::SetDirtyFlag();
         // so refreshes syntax highlighting
         if ($sDBOutput != '') {
             echo $sDBOutput;
         } else {
             //admin/survey/sa/view/surveyid/
             $this->getController()->redirect(array('admin/questions/sa/view/surveyid/' . $iSurveyID . '/gid/' . $iQuestionGroupID . '/qid/' . $iQuestionID));
         }
     }
     /**
      * Update question
      */
     if ($sAction == "updatequestion" && Permission::model()->hasSurveyPermission($iSurveyID, 'surveycontent', 'update')) {
         LimeExpressionManager::RevertUpgradeConditionsToRelevance($iSurveyID);
         $cqr = Question::model()->findByAttributes(array('qid' => $iQuestionID));
         $oldtype = $cqr['type'];
         $oldgid = $cqr['gid'];
         $survey = Survey::model()->findByPk($iSurveyID);
         // If the survey is activate the question type may not be changed
         if ($survey->active !== 'N') {
             $sQuestionType = $oldtype;
         } else {
             $sQuestionType = Yii::app()->request->getPost('type');
         }
         // Remove invalid question attributes on saving
         $qattributes = questionAttributes();
         $criteria = new CDbCriteria();
         $criteria->compare('qid', $iQuestionID);
         if (isset($qattributes[$sQuestionType])) {
             $validAttributes = $qattributes[$sQuestionType];
             foreach ($validAttributes as $validAttribute) {
                 $criteria->compare('attribute', '<>' . $validAttribute['name']);
             }
         }
         QuestionAttribute::model()->deleteAll($criteria);
         $aLanguages = array_merge(array(Survey::model()->findByPk($iSurveyID)->language), Survey::model()->findByPk($iSurveyID)->additionalLanguages);
         //now save all valid attributes
         $validAttributes = $qattributes[$sQuestionType];
         foreach ($validAttributes as $validAttribute) {
             if ($validAttribute['i18n']) {
                 foreach ($aLanguages as $sLanguage) {
                     // TODO sanitise XSS
                     $value = Yii::app()->request->getPost($validAttribute['name'] . '_' . $sLanguage);
                     $iInsertCount = QuestionAttribute::model()->findAllByAttributes(array('attribute' => $validAttribute['name'], 'qid' => $iQuestionID, 'language' => $sLanguage));
                     if (count($iInsertCount) > 0) {
                         if ($value != '') {
                             QuestionAttribute::model()->updateAll(array('value' => $value), 'attribute=:attribute AND qid=:qid AND language=:language', array(':attribute' => $validAttribute['name'], ':qid' => $iQuestionID, ':language' => $sLanguage));
                         } else {
                             QuestionAttribute::model()->deleteAll('attribute=:attribute AND qid=:qid AND language=:language', array(':attribute' => $validAttribute['name'], ':qid' => $iQuestionID, ':language' => $sLanguage));
                         }
                     } elseif ($value != '') {
                         $attribute = new QuestionAttribute();
                         $attribute->qid = $iQuestionID;
                         $attribute->value = $value;
                         $attribute->attribute = $validAttribute['name'];
                         $attribute->language = $sLanguage;
                         $attribute->save();
                     }
                 }
             } else {
                 $value = Yii::app()->request->getPost($validAttribute['name']);
                 if ($validAttribute['name'] == 'multiflexible_step' && trim($value) != '') {
                     $value = floatval($value);
                     if ($value == 0) {
                         $value = 1;
                     }
                 }
                 $iInsertCount = QuestionAttribute::model()->findAllByAttributes(array('attribute' => $validAttribute['name'], 'qid' => $iQuestionID));
                 if (count($iInsertCount) > 0) {
                     if ($value != $validAttribute['default'] && trim($value) != "") {
                         QuestionAttribute::model()->updateAll(array('value' => $value), 'attribute=:attribute AND qid=:qid', array(':attribute' => $validAttribute['name'], ':qid' => $iQuestionID));
                     } else {
                         QuestionAttribute::model()->deleteAll('attribute=:attribute AND qid=:qid', array(':attribute' => $validAttribute['name'], ':qid' => $iQuestionID));
                     }
                 } elseif ($value != $validAttribute['default'] && trim($value) != "") {
                     $attribute = new QuestionAttribute();
                     $attribute->qid = $iQuestionID;
                     $attribute->value = $value;
                     $attribute->attribute = $validAttribute['name'];
                     $attribute->save();
                 }
             }
         }
         $aQuestionTypeList = getQuestionTypeList('', 'array');
         // These are the questions types that have no answers and therefore we delete the answer in that case
         $iAnswerScales = $aQuestionTypeList[$sQuestionType]['answerscales'];
         $iSubquestionScales = $aQuestionTypeList[$sQuestionType]['subquestions'];
         // These are the questions types that have the other option therefore we set everything else to 'No Other'
         if ($sQuestionType != "L" && $sQuestionType != "!" && $sQuestionType != "P" && $sQuestionType != "M") {
             $_POST['other'] = 'N';
         }
         // These are the questions types that have no validation - so zap it accordingly
         if ($sQuestionType == "!" || $sQuestionType == "L" || $sQuestionType == "M" || $sQuestionType == "P" || $sQuestionType == "F" || $sQuestionType == "H" || $sQuestionType == "X" || $sQuestionType == "") {
             $_POST['preg'] = '';
         }
         // For Bootstrap Version usin YiiWheels switch :
         $_POST['mandatory'] = Yii::app()->request->getPost('mandatory') == '1' ? 'Y' : 'N';
         $_POST['other'] = Yii::app()->request->getPost('other') == '1' ? 'Y' : 'N';
         // These are the questions types that have no mandatory property - so zap it accordingly
         if ($sQuestionType == "X" || $sQuestionType == "|") {
             $_POST['mandatory'] = 'N';
         }
         if ($oldtype != $sQuestionType) {
             // TMSW Condition->Relevance:  Do similar check via EM, but do allow such a change since will be easier to modify relevance
             //Make sure there are no conditions based on this question, since we are changing the type
             $ccresult = Condition::model()->findAllByAttributes(array('cqid' => $iQuestionID));
             $cccount = count($ccresult);
             foreach ($ccresult as $ccr) {
                 $qidarray[] = $ccr['qid'];
             }
             if (isset($qidarray) && $qidarray) {
                 $qidlist = implode(", ", $qidarray);
             }
         }
         if (isset($cccount) && $cccount) {
             Yii::app()->setFlashMessage(gT("Question could not be updated. There are conditions for other questions that rely on the answers to this question and changing the type will cause problems. You must delete these conditions  before you can change the type of this question."), 'error');
         } else {
             if (isset($iQuestionGroupID) && $iQuestionGroupID != "") {
                 //                    $array_result=checkMoveQuestionConstraintsForConditions(sanitize_int($surveyid),sanitize_int($qid), sanitize_int($gid));
                 //                    // If there is no blocking conditions that could prevent this move
                 //
                 //                    if (is_null($array_result['notAbove']) && is_null($array_result['notBelow']))
                 //                    {
                 $aSurveyLanguages = Survey::model()->findByPk($iSurveyID)->additionalLanguages;
                 $sBaseLanguage = Survey::model()->findByPk($iSurveyID)->language;
                 array_push($aSurveyLanguages, $sBaseLanguage);
                 foreach ($aSurveyLanguages as $qlang) {
                     if (isset($qlang) && $qlang != "") {
                         // &eacute; to é and &amp; to & : really needed ? Why not for answers ? (130307)
                         $sQuestionText = Yii::app()->request->getPost('question_' . $qlang, '');
                         $sQuestionHelp = Yii::app()->request->getPost('help_' . $qlang, '');
                         // Fix bug with FCKEditor saving strange BR types : in rules ?
                         $sQuestionText = $oFixCKeditor->fixCKeditor($sQuestionText);
                         $sQuestionHelp = $oFixCKeditor->fixCKeditor($sQuestionHelp);
                         $udata = array('type' => $sQuestionType, 'title' => Yii::app()->request->getPost('title'), 'question' => $sQuestionText, 'preg' => Yii::app()->request->getPost('preg'), 'help' => $sQuestionHelp, 'gid' => $iQuestionGroupID, 'other' => Yii::app()->request->getPost('other'), 'mandatory' => Yii::app()->request->getPost('mandatory'), 'relevance' => Yii::app()->request->getPost('relevance'));
                         // Update question module
                         if (Yii::app()->request->getPost('module_name') != '') {
                             // The question module is not empty. So it's an external question module.
                             $udata['modulename'] = Yii::app()->request->getPost('module_name');
                         } else {
                             // If it was a module before, we must
                             $udata['modulename'] = '';
                         }
                         if ($oldgid != $iQuestionGroupID) {
                             if (getGroupOrder($iSurveyID, $oldgid) > getGroupOrder($iSurveyID, $iQuestionGroupID)) {
                                 // TMSW Condition->Relevance:  What is needed here?
                                 // Moving question to a 'upper' group
                                 // insert question at the end of the destination group
                                 // this prevent breaking conditions if the target qid is in the dest group
                                 $insertorder = getMaxQuestionOrder($iQuestionGroupID, $iSurveyID) + 1;
                                 $udata = array_merge($udata, array('question_order' => $insertorder));
                             } else {
                                 // Moving question to a 'lower' group
                                 // insert question at the beginning of the destination group
                                 shiftOrderQuestions($iSurveyID, $iQuestionGroupID, 1);
                                 // makes 1 spare room for new question at top of dest group
                                 $udata = array_merge($udata, array('question_order' => 0));
                             }
                         }
                         //$condn = array('sid' => $surveyid, 'qid' => $qid, 'language' => $qlang);
                         $oQuestion = Question::model()->findByPk(array("qid" => $iQuestionID, 'language' => $qlang));
                         foreach ($udata as $k => $v) {
                             $oQuestion->{$k} = $v;
                         }
                         $uqresult = $oQuestion->save();
                         //($uqquery); // or safeDie ("Error Update Question: ".$uqquery."<br />");  // Checked)
                         if (!$uqresult) {
                             $bOnError = true;
                             $aErrors = $oQuestion->getErrors();
                             if (count($aErrors)) {
                                 foreach ($aErrors as $sAttribute => $aStringErrors) {
                                     foreach ($aStringErrors as $sStringErrors) {
                                         Yii::app()->setFlashMessage(sprintf(gT("Question could not be updated with error on %s: %s"), $sAttribute, $sStringErrors), 'error');
                                     }
                                 }
                             } else {
                                 Yii::app()->setFlashMessage(gT("Question could not be updated."), 'error');
                             }
                         }
                     }
                 }
                 // Update the group ID on subquestions, too
                 if ($oldgid != $iQuestionGroupID) {
                     Question::model()->updateAll(array('gid' => $iQuestionGroupID), 'qid=:qid and parent_qid>0', array(':qid' => $iQuestionID));
                     // if the group has changed then fix the sortorder of old and new group
                     Question::model()->updateQuestionOrder($oldgid, $iSurveyID);
                     Question::model()->updateQuestionOrder($iQuestionGroupID, $iSurveyID);
                     // If some questions have conditions set on this question's answers
                     // then change the cfieldname accordingly
                     fixMovedQuestionConditions($iQuestionID, $oldgid, $iQuestionGroupID);
                 }
                 // Update subquestions
                 if ($oldtype != $sQuestionType) {
                     Question::model()->updateAll(array('type' => $sQuestionType), 'parent_qid=:qid', array(':qid' => $iQuestionID));
                 }
                 // Update subquestions if question module
                 if (Yii::app()->request->getPost('module_name') != '') {
                     // The question module is not empty. So it's an external question module.
                     Question::model()->updateAll(array('modulename' => Yii::app()->request->getPost('module_name')), 'parent_qid=:qid', array(':qid' => $iQuestionID));
                 } else {
                     // If it was a module before, we must
                     Question::model()->updateAll(array('modulename' => ''), 'parent_qid=:qid', array(':qid' => $iQuestionID));
                 }
                 Answer::model()->deleteAllByAttributes(array('qid' => $iQuestionID), 'scale_id >= :scale_id', array(':scale_id' => $iAnswerScales));
                 // Remove old subquestion scales
                 Question::model()->deleteAllByAttributes(array('parent_qid' => $iQuestionID), 'scale_id >= :scale_id', array(':scale_id' => $iSubquestionScales));
                 if (!isset($bOnError) || !$bOnError) {
                     // This really a quick hack and need a better system
                     Yii::app()->setFlashMessage(gT("Question was successfully saved."));
                 }
                 //                    }
                 //                    else
                 //                    {
                 //
                 //                        // There are conditions constraints: alert the user
                 //                        $errormsg="";
                 //                        if (!is_null($array_result['notAbove']))
                 //                        {
                 //                            $errormsg.=gT("This question relies on other question's answers and can't be moved above groupId:","js")
                 //                            . " " . $array_result['notAbove'][0][0] . " " . gT("in position","js")." ".$array_result['notAbove'][0][1]."\\n"
                 //                            . gT("See conditions:")."\\n";
                 //
                 //                            foreach ($array_result['notAbove'] as $notAboveCond)
                 //                            {
                 //                                $errormsg.="- cid:". $notAboveCond[3]."\\n";
                 //                            }
                 //
                 //                        }
                 //                        if (!is_null($array_result['notBelow']))
                 //                        {
                 //                            $errormsg.=gT("Some questions rely on this question's answers. You can't move this question below groupId:","js")
                 //                            . " " . $array_result['notBelow'][0][0] . " " . gT("in position","js")." ".$array_result['notBelow'][0][1]."\\n"
                 //                            . gT("See conditions:")."\\n";
                 //
                 //                            foreach ($array_result['notBelow'] as $notBelowCond)
                 //                            {
                 //                                $errormsg.="- cid:". $notBelowCond[3]."\\n";
                 //                            }
                 //                        }
                 //
                 //                        $databaseoutput .= "<script type=\"text/javascript\">\n<!--\n alert(\"$errormsg\")\n //-->\n</script>\n";
                 //                        $gid= $oldgid; // group move impossible ==> keep display on oldgid
                 //                    }
             } else {
                 Yii::app()->setFlashMessage(gT("Question could not be updated"), 'error');
             }
         }
         LimeExpressionManager::UpgradeConditionsToRelevance($iSurveyID);
         if ($sDBOutput != '') {
             echo $sDBOutput;
         } else {
             $closeAfterSave = Yii::app()->request->getPost('close-after-save') === 'true';
             if ($closeAfterSave) {
                 // Redirect to summary
                 $this->getController()->redirect(array('admin/questions/sa/view/surveyid/' . $iSurveyID . '/gid/' . $iQuestionGroupID . '/qid/' . $iQuestionID));
             } else {
                 // Redirect to edit
                 $this->getController()->redirect(array('admin/questions/sa/editquestion/surveyid/' . $iSurveyID . '/gid/' . $iQuestionGroupID . '/qid/' . $iQuestionID));
                 // This works too: $this->getController()->redirect(Yii::app()->request->urlReferrer);
             }
         }
     }
     /**
      * updatesurveylocalesettings
      */
     if ($sAction == "updatesurveylocalesettings" && Permission::model()->hasSurveyPermission($iSurveyID, 'surveylocale', 'update')) {
         $languagelist = Survey::model()->findByPk($iSurveyID)->additionalLanguages;
         $languagelist[] = Survey::model()->findByPk($iSurveyID)->language;
         Yii::app()->loadHelper('database');
         foreach ($languagelist as $langname) {
             if ($langname) {
                 $url = Yii::app()->request->getPost('url_' . $langname);
                 if ($url == 'http://') {
                     $url = "";
                 }
                 $sURLDescription = html_entity_decode(Yii::app()->request->getPost('urldescrip_' . $langname), ENT_QUOTES, "UTF-8");
                 $sURL = html_entity_decode(Yii::app()->request->getPost('url_' . $langname), ENT_QUOTES, "UTF-8");
                 // Fix bug with FCKEditor saving strange BR types
                 $short_title = Yii::app()->request->getPost('short_title_' . $langname);
                 $description = Yii::app()->request->getPost('description_' . $langname);
                 $welcome = Yii::app()->request->getPost('welcome_' . $langname);
                 $endtext = Yii::app()->request->getPost('endtext_' . $langname);
                 $short_title = $oFixCKeditor->fixCKeditor($short_title);
                 $description = $oFixCKeditor->fixCKeditor($description);
                 $welcome = $oFixCKeditor->fixCKeditor($welcome);
                 $endtext = $oFixCKeditor->fixCKeditor($endtext);
                 $data = array('surveyls_title' => $short_title, 'surveyls_description' => $description, 'surveyls_welcometext' => $welcome, 'surveyls_endtext' => $endtext, 'surveyls_url' => $sURL, 'surveyls_urldescription' => $sURLDescription, 'surveyls_dateformat' => Yii::app()->request->getPost('dateformat_' . $langname), 'surveyls_numberformat' => Yii::app()->request->getPost('numberformat_' . $langname));
                 $SurveyLanguageSetting = SurveyLanguageSetting::model()->findByPk(array('surveyls_survey_id' => $iSurveyID, 'surveyls_language' => $langname));
                 $SurveyLanguageSetting->attributes = $data;
                 $SurveyLanguageSetting->save();
                 // save the change to database
             }
         }
         //Yii::app()->session['flashmessage'] = gT("Survey text elements successfully saved.");
         ////////////////////////////////////////////////////////////////////////////////////
         // General settings (copy / paste from surveyadmin::update)
         // Preload survey
         $oSurvey = Survey::model()->findByPk($iSurveyID);
         // Save plugin settings.
         $pluginSettings = App()->request->getPost('plugin', array());
         foreach ($pluginSettings as $plugin => $settings) {
             $settingsEvent = new PluginEvent('newSurveySettings');
             $settingsEvent->set('settings', $settings);
             $settingsEvent->set('survey', $iSurveyID);
             App()->getPluginManager()->dispatchEvent($settingsEvent, $plugin);
         }
         /* Start to fix some param before save (TODO : use models directly ?) */
         /* Date management */
         Yii::app()->loadHelper('surveytranslator');
         $formatdata = getDateFormatData(Yii::app()->session['dateformat']);
         Yii::app()->loadLibrary('Date_Time_Converter');
         $startdate = App()->request->getPost('startdate');
         if (trim($startdate) == "") {
             $startdate = null;
         } else {
             Yii::app()->loadLibrary('Date_Time_Converter');
             $datetimeobj = new date_time_converter($startdate, $formatdata['phpdate'] . ' H:i');
             //new Date_Time_Converter($startdate,$formatdata['phpdate'].' H:i');
             $startdate = $datetimeobj->convert("Y-m-d H:i:s");
         }
         $expires = App()->request->getPost('expires');
         if (trim($expires) == "") {
             $expires = null;
         } else {
             $datetimeobj = new date_time_converter($expires, $formatdata['phpdate'] . ' H:i');
             //new Date_Time_Converter($expires, $formatdata['phpdate'].' H:i');
             $expires = $datetimeobj->convert("Y-m-d H:i:s");
         }
         // We have $oSurvey : update and save it
         $oSurvey->owner_id = Yii::app()->request->getPost('owner_id');
         $oSurvey->admin = Yii::app()->request->getPost('admin');
         $oSurvey->expires = $expires;
         $oSurvey->startdate = $startdate;
         $oSurvey->faxto = App()->request->getPost('faxto');
         $oSurvey->format = App()->request->getPost('format');
         $oSurvey->template = Yii::app()->request->getPost('template');
         $oSurvey->assessments = App()->request->getPost('assessments');
         $oSurvey->additional_languages = Yii::app()->request->getPost('languageids');
         if ($oSurvey->active != 'Y') {
             $oSurvey->anonymized = App()->request->getPost('anonymized');
             $oSurvey->savetimings = App()->request->getPost('savetimings');
             $oSurvey->datestamp = App()->request->getPost('datestamp');
             $oSurvey->ipaddr = App()->request->getPost('ipaddr');
             $oSurvey->refurl = App()->request->getPost('refurl');
         }
         $oSurvey->publicgraphs = App()->request->getPost('publicgraphs');
         $oSurvey->usecookie = App()->request->getPost('usecookie');
         $oSurvey->allowregister = App()->request->getPost('allowregister');
         $oSurvey->allowsave = App()->request->getPost('allowsave');
         $oSurvey->navigationdelay = App()->request->getPost('navigationdelay');
         $oSurvey->printanswers = App()->request->getPost('printanswers');
         $oSurvey->publicstatistics = App()->request->getPost('publicstatistics');
         $oSurvey->autoredirect = App()->request->getPost('autoredirect');
         $oSurvey->showxquestions = App()->request->getPost('showxquestions');
         $oSurvey->showgroupinfo = App()->request->getPost('showgroupinfo');
         $oSurvey->showqnumcode = App()->request->getPost('showqnumcode');
         $oSurvey->shownoanswer = App()->request->getPost('shownoanswer');
         $oSurvey->showwelcome = App()->request->getPost('showwelcome');
         $oSurvey->allowprev = App()->request->getPost('allowprev');
         $oSurvey->questionindex = App()->request->getPost('questionindex');
         $oSurvey->nokeyboard = App()->request->getPost('nokeyboard');
         $oSurvey->showprogress = App()->request->getPost('showprogress');
         $oSurvey->listpublic = App()->request->getPost('public');
         $oSurvey->htmlemail = App()->request->getPost('htmlemail');
         $oSurvey->sendconfirmation = App()->request->getPost('sendconfirmation');
         $oSurvey->tokenanswerspersistence = App()->request->getPost('tokenanswerspersistence');
         $oSurvey->alloweditaftercompletion = App()->request->getPost('alloweditaftercompletion');
         $oSurvey->usecaptcha = Survey::transcribeCaptchaOptions();
         $oSurvey->emailresponseto = App()->request->getPost('emailresponseto');
         $oSurvey->emailnotificationto = App()->request->getPost('emailnotificationto');
         $oSurvey->googleanalyticsapikey = App()->request->getPost('googleanalyticsapikey');
         $oSurvey->googleanalyticsstyle = App()->request->getPost('googleanalyticsstyle');
         $oSurvey->tokenlength = App()->request->getPost('tokenlength');
         $oSurvey->adminemail = App()->request->getPost('adminemail');
         $oSurvey->bounce_email = App()->request->getPost('bounce_email');
         if ($oSurvey->save()) {
             Yii::app()->setFlashMessage(gT("Survey settings were successfully saved."));
         } else {
             Yii::app()->setFlashMessage(gT("Survey could not be updated."), "error");
             tracevar($oSurvey->getErrors());
         }
         /* Reload $oSurvey (language are fixed : need it ?) */
         $oSurvey = Survey::model()->findByPk($iSurveyID);
         /* Delete removed language cleanLanguagesFromSurvey do it already why redo it (cleanLanguagesFromSurvey must be moved to model) ?*/
         $aAvailableLanguage = $oSurvey->getAllLanguages();
         $oCriteria = new CDbCriteria();
         $oCriteria->compare('surveyls_survey_id', $iSurveyID);
         $oCriteria->addNotInCondition('surveyls_language', $aAvailableLanguage);
         SurveyLanguageSetting::model()->deleteAll($oCriteria);
         /* Add new language fixLanguageConsistency do it ?*/
         foreach ($oSurvey->additionalLanguages as $sLang) {
             if ($sLang) {
                 $oLanguageSettings = SurveyLanguageSetting::model()->find('surveyls_survey_id=:surveyid AND surveyls_language=:langname', array(':surveyid' => $iSurveyID, ':langname' => $sLang));
                 if (!$oLanguageSettings) {
                     $oLanguageSettings = new SurveyLanguageSetting();
                     $languagedetails = getLanguageDetails($sLang);
                     $oLanguageSettings->surveyls_survey_id = $iSurveyID;
                     $oLanguageSettings->surveyls_language = $sLang;
                     $oLanguageSettings->surveyls_title = '';
                     // Not in default model ?
                     $oLanguageSettings->surveyls_dateformat = $languagedetails['dateformat'];
                     if (!$oLanguageSettings->save()) {
                         Yii::app()->setFlashMessage(gT("Survey language could not be created."), "error");
                         tracevar($oLanguageSettings->getErrors());
                     }
                 }
             }
         }
         /* Language fix : remove and add question/group */
         cleanLanguagesFromSurvey($iSurveyID, implode(" ", $oSurvey->additionalLanguages));
         fixLanguageConsistency($iSurveyID, implode(" ", $oSurvey->additionalLanguages));
         // Url params in json
         $aURLParams = json_decode(Yii::app()->request->getPost('allurlparams'), true);
         SurveyURLParameter::model()->deleteAllByAttributes(array('sid' => $iSurveyID));
         if (isset($aURLParams)) {
             foreach ($aURLParams as $aURLParam) {
                 $aURLParam['parameter'] = trim($aURLParam['parameter']);
                 if ($aURLParam['parameter'] == '' || !preg_match('/^[a-zA-Z_][a-zA-Z0-9_]*$/', $aURLParam['parameter']) || $aURLParam['parameter'] == 'sid' || $aURLParam['parameter'] == 'newtest' || $aURLParam['parameter'] == 'token' || $aURLParam['parameter'] == 'lang') {
                     continue;
                     // this parameter name seems to be invalid - just ignore it
                 }
                 unset($aURLParam['act']);
                 unset($aURLParam['title']);
                 unset($aURLParam['id']);
                 if ($aURLParam['targetqid'] == '') {
                     $aURLParam['targetqid'] = NULL;
                 }
                 if ($aURLParam['targetsqid'] == '') {
                     $aURLParam['targetsqid'] = NULL;
                 }
                 $aURLParam['sid'] = $iSurveyID;
                 $param = new SurveyURLParameter();
                 foreach ($aURLParam as $k => $v) {
                     $param->{$k} = $v;
                 }
                 $param->save();
             }
         }
         ////////////////////////////////////////
         if ($sDBOutput != '') {
             echo $sDBOutput;
         } else {
             if (Yii::app()->request->getPost('close-after-save') === 'true') {
                 $this->getController()->redirect(array('admin/survey/sa/view/surveyid/' . $iSurveyID));
             }
             $this->getController()->redirect(array('/admin/survey/sa/editlocalsettings/surveyid/' . $iSurveyID));
         }
     }
     $this->getController()->redirect(array("/admin"), "refresh");
 }
 /**
  * Load edit/new question screen depending on $action.
  *
  * @access public
  * @param string $sa subaction
  * @param int $surveyid
  * @param int $gid
  * @param int $qid
  * @return void
  */
 public function index($sa, $surveyid, $gid, $qid = null)
 {
     App()->getClientScript()->registerPackage('qTip2');
     $action = $sa;
     $surveyid = $iSurveyID = sanitize_int($surveyid);
     $gid = sanitize_int($gid);
     if (isset($qid)) {
         $qid = sanitize_int($qid);
     }
     $aViewUrls = array();
     $aData['surveyid'] = $surveyid;
     $aData['gid'] = $gid;
     $aData['qid'] = $qid;
     $aData['display']['menu_bars']['surveysummary'] = 'viewgroup';
     $aData['display']['menu_bars']['gid_action'] = 'addquestion';
     $surveyinfo = Survey::model()->findByPk($iSurveyID)->surveyinfo;
     $aData['title_bar']['title'] = $surveyinfo['surveyls_title'] . "(" . gT("ID") . ":" . $iSurveyID . ")";
     $aData['questiongroupbar']['savebutton']['form'] = 'frmeditgroup';
     $aData['questiongroupbar']['saveandclosebutton']['form'] = 'frmeditgroup';
     $aData['questiongroupbar']['closebutton']['url'] = 'admin/questions/sa/view/surveyid/' . $surveyid . '/gid/' . $gid . '/qid/' . $qid;
     Yii::app()->session['FileManagerContext'] = "create:question:{$surveyid}";
     if (Permission::model()->hasSurveyPermission($surveyid, 'surveycontent', 'read')) {
         $surveyinfo = getSurveyInfo($surveyid);
         Yii::app()->loadHelper('admin/htmleditor');
         Yii::app()->loadHelper('surveytranslator');
         if (isset($_POST['sortorder'])) {
             $postsortorder = sanitize_int($_POST['sortorder']);
         }
         $aData['adding'] = $adding = $action == 'addquestion';
         $aData['copying'] = $copying = $action == 'copyquestion';
         $questlangs = Survey::model()->findByPk($surveyid)->additionalLanguages;
         $baselang = Survey::model()->findByPk($surveyid)->language;
         $questlangs[] = $baselang;
         $questlangs = array_flip($questlangs);
         // Prepare selector Mode TODO: with and without image
         if (!$adding) {
             Yii::app()->session['FileManagerContext'] = "edit:question:{$surveyid}";
             $aData['display']['menu_bars']['qid_action'] = 'editquestion';
             $egresult = Question::model()->findAllByAttributes(array('sid' => $surveyid, 'gid' => $gid, 'qid' => $qid));
             foreach ($egresult as $esrow) {
                 if (!array_key_exists($esrow->language, $questlangs)) {
                     // Language Exists, BUT ITS NOT ON THE SURVEY ANYMORE.
                     $esrow->delete();
                 } else {
                     $questlangs[$esrow->language] = 99;
                 }
                 if ($esrow->language == $baselang) {
                     $esrow = $esrow->attributes;
                     $basesettings = array('question_order' => $esrow['question_order'], 'other' => $esrow['other'], 'mandatory' => $esrow['mandatory'], 'type' => $esrow['type'], 'title' => $esrow['title'], 'preg' => $esrow['preg'], 'question' => $esrow['question'], 'help' => $esrow['help']);
                 }
             }
             if (!$egresult) {
                 $this->getController()->error('Invalid question id');
             }
             while (list($key, $value) = each($questlangs)) {
                 if ($value != 99) {
                     $arQuestion = new Question();
                     $arQuestion->qid = $qid;
                     $arQuestion->sid = $surveyid;
                     $arQuestion->gid = $gid;
                     $arQuestion->type = $basesettings['type'];
                     $arQuestion->title = $basesettings['title'];
                     $arQuestion->question = $basesettings['question'];
                     $arQuestion->preg = $basesettings['preg'];
                     $arQuestion->help = $basesettings['help'];
                     $arQuestion->other = $basesettings['other'];
                     $arQuestion->mandatory = $basesettings['mandatory'];
                     $arQuestion->question_order = $basesettings['question_order'];
                     $arQuestion->language = $key;
                     $arQuestion->insert();
                 }
             }
             $eqresult = Question::model()->with('groups')->together()->findByAttributes(array('sid' => $surveyid, 'gid' => $gid, 'qid' => $qid, 'language' => $baselang));
         } else {
             // This is needed to properly color-code content if it contains replacements
             LimeExpressionManager::StartProcessingPage(false, Yii::app()->baseUrl, true);
             // so can click on syntax highlighting to edit questions
         }
         $qtypelist = getQuestionTypeList('', 'array');
         $qDescToCode = 'qDescToCode = {';
         $qCodeToInfo = 'qCodeToInfo = {';
         foreach ($qtypelist as $qtype => $qdesc) {
             $qDescToCode .= " '{$qdesc['description']}' : '{$qtype}', \n";
             $qCodeToInfo .= " '{$qtype}' : '" . ls_json_encode($qdesc) . "', \n";
         }
         $aData['qTypeOutput'] = "{$qDescToCode} 'null':'null' }; \n {$qCodeToInfo} 'null':'null' };";
         if (!$adding) {
             if (is_object($eqresult->groups)) {
                 $eqrow = array_merge($eqresult->attributes, $eqresult->groups->attributes);
             } else {
                 $eqrow = $eqresult->attributes;
             }
             // Todo: handler in case that record is not found
             if ($copying) {
                 $eqrow['title'] = '';
             }
         } else {
             $eqrow['language'] = $baselang;
             $eqrow['title'] = '';
             $eqrow['question'] = '';
             $eqrow['help'] = '';
             $eqrow['type'] = 'T';
             $eqrow['lid'] = 0;
             $eqrow['lid1'] = 0;
             $eqrow['gid'] = $gid;
             $eqrow['other'] = 'N';
             $eqrow['mandatory'] = 'N';
             $eqrow['preg'] = '';
             $eqrow['relevance'] = 1;
             $eqrow['group_name'] = '';
         }
         $eqrow['conditions_number'] = Condition::Model()->count("qid=:qid", array('qid' => $qid));
         if ($eqrow['modulename'] != null) {
             $oQuestionModule = Question::getQuestionModule($esrow['modulename']);
             $questionTitle = (array) $oQuestionModule->title;
             $questionModuleName = (array) $oQuestionModule->modulename;
             $eqrow['modulename'] = $questionModuleName[0];
             $eqrow['moduletitle'] = $questionTitle[0];
         }
         $aData['eqrow'] = $eqrow;
         $aData['surveyid'] = $surveyid;
         $aData['gid'] = $gid;
         if (!$adding) {
             $criteria = new CDbCriteria();
             $criteria->addColumnCondition(array('sid' => $surveyid, 'gid' => $gid, 'qid' => $qid));
             $criteria->params[':lang'] = $baselang;
             $criteria->addCondition('language != :lang');
             $aqresult = Question::model()->findAll($criteria);
             $aData['aqresult'] = $aqresult;
         }
         $aData['action'] = $action;
         $sumresult1 = Survey::model()->findByPk($surveyid);
         if (is_null($sumresult1)) {
             $this->getController()->error('Invalid Survey ID');
         }
         $surveyinfo = $sumresult1->attributes;
         $surveyinfo = array_map('flattenText', $surveyinfo);
         $aData['activated'] = $activated = $surveyinfo['active'];
         if ($activated != "Y") {
             // Prepare selector Class for javascript function
             if (Yii::app()->session['questionselectormode'] !== 'default') {
                 $selectormodeclass = Yii::app()->session['questionselectormode'];
             } else {
                 $selectormodeclass = getGlobalSetting('defaultquestionselectormode', 'default');
             }
             $aData['selectormodeclass'] = $selectormodeclass;
         }
         if (!$adding) {
             $qattributes = questionAttributes();
         } else {
             $qattributes = array();
         }
         if ($adding) {
             // Get the questions for this group
             $baselang = Survey::model()->findByPk($surveyid)->language;
             $oqresult = Question::model()->findAllByAttributes(array('sid' => $surveyid, 'gid' => $gid, 'language' => $baselang, 'parent_qid' => 0), array('order' => 'question_order'));
             $aData['oqresult'] = $oqresult;
         }
         App()->getClientScript()->registerScriptFile(App()->getAssetManager()->publish(ADMIN_SCRIPT_PATH . 'questions.js'));
         $aData['sValidateUrl'] = $adding || $copying ? $this->getController()->createUrl('admin/questions', array('sa' => 'ajaxValidate', 'surveyid' => $surveyid)) : $this->getController()->createUrl('admin/questions', array('sa' => 'ajaxValidate', 'surveyid' => $surveyid, 'qid' => $qid));
         $aData['addlanguages'] = Survey::model()->findByPk($surveyid)->additionalLanguages;
         $aViewUrls['editQuestion_view'][] = $aData;
         $aViewUrls['questionJavascript_view'][] = array('type' => $eqrow['type']);
     } else {
         include 'accessDenied.php';
     }
     $aData['ajaxDatas']['sValidateUrl'] = isset($aData['sValidateUrl']) ? $aData['sValidateUrl'] : $this->getController()->createUrl('admin/questions', array('sa' => 'ajaxValidate', 'surveyid' => $surveyid));
     $aData['ajaxDatas']['qTypeOutput'] = $aData['qTypeOutput'];
     ///////////
     // sidemenu
     $aData['sidemenu']['state'] = false;
     $aData['sidemenu']['explorer']['state'] = true;
     $aData['sidemenu']['explorer']['gid'] = isset($gid) ? $gid : false;
     $aData['sidemenu']['explorer']['qid'] = isset($qid) ? $qid : false;
     $this->_renderWrappedTemplate('survey/Question', $aViewUrls, $aData);
 }
 /**
  * Shows admin menu for question
  *
  * @param int Survey id
  * @param int Group id
  * @param int Question id
  * @param string action
  */
 function _questionbar($aData)
 {
     if (isset($aData['questionbar'])) {
         if (is_object($aData['oSurvey'])) {
             $iSurveyID = $aData['surveyid'];
             $oSurvey = $aData['oSurvey'];
             $gid = $aData['gid'];
             $qid = $aData['qid'];
             // action
             $action = !empty($aData['display']['menu_bars']['qid_action']) ? $aData['display']['menu_bars']['qid_action'] : null;
             $baselang = $oSurvey->language;
             //Show Question Details
             //Count answer-options for this question
             $qrr = Answer::model()->findAllByAttributes(array('qid' => $qid, 'language' => $baselang));
             $aData['qct'] = $qct = count($qrr);
             //Count sub-questions for this question
             $sqrq = Question::model()->findAllByAttributes(array('parent_qid' => $qid, 'language' => $baselang));
             $aData['sqct'] = $sqct = count($sqrq);
             $qrrow = Question::model()->findByAttributes(array('qid' => $qid, 'gid' => $gid, 'sid' => $iSurveyID, 'language' => $baselang));
             if (is_null($qrrow)) {
                 return;
             }
             $questionsummary = "<div class='menubar'>\n";
             // Check if other questions in the Survey are dependent upon this question
             $condarray = getQuestDepsForConditions($iSurveyID, "all", "all", $qid, "by-targqid", "outsidegroup");
             $surveyinfo = $oSurvey->attributes;
             $surveyinfo = array_map('flattenText', $surveyinfo);
             $aData['activated'] = $surveyinfo['active'];
             $qrrow = $qrrow->attributes;
             $aData['languagelist'] = $oSurvey->getAllLanguages();
             $aData['qtypes'] = $qtypes = getQuestionTypeList('', 'array');
             $aData['action'] = $action;
             $aData['surveyid'] = $iSurveyID;
             $aData['qid'] = $qid;
             $aData['gid'] = $gid;
             $aData['qrrow'] = $qrrow;
             $aData['baselang'] = $baselang;
             $aAttributesWithValues = Question::model()->getAdvancedSettingsWithValues($qid, $qrrow['type'], $iSurveyID, $baselang);
             $DisplayArray = array();
             foreach ($aAttributesWithValues as $aAttribute) {
                 if ($aAttribute['i18n'] == false && isset($aAttribute['value']) && $aAttribute['value'] != $aAttribute['default'] || $aAttribute['i18n'] == true && isset($aAttribute['value'][$baselang]) && $aAttribute['value'][$baselang] != $aAttribute['default']) {
                     if ($aAttribute['inputtype'] == 'singleselect') {
                         $aAttribute['value'] = $aAttribute['options'][$aAttribute['value']];
                     }
                     $DisplayArray[] = $aAttribute;
                 }
             }
             $aData['advancedsettings'] = $DisplayArray;
             $aData['condarray'] = $condarray;
             $questionsummary .= $this->getController()->renderPartial('/admin/survey/Question/questionbar_view', $aData, true);
             $finaldata['display'] = $questionsummary;
             $this->getController()->renderPartial('/survey_view', $finaldata);
         } else {
             Yii::app()->session['flashmessage'] = gT("Invalid survey ID");
             $this->getController()->redirect(array("admin/index"));
         }
     }
 }
 public function set_question_sub_questions($sSessionKey, $iSurveyID, $iQuestionID, $data)
 {
     $data_array = unserialize($data);
     Yii::app()->loadHelper('database');
     $aSurveyLanguages = Survey::model()->findByPk($iSurveyID)->additionalLanguages;
     $sBaseLanguage = Survey::model()->findByPk($iSurveyID)->language;
     array_unshift($aSurveyLanguages, $sBaseLanguage);
     $arQuestion = Question::model()->findByAttributes(array('qid' => $iQuestionID));
     $sQuestionType = $arQuestion['type'];
     // Checked
     $aQuestionTypeList = getQuestionTypeList('', 'array');
     $iScaleCount = $aQuestionTypeList[$sQuestionType]['subquestions'];
     //$clang = $this->getController()->lang;
     // First delete any deleted ids
     //$aDeletedQIDs = explode(' ', trim($data));
     $aDeletedQIDs = explode('+', $data_array['deletedqids']);
     $iQuestionGroupID = $data_array['gid'];
     LimeExpressionManager::RevertUpgradeConditionsToRelevance($iSurveyID);
     $aDeletedQIDs = array_unique($aDeletedQIDs, SORT_NUMERIC);
     foreach ($aDeletedQIDs as $iDeletedQID) {
         $iDeletedQID = (int) $iDeletedQID;
         if ($iDeletedQID > 0) {
             // don't remove undefined
             $iInsertCount = Question::model()->deleteAllByAttributes(array('qid' => $iDeletedQID));
             if (!$iInsertCount) {
                 return "Failed to delete answer";
             }
         }
     }
     //Determine ids by evaluating the hidden field
     $aRows = array();
     $aCodes = array();
     $aOldCodes = array();
     foreach ($data_array as $key => $value) {
         $key = explode('_', $key);
         if ($key[0] == 'answer') {
             $aRows[$key[3]][$key[1]][$key[2]] = $value;
         }
         if ($key[0] == 'code') {
             $aCodes[$key[2]][] = $value;
         }
         if ($key[0] == 'oldcode') {
             $aOldCodes[$key[2]][] = $value;
         }
     }
     $aInsertQID = array();
     for ($iScaleID = 0; $iScaleID < $iScaleCount; $iScaleID++) {
         foreach ($aSurveyLanguages as $sLanguage) {
             $iPosition = 0;
             $test = '';
             foreach ($aRows[$iScaleID][$sLanguage] as $subquestionkey => $subquestionvalue) {
                 $test .= $subquestionvalue . ', ';
                 // create a new sub question
                 if (substr($subquestionkey, 0, 3) != 'new') {
                     $oSubQuestion = Question::model()->find("qid=:qid AND language=:language", array(":qid" => $subquestionkey, ':language' => $sLanguage));
                     $oSubQuestion->question_order = $iPosition + 1;
                     $oSubQuestion->title = $aCodes[$iScaleID][$iPosition];
                     $oSubQuestion->question = $subquestionvalue;
                     $oSubQuestion->scale_id = $iScaleID;
                     // update the old sub questions
                 } else {
                     if (!isset($aInsertQID[$iScaleID][$iPosition])) {
                         $oSubQuestion = new Question();
                         $oSubQuestion->sid = $iSurveyID;
                         $oSubQuestion->gid = $iQuestionGroupID;
                         $oSubQuestion->question_order = $iPosition + 1;
                         $oSubQuestion->title = $aCodes[$iScaleID][$iPosition];
                         $oSubQuestion->question = $subquestionvalue;
                         $oSubQuestion->parent_qid = $iQuestionID;
                         $oSubQuestion->language = $sLanguage;
                         $oSubQuestion->scale_id = $iScaleID;
                         // update old sub questions
                     } else {
                         $oSubQuestion = Question::model()->find("qid=:qid AND language=:language", array(":qid" => $aInsertQID[$iScaleID][$iPosition], ':language' => $sLanguage));
                         if (!$oSubQuestion) {
                             $oSubQuestion = new Question();
                         }
                         $oSubQuestion->sid = $iSurveyID;
                         $oSubQuestion->gid = $iQuestionGroupID;
                         $oSubQuestion->question_order = $iPosition + 1;
                         $oSubQuestion->title = $aCodes[$iScaleID][$iPosition];
                         $oSubQuestion->question = $subquestionvalue;
                         $oSubQuestion->parent_qid = $iQuestionID;
                         $oSubQuestion->language = $sLanguage;
                         $oSubQuestion->scale_id = $iScaleID;
                     }
                 }
                 $bSubQuestionResult = $oSubQuestion->save();
                 if ($bSubQuestionResult) {
                     if (substr($subquestionkey, 0, 3) != 'new' && isset($aOldCodes[$iScaleID][$iPosition]) && $aCodes[$iScaleID][$iPosition] !== $aOldCodes[$iScaleID][$iPosition]) {
                         Condition::model()->updateAll(array('cfieldname' => '+' . $iSurveyID . 'X' . $iQuestionGroupID . 'X' . $iQuestionID . $aCodes[$iScaleID][$iPosition], 'value' => $aCodes[$iScaleID][$iPosition]), 'cqid=:cqid AND cfieldname=:cfieldname AND value=:value', array(':cqid' => $iQuestionID, ':cfieldname' => $iSurveyID . 'X' . $iQuestionGroupID . 'X' . $iQuestionID, ':value' => $aOldCodes[$iScaleID][$iPosition]));
                     }
                     if (!isset($aInsertQID[$iScaleID][$iPosition])) {
                         $aInsertQID[$iScaleID][$iPosition] = $oSubQuestion->qid;
                     }
                 } else {
                     $aErrors = $oSubQuestion->getErrors();
                     if (count($aErrors)) {
                         foreach ($aErrors as $sAttribute => $aStringErrors) {
                             foreach ($aStringErrors as $sStringErrors) {
                                 return sprintf("Error on %s for subquestion %s: %s", $sAttribute, $aCodes[$iScaleID][$iPosition], $sStringErrors);
                             }
                         }
                     } else {
                         return sprintf("Subquestions %s could not be updated.", $aCodes[$iScaleID][$iPosition]);
                     }
                 }
                 $iPosition++;
             }
         }
     }
     LimeExpressionManager::UpgradeConditionsToRelevance($iSurveyID);
     // Do it only if there are no error ?
     //return "Sub-questions were successfully saved";
     return "(" . $test . ")";
 }
                $groups[$questionType['group']] = array();
            }
            $groups[$questionType['group']][$key] = $questionType['description'];
        }
        $this->widget('ext.bootstrap.widgets.TbSelect2', array('data' => $groups, 'name' => 'type', 'options' => array('width' => '300px', 'minimumResultsForSearch' => 1000), 'events' => array(), 'htmlOptions' => array('id' => 'question_type', 'options' => array($eqrow['type'] => array('selected' => true)))));
        $script = '$("#question_type option").addClass("questionType");';
        App()->getClientScript()->registerScript('add_class_to_options', $script);
    } else {
        $aQtypeData = array();
        foreach (getQuestionTypeList($eqrow['type'], 'array') as $key => $questionType) {
            $aQtypeData[] = array('code' => $key, 'description' => $questionType['description'], 'group' => $questionType['group']);
        }
        echo CHtml::dropDownList('type', 'category', CHtml::listData($aQtypeData, 'code', 'description', 'group'), array('class' => 'none', 'id' => 'question_type', 'options' => array($eqrow['type'] => array('selected' => true))));
    }
} else {
    $qtypelist = getQuestionTypeList('', 'array');
    echo "{$qtypelist[$eqrow['type']]['description']} - " . gT("Cannot be changed (survey is active)");
    ?>
                            <input type='hidden' name='type' id='question_type' value='<?php 
    echo $eqrow['type'];
    ?>
' />
                        <?php 
}
?>

                </li>



                <?php 
 /**
  * Function responsible to activate survey.
  *
  * @access public
  * @param int $iSurveyID
  * @return void
  */
 public function activate($iSurveyID)
 {
     if (!Permission::model()->hasSurveyPermission($iSurveyID, 'surveyactivation', 'update')) {
         die;
     }
     $iSurveyID = (int) $iSurveyID;
     $aData = array();
     $aData['sidemenu']['state'] = false;
     $aData['aSurveysettings'] = getSurveyInfo($iSurveyID);
     $aData['surveyid'] = $iSurveyID;
     $surveyinfo = Survey::model()->findByPk($iSurveyID)->surveyinfo;
     $aData['title_bar']['title'] = $surveyinfo['surveyls_title'] . "(" . gT("ID") . ":" . $iSurveyID . ")";
     // Die if this is not possible
     if (!isset($aData['aSurveysettings']['active']) || $aData['aSurveysettings']['active'] == 'Y') {
         $this->getController()->error('Survey not active');
     }
     $qtypes = getQuestionTypeList('', 'array');
     Yii::app()->loadHelper("admin/activate");
     if (empty($_POST['ok'])) {
         if (isset($_GET['fixnumbering']) && $_GET['fixnumbering']) {
             fixNumbering($_GET['fixnumbering'], $iSurveyID);
         }
         // Check consistency for groups and questions
         $failedgroupcheck = checkGroup($iSurveyID);
         $failedcheck = checkQuestions($iSurveyID, $iSurveyID, $qtypes);
         $aData['failedcheck'] = $failedcheck;
         $aData['failedgroupcheck'] = $failedgroupcheck;
         $aData['aSurveysettings'] = getSurveyInfo($iSurveyID);
         $this->_renderWrappedTemplate('survey', 'activateSurvey_view', $aData);
     } else {
         $survey = Survey::model()->findByAttributes(array('sid' => $iSurveyID));
         if (!is_null($survey)) {
             $survey->anonymized = Yii::app()->request->getPost('anonymized');
             $survey->datestamp = Yii::app()->request->getPost('datestamp');
             $survey->ipaddr = Yii::app()->request->getPost('ipaddr');
             $survey->refurl = Yii::app()->request->getPost('refurl');
             $survey->savetimings = Yii::app()->request->getPost('savetimings');
             $survey->save();
             Survey::model()->resetCache();
             // Make sure the saved values will be picked up
         }
         $aResult = activateSurvey($iSurveyID);
         if (isset($aResult['error'])) {
             $aViewUrls['output'] = "<br />\n<div class='messagebox ui-corner-all'>\n";
             if ($aResult['error'] == 'surveytablecreation') {
                 $aViewUrls['output'] .= "<div class='alert alert-warning' role='alert'>" . gT("Survey table could not be created.") . "</div>\n";
             } else {
                 $aViewUrls['output'] .= "<div class='alert alert-success' role='alert'>" . gT("Timings table could not be created.") . "</div>\n";
             }
             $aViewUrls['output'] .= "<strong class='text-warning'>" . gT("Database error!!") . "\n " . "\n" . "<pre>" . var_export($aResult['error'], true) . "</pre>\n\n                <a href='" . Yii::app()->getController()->createUrl("admin/survey/sa/view/surveyid/" . $iSurveyID) . "'>" . gT("Main Admin Screen") . "</a>\n</strong><br/>";
         } else {
             $warning = isset($aResult['warning']) ? true : false;
             $allowregister = $survey->allowregister == 'Y' ? true : false;
             $onclickAction = convertGETtoPOST(Yii::app()->getController()->createUrl("admin/tokens/sa/index/surveyid/" . $iSurveyID));
             $closedOnclickAction = convertGETtoPOST(Yii::app()->getController()->createUrl("admin/tokens/sa/index/surveyid/" . $iSurveyID));
             $noOnclickAction = convertGETtoPOST(Yii::app()->getController()->createUrl("admin/survey/sa/view/surveyid/" . $iSurveyID));
             $activationData = array('iSurveyID' => $iSurveyID, 'warning' => $warning, 'allowregister' => $allowregister, 'onclickAction' => $onclickAction, 'closedOnclickAction' => $closedOnclickAction, 'noOnclickAction' => $noOnclickAction);
             $aViewUrls['output'] = $this->getController()->renderPartial('/admin/survey/_activation_feedback', $activationData, true);
         }
         $this->_renderWrappedTemplate('survey', $aViewUrls, $aData);
     }
 }
/**
 * This function builds all the required session variables when a survey is first started and
 * it loads any answer defaults from command line or from the table defaultvalues
 * It is called from the related format script (group.php, question.php, survey.php)
 * if the survey has just started.
 * @param int $surveyid
 * @param boolean $preview Defaults to false
 * @return void
 */
function buildsurveysession($surveyid, $preview = false)
{
    Yii::trace('start', 'survey.buildsurveysession');
    global $secerror, $clienttoken;
    global $tokensexist;
    global $move, $rooturl;
    $sLangCode = App()->language;
    $languagechanger = makeLanguageChangerSurvey($sLangCode);
    if (!$preview) {
        $preview = Yii::app()->getConfig('previewmode');
    }
    $thissurvey = getSurveyInfo($surveyid, $sLangCode);
    if ($thissurvey['nokeyboard'] == 'Y') {
        includeKeypad();
        $kpclass = "text-keypad";
    } else {
        $kpclass = '';
    }
    // $thissurvey['template'] already fixed by model : but why put this in session ?
    $_SESSION['survey_' . $surveyid]['templatename'] = $thissurvey['template'];
    $_SESSION['survey_' . $surveyid]['templatepath'] = getTemplatePath($thissurvey['template']) . DIRECTORY_SEPARATOR;
    $sTemplatePath = $_SESSION['survey_' . $surveyid]['templatepath'];
    $oTemplate = Template::model()->getInstance('', $surveyid);
    $sTemplatePath = $oTemplate->path;
    $sTemplateViewPath = $oTemplate->viewPath;
    /**
     * This method has multiple outcomes that virtually do the same thing
     * Possible scenarios/subscenarios are =>
     *   - No token required & no captcha required
     *   - No token required & captcha required
     *       > captcha may be wrong
     *   - token required & captcha required
     *       > token may be wrong/used
     *       > captcha may be wrong
     */
    $scenarios = array("tokenRequired" => $tokensexist == 1, "captchaRequired" => isCaptchaEnabled('surveyaccessscreen', $thissurvey['usecaptcha']) && !isset($_SESSION['survey_' . $surveyid]['captcha_surveyaccessscreen']));
    /**
     *   Set subscenarios depending on scenario outcome
     */
    $subscenarios = array("captchaCorrect" => false, "tokenValid" => false);
    //Check the scenario for token required
    if ($scenarios['tokenRequired']) {
        //Check for the token-validity
        if ($thissurvey['alloweditaftercompletion'] == 'Y') {
            $oTokenEntry = Token::model($surveyid)->findByAttributes(array('token' => $clienttoken));
        } else {
            $oTokenEntry = Token::model($surveyid)->usable()->incomplete()->findByAttributes(array('token' => $clienttoken));
        }
        $subscenarios['tokenValid'] = !empty($oTokenEntry) && $clienttoken != "";
    } else {
        $subscenarios['tokenValid'] = true;
    }
    //Check the scenario for captcha required
    if ($scenarios['captchaRequired']) {
        //Check if the Captcha was correct
        $loadsecurity = returnGlobal('loadsecurity', true);
        $captcha = Yii::app()->getController()->createAction('captcha');
        $subscenarios['captchaCorrect'] = $captcha->validate($loadsecurity, false);
    } else {
        $subscenarios['captchaCorrect'] = true;
        $loadsecurity = false;
    }
    //RenderWay defines which html gets rendered to the user_error
    // Possibilities are main,register,correct
    $renderCaptcha = "";
    $renderToken = "";
    //Define array to render the partials
    $aEnterTokenData = array();
    $aEnterTokenData['bNewTest'] = false;
    $aEnterTokenData['bDirectReload'] = false;
    $aEnterTokenData['error'] = $secerror;
    $aEnterTokenData['iSurveyId'] = $surveyid;
    $aEnterTokenData['sKpClass'] = $kpclass;
    // ???
    $aEnterTokenData['sLangCode'] = $sLangCode;
    if (isset($_GET['bNewTest']) && $_GET['newtest'] == "Y") {
        $aEnterTokenData['bNewTest'] = true;
    }
    // If this is a direct Reload previous answers URL, then add hidden fields
    if (isset($loadall) && isset($scid) && isset($loadname) && isset($loadpass)) {
        $aEnterTokenData['bDirectReload'] = true;
        $aEnterTokenData['sCid'] = $scid;
        $aEnterTokenData['sLoadname'] = htmlspecialchars($loadname);
        $aEnterTokenData['sLoadpass'] = htmlspecialchars($loadpass);
    }
    $FlashError = "";
    // Scenario => Captcha required
    if ($scenarios['captchaRequired'] && !$preview) {
        list($renderCaptcha, $FlashError) = testCaptcha($aEnterTokenData, $subscenarios, $surveyid, $loadsecurity);
    }
    // Scenario => Token required
    if ($scenarios['tokenRequired'] && !$preview) {
        //Test if token is valid
        list($renderToken, $FlashError) = testIfTokenIsValid($subscenarios, $thissurvey, $aEnterTokenData, $clienttoken);
    }
    //If there were errors, display through yii->FlashMessage
    if ($FlashError !== "") {
        $aEnterTokenData['errorMessage'] = $FlashError;
    }
    $renderWay = getRenderWay($renderToken, $renderCaptcha);
    $redata = compact(array_keys(get_defined_vars()));
    renderRenderWayForm($renderWay, $redata, $scenarios, $sTemplateViewPath, $aEnterTokenData, $surveyid);
    // Reset all the session variables and start again
    resetAllSessionVariables($surveyid);
    // Multi lingual support order : by REQUEST, if not by Token->language else by survey default language
    if (returnGlobal('lang', true)) {
        $language_to_set = returnGlobal('lang', true);
    } elseif (isset($oTokenEntry) && $oTokenEntry) {
        // If survey have token : we have a $oTokenEntry
        // Can use $oTokenEntry = Token::model($surveyid)->findByAttributes(array('token'=>$clienttoken)); if we move on another function : this par don't validate the token validity
        $language_to_set = $oTokenEntry->language;
    } else {
        $language_to_set = $thissurvey['language'];
    }
    // Always SetSurveyLanguage : surveys controller SetSurveyLanguage too, if different : broke survey (#09769)
    SetSurveyLanguage($surveyid, $language_to_set);
    UpdateGroupList($surveyid, $_SESSION['survey_' . $surveyid]['s_lang']);
    $totalquestions = Question::model()->getTotalQuestions($surveyid);
    $iTotalGroupsWithoutQuestions = QuestionGroup::model()->getTotalGroupsWithoutQuestions($surveyid);
    // Fix totalquestions by substracting Test Display questions
    $iNumberofQuestions = Question::model()->getNumberOfQuestions($surveyid);
    $_SESSION['survey_' . $surveyid]['totalquestions'] = $totalquestions - (int) reset($iNumberofQuestions);
    // 2. SESSION VARIABLE: totalsteps
    setTotalSteps($surveyid, $thissurvey, $totalquestions);
    // Break out and crash if there are no questions!
    if ($totalquestions == 0 || $iTotalGroupsWithoutQuestions > 0) {
        $redata = compact(array_keys(get_defined_vars()));
        breakOutAndCrash($redata, $sTemplateViewPath, $totalquestions, $iTotalGroupsWithoutQuestions, $thissurvey);
    }
    //Perform a case insensitive natural sort on group name then question title of a multidimensional array
    //    usort($arows, 'groupOrderThenQuestionOrder');
    //3. SESSION VARIABLE - insertarray
    //An array containing information about used to insert the data into the db at the submit stage
    //4. SESSION VARIABLE - fieldarray
    //See rem at end..
    if ($tokensexist == 1 && $clienttoken) {
        $_SESSION['survey_' . $surveyid]['token'] = $clienttoken;
    }
    if ($thissurvey['anonymized'] == "N") {
        $_SESSION['survey_' . $surveyid]['insertarray'][] = "token";
    }
    $qtypes = getQuestionTypeList('', 'array');
    $fieldmap = createFieldMap($surveyid, 'full', true, false, $_SESSION['survey_' . $surveyid]['s_lang']);
    //$seed = ls\mersenne\getSeed($surveyid, $preview);
    // Randomization groups for groups
    list($fieldmap, $randomized1) = randomizationGroup($surveyid, $fieldmap, $preview);
    // Randomization groups for questions
    list($fieldmap, $randomized2) = randomizationQuestion($surveyid, $fieldmap, $preview);
    $randomized = $randomized1 || $randomized2;
    if ($randomized === true) {
        $fieldmap = finalizeRandomization($fieldmap);
        $_SESSION['survey_' . $surveyid]['fieldmap-' . $surveyid . $_SESSION['survey_' . $surveyid]['s_lang']] = $fieldmap;
        $_SESSION['survey_' . $surveyid]['fieldmap-' . $surveyid . '-randMaster'] = 'fieldmap-' . $surveyid . $_SESSION['survey_' . $surveyid]['s_lang'];
    }
    // TMSW Condition->Relevance:  don't need hasconditions, or usedinconditions
    $_SESSION['survey_' . $surveyid]['fieldmap'] = $fieldmap;
    initFieldArray($surveyid, $fieldmap);
    // Prefill questions/answers from command line params
    prefillFromCommandLine($surveyid);
    if (isset($_SESSION['survey_' . $surveyid]['fieldarray'])) {
        $_SESSION['survey_' . $surveyid]['fieldarray'] = array_values($_SESSION['survey_' . $surveyid]['fieldarray']);
    }
    //Check if a passthru label and value have been included in the query url
    checkPassthruLabel($surveyid, $preview, $fieldmap);
    Yii::trace('end', 'survey.buildsurveysession');
    //traceVar($_SESSION['survey_' . $surveyid]);
}
 /**
  * Database::index()
  *
  * @param mixed $action
  * @return
  */
 function index($sa = null)
 {
     $action = Yii::app()->request->getPost('action');
     $clang = $this->getController()->lang;
     $postsid = returnGlobal('sid');
     $postgid = returnGlobal('gid');
     $postqid = returnGlobal('qid');
     $postqaid = returnGlobal('qaid');
     $databaseoutput = '';
     $surveyid = returnGlobal('sid');
     $gid = returnGlobal('gid');
     $qid = returnGlobal('qid');
     // if $action is not passed, check post data.
     if (Yii::app()->getConfig('filterxsshtml') && Yii::app()->session['USER_RIGHT_SUPERADMIN'] != 1) {
         $filter = new CHtmlPurifier();
         $filter->options = array('URI.AllowedSchemes' => array('http' => true, 'https' => true));
         $xssfilter = true;
     } else {
         $xssfilter = false;
     }
     if ($action == "updatedefaultvalues" && hasSurveyPermission($surveyid, 'surveycontent', 'update')) {
         $questlangs = Survey::model()->findByPk($surveyid)->additionalLanguages;
         $baselang = Survey::model()->findByPk($surveyid)->language;
         array_unshift($questlangs, $baselang);
         Questions::model()->updateAll(array('same_default' => Yii::app()->request->getPost('samedefault') ? 1 : 0), 'sid=:sid ANd qid=:qid', array(':sid' => $surveyid, ':qid' => $qid));
         $resrow = Questions::model()->findByAttributes(array('qid' => $qid));
         $questiontype = $resrow['type'];
         $qtproperties = getQuestionTypeList('', 'array');
         if ($qtproperties[$questiontype]['answerscales'] > 0 && $qtproperties[$questiontype]['subquestions'] == 0) {
             for ($scale_id = 0; $scale_id < $qtproperties[$questiontype]['answerscales']; $scale_id++) {
                 foreach ($questlangs as $language) {
                     if (!is_null(Yii::app()->request->getPost('defaultanswerscale_' . $scale_id . '_' . $language))) {
                         $this->_updateDefaultValues($qid, 0, $scale_id, '', $language, Yii::app()->request->getPost('defaultanswerscale_' . $scale_id . '_' . $language), true);
                     }
                     if (!is_null(Yii::app()->request->getPost('other_' . $scale_id . '_' . $language))) {
                         $this->_updateDefaultValues($qid, 0, $scale_id, 'other', $language, Yii::app()->request->getPost('other_' . $scale_id . '_' . $language), true);
                     }
                 }
             }
         }
         if ($qtproperties[$questiontype]['subquestions'] > 0) {
             foreach ($questlangs as $language) {
                 $sqresult = Questions::model()->findAllByAttributes(array('sid' => $surveyid, 'gid' => $gid, 'parent_qid' => $qid, 'language' => $language, 'scale_id' => 0));
                 for ($scale_id = 0; $scale_id < $qtproperties[$questiontype]['subquestions']; $scale_id++) {
                     foreach ($sqresult as $aSubquestionrow) {
                         if (!is_null(Yii::app()->request->getPost('defaultanswerscale_' . $scale_id . '_' . $language . '_' . $aSubquestionrow['qid']))) {
                             $this->_updateDefaultValues($qid, $aSubquestionrow['qid'], $scale_id, '', $language, Yii::app()->request->getPost('defaultanswerscale_' . $scale_id . '_' . $language . '_' . $aSubquestionrow['qid']), true);
                         }
                     }
                 }
             }
         }
         if ($qtproperties[$questiontype]['answerscales'] == 0 && $qtproperties[$questiontype]['subquestions'] == 0) {
             foreach ($questlangs as $language) {
                 if (!is_null(Yii::app()->request->getPost('defaultanswerscale_0_' . $language . '_0'))) {
                     $this->_updateDefaultValues($postqid, 0, 0, '', $language, Yii::app()->request->getPost('defaultanswerscale_0_' . $language . '_0'), true);
                 }
             }
         }
         Yii::app()->session['flashmessage'] = $clang->gT("Default value settings were successfully saved.");
         LimeExpressionManager::SetDirtyFlag();
         if ($databaseoutput != '') {
             echo $databaseoutput;
         } else {
             $this->getController()->redirect($this->getController()->createUrl('admin/survey/sa/view/surveyid/' . $surveyid . '/gid/' . $gid . '/qid/' . $qid));
         }
     }
     if ($action == "updateansweroptions" && hasSurveyPermission($surveyid, 'surveycontent', 'update')) {
         Yii::app()->loadHelper('database');
         $anslangs = Survey::model()->findByPk($surveyid)->additionalLanguages;
         $baselang = Survey::model()->findByPk($surveyid)->language;
         $alllanguages = $anslangs;
         array_unshift($alllanguages, $baselang);
         $resrow = Questions::model()->findByAttributes(array('qid' => $qid));
         $questiontype = $resrow['type'];
         // Checked)
         $qtypes = getQuestionTypeList('', 'array');
         $scalecount = $qtypes[$questiontype]['answerscales'];
         $count = 0;
         $invalidCode = 0;
         $duplicateCode = 0;
         //require_once("../classes/inputfilter/class.inputfilter_clean.php");
         //$myFilter = new InputFilter('','',1,1,1);
         //First delete all answers
         Answers::model()->deleteAllByAttributes(array('qid' => $qid));
         LimeExpressionManager::RevertUpgradeConditionsToRelevance($surveyid);
         for ($scale_id = 0; $scale_id < $scalecount; $scale_id++) {
             $maxcount = (int) Yii::app()->request->getPost('answercount_' . $scale_id);
             for ($sortorderid = 1; $sortorderid < $maxcount; $sortorderid++) {
                 $code = sanitize_paranoid_string(Yii::app()->request->getPost('code_' . $sortorderid . '_' . $scale_id));
                 if (Yii::app()->request->getPost('oldcode_' . $sortorderid . '_' . $scale_id)) {
                     $oldcode = sanitize_paranoid_string(Yii::app()->request->getPost('oldcode_' . $sortorderid . '_' . $scale_id));
                     if ($code !== $oldcode) {
                         Conditions::model()->updateAll(array('value' => $code), 'cqid=:cqid AND value=:value', array(':cqid' => $qid, ':value' => $oldcode));
                     }
                 }
                 $assessmentvalue = (int) Yii::app()->request->getPost('assessment_' . $sortorderid . '_' . $scale_id);
                 foreach ($alllanguages as $language) {
                     $answer = Yii::app()->request->getPost('answer_' . $language . '_' . $sortorderid . '_' . $scale_id);
                     if ($xssfilter) {
                         $answer = $filter->purify($answer);
                     } else {
                         $answer = html_entity_decode($answer, ENT_QUOTES, "UTF-8");
                     }
                     // Fix bug with FCKEditor saving strange BR types
                     $answer = fixCKeditorText($answer);
                     // Now we insert the answers
                     $result = Answers::model()->insertRecords(array('code' => $code, 'answer' => $answer, 'qid' => $qid, 'sortorder' => $sortorderid, 'language' => $language, 'assessment_value' => $assessmentvalue, 'scale_id' => $scale_id));
                     if (!$result) {
                         $databaseoutput .= "<script type=\"text/javascript\">\n<!--\n alert(\"" . $clang->gT("Failed to update answers", "js") . "\")\n //-->\n</script>\n";
                     }
                 }
                 // foreach ($alllanguages as $language)
                 if (isset($oldcode) && $code !== $oldcode) {
                     Conditions::model()->updateAll(array('value' => $code), 'cqid=:cqid AND value=:value', array(':cqid' => $qid, ':value' => $oldcode));
                 }
             }
             // for ($sortorderid=0;$sortorderid<$maxcount;$sortorderid++)
         }
         //  for ($scale_id=0;
         LimeExpressionManager::UpgradeConditionsToRelevance($surveyid);
         if ($invalidCode == 1) {
             $databaseoutput .= "<script type=\"text/javascript\">\n<!--\n alert(\"" . $clang->gT("Answers with a code of 0 (zero) or blank code are not allowed, and will not be saved", "js") . "\")\n //-->\n</script>\n";
         }
         if ($duplicateCode == 1) {
             $databaseoutput .= "<script type=\"text/javascript\">\n<!--\n alert(\"" . $clang->gT("Duplicate codes found, these entries won't be updated", "js") . "\")\n //-->\n</script>\n";
         }
         Yii::app()->session['flashmessage'] = $clang->gT("Answer options were successfully saved.");
         LimeExpressionManager::SetDirtyFlag();
         if ($databaseoutput != '') {
             echo $databaseoutput;
         } else {
             $this->getController()->redirect($this->getController()->createUrl('/admin/question/sa/answeroptions/surveyid/' . $surveyid . '/gid/' . $gid . '/qid/' . $qid));
         }
         //$action='editansweroptions';
     }
     if ($action == "updatesubquestions" && hasSurveyPermission($surveyid, 'surveycontent', 'update')) {
         Yii::app()->loadHelper('database');
         $anslangs = Survey::model()->findByPk($surveyid)->additionalLanguages;
         $baselang = Survey::model()->findByPk($surveyid)->language;
         array_unshift($anslangs, $baselang);
         $row = Questions::model()->findByAttributes(array('qid' => $qid));
         $questiontype = $row['type'];
         // Checked
         $qtypes = getQuestionTypeList('', 'array');
         $scalecount = $qtypes[$questiontype]['subquestions'];
         $clang = $this->getController()->lang;
         // First delete any deleted ids
         $deletedqids = explode(' ', trim(Yii::app()->request->getPost('deletedqids')));
         LimeExpressionManager::RevertUpgradeConditionsToRelevance($surveyid);
         foreach ($deletedqids as $deletedqid) {
             $deletedqid = (int) $deletedqid;
             if ($deletedqid > 0) {
                 // don't remove undefined
                 $result = Questions::model()->deleteAllByAttributes(array('qid' => $deletedqid));
                 if (!$result) {
                     $databaseoutput .= "<script type=\"text/javascript\">\n<!--\n alert(\"" . $clang->gT("Failed to delete answer", "js") . " \")\n //-->\n</script>\n";
                 }
             }
         }
         //Determine ids by evaluating the hidden field
         $rows = array();
         $codes = array();
         $oldcodes = array();
         foreach ($_POST as $postkey => $postvalue) {
             $postkey = explode('_', $postkey);
             if ($postkey[0] == 'answer') {
                 $rows[$postkey[3]][$postkey[1]][$postkey[2]] = $postvalue;
             }
             if ($postkey[0] == 'code') {
                 $codes[$postkey[2]][] = $postvalue;
             }
             if ($postkey[0] == 'oldcode') {
                 $oldcodes[$postkey[2]][] = $postvalue;
             }
         }
         $count = 0;
         $invalidCode = 0;
         $duplicateCode = 0;
         $dupanswers = array();
         /*
         for ($scale_id=0;$scale_id<$scalecount;$scale_id++)
         {
         
         // Find duplicate codes and add these to dupanswers array
         $foundCat=array_count_values($codes);
         foreach($foundCat as $key=>$value){
         if($value>=2){
         $dupanswers[]=$key;
         }
         }
         }
         */
         //require_once("../classes/inputfilter/class.inputfilter_clean.php");
         //$myFilter = new InputFilter('','',1,1,1);
         //$insertqids=array(); //?
         $insertqid = array();
         for ($scale_id = 0; $scale_id < $scalecount; $scale_id++) {
             foreach ($anslangs as $language) {
                 $position = 0;
                 foreach ($rows[$scale_id][$language] as $subquestionkey => $subquestionvalue) {
                     if (substr($subquestionkey, 0, 3) != 'new') {
                         Questions::model()->updateByPk(array('qid' => $subquestionkey, 'language' => $language), array('question_order' => $position + 1, 'title' => $codes[$scale_id][$position], 'question' => $subquestionvalue, 'scale_id' => $scale_id));
                         if (isset($oldcodes[$scale_id][$position]) && $codes[$scale_id][$position] !== $oldcodes[$scale_id][$position]) {
                             Conditions::model()->updateAll(array('cfieldname' => '+' . $surveyid . 'X' . $gid . 'X' . $qid . $codes[$scale_id][$position], 'value' => $codes[$scale_id][$position]), 'cqid=:cqid AND cfieldname=:cfieldname AND value=:value', array(':cqid' => $qid, ':cfieldname' => $surveyid . 'X' . $gid . 'X' . $qid, ':value' => $oldcodes[$scale_id][$position]));
                         }
                     } else {
                         if (!isset($insertqid[$scale_id][$position])) {
                             $insertqid[$scale_id][$position] = Questions::model()->insertRecords(array('sid' => $surveyid, 'gid' => $gid, 'question_order' => $position + 1, 'title' => $codes[$scale_id][$position], 'question' => $subquestionvalue, 'parent_qid' => $qid, 'language' => $language, 'scale_id' => $scale_id));
                         } else {
                             switchMSSQLIdentityInsert('questions', true);
                             Questions::model()->insertRecords(array('qid' => $insertqid[$scale_id][$position], 'sid' => $surveyid, 'gid' => $gid, 'question_order' => $position + 1, 'title' => $codes[$scale_id][$position], 'question' => $subquestionvalue, 'parent_qid' => $qid, 'language' => $language, 'scale_id' => $scale_id));
                             switchMSSQLIdentityInsert('questions', true);
                         }
                     }
                     $position++;
                 }
             }
         }
         LimeExpressionManager::UpgradeConditionsToRelevance($surveyid);
         //include("surveytable_functions.php");
         //surveyFixColumns($surveyid);
         Yii::app()->session['flashmessage'] = $clang->gT("Subquestions were successfully saved.");
         //$action='editsubquestions';
         LimeExpressionManager::SetDirtyFlag();
         if ($databaseoutput != '') {
             echo $databaseoutput;
         } else {
             $this->getController()->redirect($this->getController()->createUrl('/admin/question/sa/subquestions/surveyid/' . $surveyid . '/gid/' . $gid . '/qid/' . $qid));
         }
     }
     if (in_array($action, array('insertquestion', 'copyquestion')) && hasSurveyPermission($surveyid, 'surveycontent', 'create')) {
         $baselang = Survey::model()->findByPk($surveyid)->language;
         if (strlen(Yii::app()->request->getPost('title')) < 1) {
             $databaseoutput .= "<script type=\"text/javascript\">\n<!--\n " . "alert(\"" . $clang->gT("The question could not be added. You must enter at least a question code.", "js") . "\")\n " . "//-->\n</script>\n";
         } else {
             if (Yii::app()->request->getPost('questionposition', "") != "") {
                 $question_order = intval(Yii::app()->request->getPost('questionposition'));
                 //Need to renumber all questions on or after this
                 $cdquery = "UPDATE {{questions}} SET question_order=question_order+1 WHERE gid=:gid AND question_order >= :order";
                 $cdresult = Yii::app()->db->createCommand($cdquery)->bindValues(array(':gid' => $gid, ':order' => $question_order))->query();
             } else {
                 $question_order = getMaxQuestionOrder($gid, $surveyid);
                 $question_order++;
             }
             $_POST['title'] = html_entity_decode(Yii::app()->request->getPost('title'), ENT_QUOTES, "UTF-8");
             $_POST['question_' . $baselang] = html_entity_decode(Yii::app()->request->getPost('question_' . $baselang), ENT_QUOTES, "UTF-8");
             $_POST['help_' . $baselang] = html_entity_decode(Yii::app()->request->getPost('help_' . $baselang), ENT_QUOTES, "UTF-8");
             // Fix bug with FCKEditor saving strange BR types
             if ($xssfilter) {
                 $_POST['title'] = $filter->purify($_POST['title']);
                 $_POST['question_' . $baselang] = $filter->purify($_POST['question_' . $baselang]);
                 $_POST['help_' . $baselang] = $filter->purify($_POST['help_' . $baselang]);
             } else {
                 $_POST['title'] = fixCKeditorText(Yii::app()->request->getPost('title'));
                 $_POST['question_' . $baselang] = fixCKeditorText(Yii::app()->request->getPost('question_' . $baselang));
                 $_POST['help_' . $baselang] = fixCKeditorText(Yii::app()->request->getPost('help_' . $baselang));
             }
             $data = array('sid' => $surveyid, 'gid' => $gid, 'type' => Yii::app()->request->getPost('type'), 'title' => Yii::app()->request->getPost('title'), 'question' => Yii::app()->request->getPost('question_' . $baselang), 'preg' => Yii::app()->request->getPost('preg'), 'help' => Yii::app()->request->getPost('help_' . $baselang), 'other' => Yii::app()->request->getPost('other'), 'mandatory' => Yii::app()->request->getPost('mandatory'), 'relevance' => Yii::app()->request->getPost('relevance'), 'question_order' => $question_order, 'language' => $baselang);
             $qid = Questions::model()->insertRecords($data);
             // Add other languages
             if ($qid) {
                 $addlangs = Survey::model()->findByPk($surveyid)->additionalLanguages;
                 foreach ($addlangs as $alang) {
                     if ($alang != "") {
                         $data = array('qid' => $qid, 'sid' => $surveyid, 'gid' => $gid, 'type' => Yii::app()->request->getPost('type'), 'title' => Yii::app()->request->getPost('title'), 'question' => Yii::app()->request->getPost('question_' . $alang), 'preg' => Yii::app()->request->getPost('preg'), 'help' => Yii::app()->request->getPost('help_' . $alang), 'other' => Yii::app()->request->getPost('other'), 'mandatory' => Yii::app()->request->getPost('mandatory'), 'question_order' => $question_order, 'language' => $alang);
                         $langqid = Questions::model()->insertRecords($data);
                         // Checked */
                         if (!$langqid) {
                             $databaseoutput .= "<script type=\"text/javascript\">\n<!--\n alert(\"" . sprintf($clang->gT("Question in language %s could not be created.", "js"), $alang) . "\\n\")\n //-->\n</script>\n";
                         }
                     }
                 }
             }
             if (!$qid) {
                 $databaseoutput .= "<script type=\"text/javascript\">\n<!--\n alert(\"" . $clang->gT("Question could not be created.", "js") . "\\n\")\n //-->\n</script>\n";
             } else {
                 if ($action == 'copyquestion') {
                     if (returnGlobal('copysubquestions') == "Y") {
                         $aSQIDMappings = array();
                         $r1 = Questions::model()->getSubQuestions(returnGlobal('oldqid'));
                         while ($qr1 = $r1->read()) {
                             $qr1['parent_qid'] = $qid;
                             if (isset($aSQIDMappings[$qr1['qid']])) {
                                 $qr1['qid'] = $aSQIDMappings[$qr1['qid']];
                             } else {
                                 $oldqid = $qr1['qid'];
                                 unset($qr1['qid']);
                             }
                             $qr1['gid'] = $postgid;
                             $iInsertID = Questions::model()->insertRecords($qr1);
                             if (!isset($qr1['qid'])) {
                                 $aSQIDMappings[$oldqid] = $iInsertID;
                             }
                         }
                     }
                     if (returnGlobal('copyanswers') == "Y") {
                         $r1 = Answers::model()->getAnswers(returnGlobal('oldqid'));
                         while ($qr1 = $r1->read()) {
                             Answers::model()->insertRecords(array('qid' => $qid, 'code' => $qr1['code'], 'answer' => $qr1['answer'], 'sortorder' => $qr1['sortorder'], 'language' => $qr1['language'], 'scale_id' => $qr1['scale_id']));
                         }
                     }
                     if (returnGlobal('copyattributes') == "Y") {
                         $r1 = Question_attributes::model()->getQuestionAttributes(returnGlobal('oldqid'));
                         while ($qr1 = $r1->read()) {
                             $qr1['qid'] = $qid;
                             unset($qr1['qaid']);
                             Question_attributes::model()->insertRecords($qr1);
                         }
                     }
                 } else {
                     $qattributes = questionAttributes();
                     $validAttributes = $qattributes[Yii::app()->request->getPost('type')];
                     $aLanguages = array_merge(array(Survey::model()->findByPk($surveyid)->language), Survey::model()->findByPk($surveyid)->additionalLanguages);
                     foreach ($validAttributes as $validAttribute) {
                         if ($validAttribute['i18n']) {
                             foreach ($aLanguages as $sLanguage) {
                                 // TODO sanitise XSS
                                 $value = Yii::app()->request->getPost($validAttribute['name'] . '_' . $sLanguage);
                                 $result = Question_attributes::model()->findAllByAttributes(array('attribute' => $validAttribute['name'], 'qid' => $qid, 'language' => $sLanguage));
                                 if (count($result) > 0) {
                                     if ($value != '') {
                                         Question_attributes::model()->updateAll(array('value' => $value), 'attribute=:attribute AND qid=:qid AND language=:language', array(':attribute' => $validAttribute['name'], ':qid' => $qid, ':language' => $sLanguage));
                                     } else {
                                         Question_attributes::model()->deleteAll('attribute=:attribute AND qid=:qid AND language=:language', array(':attribute' => $validAttribute['name'], ':qid' => $qid, ':language' => $sLanguage));
                                     }
                                 } elseif ($value != '') {
                                     $attribute = new Question_attributes();
                                     $attribute->qid = $qid;
                                     $attribute->value = $value;
                                     $attribute->attribute = $validAttribute['name'];
                                     $attribute->language = $sLanguage;
                                     $attribute->save();
                                 }
                             }
                         } else {
                             $value = Yii::app()->request->getPost($validAttribute['name']);
                             if ($validAttribute['name'] == 'multiflexible_step' && trim($value) != '') {
                                 $value = floatval($value);
                                 if ($value == 0) {
                                     $value = 1;
                                 }
                             }
                             $result = Question_attributes::model()->findAllByAttributes(array('attribute' => $validAttribute['name'], 'qid' => $qid));
                             if (count($result) > 0) {
                                 if ($value != $validAttribute['default'] && trim($value) != "") {
                                     Question_attributes::model()->updateAll(array('value' => $value), 'attribute=:attribute AND qid=:qid', array(':attribute' => $validAttribute['name'], ':qid' => $qid));
                                 } else {
                                     Question_attributes::model()->deleteAll('attribute=:attribute AND qid=:qid', array(':attribute' => $validAttribute['name'], ':qid' => $qid));
                                 }
                             } elseif ($value != $validAttribute['default'] && trim($value) != "") {
                                 $attribute = new Question_attributes();
                                 $attribute->qid = $qid;
                                 $attribute->value = $value;
                                 $attribute->attribute = $validAttribute['name'];
                                 $attribute->save();
                             }
                         }
                     }
                 }
                 Questions::model()->updateQuestionOrder($gid, $surveyid);
                 Yii::app()->session['flashmessage'] = $clang->gT("Question was successfully added.");
             }
         }
         LimeExpressionManager::SetDirtyFlag();
         // so refreshes syntax highlighting
         if ($databaseoutput != '') {
             echo $databaseoutput;
         } else {
             $this->getController()->redirect($this->getController()->createUrl('admin/survey/sa/view/surveyid/' . $surveyid . '/gid/' . $gid . '/qid/' . $qid));
         }
     }
     if ($action == "updatequestion" && hasSurveyPermission($surveyid, 'surveycontent', 'update')) {
         LimeExpressionManager::RevertUpgradeConditionsToRelevance($surveyid);
         $cqr = Questions::model()->findByAttributes(array('qid' => $qid));
         $oldtype = $cqr['type'];
         $oldgid = $cqr['gid'];
         // Remove invalid question attributes on saving
         $qattributes = questionAttributes();
         $criteria = new CDbCriteria();
         $criteria->compare('qid', $qid);
         if (isset($qattributes[Yii::app()->request->getPost('type')])) {
             $validAttributes = $qattributes[Yii::app()->request->getPost('type')];
             foreach ($validAttributes as $validAttribute) {
                 $criteria->compare('attribute', '<>' . $validAttribute['name']);
             }
         }
         Question_attributes::model()->deleteAll($criteria);
         $aLanguages = array_merge(array(Survey::model()->findByPk($surveyid)->language), Survey::model()->findByPk($surveyid)->additionalLanguages);
         //now save all valid attributes
         $validAttributes = $qattributes[Yii::app()->request->getPost('type')];
         foreach ($validAttributes as $validAttribute) {
             if ($validAttribute['i18n']) {
                 foreach ($aLanguages as $sLanguage) {
                     // TODO sanitise XSS
                     $value = Yii::app()->request->getPost($validAttribute['name'] . '_' . $sLanguage);
                     $result = Question_attributes::model()->findAllByAttributes(array('attribute' => $validAttribute['name'], 'qid' => $qid, 'language' => $sLanguage));
                     if (count($result) > 0) {
                         if ($value != '') {
                             Question_attributes::model()->updateAll(array('value' => $value), 'attribute=:attribute AND qid=:qid AND language=:language', array(':attribute' => $validAttribute['name'], ':qid' => $qid, ':language' => $sLanguage));
                         } else {
                             Question_attributes::model()->deleteAll('attribute=:attribute AND qid=:qid AND language=:language', array(':attribute' => $validAttribute['name'], ':qid' => $qid, ':language' => $sLanguage));
                         }
                     } elseif ($value != '') {
                         $attribute = new Question_attributes();
                         $attribute->qid = $qid;
                         $attribute->value = $value;
                         $attribute->attribute = $validAttribute['name'];
                         $attribute->language = $sLanguage;
                         $attribute->save();
                     }
                 }
             } else {
                 $value = Yii::app()->request->getPost($validAttribute['name']);
                 if ($validAttribute['name'] == 'multiflexible_step' && trim($value) != '') {
                     $value = floatval($value);
                     if ($value == 0) {
                         $value = 1;
                     }
                 }
                 $result = Question_attributes::model()->findAllByAttributes(array('attribute' => $validAttribute['name'], 'qid' => $qid));
                 if (count($result) > 0) {
                     if ($value != $validAttribute['default'] && trim($value) != "") {
                         Question_attributes::model()->updateAll(array('value' => $value), 'attribute=:attribute AND qid=:qid', array(':attribute' => $validAttribute['name'], ':qid' => $qid));
                     } else {
                         Question_attributes::model()->deleteAll('attribute=:attribute AND qid=:qid', array(':attribute' => $validAttribute['name'], ':qid' => $qid));
                     }
                 } elseif ($value != $validAttribute['default'] && trim($value) != "") {
                     $attribute = new Question_attributes();
                     $attribute->qid = $qid;
                     $attribute->value = $value;
                     $attribute->attribute = $validAttribute['name'];
                     $attribute->save();
                 }
             }
         }
         $qtypes = getQuestionTypeList('', 'array');
         // These are the questions types that have no answers and therefore we delete the answer in that case
         $iAnswerScales = $qtypes[Yii::app()->request->getPost('type')]['answerscales'];
         $iSubquestionScales = $qtypes[Yii::app()->request->getPost('type')]['subquestions'];
         // These are the questions types that have the other option therefore we set everything else to 'No Other'
         if (Yii::app()->request->getPost('type') != "L" && Yii::app()->request->getPost('type') != "!" && Yii::app()->request->getPost('type') != "P" && Yii::app()->request->getPost('type') != "M") {
             $_POST['other'] = 'N';
         }
         // These are the questions types that have no validation - so zap it accordingly
         if (Yii::app()->request->getPost('type') == "!" || Yii::app()->request->getPost('type') == "L" || Yii::app()->request->getPost('type') == "M" || Yii::app()->request->getPost('type') == "P" || Yii::app()->request->getPost('type') == "F" || Yii::app()->request->getPost('type') == "H" || Yii::app()->request->getPost('type') == "X" || Yii::app()->request->getPost('type') == "") {
             $_POST['preg'] = '';
         }
         // These are the questions types that have no mandatory property - so zap it accordingly
         if (Yii::app()->request->getPost('type') == "X" || Yii::app()->request->getPost('type') == "|") {
             $_POST['mandatory'] = 'N';
         }
         if ($oldtype != Yii::app()->request->getPost('type')) {
             // TMSW Conditions->Relevance:  Do similar check via EM, but do allow such a change since will be easier to modify relevance
             //Make sure there are no conditions based on this question, since we are changing the type
             $ccresult = Conditions::model()->findAllByAttributes(array('cqid' => $qid));
             $cccount = count($ccresult);
             foreach ($ccresult as $ccr) {
                 $qidarray[] = $ccr['qid'];
             }
             if (isset($qidarray) && $qidarray) {
                 $qidlist = implode(", ", $qidarray);
             }
         }
         if (isset($cccount) && $cccount) {
             $databaseoutput .= "<script type=\"text/javascript\">\n<!--\n alert(\"" . $clang->gT("Question could not be updated. There are conditions for other questions that rely on the answers to this question and changing the type will cause problems. You must delete these conditions before you can change the type of this question.", "js") . " ({$qidlist})\")\n //-->\n</script>\n";
         } else {
             if (isset($gid) && $gid != "") {
                 //                    $array_result=checkMoveQuestionConstraintsForConditions(sanitize_int($surveyid),sanitize_int($qid), sanitize_int($gid));
                 //                    // If there is no blocking conditions that could prevent this move
                 //
                 //                    if (is_null($array_result['notAbove']) && is_null($array_result['notBelow']))
                 //                    {
                 $questlangs = Survey::model()->findByPk($surveyid)->additionalLanguages;
                 $baselang = Survey::model()->findByPk($surveyid)->language;
                 array_push($questlangs, $baselang);
                 if ($xssfilter) {
                     $_POST['title'] = $filter->purify($_POST['title']);
                 } else {
                     $_POST['title'] = html_entity_decode(Yii::app()->request->getPost('title'), ENT_QUOTES, "UTF-8");
                 }
                 // Fix bug with FCKEditor saving strange BR types
                 $_POST['title'] = fixCKeditorText(Yii::app()->request->getPost('title'));
                 foreach ($questlangs as $qlang) {
                     if ($xssfilter) {
                         $_POST['question_' . $qlang] = $filter->purify($_POST['question_' . $qlang]);
                         $_POST['help_' . $qlang] = $filter->purify($_POST['help_' . $qlang]);
                     } else {
                         $_POST['question_' . $qlang] = html_entity_decode(Yii::app()->request->getPost('question_' . $qlang), ENT_QUOTES, "UTF-8");
                         $_POST['help_' . $qlang] = html_entity_decode(Yii::app()->request->getPost('help_' . $qlang), ENT_QUOTES, "UTF-8");
                     }
                     // Fix bug with FCKEditor saving strange BR types
                     $_POST['question_' . $qlang] = fixCKeditorText(Yii::app()->request->getPost('question_' . $qlang));
                     $_POST['help_' . $qlang] = fixCKeditorText(Yii::app()->request->getPost('help_' . $qlang));
                     if (isset($qlang) && $qlang != "") {
                         // ToDo: Sanitize the POST variables !
                         $udata = array('type' => Yii::app()->request->getPost('type'), 'title' => Yii::app()->request->getPost('title'), 'question' => Yii::app()->request->getPost('question_' . $qlang), 'preg' => Yii::app()->request->getPost('preg'), 'help' => Yii::app()->request->getPost('help_' . $qlang), 'gid' => $gid, 'other' => Yii::app()->request->getPost('other'), 'mandatory' => Yii::app()->request->getPost('mandatory'), 'relevance' => Yii::app()->request->getPost('relevance'));
                         if ($oldgid != $gid) {
                             if (getGroupOrder($surveyid, $oldgid) > getGroupOrder($surveyid, $gid)) {
                                 // TMSW Conditions->Relevance:  What is needed here?
                                 // Moving question to a 'upper' group
                                 // insert question at the end of the destination group
                                 // this prevent breaking conditions if the target qid is in the dest group
                                 $insertorder = getMaxQuestionOrder($gid, $surveyid) + 1;
                                 $udata = array_merge($udata, array('question_order' => $insertorder));
                             } else {
                                 // Moving question to a 'lower' group
                                 // insert question at the beginning of the destination group
                                 shiftOrderQuestions($surveyid, $gid, 1);
                                 // makes 1 spare room for new question at top of dest group
                                 $udata = array_merge($udata, array('question_order' => 0));
                             }
                         }
                         $condn = array('sid' => $surveyid, 'qid' => $qid, 'language' => $qlang);
                         $question = Questions::model()->findByAttributes($condn);
                         foreach ($udata as $k => $v) {
                             $question->{$k} = $v;
                         }
                         $uqresult = $question->save();
                         //($uqquery); // or safeDie ("Error Update Question: ".$uqquery."<br />");  // Checked)
                         if (!$uqresult) {
                             $databaseoutput .= "<script type=\"text/javascript\">\n<!--\n alert(\"" . $clang->gT("Question could not be updated", "js") . "\n\")\n //-->\n</script>\n";
                         }
                     }
                 }
                 // Update the group ID on subquestions, too
                 if ($oldgid != $gid) {
                     Questions::model()->updateAll(array('gid' => $gid), 'qid=:qid and parent_qid>0', array(':qid' => $qid));
                     // if the group has changed then fix the sortorder of old and new group
                     Questions::model()->updateQuestionOrder($oldgid, $surveyid);
                     Questions::model()->updateQuestionOrder($gid, $surveyid);
                     // If some questions have conditions set on this question's answers
                     // then change the cfieldname accordingly
                     fixMovedQuestionConditions($qid, $oldgid, $gid);
                 }
                 if ($oldtype != Yii::app()->request->getPost('type')) {
                     Questions::model()->updateAll(array('type' => Yii::app()->request->getPost('type')), 'parent_qid=:qid', array(':qid' => $qid));
                 }
                 Answers::model()->deleteAllByAttributes(array('qid' => $qid), 'scale_id >= :scale_id', array(':scale_id' => $iAnswerScales));
                 // Remove old subquestion scales
                 Questions::model()->deleteAllByAttributes(array('parent_qid' => $qid), 'scale_id >= :scale_id', array(':scale_id' => $iSubquestionScales));
                 Yii::app()->session['flashmessage'] = $clang->gT("Question was successfully saved.");
                 //                    }
                 //                    else
                 //                    {
                 //
                 //                        // There are conditions constraints: alert the user
                 //                        $errormsg="";
                 //                        if (!is_null($array_result['notAbove']))
                 //                        {
                 //                            $errormsg.=$clang->gT("This question relies on other question's answers and can't be moved above groupId:","js")
                 //                            . " " . $array_result['notAbove'][0][0] . " " . $clang->gT("in position","js")." ".$array_result['notAbove'][0][1]."\\n"
                 //                            . $clang->gT("See conditions:")."\\n";
                 //
                 //                            foreach ($array_result['notAbove'] as $notAboveCond)
                 //                            {
                 //                                $errormsg.="- cid:". $notAboveCond[3]."\\n";
                 //                            }
                 //
                 //                        }
                 //                        if (!is_null($array_result['notBelow']))
                 //                        {
                 //                            $errormsg.=$clang->gT("Some questions rely on this question's answers. You can't move this question below groupId:","js")
                 //                            . " " . $array_result['notBelow'][0][0] . " " . $clang->gT("in position","js")." ".$array_result['notBelow'][0][1]."\\n"
                 //                            . $clang->gT("See conditions:")."\\n";
                 //
                 //                            foreach ($array_result['notBelow'] as $notBelowCond)
                 //                            {
                 //                                $errormsg.="- cid:". $notBelowCond[3]."\\n";
                 //                            }
                 //                        }
                 //
                 //                        $databaseoutput .= "<script type=\"text/javascript\">\n<!--\n alert(\"$errormsg\")\n //-->\n</script>\n";
                 //                        $gid= $oldgid; // group move impossible ==> keep display on oldgid
                 //                    }
             } else {
                 $databaseoutput .= "<script type=\"text/javascript\">\n<!--\n alert(\"" . $clang->gT("Question could not be updated", "js") . "\")\n //-->\n</script>\n";
             }
         }
         LimeExpressionManager::UpgradeConditionsToRelevance($surveyid);
         if ($databaseoutput != '') {
             echo $databaseoutput;
         } else {
             if (Yii::app()->request->getPost('newpage') == "return") {
                 $this->getController()->redirect($this->getController()->createUrl('admin/question/sa/editquestion/surveyid/' . $surveyid . '/gid/' . $gid . '/qid/' . $qid));
             } else {
                 $this->getController()->redirect($this->getController()->createUrl('admin/survey/sa/view/surveyid/' . $surveyid . '/gid/' . $gid . '/qid/' . $qid));
             }
         }
     }
     if ($action == "updatesurveylocalesettings" && hasSurveyPermission($surveyid, 'surveylocale', 'update')) {
         $languagelist = Survey::model()->findByPk($surveyid)->additionalLanguages;
         $languagelist[] = Survey::model()->findByPk($surveyid)->language;
         Yii::app()->loadHelper('database');
         foreach ($languagelist as $langname) {
             if ($langname) {
                 $url = Yii::app()->request->getPost('url_' . $langname);
                 if ($url == 'http://') {
                     $url = "";
                 }
                 // Clean XSS attacks
                 if ($xssfilter) {
                     $purifier = new CHtmlPurifier();
                     $purifier->options = array('HTML.Allowed' => 'p,a[href],b,i');
                     $short_title = $purifier->purify(Yii::app()->request->getPost('short_title_' . $langname));
                     $description = $purifier->purify(Yii::app()->request->getPost('description_' . $langname));
                     $welcome = $purifier->purify(Yii::app()->request->getPost('welcome_' . $langname));
                     $endtext = $purifier->purify(Yii::app()->request->getPost('endtext_' . $langname));
                     $sURLDescription = $purifier->purify(Yii::app()->request->getPost('urldescrip_' . $langname));
                     $sURL = $purifier->purify(Yii::app()->request->getPost('url_' . $langname));
                 } else {
                     $short_title = html_entity_decode(Yii::app()->request->getPost('short_title_' . $langname), ENT_QUOTES, "UTF-8");
                     $description = html_entity_decode(Yii::app()->request->getPost('description_' . $langname), ENT_QUOTES, "UTF-8");
                     $welcome = html_entity_decode(Yii::app()->request->getPost('welcome_' . $langname), ENT_QUOTES, "UTF-8");
                     $endtext = html_entity_decode(Yii::app()->request->getPost('endtext_' . $langname), ENT_QUOTES, "UTF-8");
                     $sURLDescription = html_entity_decode(Yii::app()->request->getPost('urldescrip_' . $langname), ENT_QUOTES, "UTF-8");
                     $sURL = html_entity_decode(Yii::app()->request->getPost('url_' . $langname), ENT_QUOTES, "UTF-8");
                 }
                 // Fix bug with FCKEditor saving strange BR types
                 $short_title = Yii::app()->request->getPost('short_title_' . $langname);
                 $description = Yii::app()->request->getPost('description_' . $langname);
                 $welcome = Yii::app()->request->getPost('welcome_' . $langname);
                 $endtext = Yii::app()->request->getPost('endtext_' . $langname);
                 $short_title = fixCKeditorText($short_title);
                 $description = fixCKeditorText($description);
                 $welcome = fixCKeditorText($welcome);
                 $endtext = fixCKeditorText($endtext);
                 $data = array('surveyls_title' => $short_title, 'surveyls_description' => $description, 'surveyls_welcometext' => $welcome, 'surveyls_endtext' => $endtext, 'surveyls_url' => $sURL, 'surveyls_urldescription' => $sURLDescription, 'surveyls_dateformat' => Yii::app()->request->getPost('dateformat_' . $langname), 'surveyls_numberformat' => Yii::app()->request->getPost('numberformat_' . $langname));
                 $Surveys_languagesettings = Surveys_languagesettings::model()->findByPk(array('surveyls_survey_id' => $postsid, 'surveyls_language' => $langname));
                 $Surveys_languagesettings->attributes = $data;
                 $Surveys_languagesettings->save();
                 // save the change to database
             }
         }
         Yii::app()->session['flashmessage'] = $clang->gT("Survey text elements successfully saved.");
         if ($databaseoutput != '') {
             echo $databaseoutput;
         } else {
             $this->getController()->redirect($this->getController()->createUrl('admin/survey/sa/view/surveyid/' . $surveyid));
         }
     }
     if (($action == "updatesurveysettingsandeditlocalesettings" || $action == "updatesurveysettings") && hasSurveyPermission($surveyid, 'surveysettings', 'update')) {
         Yii::app()->loadHelper('surveytranslator');
         Yii::app()->loadHelper('database');
         $formatdata = getDateFormatData(Yii::app()->session['dateformat']);
         $expires = $_POST['expires'];
         if (trim($expires) == "") {
             $expires = null;
         } else {
             Yii::app()->loadLibrary('Date_Time_Converter');
             $datetimeobj = new date_time_converter($expires, $formatdata['phpdate'] . ' H:i');
             //new Date_Time_Converter($expires, $formatdata['phpdate'].' H:i');
             $expires = $datetimeobj->convert("Y-m-d H:i:s");
         }
         $startdate = $_POST['startdate'];
         if (trim($startdate) == "") {
             $startdate = null;
         } else {
             Yii::app()->loadLibrary('Date_Time_Converter');
             $datetimeobj = new date_time_converter($startdate, $formatdata['phpdate'] . ' H:i');
             //new Date_Time_Converter($startdate,$formatdata['phpdate'].' H:i');
             $startdate = $datetimeobj->convert("Y-m-d H:i:s");
         }
         //make sure only numbers are passed within the $_POST variable
         $tokenlength = (int) $_POST['tokenlength'];
         //token length has to be at least 5, otherwise set it to default (15)
         if ($tokenlength < 5) {
             $tokenlength = 15;
         }
         cleanLanguagesFromSurvey($surveyid, Yii::app()->request->getPost('languageids'));
         fixLanguageConsistency($surveyid, Yii::app()->request->getPost('languageids'));
         $template = Yii::app()->request->getPost('template');
         if (Yii::app()->session['USER_RIGHT_SUPERADMIN'] != 1 && Yii::app()->session['USER_RIGHT_MANAGE_TEMPLATE'] != 1 && !hasTemplateManageRights(Yii::app()->session['loginID'], $template)) {
             $template = "default";
         }
         $aURLParams = json_decode(Yii::app()->request->getPost('allurlparams'), true);
         Survey_url_parameters::model()->deleteAllByAttributes(array('sid' => $surveyid));
         foreach ($aURLParams as $aURLParam) {
             $aURLParam['parameter'] = trim($aURLParam['parameter']);
             if ($aURLParam['parameter'] == '' || !preg_match('/^[a-zA-Z_][a-zA-Z0-9_]*$/', $aURLParam['parameter']) || $aURLParam['parameter'] == 'sid' || $aURLParam['parameter'] == 'newtest' || $aURLParam['parameter'] == 'token' || $aURLParam['parameter'] == 'lang') {
                 continue;
                 // this parameter name seems to be invalid - just ignore it
             }
             unset($aURLParam['act']);
             unset($aURLParam['title']);
             unset($aURLParam['id']);
             if ($aURLParam['targetqid'] == '') {
                 $aURLParam['targetqid'] = NULL;
             }
             if ($aURLParam['targetsqid'] == '') {
                 $aURLParam['targetsqid'] = NULL;
             }
             $aURLParam['sid'] = $surveyid;
             $param = new Survey_url_parameters();
             foreach ($aURLParam as $k => $v) {
                 $param->{$k} = $v;
             }
             $param->save();
         }
         $updatearray = array('admin' => Yii::app()->request->getPost('admin'), 'expires' => $expires, 'adminemail' => Yii::app()->request->getPost('adminemail'), 'startdate' => $startdate, 'bounce_email' => Yii::app()->request->getPost('bounce_email'), 'anonymized' => Yii::app()->request->getPost('anonymized'), 'faxto' => Yii::app()->request->getPost('faxto'), 'format' => Yii::app()->request->getPost('format'), 'savetimings' => Yii::app()->request->getPost('savetimings'), 'template' => $template, 'assessments' => Yii::app()->request->getPost('assessments'), 'language' => Yii::app()->request->getPost('language'), 'additional_languages' => Yii::app()->request->getPost('languageids'), 'datestamp' => Yii::app()->request->getPost('datestamp'), 'ipaddr' => Yii::app()->request->getPost('ipaddr'), 'refurl' => Yii::app()->request->getPost('refurl'), 'publicgraphs' => Yii::app()->request->getPost('publicgraphs'), 'usecookie' => Yii::app()->request->getPost('usecookie'), 'allowregister' => Yii::app()->request->getPost('allowregister'), 'allowsave' => Yii::app()->request->getPost('allowsave'), 'navigationdelay' => Yii::app()->request->getPost('navigationdelay'), 'printanswers' => Yii::app()->request->getPost('printanswers'), 'publicstatistics' => Yii::app()->request->getPost('publicstatistics'), 'autoredirect' => Yii::app()->request->getPost('autoredirect'), 'showxquestions' => Yii::app()->request->getPost('showxquestions'), 'showgroupinfo' => Yii::app()->request->getPost('showgroupinfo'), 'showqnumcode' => Yii::app()->request->getPost('showqnumcode'), 'shownoanswer' => Yii::app()->request->getPost('shownoanswer'), 'showwelcome' => Yii::app()->request->getPost('showwelcome'), 'allowprev' => Yii::app()->request->getPost('allowprev'), 'allowjumps' => Yii::app()->request->getPost('allowjumps'), 'nokeyboard' => Yii::app()->request->getPost('nokeyboard'), 'showprogress' => Yii::app()->request->getPost('showprogress'), 'listpublic' => Yii::app()->request->getPost('public'), 'htmlemail' => Yii::app()->request->getPost('htmlemail'), 'sendconfirmation' => Yii::app()->request->getPost('sendconfirmation'), 'tokenanswerspersistence' => Yii::app()->request->getPost('tokenanswerspersistence'), 'alloweditaftercompletion' => Yii::app()->request->getPost('alloweditaftercompletion'), 'usecaptcha' => Yii::app()->request->getPost('usecaptcha'), 'emailresponseto' => trim(Yii::app()->request->getPost('emailresponseto')), 'emailnotificationto' => trim(Yii::app()->request->getPost('emailnotificationto')), 'googleanalyticsapikey' => trim(Yii::app()->request->getPost('googleanalyticsapikey')), 'googleanalyticsstyle' => trim(Yii::app()->request->getPost('googleanalyticsstyle')), 'tokenlength' => $tokenlength);
         // use model
         $Survey = Survey::model()->findByPk($surveyid);
         foreach ($updatearray as $k => $v) {
             $Survey->{$k} = $v;
         }
         $Survey->save();
         #            Survey::model()->updateByPk($surveyid, $updatearray);
         $sqlstring = "surveyls_survey_id=:sid AND surveyls_language <> :base ";
         $params = array(':sid' => $surveyid, ':base' => Survey::model()->findByPk($surveyid)->language);
         $i = 100000;
         foreach (Survey::model()->findByPk($surveyid)->additionalLanguages as $langname) {
             if ($langname) {
                 $sqlstring .= "AND surveyls_language <> :{$i} ";
                 $params[':' . $i] = $langname;
             }
             $i++;
         }
         Surveys_languagesettings::model()->deleteAll($sqlstring, $params);
         $usresult = true;
         foreach (Survey::model()->findByPk($surveyid)->additionalLanguages as $langname) {
             if ($langname) {
                 $oLanguageSettings = Surveys_languagesettings::model()->find('surveyls_survey_id=:surveyid AND surveyls_language=:langname', array(':surveyid' => $surveyid, ':langname' => $langname));
                 if (!$oLanguageSettings) {
                     $oLanguageSettings = new Surveys_languagesettings();
                     $languagedetails = getLanguageDetails($langname);
                     $insertdata = array('surveyls_survey_id' => $surveyid, 'surveyls_language' => $langname, 'surveyls_title' => '', 'surveyls_dateformat' => $languagedetails['dateformat']);
                     foreach ($insertdata as $k => $v) {
                         $oLanguageSettings->{$k} = $v;
                     }
                     $usresult = $oLanguageSettings->save();
                 }
             }
         }
         if ($usresult) {
             Yii::app()->session['flashmessage'] = $clang->gT("Survey settings were successfully saved.");
         } else {
             Yii::app()->session['flashmessage'] = $clang->gT("Error:") . '<br>' . $clang->gT("Survey could not be updated.");
         }
         if (Yii::app()->request->getPost('action') == "updatesurveysettingsandeditlocalesettings") {
             $this->getController()->redirect($this->getController()->createUrl('admin/survey/sa/editlocalsettings/surveyid/' . $surveyid));
         } else {
             $this->getController()->redirect($this->getController()->createUrl('admin/survey/sa/view/surveyid/' . $surveyid));
         }
     }
     if (!$action) {
         $this->getController()->redirect("/admin", "refresh");
     }
 }
 /**
  * Create HTML view of the survey, showing everything that uses EM
  * @param <type> $sid
  * @param <type> $gid
  * @param <type> $qid
  */
 public static function ShowSurveyLogicFile($sid, $gid = NULL, $qid = NULL, $LEMdebugLevel = 0, $assessments = false)
 {
     // Title
     // Welcome
     // G1, name, relevance, text
     // *Q1, name [type], relevance [validation], text, help, default, help_msg
     // SQ1, name [scale], relevance [validation], text
     // A1, code, assessment_value, text
     // End Message
     $LEM =& LimeExpressionManager::singleton();
     $LEM->sPreviewMode = 'logic';
     $aSurveyInfo = getSurveyInfo($sid, $_SESSION['LEMlang']);
     $allErrors = array();
     $warnings = 0;
     $surveyOptions = array('assessments' => $aSurveyInfo['assessments'] == 'Y', 'hyperlinkSyntaxHighlighting' => true);
     $varNamesUsed = array();
     // keeps track of whether variables have been declared
     if (!is_null($qid)) {
         $surveyMode = 'question';
         LimeExpressionManager::StartSurvey($sid, 'question', $surveyOptions, false, $LEMdebugLevel);
         $qseq = LimeExpressionManager::GetQuestionSeq($qid);
         $moveResult = LimeExpressionManager::JumpTo($qseq + 1, true, false, true);
     } else {
         if (!is_null($gid)) {
             $surveyMode = 'group';
             LimeExpressionManager::StartSurvey($sid, 'group', $surveyOptions, false, $LEMdebugLevel);
             $gseq = LimeExpressionManager::GetGroupSeq($gid);
             $moveResult = LimeExpressionManager::JumpTo($gseq + 1, true, false, true);
         } else {
             $surveyMode = 'survey';
             LimeExpressionManager::StartSurvey($sid, 'survey', $surveyOptions, false, $LEMdebugLevel);
             $moveResult = LimeExpressionManager::NavigateForwards();
         }
     }
     $qtypes = getQuestionTypeList('', 'array');
     if (is_null($moveResult) || is_null($LEM->currentQset) || count($LEM->currentQset) == 0) {
         return array('errors' => 1, 'html' => sprintf($LEM->gT('Invalid question - probably missing sub-questions or language-specific settings for language %s'), $_SESSION['LEMlang']));
     }
     $surveyname = templatereplace('{SURVEYNAME}', array('SURVEYNAME' => $aSurveyInfo['surveyls_title']));
     $out = '<div id="showlogicfilediv" ><H3>' . $LEM->gT('Logic File for Survey # ') . '[' . $LEM->sid . "]: {$surveyname}</H3>\n";
     $out .= "<table class='table' id='logicfiletable'>";
     if (is_null($gid) && is_null($qid)) {
         if ($aSurveyInfo['surveyls_description'] != '') {
             $LEM->ProcessString($aSurveyInfo['surveyls_description'], 0);
             $sPrint = $LEM->GetLastPrettyPrintExpression();
             $errClass = $LEM->em->HasErrors() ? 'LEMerror' : '';
             $out .= "<tr class='LEMgroup {$errClass}'><td colspan=2>" . $LEM->gT("Description:") . "</td><td colspan=2>" . $sPrint . "</td></tr>";
         }
         if ($aSurveyInfo['surveyls_welcometext'] != '') {
             $LEM->ProcessString($aSurveyInfo['surveyls_welcometext'], 0);
             $sPrint = $LEM->GetLastPrettyPrintExpression();
             $errClass = $LEM->em->HasErrors() ? 'LEMerror' : '';
             $out .= "<tr class='LEMgroup {$errClass}'><td colspan=2>" . $LEM->gT("Welcome:") . "</td><td colspan=2>" . $sPrint . "</td></tr>";
         }
         if ($aSurveyInfo['surveyls_endtext'] != '') {
             $LEM->ProcessString($aSurveyInfo['surveyls_endtext']);
             $sPrint = $LEM->GetLastPrettyPrintExpression();
             $errClass = $LEM->em->HasErrors() ? 'LEMerror' : '';
             $out .= "<tr class='LEMgroup {$errClass}'><td colspan=2>" . $LEM->gT("End message:") . "</td><td colspan=2>" . $sPrint . "</td></tr>";
         }
         if ($aSurveyInfo['surveyls_url'] != '') {
             $LEM->ProcessString($aSurveyInfo['surveyls_urldescription'] . " - " . $aSurveyInfo['surveyls_url']);
             $sPrint = $LEM->GetLastPrettyPrintExpression();
             $errClass = $LEM->em->HasErrors() ? 'LEMerror' : '';
             $out .= "<tr class='LEMgroup {$errClass}'><td colspan=2>" . $LEM->gT("End URL:") . "</td><td colspan=2>" . $sPrint . "</td></tr>";
         }
     }
     $out .= "<tr><th>#</th><th>" . $LEM->gT('Name [ID]') . "</th><th>" . $LEM->gT('Relevance [Validation] (Default value)') . "</th><th>" . $LEM->gT('Text [Help] (Tip)') . "</th></tr>\n";
     $_gseq = -1;
     foreach ($LEM->currentQset as $q) {
         $gseq = $q['info']['gseq'];
         $gid = $q['info']['gid'];
         $qid = $q['info']['qid'];
         $qseq = $q['info']['qseq'];
         $errorCount = 0;
         //////
         // SHOW GROUP-LEVEL INFO
         //////
         if ($gseq != $_gseq) {
             $LEM->ParseResultCache = array();
             // reset for each group so get proper color coding?
             $_gseq = $gseq;
             $ginfo = $LEM->gseq2info[$gseq];
             $grelevance = '{' . ($ginfo['grelevance'] == '' ? 1 : $ginfo['grelevance']) . '}';
             $gtext = trim($ginfo['description']) == '' ? '&nbsp;' : $ginfo['description'];
             $editlink = Yii::app()->getController()->createUrl('admin/questiongroups/sa/view/surveyid/' . $LEM->sid . '/gid/' . $gid);
             $groupRow = "<tr class='LEMgroup'>" . "<td>G-{$gseq}</td>" . "<td><b>" . $ginfo['group_name'] . "</b><br />[<a target='_blank' href='{$editlink}'>GID " . $gid . "</a>]</td>" . "<td>" . $grelevance . "</td>" . "<td>" . $gtext . "</td>" . "</tr>\n";
             $LEM->ProcessString($groupRow, $qid, NULL, false, 1, 1, false, false);
             $out .= $LEM->GetLastPrettyPrintExpression();
             if ($LEM->em->HasErrors()) {
                 ++$errorCount;
             }
         }
         //////
         // SHOW QUESTION-LEVEL INFO
         //////
         $mandatory = $q['info']['mandatory'] == 'Y' ? "<span class='mandatory'>*</span>" : '';
         $type = $q['info']['type'];
         $typedesc = $qtypes[$type]['description'];
         $sgqas = explode('|', $q['sgqa']);
         if (count($sgqas) == 1 && !is_null($q['info']['default'])) {
             $LEM->ProcessString($q['info']['default'], $qid, NULL, false, 1, 1, false, false);
             // Default value is Y or answer code or go to input/textarea, then we can filter it
             $_default = $LEM->GetLastPrettyPrintExpression();
             if ($LEM->em->HasErrors()) {
                 ++$errorCount;
             }
             $default = '<br />(' . $LEM->gT('Default:') . '  ' . viewHelper::filterScript($_default) . ')';
         } else {
             $default = '';
         }
         $qtext = $q['info']['qtext'] != '' ? $q['info']['qtext'] : '&nbsp';
         $help = $q['info']['help'] != '' ? '<hr/>[' . $LEM->gT("Help:") . ' ' . $q['info']['help'] . ']' : '';
         $prettyValidTip = $q['prettyValidTip'] == '' ? '' : '<hr/>(' . $LEM->gT("Tip:") . ' ' . $q['prettyValidTip'] . ')';
         //////
         // SHOW QUESTION ATTRIBUTES THAT ARE PROCESSED BY EM
         //////
         $attrTable = '';
         $attrs = isset($LEM->qattr[$qid]) ? $LEM->qattr[$qid] : array();
         if (isset($LEM->q2subqInfo[$qid]['preg'])) {
             $attrs['regex_validation'] = $LEM->q2subqInfo[$qid]['preg'];
         }
         if (isset($LEM->questionSeq2relevance[$qseq]['other'])) {
             $attrs['other'] = $LEM->questionSeq2relevance[$qseq]['other'];
         }
         if (count($attrs) > 0) {
             $attrTable = "<table class='table' id='logicfileattributetable'><tr><th>" . $LEM->gT("Question attribute") . "</th><th>" . $LEM->gT("Value") . "</th></tr>\n";
             $count = 0;
             foreach ($attrs as $key => $value) {
                 if (is_null($value) || trim($value) == '') {
                     continue;
                 }
                 switch ($key) {
                     // @todo: Rather compares the current attribute value to the defaults in the question attributes array to decide which ones should show (only the ones that are non-standard)
                     default:
                     case 'exclude_all_others':
                     case 'exclude_all_others_auto':
                     case 'hidden':
                         if ($value == false || $value == '0') {
                             $value = NULL;
                             // so can skip this one - just using continue here doesn't work.
                         }
                         break;
                     case 'time_limit_action':
                         if ($value == '1') {
                             $value = NULL;
                             // so can skip this one - just using continue here doesn't work.
                         }
                     case 'relevance':
                         $value = NULL;
                         // means an outdate database structure
                         break;
                     case 'array_filter':
                     case 'array_filter_exclude':
                     case 'code_filter':
                     case 'date_max':
                     case 'date_min':
                     case 'em_validation_q_tip':
                     case 'em_validation_sq_tip':
                         break;
                     case 'equals_num_value':
                     case 'em_validation_q':
                     case 'em_validation_sq':
                     case 'max_answers':
                     case 'max_num_value':
                     case 'max_num_value_n':
                     case 'min_answers':
                     case 'min_num_value':
                     case 'min_num_value_n':
                     case 'min_num_of_files':
                     case 'max_num_of_files':
                     case 'multiflexible_max':
                     case 'multiflexible_min':
                     case 'slider_accuracy':
                     case 'slider_min':
                     case 'slider_max':
                     case 'slider_default':
                         $value = '{' . $value . '}';
                         break;
                     case 'other_replace_text':
                     case 'show_totals':
                     case 'regex_validation':
                         break;
                     case 'other':
                         if ($value == 'N') {
                             $value = NULL;
                             // so can skip this one
                         }
                         break;
                 }
                 if (is_null($value)) {
                     continue;
                     // since continuing from within a switch statement doesn't work
                 }
                 ++$count;
                 $attrTable .= "<tr><td>{$key}</td><td>{$value}</td></tr>\n";
             }
             $attrTable .= "</table>\n";
             if ($count == 0) {
                 $attrTable = '';
             }
         }
         $LEM->ProcessString($qtext . $help . $prettyValidTip . $attrTable, $qid, NULL, false, 1, 1, false, false);
         $qdetails = viewHelper::filterScript($LEM->GetLastPrettyPrintExpression());
         if ($LEM->em->HasErrors()) {
             ++$errorCount;
         }
         //////
         // SHOW RELEVANCE
         //////
         // Must parse Relevance this way, otherwise if try to first split expressions, regex equations won't work
         $relevanceEqn = $q['info']['relevance'] == '' ? 1 : $q['info']['relevance'];
         if (!isset($LEM->ParseResultCache[$relevanceEqn])) {
             $result = $LEM->em->ProcessBooleanExpression($relevanceEqn, $gseq, $qseq);
             $prettyPrint = $LEM->em->GetPrettyPrintString();
             $hasErrors = $LEM->em->HasErrors();
             $LEM->ParseResultCache[$relevanceEqn] = array('result' => $result, 'prettyprint' => $prettyPrint, 'hasErrors' => $hasErrors);
         }
         $relevance = $LEM->ParseResultCache[$relevanceEqn]['prettyprint'];
         if ($LEM->ParseResultCache[$relevanceEqn]['hasErrors']) {
             ++$errorCount;
         }
         //////
         // SHOW VALIDATION EQUATION
         //////
         // Must parse Validation this way so that regex (preg) works
         $prettyValidEqn = '';
         if ($q['prettyValidEqn'] != '') {
             $validationEqn = $q['validEqn'];
             if (!isset($LEM->ParseResultCache[$validationEqn])) {
                 $result = $LEM->em->ProcessBooleanExpression($validationEqn, $gseq, $qseq);
                 $prettyPrint = $LEM->em->GetPrettyPrintString();
                 $hasErrors = $LEM->em->HasErrors();
                 $LEM->ParseResultCache[$validationEqn] = array('result' => $result, 'prettyprint' => $prettyPrint, 'hasErrors' => $hasErrors);
             }
             $prettyValidEqn = '<hr/>(VALIDATION: ' . $LEM->ParseResultCache[$validationEqn]['prettyprint'] . ')';
             if ($LEM->ParseResultCache[$validationEqn]['hasErrors']) {
                 ++$errorCount;
             }
         }
         //////
         // TEST VALIDITY OF ROOT VARIABLE NAME AND WHETHER HAS BEEN USED
         //////
         $rootVarName = $q['info']['rootVarName'];
         $varNameErrorMsg = '';
         $varNameError = NULL;
         if (isset($varNamesUsed[$rootVarName])) {
             $varNameErrorMsg .= $LEM->gT('This variable name has already been used.');
         } else {
             $varNamesUsed[$rootVarName] = array('gseq' => $gseq, 'qid' => $qid);
         }
         if (!preg_match('/^[a-zA-Z][0-9a-zA-Z]*$/', $rootVarName)) {
             $varNameErrorMsg .= $LEM->gT('Starting in 2.05, variable names should only contain letters and numbers; and may not start with a number. This variable name is deprecated.');
         }
         if ($varNameErrorMsg != '') {
             $varNameError = array('message' => $varNameErrorMsg, 'gseq' => $varNamesUsed[$rootVarName]['gseq'], 'qid' => $varNamesUsed[$rootVarName]['qid'], 'gid' => $gid);
             if (!$LEM->sgqaNaming) {
                 ++$errorCount;
             } else {
                 ++$warnings;
             }
         }
         //////
         // SHOW ALL SUB-QUESTIONS
         //////
         $sqRows = '';
         $i = 0;
         $sawThis = array();
         // array of rowdivids already seen so only show them once
         foreach ($sgqas as $sgqa) {
             if ($LEM->knownVars[$sgqa]['qcode'] == $rootVarName) {
                 continue;
                 // so don't show the main question as a sub-question too
             }
             $rowdivid = $sgqa;
             $varName = $LEM->knownVars[$sgqa]['qcode'];
             switch ($q['info']['type']) {
                 case '1':
                     if (preg_match('/#1$/', $sgqa)) {
                         $rowdivid = NULL;
                         // so that doesn't show same message for second scale
                     } else {
                         $rowdivid = substr($sgqa, 0, -2);
                         // strip suffix
                         $varName = substr($LEM->knownVars[$sgqa]['qcode'], 0, -2);
                     }
                     break;
                 case 'P':
                     if (preg_match('/comment$/', $sgqa)) {
                         $rowdivid = NULL;
                     }
                     break;
                 case ':':
                 case ';':
                     $_rowdivid = $LEM->knownVars[$sgqa]['rowdivid'];
                     if (isset($sawThis[$qid . '~' . $_rowdivid])) {
                         $rowdivid = NULL;
                         // so don't show again
                     } else {
                         $sawThis[$qid . '~' . $_rowdivid] = true;
                         $rowdivid = $_rowdivid;
                         $sgqa_len = strlen($sid . 'X' . $gid . 'X' . $qid);
                         $varName = $rootVarName . '_' . substr($_rowdivid, $sgqa_len);
                     }
             }
             if (is_null($rowdivid)) {
                 continue;
             }
             ++$i;
             $subQeqn = '&nbsp;';
             if (isset($LEM->subQrelInfo[$qid][$rowdivid])) {
                 $sq = $LEM->subQrelInfo[$qid][$rowdivid];
                 $subQeqn = $sq['prettyPrintEqn'];
                 // {' . $sq['eqn'] . '}';  // $sq['prettyPrintEqn'];
                 if ($sq['hasErrors']) {
                     ++$errorCount;
                 }
             }
             $sgqaInfo = $LEM->knownVars[$sgqa];
             $subqText = $sgqaInfo['subqtext'];
             if (isset($sgqaInfo['default']) && $sgqaInfo['default'] !== '') {
                 $LEM->ProcessString(htmlspecialchars($sgqaInfo['default']), $qid, NULL, false, 1, 1, false, false);
                 $_default = viewHelper::filterScript($LEM->GetLastPrettyPrintExpression());
                 if ($LEM->em->HasErrors()) {
                     ++$errorCount;
                 }
                 $subQeqn .= '<br />(' . $LEM->gT('Default:') . '  ' . $_default . ')';
             }
             $sqRows .= "<tr class='LEMsubq'>" . "<td>SQ-{$i}</td>" . "<td><b>" . $varName . "</b></td>" . "<td>{$subQeqn}</td>" . "<td>" . $subqText . "</td>" . "</tr>";
         }
         $LEM->ProcessString($sqRows, $qid, NULL, false, 1, 1, false, false);
         $sqRows = viewHelper::filterScript($LEM->GetLastPrettyPrintExpression());
         if ($LEM->em->HasErrors()) {
             ++$errorCount;
         }
         //////
         // SHOW ANSWER OPTIONS FOR ENUMERATED LISTS, AND FOR MULTIFLEXI
         //////
         $answerRows = '';
         if (isset($LEM->qans[$qid]) || isset($LEM->multiflexiAnswers[$qid])) {
             $_scale = -1;
             if (isset($LEM->multiflexiAnswers[$qid])) {
                 $ansList = $LEM->multiflexiAnswers[$qid];
             } else {
                 $ansList = $LEM->qans[$qid];
             }
             foreach ($ansList as $ans => $value) {
                 $ansInfo = explode('~', $ans);
                 $valParts = explode('|', $value);
                 $valInfo[0] = array_shift($valParts);
                 $valInfo[1] = implode('|', $valParts);
                 if ($_scale != $ansInfo[0]) {
                     $i = 1;
                     $_scale = $ansInfo[0];
                 }
                 $subQeqn = '';
                 $rowdivid = $sgqas[0] . $ansInfo[1];
                 if ($q['info']['type'] == 'R') {
                     $rowdivid = $LEM->sid . 'X' . $gid . 'X' . $qid . $ansInfo[1];
                 }
                 if (isset($LEM->subQrelInfo[$qid][$rowdivid])) {
                     $sq = $LEM->subQrelInfo[$qid][$rowdivid];
                     $subQeqn = ' ' . $sq['prettyPrintEqn'];
                     if ($sq['hasErrors']) {
                         ++$errorCount;
                     }
                 }
                 $answerRows .= "<tr class='LEManswer'>" . "<td>A[" . $ansInfo[0] . "]-" . $i++ . "</td>" . "<td><b>" . $ansInfo[1] . "</b></td>" . "<td>[VALUE: " . $valInfo[0] . "]" . $subQeqn . "</td>" . "<td>" . $valInfo[1] . "</td>" . "</tr>\n";
             }
             $LEM->ProcessString($answerRows, $qid, NULL, false, 1, 1, false, false);
             $answerRows = viewHelper::filterScript($LEM->GetLastPrettyPrintExpression());
             if ($LEM->em->HasErrors()) {
                 ++$errorCount;
             }
         }
         //////
         // FINALLY, SHOW THE QUESTION ROW(S), COLOR-CODING QUESTIONS THAT CONTAIN ERRORS
         //////
         $errclass = $errorCount > 0 ? "class='LEMerror' title='" . $LEM->ngT("This question has at least {n} error.|This question has at least {n} errors.", $errorCount) . "'" : '';
         $questionRow = "<tr class='LEMquestion'>" . "<td {$errclass}>Q-" . $q['info']['qseq'] . "</td>" . "<td><b>" . $mandatory;
         if ($varNameErrorMsg == '') {
             $questionRow .= $rootVarName;
         } else {
             $editlink = Yii::app()->getController()->createUrl('admin/questions/sa/view/surveyid/' . $LEM->sid . '/gid/' . $varNameError['gid'] . '/qid/' . $varNameError['qid']);
             $questionRow .= "<span class='highlighterror' title='" . $varNameError['message'] . "' " . "onclick='window.open(\"{$editlink}\",\"_blank\")'>" . $rootVarName . "</span>";
         }
         $editlink = Yii::app()->getController()->createUrl('admin/questions/sa/view/surveyid/' . $sid . '/gid/' . $gid . '/qid/' . $qid);
         $questionRow .= "</b><br />[<a target='_blank' href='{$editlink}'>QID {$qid}</a>]<br/>{$typedesc} [{$type}]</td>" . "<td>" . $relevance . $prettyValidEqn . $default . "</td>" . "<td>" . $qdetails . "</td>" . "</tr>\n";
         $out .= $questionRow;
         $out .= $sqRows;
         $out .= $answerRows;
         if ($errorCount > 0) {
             $allErrors[$gid . '~' . $qid] = $errorCount;
         }
     }
     $out .= "</table>";
     LimeExpressionManager::FinishProcessingPage();
     if (($LEMdebugLevel & LEM_DEBUG_TIMING) == LEM_DEBUG_TIMING) {
         $out .= LimeExpressionManager::GetDebugTimingMessage();
     }
     if (count($allErrors) > 0) {
         $out = "<p class='LEMerror'>" . $LEM->ngT("{n} question contains errors that need to be corrected.|{n} questions contain errors that need to be corrected.", count($allErrors)) . "</p>\n" . $out;
     } else {
         switch ($surveyMode) {
             case 'survey':
                 $message = $LEM->gT('No syntax errors detected in this survey.');
                 break;
             case 'group':
                 $message = $LEM->gT('This group, by itself, does not contain any syntax errors.');
                 break;
             case 'question':
                 $message = $LEM->gT('This question, by itself, does not contain any syntax errors.');
                 break;
         }
         $out = "<p class='LEMheading'>{$message}</p>\n" . $out . "</div>";
     }
     return array('errors' => $allErrors, 'html' => $out);
 }
Exemple #11
0
 /**
  * Database::index()
  *
  * @param mixed $sa
  * @return
  */
 function index($sa = null)
 {
     $sAction = Yii::app()->request->getPost('action');
     $iSurveyID = returnGlobal('sid');
     $iQuestionGroupID = returnGlobal('gid');
     $iQuestionID = returnGlobal('qid');
     $sDBOutput = '';
     $oFixCKeditor = new LSYii_Validators();
     $oFixCKeditor->fixCKeditor = true;
     $oFixCKeditor->xssfilter = false;
     if ($sAction == "updatedefaultvalues" && Permission::model()->hasSurveyPermission($iSurveyID, 'surveycontent', 'update')) {
         $aSurveyLanguages = Survey::model()->findByPk($iSurveyID)->additionalLanguages;
         $sBaseLanguage = Survey::model()->findByPk($iSurveyID)->language;
         array_unshift($aSurveyLanguages, $sBaseLanguage);
         Question::model()->updateAll(array('same_default' => Yii::app()->request->getPost('samedefault') ? 1 : 0), 'sid=:sid ANd qid=:qid', array(':sid' => $iSurveyID, ':qid' => $iQuestionID));
         $arQuestion = Question::model()->findByAttributes(array('qid' => $iQuestionID));
         $sQuestionType = $arQuestion['type'];
         $aQuestionTypeList = getQuestionTypeList('', 'array');
         if ($aQuestionTypeList[$sQuestionType]['answerscales'] > 0 && $aQuestionTypeList[$sQuestionType]['subquestions'] == 0) {
             for ($iScaleID = 0; $iScaleID < $aQuestionTypeList[$sQuestionType]['answerscales']; $iScaleID++) {
                 foreach ($aSurveyLanguages as $sLanguage) {
                     if (!is_null(Yii::app()->request->getPost('defaultanswerscale_' . $iScaleID . '_' . $sLanguage))) {
                         $this->_updateDefaultValues($iQuestionID, 0, $iScaleID, '', $sLanguage, Yii::app()->request->getPost('defaultanswerscale_' . $iScaleID . '_' . $sLanguage), true);
                     }
                     if (!is_null(Yii::app()->request->getPost('other_' . $iScaleID . '_' . $sLanguage))) {
                         $this->_updateDefaultValues($iQuestionID, 0, $iScaleID, 'other', $sLanguage, Yii::app()->request->getPost('other_' . $iScaleID . '_' . $sLanguage), true);
                     }
                 }
             }
         }
         if ($aQuestionTypeList[$sQuestionType]['subquestions'] > 0) {
             foreach ($aSurveyLanguages as $sLanguage) {
                 $arQuestions = Question::model()->findAllByAttributes(array('sid' => $iSurveyID, 'gid' => $iQuestionGroupID, 'parent_qid' => $iQuestionID, 'language' => $sLanguage, 'scale_id' => 0));
                 for ($iScaleID = 0; $iScaleID < $aQuestionTypeList[$sQuestionType]['subquestions']; $iScaleID++) {
                     foreach ($arQuestions as $aSubquestionrow) {
                         if (!is_null(Yii::app()->request->getPost('defaultanswerscale_' . $iScaleID . '_' . $sLanguage . '_' . $aSubquestionrow['qid']))) {
                             $this->_updateDefaultValues($iQuestionID, $aSubquestionrow['qid'], $iScaleID, '', $sLanguage, Yii::app()->request->getPost('defaultanswerscale_' . $iScaleID . '_' . $sLanguage . '_' . $aSubquestionrow['qid']), true);
                         }
                     }
                 }
             }
         }
         if ($aQuestionTypeList[$sQuestionType]['answerscales'] == 0 && $aQuestionTypeList[$sQuestionType]['subquestions'] == 0) {
             foreach ($aSurveyLanguages as $sLanguage) {
                 // Qick and dirty insert for yes/no defaul value
                 // write the the selectbox option, or if "EM" is slected, this value to table
                 if ($sQuestionType == 'Y') {
                     /// value for all langs
                     if (Yii::app()->request->getPost('samedefault') == 1) {
                         $sLanguage = $aSurveyLanguages[0];
                         // turn
                     } else {
                         $sCurrentLang = $sLanguage;
                         // edit the next lines
                     }
                     if (Yii::app()->request->getPost('defaultanswerscale_0_' . $sLanguage) == 'EM') {
                         // Case EM, write expression to database
                         $this->_updateDefaultValues($iQuestionID, 0, 0, '', $sLanguage, Yii::app()->request->getPost('defaultanswerscale_0_' . $sLanguage . '_EM'), true);
                     } else {
                         // Case "other", write list value to database
                         $this->_updateDefaultValues($iQuestionID, 0, 0, '', $sLanguage, Yii::app()->request->getPost('defaultanswerscale_0_' . $sLanguage), true);
                     }
                     ///// end yes/no
                 } else {
                     if (!is_null(Yii::app()->request->getPost('defaultanswerscale_0_' . $sLanguage . '_0'))) {
                         $this->_updateDefaultValues($iQuestionID, 0, 0, '', $sLanguage, Yii::app()->request->getPost('defaultanswerscale_0_' . $sLanguage . '_0'), true);
                     }
                 }
             }
         }
         Yii::app()->session['flashmessage'] = gT("Default value settings were successfully saved.");
         LimeExpressionManager::SetDirtyFlag();
         if ($sDBOutput != '') {
             echo $sDBOutput;
         } else {
             $this->getController()->redirect(array('admin/survey/sa/view/surveyid/' . $iSurveyID . '/gid/' . $iQuestionGroupID . '/qid/' . $iQuestionID));
         }
     }
     if ($sAction == "updateansweroptions" && Permission::model()->hasSurveyPermission($iSurveyID, 'surveycontent', 'update')) {
         Yii::app()->loadHelper('database');
         $aSurveyLanguages = Survey::model()->findByPk($iSurveyID)->additionalLanguages;
         $sBaseLanguage = Survey::model()->findByPk($iSurveyID)->language;
         array_unshift($aSurveyLanguages, $sBaseLanguage);
         $arQuestion = Question::model()->findByAttributes(array('qid' => $iQuestionID));
         $sQuestionType = $arQuestion['type'];
         // Checked)
         $aQuestionTypeList = getQuestionTypeList('', 'array');
         $iScaleCount = $aQuestionTypeList[$sQuestionType]['answerscales'];
         //First delete all answers
         Answer::model()->deleteAllByAttributes(array('qid' => $iQuestionID));
         LimeExpressionManager::RevertUpgradeConditionsToRelevance($iSurveyID);
         for ($iScaleID = 0; $iScaleID < $iScaleCount; $iScaleID++) {
             $iMaxCount = (int) Yii::app()->request->getPost('answercount_' . $iScaleID);
             for ($iSortOrderID = 1; $iSortOrderID < $iMaxCount; $iSortOrderID++) {
                 $sCode = sanitize_paranoid_string(Yii::app()->request->getPost('code_' . $iSortOrderID . '_' . $iScaleID));
                 $iAssessmentValue = (int) Yii::app()->request->getPost('assessment_' . $iSortOrderID . '_' . $iScaleID);
                 foreach ($aSurveyLanguages as $sLanguage) {
                     $sAnswerText = Yii::app()->request->getPost('answer_' . $sLanguage . '_' . $iSortOrderID . '_' . $iScaleID);
                     // Fix bug with FCKEditor saving strange BR types
                     $sAnswerText = $oFixCKeditor->fixCKeditor($sAnswerText);
                     // Now we insert the answers
                     $iInsertCount = Answer::model()->insertRecords(array('code' => $sCode, 'answer' => $sAnswerText, 'qid' => $iQuestionID, 'sortorder' => $iSortOrderID, 'language' => $sLanguage, 'assessment_value' => $iAssessmentValue, 'scale_id' => $iScaleID));
                     if (!$iInsertCount) {
                         Yii::app()->setFlashMessage(gT("Failed to update answers"), 'error');
                     }
                 }
                 // Updating code (oldcode!==null) => update condition with the new code
                 $sOldCode = Yii::app()->request->getPost('oldcode_' . $iSortOrderID . '_' . $iScaleID);
                 if (isset($sOldCode) && $sCode !== $sOldCode) {
                     Condition::model()->updateAll(array('value' => $sCode), 'cqid=:cqid AND value=:value', array(':cqid' => $iQuestionID, ':value' => $sOldCode));
                 }
             }
             // for ($sortorderid=0;$sortorderid<$maxcount;$sortorderid++)
         }
         //  for ($scale_id=0;
         LimeExpressionManager::UpgradeConditionsToRelevance($iSurveyID);
         if (!Yii::app()->request->getPost('bFullPOST')) {
             Yii::app()->setFlashMessage(gT("Not all answer options were saved. This usually happens due to server limitations ( PHP setting max_input_vars) - please contact your system administrator."));
         } else {
             Yii::app()->session['flashmessage'] = gT("Answer options were successfully saved.");
         }
         LimeExpressionManager::SetDirtyFlag();
         if ($sDBOutput != '') {
             echo $sDBOutput;
         } else {
             $this->getController()->redirect(array('/admin/questions/sa/answeroptions/surveyid/' . $iSurveyID . '/gid/' . $iQuestionGroupID . '/qid/' . $iQuestionID));
         }
     }
     if ($sAction == "updatesubquestions" && Permission::model()->hasSurveyPermission($iSurveyID, 'surveycontent', 'update')) {
         Yii::app()->loadHelper('database');
         $aSurveyLanguages = Survey::model()->findByPk($iSurveyID)->additionalLanguages;
         $sBaseLanguage = Survey::model()->findByPk($iSurveyID)->language;
         array_unshift($aSurveyLanguages, $sBaseLanguage);
         $arQuestion = Question::model()->findByAttributes(array('qid' => $iQuestionID));
         $sQuestionType = $arQuestion['type'];
         // Checked
         $aQuestionTypeList = getQuestionTypeList('', 'array');
         $iScaleCount = $aQuestionTypeList[$sQuestionType]['subquestions'];
         // First delete any deleted ids
         $aDeletedQIDs = explode(' ', trim(Yii::app()->request->getPost('deletedqids')));
         LimeExpressionManager::RevertUpgradeConditionsToRelevance($iSurveyID);
         $aDeletedQIDs = array_unique($aDeletedQIDs, SORT_NUMERIC);
         foreach ($aDeletedQIDs as $iDeletedQID) {
             $iDeletedQID = (int) $iDeletedQID;
             if ($iDeletedQID > 0) {
                 // don't remove undefined
                 $iInsertCount = Question::model()->deleteAllByAttributes(array('qid' => $iDeletedQID));
                 if (!$iInsertCount) {
                     Yii::app()->setFlashMessage(gT("Failed to delete answer"), 'error');
                 }
             }
         }
         //Determine ids by evaluating the hidden field
         $aRows = array();
         $aCodes = array();
         $aOldCodes = array();
         $aRelevance = array();
         foreach ($_POST as $sPOSTKey => $sPOSTValue) {
             $sPOSTKey = explode('_', $sPOSTKey);
             if ($sPOSTKey[0] == 'answer') {
                 $aRows[$sPOSTKey[3]][$sPOSTKey[1]][$sPOSTKey[2]] = $sPOSTValue;
             }
             if ($sPOSTKey[0] == 'code') {
                 $aCodes[$sPOSTKey[2]][] = $sPOSTValue;
             }
             if ($sPOSTKey[0] == 'oldcode') {
                 $aOldCodes[$sPOSTKey[2]][] = $sPOSTValue;
             }
             if ($sPOSTKey[0] == 'relevance') {
                 $aRelevance[$sPOSTKey[2]][] = $sPOSTValue;
             }
         }
         $aInsertQID = array();
         for ($iScaleID = 0; $iScaleID < $iScaleCount; $iScaleID++) {
             foreach ($aSurveyLanguages as $sLanguage) {
                 $iPosition = 0;
                 foreach ($aRows[$iScaleID][$sLanguage] as $subquestionkey => $subquestionvalue) {
                     if (substr($subquestionkey, 0, 3) != 'new') {
                         $oSubQuestion = Question::model()->find("qid=:qid AND language=:language", array(":qid" => $subquestionkey, ':language' => $sLanguage));
                         $oSubQuestion->question_order = $iPosition + 1;
                         $oSubQuestion->title = $aCodes[$iScaleID][$iPosition];
                         $oSubQuestion->question = $subquestionvalue;
                         $oSubQuestion->scale_id = $iScaleID;
                         //dual matrix, text/number matrix: subQ relevance per line not per scale, so ScaleID is always 0
                         $oSubQuestion->relevance = $aRelevance[0][$iPosition];
                     } else {
                         if (!isset($aInsertQID[$iScaleID][$iPosition])) {
                             $oSubQuestion = new Question();
                             $oSubQuestion->sid = $iSurveyID;
                             $oSubQuestion->gid = $iQuestionGroupID;
                             $oSubQuestion->question_order = $iPosition + 1;
                             $oSubQuestion->title = $aCodes[$iScaleID][$iPosition];
                             $oSubQuestion->question = $subquestionvalue;
                             $oSubQuestion->parent_qid = $iQuestionID;
                             $oSubQuestion->language = $sLanguage;
                             $oSubQuestion->scale_id = $iScaleID;
                             $oSubQuestion->relevance = $aRelevance[0][$iPosition];
                         } else {
                             $oSubQuestion = Question::model()->find("qid=:qid AND language=:language", array(":qid" => $aInsertQID[$iScaleID][$iPosition], ':language' => $sLanguage));
                             if (!$oSubQuestion) {
                                 $oSubQuestion = new Question();
                             }
                             $oSubQuestion->sid = $iSurveyID;
                             $oSubQuestion->qid = $aInsertQID[$iScaleID][$iPosition];
                             $oSubQuestion->gid = $iQuestionGroupID;
                             $oSubQuestion->question_order = $iPosition + 1;
                             $oSubQuestion->title = $aCodes[$iScaleID][$iPosition];
                             $oSubQuestion->question = $subquestionvalue;
                             $oSubQuestion->parent_qid = $iQuestionID;
                             $oSubQuestion->language = $sLanguage;
                             $oSubQuestion->scale_id = $iScaleID;
                             $oSubQuestion->relevance = $aRelevance[$iScaleID][$iPosition];
                         }
                     }
                     if ($oSubQuestion->qid) {
                         switchMSSQLIdentityInsert('questions', true);
                         $bSubQuestionResult = $oSubQuestion->save();
                         switchMSSQLIdentityInsert('questions', false);
                     } else {
                         $bSubQuestionResult = $oSubQuestion->save();
                     }
                     if ($bSubQuestionResult) {
                         if (substr($subquestionkey, 0, 3) != 'new' && isset($aOldCodes[$iScaleID][$iPosition]) && $aCodes[$iScaleID][$iPosition] !== $aOldCodes[$iScaleID][$iPosition]) {
                             Condition::model()->updateAll(array('cfieldname' => '+' . $iSurveyID . 'X' . $iQuestionGroupID . 'X' . $iQuestionID . $aCodes[$iScaleID][$iPosition], 'value' => $aCodes[$iScaleID][$iPosition]), 'cqid=:cqid AND cfieldname=:cfieldname AND value=:value', array(':cqid' => $iQuestionID, ':cfieldname' => $iSurveyID . 'X' . $iQuestionGroupID . 'X' . $iQuestionID, ':value' => $aOldCodes[$iScaleID][$iPosition]));
                         }
                         if (!isset($aInsertQID[$iScaleID][$iPosition])) {
                             $aInsertQID[$iScaleID][$iPosition] = $oSubQuestion->qid;
                         }
                     } else {
                         $aErrors = $oSubQuestion->getErrors();
                         if (count($aErrors)) {
                             //$sErrorMessage=gT("Question could not be updated with this errors:");
                             foreach ($aErrors as $sAttribute => $aStringErrors) {
                                 foreach ($aStringErrors as $sStringErrors) {
                                     Yii::app()->setFlashMessage(sprintf(gT("Error on %s for subquestion %s: %s"), $sAttribute, $aCodes[$iScaleID][$iPosition], $sStringErrors), 'error');
                                 }
                             }
                         } else {
                             Yii::app()->setFlashMessage(sprintf(gT("Subquestions %s could not be updated."), $aCodes[$iScaleID][$iPosition]), 'error');
                         }
                     }
                     $iPosition++;
                 }
             }
         }
         LimeExpressionManager::UpgradeConditionsToRelevance($iSurveyID);
         // Do it only if there are no error ?
         if (!isset($aErrors) || !count($aErrors)) {
             if (!Yii::app()->request->getPost('bFullPOST')) {
                 Yii::app()->session['flashmessage'] = gT("Not all subquestions were saved. This usually happens due to server limitations ( PHP setting max_input_vars) - please contact your system administrator.");
             } else {
                 Yii::app()->session['flashmessage'] = gT("Subquestions were successfully saved.");
             }
         }
         //$action='editsubquestions';
         LimeExpressionManager::SetDirtyFlag();
         if ($sDBOutput != '') {
             echo $sDBOutput;
         } else {
             $this->getController()->redirect(array('/admin/questions/sa/subquestions/surveyid/' . $iSurveyID . '/gid/' . $iQuestionGroupID . '/qid/' . $iQuestionID));
         }
     }
     if (in_array($sAction, array('insertquestion', 'copyquestion')) && Permission::model()->hasSurveyPermission($iSurveyID, 'surveycontent', 'create')) {
         $sBaseLanguage = Survey::model()->findByPk($iSurveyID)->language;
         if (strlen(Yii::app()->request->getPost('title')) < 1) {
             Yii::app()->setFlashMessage(gT("The question could not be added. You must enter at least a question code."), 'error');
         } else {
             if (Yii::app()->request->getPost('questionposition', "") != "") {
                 $iQuestionOrder = intval(Yii::app()->request->getPost('questionposition'));
                 //Need to renumber all questions on or after this
                 $sQuery = "UPDATE {{questions}} SET question_order=question_order+1 WHERE gid=:gid AND question_order >= :order";
                 Yii::app()->db->createCommand($sQuery)->bindValues(array(':gid' => $iQuestionGroupID, ':order' => $iQuestionOrder))->query();
             } else {
                 $iQuestionOrder = getMaxQuestionOrder($iQuestionGroupID, $iSurveyID);
                 $iQuestionOrder++;
             }
             $sQuestionText = Yii::app()->request->getPost('question_' . $sBaseLanguage, '');
             $sQuestionHelp = Yii::app()->request->getPost('help_' . $sBaseLanguage, '');
             // Fix bug with FCKEditor saving strange BR types : in rules ?
             $sQuestionText = $oFixCKeditor->fixCKeditor($sQuestionText);
             $sQuestionHelp = $oFixCKeditor->fixCKeditor($sQuestionHelp);
             $iQuestionID = 0;
             $oQuestion = new Question();
             $oQuestion->sid = $iSurveyID;
             $oQuestion->gid = $iQuestionGroupID;
             $oQuestion->type = Yii::app()->request->getPost('type');
             $oQuestion->title = Yii::app()->request->getPost('title');
             $oQuestion->question = $sQuestionText;
             $oQuestion->preg = Yii::app()->request->getPost('preg');
             $oQuestion->help = $sQuestionHelp;
             $oQuestion->other = Yii::app()->request->getPost('other');
             $oQuestion->mandatory = Yii::app()->request->getPost('mandatory');
             $oQuestion->relevance = Yii::app()->request->getPost('relevance');
             $oQuestion->question_order = $iQuestionOrder;
             $oQuestion->language = $sBaseLanguage;
             $oQuestion->save();
             if ($oQuestion) {
                 $iQuestionID = $oQuestion->qid;
             }
             $aErrors = $oQuestion->getErrors();
             if (count($aErrors)) {
                 foreach ($aErrors as $sAttribute => $aStringErrors) {
                     foreach ($aStringErrors as $sStringErrors) {
                         Yii::app()->setFlashMessage(sprintf(gT("Question could not be created with error on %s: %s"), $sAttribute, $sStringErrors), 'error');
                     }
                 }
             }
             // Add other languages
             if ($iQuestionID) {
                 $addlangs = Survey::model()->findByPk($iSurveyID)->additionalLanguages;
                 foreach ($addlangs as $alang) {
                     if ($alang != "") {
                         $langqid = 0;
                         $oQuestion = new Question();
                         $oQuestion->qid = $iQuestionID;
                         $oQuestion->sid = $iSurveyID;
                         $oQuestion->gid = $iQuestionGroupID;
                         $oQuestion->type = Yii::app()->request->getPost('type');
                         $oQuestion->title = Yii::app()->request->getPost('title');
                         $oQuestion->question = Yii::app()->request->getPost('question_' . $alang);
                         $oQuestion->preg = Yii::app()->request->getPost('preg');
                         $oQuestion->help = Yii::app()->request->getPost('help_' . $alang);
                         $oQuestion->other = Yii::app()->request->getPost('other');
                         $oQuestion->mandatory = Yii::app()->request->getPost('mandatory');
                         $oQuestion->relevance = Yii::app()->request->getPost('relevance');
                         $oQuestion->question_order = $iQuestionOrder;
                         $oQuestion->language = $alang;
                         switchMSSQLIdentityInsert('questions', true);
                         // Not sure for this one ?
                         $oQuestion->save();
                         switchMSSQLIdentityInsert('questions', false);
                         if ($oQuestion) {
                             $langqid = $oQuestion->qid;
                         }
                         $aErrors = $oQuestion->getErrors();
                         if (count($aErrors)) {
                             foreach ($aErrors as $sAttribute => $aStringErrors) {
                                 foreach ($aStringErrors as $sStringErrors) {
                                     Yii::app()->setFlashMessage(sprintf(gT("Question in language %s could not be created with error on %s: %s"), $alang, $sAttribute, $sStringErrors), 'error');
                                 }
                             }
                         }
                         #                            if (!$langqid)
                         #                            {
                         #                                Yii::app()->setFlashMessage(gT("Question in language %s could not be created."),'error');
                         #                            }
                     }
                 }
             }
             if (!$iQuestionID) {
                 Yii::app()->setFlashMessage(gT("Question could not be created."), 'error');
             } else {
                 if ($sAction == 'copyquestion') {
                     if (returnGlobal('copysubquestions') == "Y") {
                         $aSQIDMappings = array();
                         $r1 = Question::model()->getSubQuestions(returnGlobal('oldqid'));
                         $aSubQuestions = $r1->readAll();
                         foreach ($aSubQuestions as $qr1) {
                             $qr1['parent_qid'] = $iQuestionID;
                             if (isset($aSQIDMappings[$qr1['qid']])) {
                                 $qr1['qid'] = $aSQIDMappings[$qr1['qid']];
                             } else {
                                 $oldqid = $qr1['qid'];
                                 unset($qr1['qid']);
                             }
                             $qr1['gid'] = $iQuestionGroupID;
                             $iInsertID = Question::model()->insertRecords($qr1);
                             if (!isset($qr1['qid'])) {
                                 $aSQIDMappings[$oldqid] = $iInsertID;
                             }
                         }
                     }
                     if (returnGlobal('copyanswers') == "Y") {
                         $r1 = Answer::model()->getAnswers(returnGlobal('oldqid'));
                         $aAnswerOptions = $r1->readAll();
                         foreach ($aAnswerOptions as $qr1) {
                             Answer::model()->insertRecords(array('qid' => $iQuestionID, 'code' => $qr1['code'], 'answer' => $qr1['answer'], 'assessment_value' => $qr1['assessment_value'], 'sortorder' => $qr1['sortorder'], 'language' => $qr1['language'], 'scale_id' => $qr1['scale_id']));
                         }
                     }
                     if (returnGlobal('copyattributes') == "Y") {
                         $oOldAttributes = QuestionAttribute::model()->findAll("qid=:qid", array("qid" => returnGlobal('oldqid')));
                         foreach ($oOldAttributes as $oOldAttribute) {
                             $attribute = new QuestionAttribute();
                             $attribute->qid = $iQuestionID;
                             $attribute->value = $oOldAttribute->value;
                             $attribute->attribute = $oOldAttribute->attribute;
                             $attribute->language = $oOldAttribute->language;
                             $attribute->save();
                         }
                     }
                 } else {
                     $qattributes = questionAttributes();
                     $validAttributes = $qattributes[Yii::app()->request->getPost('type')];
                     $aLanguages = array_merge(array(Survey::model()->findByPk($iSurveyID)->language), Survey::model()->findByPk($iSurveyID)->additionalLanguages);
                     foreach ($validAttributes as $validAttribute) {
                         if ($validAttribute['i18n']) {
                             foreach ($aLanguages as $sLanguage) {
                                 $value = Yii::app()->request->getPost($validAttribute['name'] . '_' . $sLanguage);
                                 $iInsertCount = QuestionAttribute::model()->findAllByAttributes(array('attribute' => $validAttribute['name'], 'qid' => $iQuestionID, 'language' => $sLanguage));
                                 if (count($iInsertCount) > 0) {
                                     if ($value != '') {
                                         QuestionAttribute::model()->updateAll(array('value' => $value), 'attribute=:attribute AND qid=:qid AND language=:language', array(':attribute' => $validAttribute['name'], ':qid' => $iQuestionID, ':language' => $sLanguage));
                                     } else {
                                         QuestionAttribute::model()->deleteAll('attribute=:attribute AND qid=:qid AND language=:language', array(':attribute' => $validAttribute['name'], ':qid' => $iQuestionID, ':language' => $sLanguage));
                                     }
                                 } elseif ($value != '') {
                                     $attribute = new QuestionAttribute();
                                     $attribute->qid = $iQuestionID;
                                     $attribute->value = $value;
                                     $attribute->attribute = $validAttribute['name'];
                                     $attribute->language = $sLanguage;
                                     $attribute->save();
                                 }
                             }
                         } else {
                             $value = Yii::app()->request->getPost($validAttribute['name']);
                             if ($validAttribute['name'] == 'multiflexible_step' && trim($value) != '') {
                                 $value = floatval($value);
                                 if ($value == 0) {
                                     $value = 1;
                                 }
                             }
                             $iInsertCount = QuestionAttribute::model()->findAllByAttributes(array('attribute' => $validAttribute['name'], 'qid' => $iQuestionID));
                             if (count($iInsertCount) > 0) {
                                 if ($value != $validAttribute['default'] && trim($value) != "") {
                                     QuestionAttribute::model()->updateAll(array('value' => $value), 'attribute=:attribute AND qid=:qid', array(':attribute' => $validAttribute['name'], ':qid' => $iQuestionID));
                                 } else {
                                     QuestionAttribute::model()->deleteAll('attribute=:attribute AND qid=:qid', array(':attribute' => $validAttribute['name'], ':qid' => $iQuestionID));
                                 }
                             } elseif ($value != $validAttribute['default'] && trim($value) != "") {
                                 $attribute = new QuestionAttribute();
                                 $attribute->qid = $iQuestionID;
                                 $attribute->value = $value;
                                 $attribute->attribute = $validAttribute['name'];
                                 $attribute->save();
                             }
                         }
                     }
                 }
                 Question::model()->updateQuestionOrder($iQuestionGroupID, $iSurveyID);
                 Yii::app()->session['flashmessage'] = gT("Question was successfully added.");
             }
         }
         LimeExpressionManager::SetDirtyFlag();
         // so refreshes syntax highlighting
         if ($sDBOutput != '') {
             echo $sDBOutput;
         } else {
             $this->getController()->redirect(array('admin/survey/sa/view/surveyid/' . $iSurveyID . '/gid/' . $iQuestionGroupID . '/qid/' . $iQuestionID));
         }
     }
     if ($sAction == "updatequestion" && Permission::model()->hasSurveyPermission($iSurveyID, 'surveycontent', 'update')) {
         LimeExpressionManager::RevertUpgradeConditionsToRelevance($iSurveyID);
         $cqr = Question::model()->findByAttributes(array('qid' => $iQuestionID));
         $oldtype = $cqr['type'];
         $oldgid = $cqr['gid'];
         // Remove invalid question attributes on saving
         $qattributes = questionAttributes();
         $criteria = new CDbCriteria();
         $criteria->compare('qid', $iQuestionID);
         if (isset($qattributes[Yii::app()->request->getPost('type')])) {
             $validAttributes = $qattributes[Yii::app()->request->getPost('type')];
             foreach ($validAttributes as $validAttribute) {
                 $criteria->compare('attribute', '<>' . $validAttribute['name']);
             }
         }
         QuestionAttribute::model()->deleteAll($criteria);
         $aLanguages = array_merge(array(Survey::model()->findByPk($iSurveyID)->language), Survey::model()->findByPk($iSurveyID)->additionalLanguages);
         //now save all valid attributes
         $validAttributes = $qattributes[Yii::app()->request->getPost('type')];
         foreach ($validAttributes as $validAttribute) {
             if ($validAttribute['i18n']) {
                 foreach ($aLanguages as $sLanguage) {
                     // TODO sanitise XSS
                     $value = Yii::app()->request->getPost($validAttribute['name'] . '_' . $sLanguage);
                     $iInsertCount = QuestionAttribute::model()->findAllByAttributes(array('attribute' => $validAttribute['name'], 'qid' => $iQuestionID, 'language' => $sLanguage));
                     if (count($iInsertCount) > 0) {
                         if ($value != '') {
                             QuestionAttribute::model()->updateAll(array('value' => $value), 'attribute=:attribute AND qid=:qid AND language=:language', array(':attribute' => $validAttribute['name'], ':qid' => $iQuestionID, ':language' => $sLanguage));
                         } else {
                             QuestionAttribute::model()->deleteAll('attribute=:attribute AND qid=:qid AND language=:language', array(':attribute' => $validAttribute['name'], ':qid' => $iQuestionID, ':language' => $sLanguage));
                         }
                     } elseif ($value != '') {
                         $attribute = new QuestionAttribute();
                         $attribute->qid = $iQuestionID;
                         $attribute->value = $value;
                         $attribute->attribute = $validAttribute['name'];
                         $attribute->language = $sLanguage;
                         $attribute->save();
                     }
                 }
             } else {
                 $value = Yii::app()->request->getPost($validAttribute['name']);
                 if ($validAttribute['name'] == 'multiflexible_step' && trim($value) != '') {
                     $value = floatval($value);
                     if ($value == 0) {
                         $value = 1;
                     }
                 }
                 $iInsertCount = QuestionAttribute::model()->findAllByAttributes(array('attribute' => $validAttribute['name'], 'qid' => $iQuestionID));
                 if (count($iInsertCount) > 0) {
                     if ($value != $validAttribute['default'] && trim($value) != "") {
                         QuestionAttribute::model()->updateAll(array('value' => $value), 'attribute=:attribute AND qid=:qid', array(':attribute' => $validAttribute['name'], ':qid' => $iQuestionID));
                     } else {
                         QuestionAttribute::model()->deleteAll('attribute=:attribute AND qid=:qid', array(':attribute' => $validAttribute['name'], ':qid' => $iQuestionID));
                     }
                 } elseif ($value != $validAttribute['default'] && trim($value) != "") {
                     $attribute = new QuestionAttribute();
                     $attribute->qid = $iQuestionID;
                     $attribute->value = $value;
                     $attribute->attribute = $validAttribute['name'];
                     $attribute->save();
                 }
             }
         }
         $aQuestionTypeList = getQuestionTypeList('', 'array');
         // These are the questions types that have no answers and therefore we delete the answer in that case
         $iAnswerScales = $aQuestionTypeList[Yii::app()->request->getPost('type')]['answerscales'];
         $iSubquestionScales = $aQuestionTypeList[Yii::app()->request->getPost('type')]['subquestions'];
         // These are the questions types that have the other option therefore we set everything else to 'No Other'
         if (Yii::app()->request->getPost('type') != "L" && Yii::app()->request->getPost('type') != "!" && Yii::app()->request->getPost('type') != "P" && Yii::app()->request->getPost('type') != "M") {
             $_POST['other'] = 'N';
         }
         // These are the questions types that have no validation - so zap it accordingly
         if (Yii::app()->request->getPost('type') == "!" || Yii::app()->request->getPost('type') == "L" || Yii::app()->request->getPost('type') == "M" || Yii::app()->request->getPost('type') == "P" || Yii::app()->request->getPost('type') == "F" || Yii::app()->request->getPost('type') == "H" || Yii::app()->request->getPost('type') == "X" || Yii::app()->request->getPost('type') == "") {
             $_POST['preg'] = '';
         }
         // These are the questions types that have no mandatory property - so zap it accordingly
         if (Yii::app()->request->getPost('type') == "X" || Yii::app()->request->getPost('type') == "|") {
             $_POST['mandatory'] = 'N';
         }
         if ($oldtype != Yii::app()->request->getPost('type')) {
             // TMSW Condition->Relevance:  Do similar check via EM, but do allow such a change since will be easier to modify relevance
             //Make sure there are no conditions based on this question, since we are changing the type
             $ccresult = Condition::model()->findAllByAttributes(array('cqid' => $iQuestionID));
             $cccount = count($ccresult);
             foreach ($ccresult as $ccr) {
                 $qidarray[] = $ccr['qid'];
             }
             if (isset($qidarray) && $qidarray) {
                 $qidlist = implode(", ", $qidarray);
             }
         }
         if (isset($cccount) && $cccount) {
             Yii::app()->setFlashMessage(gT("Question could not be updated. There are conditions for other questions that rely on the answers to this question and changing the type will cause problems. You must delete these conditions  before you can change the type of this question."), 'error');
         } else {
             if (isset($iQuestionGroupID) && $iQuestionGroupID != "") {
                 //                    $array_result=checkMoveQuestionConstraintsForConditions(sanitize_int($surveyid),sanitize_int($qid), sanitize_int($gid));
                 //                    // If there is no blocking conditions that could prevent this move
                 //
                 //                    if (is_null($array_result['notAbove']) && is_null($array_result['notBelow']))
                 //                    {
                 $aSurveyLanguages = Survey::model()->findByPk($iSurveyID)->additionalLanguages;
                 $sBaseLanguage = Survey::model()->findByPk($iSurveyID)->language;
                 array_push($aSurveyLanguages, $sBaseLanguage);
                 foreach ($aSurveyLanguages as $qlang) {
                     if (isset($qlang) && $qlang != "") {
                         // &eacute; to é and &amp; to & : really needed ? Why not for answers ? (130307)
                         $sQuestionText = Yii::app()->request->getPost('question_' . $qlang, '');
                         $sQuestionHelp = Yii::app()->request->getPost('help_' . $qlang, '');
                         // Fix bug with FCKEditor saving strange BR types : in rules ?
                         $sQuestionText = $oFixCKeditor->fixCKeditor($sQuestionText);
                         $sQuestionHelp = $oFixCKeditor->fixCKeditor($sQuestionHelp);
                         $udata = array('type' => Yii::app()->request->getPost('type'), 'title' => Yii::app()->request->getPost('title'), 'question' => $sQuestionText, 'preg' => Yii::app()->request->getPost('preg'), 'help' => $sQuestionHelp, 'gid' => $iQuestionGroupID, 'other' => Yii::app()->request->getPost('other'), 'mandatory' => Yii::app()->request->getPost('mandatory'), 'relevance' => Yii::app()->request->getPost('relevance'));
                         if ($oldgid != $iQuestionGroupID) {
                             if (getGroupOrder($iSurveyID, $oldgid) > getGroupOrder($iSurveyID, $iQuestionGroupID)) {
                                 // TMSW Condition->Relevance:  What is needed here?
                                 // Moving question to a 'upper' group
                                 // insert question at the end of the destination group
                                 // this prevent breaking conditions if the target qid is in the dest group
                                 $insertorder = getMaxQuestionOrder($iQuestionGroupID, $iSurveyID) + 1;
                                 $udata = array_merge($udata, array('question_order' => $insertorder));
                             } else {
                                 // Moving question to a 'lower' group
                                 // insert question at the beginning of the destination group
                                 shiftOrderQuestions($iSurveyID, $iQuestionGroupID, 1);
                                 // makes 1 spare room for new question at top of dest group
                                 $udata = array_merge($udata, array('question_order' => 0));
                             }
                         }
                         //$condn = array('sid' => $surveyid, 'qid' => $qid, 'language' => $qlang);
                         $oQuestion = Question::model()->findByPk(array("qid" => $iQuestionID, 'language' => $qlang));
                         foreach ($udata as $k => $v) {
                             $oQuestion->{$k} = $v;
                         }
                         $uqresult = $oQuestion->save();
                         //($uqquery); // or safeDie ("Error Update Question: ".$uqquery."<br />");  // Checked)
                         if (!$uqresult) {
                             $bOnError = true;
                             $aErrors = $oQuestion->getErrors();
                             if (count($aErrors)) {
                                 foreach ($aErrors as $sAttribute => $aStringErrors) {
                                     foreach ($aStringErrors as $sStringErrors) {
                                         Yii::app()->setFlashMessage(sprintf(gT("Question could not be updated with error on %s: %s"), $sAttribute, $sStringErrors), 'error');
                                     }
                                 }
                             } else {
                                 Yii::app()->setFlashMessage(gT("Question could not be updated."), 'error');
                             }
                         }
                     }
                 }
                 // Update the group ID on subquestions, too
                 if ($oldgid != $iQuestionGroupID) {
                     Question::model()->updateAll(array('gid' => $iQuestionGroupID), 'qid=:qid and parent_qid>0', array(':qid' => $iQuestionID));
                     // if the group has changed then fix the sortorder of old and new group
                     Question::model()->updateQuestionOrder($oldgid, $iSurveyID);
                     Question::model()->updateQuestionOrder($iQuestionGroupID, $iSurveyID);
                     // If some questions have conditions set on this question's answers
                     // then change the cfieldname accordingly
                     fixMovedQuestionConditions($iQuestionID, $oldgid, $iQuestionGroupID);
                 }
                 if ($oldtype != Yii::app()->request->getPost('type')) {
                     Question::model()->updateAll(array('type' => Yii::app()->request->getPost('type')), 'parent_qid=:qid', array(':qid' => $iQuestionID));
                 }
                 Answer::model()->deleteAllByAttributes(array('qid' => $iQuestionID), 'scale_id >= :scale_id', array(':scale_id' => $iAnswerScales));
                 // Remove old subquestion scales
                 Question::model()->deleteAllByAttributes(array('parent_qid' => $iQuestionID), 'scale_id >= :scale_id', array(':scale_id' => $iSubquestionScales));
                 if (!isset($bOnError) || !$bOnError) {
                     // This really a quick hack and need a better system
                     Yii::app()->setFlashMessage(gT("Question was successfully saved."));
                 }
                 //                    }
                 //                    else
                 //                    {
                 //
                 //                        // There are conditions constraints: alert the user
                 //                        $errormsg="";
                 //                        if (!is_null($array_result['notAbove']))
                 //                        {
                 //                            $errormsg.=gT("This question relies on other question's answers and can't be moved above groupId:","js")
                 //                            . " " . $array_result['notAbove'][0][0] . " " . gT("in position","js")." ".$array_result['notAbove'][0][1]."\\n"
                 //                            . gT("See conditions:")."\\n";
                 //
                 //                            foreach ($array_result['notAbove'] as $notAboveCond)
                 //                            {
                 //                                $errormsg.="- cid:". $notAboveCond[3]."\\n";
                 //                            }
                 //
                 //                        }
                 //                        if (!is_null($array_result['notBelow']))
                 //                        {
                 //                            $errormsg.=gT("Some questions rely on this question's answers. You can't move this question below groupId:","js")
                 //                            . " " . $array_result['notBelow'][0][0] . " " . gT("in position","js")." ".$array_result['notBelow'][0][1]."\\n"
                 //                            . gT("See conditions:")."\\n";
                 //
                 //                            foreach ($array_result['notBelow'] as $notBelowCond)
                 //                            {
                 //                                $errormsg.="- cid:". $notBelowCond[3]."\\n";
                 //                            }
                 //                        }
                 //
                 //                        $databaseoutput .= "<script type=\"text/javascript\">\n<!--\n alert(\"$errormsg\")\n //-->\n</script>\n";
                 //                        $gid= $oldgid; // group move impossible ==> keep display on oldgid
                 //                    }
             } else {
                 Yii::app()->setFlashMessage(gT("Question could not be updated"), 'error');
             }
         }
         LimeExpressionManager::UpgradeConditionsToRelevance($iSurveyID);
         if ($sDBOutput != '') {
             echo $sDBOutput;
         } else {
             if (Yii::app()->request->getPost('redirection') == "edit") {
                 $this->getController()->redirect(array('admin/questions/sa/editquestion/surveyid/' . $iSurveyID . '/gid/' . $iQuestionGroupID . '/qid/' . $iQuestionID));
             } else {
                 $this->getController()->redirect(array('admin/survey/sa/view/surveyid/' . $iSurveyID . '/gid/' . $iQuestionGroupID . '/qid/' . $iQuestionID));
             }
         }
     }
     if ($sAction == "updatesurveylocalesettings" && Permission::model()->hasSurveyPermission($iSurveyID, 'surveylocale', 'update')) {
         $languagelist = Survey::model()->findByPk($iSurveyID)->additionalLanguages;
         $languagelist[] = Survey::model()->findByPk($iSurveyID)->language;
         Yii::app()->loadHelper('database');
         foreach ($languagelist as $langname) {
             if ($langname) {
                 $url = Yii::app()->request->getPost('url_' . $langname);
                 if ($url == 'http://') {
                     $url = "";
                 }
                 $sURLDescription = html_entity_decode(Yii::app()->request->getPost('urldescrip_' . $langname), ENT_QUOTES, "UTF-8");
                 $sURL = html_entity_decode(Yii::app()->request->getPost('url_' . $langname), ENT_QUOTES, "UTF-8");
                 // Fix bug with FCKEditor saving strange BR types
                 $short_title = Yii::app()->request->getPost('short_title_' . $langname);
                 $description = Yii::app()->request->getPost('description_' . $langname);
                 $welcome = Yii::app()->request->getPost('welcome_' . $langname);
                 $endtext = Yii::app()->request->getPost('endtext_' . $langname);
                 $short_title = $oFixCKeditor->fixCKeditor($short_title);
                 $description = $oFixCKeditor->fixCKeditor($description);
                 $welcome = $oFixCKeditor->fixCKeditor($welcome);
                 $endtext = $oFixCKeditor->fixCKeditor($endtext);
                 $data = array('surveyls_title' => $short_title, 'surveyls_description' => $description, 'surveyls_welcometext' => $welcome, 'surveyls_endtext' => $endtext, 'surveyls_url' => $sURL, 'surveyls_urldescription' => $sURLDescription, 'surveyls_dateformat' => Yii::app()->request->getPost('dateformat_' . $langname), 'surveyls_numberformat' => Yii::app()->request->getPost('numberformat_' . $langname));
                 $SurveyLanguageSetting = SurveyLanguageSetting::model()->findByPk(array('surveyls_survey_id' => $iSurveyID, 'surveyls_language' => $langname));
                 $SurveyLanguageSetting->attributes = $data;
                 $SurveyLanguageSetting->save();
                 // save the change to database
             }
         }
         Yii::app()->session['flashmessage'] = gT("Survey text elements successfully saved.");
         if ($sDBOutput != '') {
             echo $sDBOutput;
         } else {
             $this->getController()->redirect(array('admin/survey/sa/view/surveyid/' . $iSurveyID));
         }
     }
     $this->getController()->redirect(array("/admin"), "refresh");
 }
/**
* 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;
}
/**
* This function generates an array containing the fieldcode, and matching data in the same order as the activate script
*
* @param string $surveyid The Survey ID
* @param mixed $style 'short' (default) or 'full' - full creates extra information like default values
* @param mixed $force_refresh - Forces to really refresh the array, not just take the session copy
* @param int $questionid Limit to a certain qid only (for question preview) - default is false
* @param string $sQuestionLanguage The language to use
* @return array
*/
function createFieldMap($surveyid, $style = 'short', $force_refresh = false, $questionid = false, $sLanguage, &$aDuplicateQIDs = array())
{
    $sLanguage = sanitize_languagecode($sLanguage);
    $surveyid = sanitize_int($surveyid);
    //checks to see if fieldmap has already been built for this page.
    if (isset(Yii::app()->session['fieldmap-' . $surveyid . $sLanguage]) && !$force_refresh && $questionid == false) {
        return Yii::app()->session['fieldmap-' . $surveyid . $sLanguage];
    }
    $sOldLanguage = App()->language;
    App()->setLanguage($sLanguage);
    $fieldmap["id"] = array("fieldname" => "id", 'sid' => $surveyid, 'type' => "id", "gid" => "", "qid" => "", "aid" => "");
    if ($style == "full") {
        $fieldmap["id"]['title'] = "";
        $fieldmap["id"]['question'] = gT("Response ID");
        $fieldmap["id"]['group_name'] = "";
    }
    $fieldmap["submitdate"] = array("fieldname" => "submitdate", 'type' => "submitdate", 'sid' => $surveyid, "gid" => "", "qid" => "", "aid" => "");
    if ($style == "full") {
        $fieldmap["submitdate"]['title'] = "";
        $fieldmap["submitdate"]['question'] = gT("Date submitted");
        $fieldmap["submitdate"]['group_name'] = "";
    }
    $fieldmap["lastpage"] = array("fieldname" => "lastpage", 'sid' => $surveyid, 'type' => "lastpage", "gid" => "", "qid" => "", "aid" => "");
    if ($style == "full") {
        $fieldmap["lastpage"]['title'] = "";
        $fieldmap["lastpage"]['question'] = gT("Last page");
        $fieldmap["lastpage"]['group_name'] = "";
    }
    $fieldmap["startlanguage"] = array("fieldname" => "startlanguage", 'sid' => $surveyid, 'type' => "startlanguage", "gid" => "", "qid" => "", "aid" => "");
    if ($style == "full") {
        $fieldmap["startlanguage"]['title'] = "";
        $fieldmap["startlanguage"]['question'] = gT("Start language");
        $fieldmap["startlanguage"]['group_name'] = "";
    }
    //Check for any additional fields for this survey and create necessary fields (token and datestamp and ipaddr)
    $prow = Survey::model()->findByPk($surveyid)->getAttributes();
    //Checked
    if ($prow['anonymized'] == "N" && Survey::model()->hasTokens($surveyid)) {
        $fieldmap["token"] = array("fieldname" => "token", 'sid' => $surveyid, 'type' => "token", "gid" => "", "qid" => "", "aid" => "");
        if ($style == "full") {
            $fieldmap["token"]['title'] = "";
            $fieldmap["token"]['question'] = gT("Token");
            $fieldmap["token"]['group_name'] = "";
        }
    }
    if ($prow['datestamp'] == "Y") {
        $fieldmap["startdate"] = array("fieldname" => "startdate", 'type' => "startdate", 'sid' => $surveyid, "gid" => "", "qid" => "", "aid" => "");
        if ($style == "full") {
            $fieldmap["startdate"]['title'] = "";
            $fieldmap["startdate"]['question'] = gT("Date started");
            $fieldmap["startdate"]['group_name'] = "";
        }
        $fieldmap["datestamp"] = array("fieldname" => "datestamp", 'type' => "datestamp", 'sid' => $surveyid, "gid" => "", "qid" => "", "aid" => "");
        if ($style == "full") {
            $fieldmap["datestamp"]['title'] = "";
            $fieldmap["datestamp"]['question'] = gT("Date last action");
            $fieldmap["datestamp"]['group_name'] = "";
        }
    }
    if ($prow['ipaddr'] == "Y") {
        $fieldmap["ipaddr"] = array("fieldname" => "ipaddr", 'type' => "ipaddress", 'sid' => $surveyid, "gid" => "", "qid" => "", "aid" => "");
        if ($style == "full") {
            $fieldmap["ipaddr"]['title'] = "";
            $fieldmap["ipaddr"]['question'] = gT("IP address");
            $fieldmap["ipaddr"]['group_name'] = "";
        }
    }
    // Add 'refurl' to fieldmap.
    if ($prow['refurl'] == "Y") {
        $fieldmap["refurl"] = array("fieldname" => "refurl", 'type' => "url", 'sid' => $surveyid, "gid" => "", "qid" => "", "aid" => "");
        if ($style == "full") {
            $fieldmap["refurl"]['title'] = "";
            $fieldmap["refurl"]['question'] = gT("Referrer URL");
            $fieldmap["refurl"]['group_name'] = "";
        }
    }
    // Collect all default values once so don't need separate query for each question with defaults
    // First collect language specific defaults
    $defaultsQuery = "SELECT a.qid, a.sqid, a.scale_id, a.specialtype, a.defaultvalue" . " FROM {{defaultvalues}} as a, {{questions}} as b" . " WHERE a.qid = b.qid" . " AND a.language = b.language" . " AND a.language = '{$sLanguage}'" . " AND b.same_default=0" . " AND b.sid = " . $surveyid;
    $defaultResults = Yii::app()->db->createCommand($defaultsQuery)->queryAll();
    $defaultValues = array();
    // indexed by question then subquestion
    foreach ($defaultResults as $dv) {
        if ($dv['specialtype'] != '') {
            $sq = $dv['specialtype'];
        } else {
            $sq = $dv['sqid'];
        }
        $defaultValues[$dv['qid'] . '~' . $sq] = $dv['defaultvalue'];
    }
    // Now overwrite language-specific defaults (if any) base language values for each question that uses same_defaults=1
    $baseLanguage = getBaseLanguageFromSurveyID($surveyid);
    $defaultsQuery = "SELECT a.qid, a.sqid, a.scale_id, a.specialtype, a.defaultvalue" . " FROM {{defaultvalues}} as a, {{questions}} as b" . " WHERE a.qid = b.qid" . " AND a.language = b.language" . " AND a.language = '{$baseLanguage}'" . " AND b.same_default=1" . " AND b.sid = " . $surveyid;
    $defaultResults = Yii::app()->db->createCommand($defaultsQuery)->queryAll();
    foreach ($defaultResults as $dv) {
        if ($dv['specialtype'] != '') {
            $sq = $dv['specialtype'];
        } else {
            $sq = $dv['sqid'];
        }
        $defaultValues[$dv['qid'] . '~' . $sq] = $dv['defaultvalue'];
    }
    $qtypes = getQuestionTypeList('', 'array');
    // Main query
    $aquery = "SELECT * " . " FROM {{questions}} as questions, {{groups}} as groups" . " WHERE questions.gid=groups.gid AND " . " questions.sid={$surveyid} AND " . " questions.language='{$sLanguage}' AND " . " questions.parent_qid=0 AND " . " groups.language='{$sLanguage}' ";
    if ($questionid !== false) {
        $aquery .= " and questions.qid={$questionid} ";
    }
    $aquery .= " ORDER BY group_order, question_order";
    $aresult = Yii::app()->db->createCommand($aquery)->queryAll();
    $questionSeq = -1;
    // this is incremental question sequence across all groups
    $groupSeq = -1;
    $_groupOrder = -1;
    foreach ($aresult as $arow) {
        ++$questionSeq;
        // fix fact taht group_order may have gaps
        if ($_groupOrder != $arow['group_order']) {
            $_groupOrder = $arow['group_order'];
            ++$groupSeq;
        }
        // Condition indicators are obsolete with EM.  However, they are so tightly coupled into LS code that easider to just set values to 'N' for now and refactor later.
        $conditions = 'N';
        $usedinconditions = 'N';
        // Field identifier
        // GXQXSXA
        // G=Group  Q=Question S=Subquestion A=Answer Option
        // If S or A don't exist then set it to 0
        // Implicit (subqestion intermal to a question type ) or explicit qubquestions/answer count starts at 1
        // Types "L", "!", "O", "D", "G", "N", "X", "Y", "5", "S", "T", "U"
        $fieldname = "{$arow['sid']}X{$arow['gid']}X{$arow['qid']}";
        if ($qtypes[$arow['type']]['subquestions'] == 0 && $arow['type'] != "R" && $arow['type'] != "|") {
            if (isset($fieldmap[$fieldname])) {
                $aDuplicateQIDs[$arow['qid']] = array('fieldname' => $fieldname, 'question' => $arow['question'], 'gid' => $arow['gid']);
            }
            $fieldmap[$fieldname] = array("fieldname" => $fieldname, 'type' => "{$arow['type']}", 'sid' => $surveyid, "gid" => $arow['gid'], "qid" => $arow['qid'], "aid" => "");
            if ($style == "full") {
                $fieldmap[$fieldname]['title'] = $arow['title'];
                $fieldmap[$fieldname]['question'] = $arow['question'];
                $fieldmap[$fieldname]['group_name'] = $arow['group_name'];
                $fieldmap[$fieldname]['mandatory'] = $arow['mandatory'];
                $fieldmap[$fieldname]['hasconditions'] = $conditions;
                $fieldmap[$fieldname]['usedinconditions'] = $usedinconditions;
                $fieldmap[$fieldname]['questionSeq'] = $questionSeq;
                $fieldmap[$fieldname]['groupSeq'] = $groupSeq;
                if (isset($defaultValues[$arow['qid'] . '~0'])) {
                    $fieldmap[$fieldname]['defaultvalue'] = $defaultValues[$arow['qid'] . '~0'];
                }
            }
            switch ($arow['type']) {
                case "L":
                    //RADIO LIST
                //RADIO LIST
                case "!":
                    //DROPDOWN LIST
                    if ($arow['other'] == "Y") {
                        $fieldname = "{$arow['sid']}X{$arow['gid']}X{$arow['qid']}other";
                        if (isset($fieldmap[$fieldname])) {
                            $aDuplicateQIDs[$arow['qid']] = array('fieldname' => $fieldname, 'question' => $arow['question'], 'gid' => $arow['gid']);
                        }
                        $fieldmap[$fieldname] = array("fieldname" => $fieldname, 'type' => $arow['type'], 'sid' => $surveyid, "gid" => $arow['gid'], "qid" => $arow['qid'], "aid" => "other");
                        // dgk bug fix line above. aid should be set to "other" for export to append to the field name in the header line.
                        if ($style == "full") {
                            $fieldmap[$fieldname]['title'] = $arow['title'];
                            $fieldmap[$fieldname]['question'] = $arow['question'];
                            $fieldmap[$fieldname]['subquestion'] = gT("Other");
                            $fieldmap[$fieldname]['group_name'] = $arow['group_name'];
                            $fieldmap[$fieldname]['mandatory'] = $arow['mandatory'];
                            $fieldmap[$fieldname]['hasconditions'] = $conditions;
                            $fieldmap[$fieldname]['usedinconditions'] = $usedinconditions;
                            $fieldmap[$fieldname]['questionSeq'] = $questionSeq;
                            $fieldmap[$fieldname]['groupSeq'] = $groupSeq;
                            if (isset($defaultValues[$arow['qid'] . '~other'])) {
                                $fieldmap[$fieldname]['defaultvalue'] = $defaultValues[$arow['qid'] . '~other'];
                            }
                        }
                    }
                    break;
                case "O":
                    //DROPDOWN LIST WITH COMMENT
                    $fieldname = "{$arow['sid']}X{$arow['gid']}X{$arow['qid']}comment";
                    if (isset($fieldmap[$fieldname])) {
                        $aDuplicateQIDs[$arow['qid']] = array('fieldname' => $fieldname, 'question' => $arow['question'], 'gid' => $arow['gid']);
                    }
                    $fieldmap[$fieldname] = array("fieldname" => $fieldname, 'type' => $arow['type'], 'sid' => $surveyid, "gid" => $arow['gid'], "qid" => $arow['qid'], "aid" => "comment");
                    // dgk bug fix line below. aid should be set to "comment" for export to append to the field name in the header line. Also needed set the type element correctly.
                    if ($style == "full") {
                        $fieldmap[$fieldname]['title'] = $arow['title'];
                        $fieldmap[$fieldname]['question'] = $arow['question'];
                        $fieldmap[$fieldname]['subquestion'] = gT("Comment");
                        $fieldmap[$fieldname]['group_name'] = $arow['group_name'];
                        $fieldmap[$fieldname]['mandatory'] = $arow['mandatory'];
                        $fieldmap[$fieldname]['hasconditions'] = $conditions;
                        $fieldmap[$fieldname]['usedinconditions'] = $usedinconditions;
                        $fieldmap[$fieldname]['questionSeq'] = $questionSeq;
                        $fieldmap[$fieldname]['groupSeq'] = $groupSeq;
                    }
                    break;
            }
        } elseif ($qtypes[$arow['type']]['subquestions'] == 2 && $qtypes[$arow['type']]['answerscales'] == 0) {
            //MULTI FLEXI
            $abrows = getSubQuestions($surveyid, $arow['qid'], $sLanguage);
            //Now first process scale=1
            $answerset = array();
            $answerList = array();
            foreach ($abrows as $key => $abrow) {
                if ($abrow['scale_id'] == 1) {
                    $answerset[] = $abrow;
                    $answerList[] = array('code' => $abrow['title'], 'answer' => $abrow['question']);
                    unset($abrows[$key]);
                }
            }
            reset($abrows);
            foreach ($abrows as $abrow) {
                foreach ($answerset as $answer) {
                    $fieldname = "{$arow['sid']}X{$arow['gid']}X{$arow['qid']}{$abrow['title']}_{$answer['title']}";
                    if (isset($fieldmap[$fieldname])) {
                        $aDuplicateQIDs[$arow['qid']] = array('fieldname' => $fieldname, 'question' => $arow['question'], 'gid' => $arow['gid']);
                    }
                    $fieldmap[$fieldname] = array("fieldname" => $fieldname, 'type' => $arow['type'], 'sid' => $surveyid, "gid" => $arow['gid'], "qid" => $arow['qid'], "aid" => $abrow['title'] . "_" . $answer['title'], "sqid" => $abrow['qid']);
                    if ($abrow['other'] == "Y") {
                        $alsoother = "Y";
                    }
                    if ($style == "full") {
                        $fieldmap[$fieldname]['title'] = $arow['title'];
                        $fieldmap[$fieldname]['question'] = $arow['question'];
                        $fieldmap[$fieldname]['subquestion1'] = $abrow['question'];
                        $fieldmap[$fieldname]['subquestion2'] = $answer['question'];
                        $fieldmap[$fieldname]['group_name'] = $arow['group_name'];
                        $fieldmap[$fieldname]['mandatory'] = $arow['mandatory'];
                        $fieldmap[$fieldname]['hasconditions'] = $conditions;
                        $fieldmap[$fieldname]['usedinconditions'] = $usedinconditions;
                        $fieldmap[$fieldname]['questionSeq'] = $questionSeq;
                        $fieldmap[$fieldname]['groupSeq'] = $groupSeq;
                        $fieldmap[$fieldname]['preg'] = $arow['preg'];
                        $fieldmap[$fieldname]['answerList'] = $answerList;
                        $fieldmap[$fieldname]['SQrelevance'] = $abrow['relevance'];
                    }
                }
            }
            unset($answerset);
        } elseif ($arow['type'] == "1") {
            $abrows = getSubQuestions($surveyid, $arow['qid'], $sLanguage);
            foreach ($abrows as $abrow) {
                $fieldname = "{$arow['sid']}X{$arow['gid']}X{$arow['qid']}{$abrow['title']}#0";
                if (isset($fieldmap[$fieldname])) {
                    $aDuplicateQIDs[$arow['qid']] = array('fieldname' => $fieldname, 'question' => $arow['question'], 'gid' => $arow['gid']);
                }
                $fieldmap[$fieldname] = array("fieldname" => $fieldname, 'type' => $arow['type'], 'sid' => $surveyid, "gid" => $arow['gid'], "qid" => $arow['qid'], "aid" => $abrow['title'], "scale_id" => 0);
                if ($style == "full") {
                    $fieldmap[$fieldname]['title'] = $arow['title'];
                    $fieldmap[$fieldname]['question'] = $arow['question'];
                    $fieldmap[$fieldname]['subquestion'] = $abrow['question'];
                    $fieldmap[$fieldname]['group_name'] = $arow['group_name'];
                    $fieldmap[$fieldname]['scale'] = gT('Scale 1');
                    $fieldmap[$fieldname]['mandatory'] = $arow['mandatory'];
                    $fieldmap[$fieldname]['hasconditions'] = $conditions;
                    $fieldmap[$fieldname]['usedinconditions'] = $usedinconditions;
                    $fieldmap[$fieldname]['questionSeq'] = $questionSeq;
                    $fieldmap[$fieldname]['groupSeq'] = $groupSeq;
                    $fieldmap[$fieldname]['SQrelevance'] = $abrow['relevance'];
                }
                $fieldname = "{$arow['sid']}X{$arow['gid']}X{$arow['qid']}{$abrow['title']}#1";
                if (isset($fieldmap[$fieldname])) {
                    $aDuplicateQIDs[$arow['qid']] = array('fieldname' => $fieldname, 'question' => $arow['question'], 'gid' => $arow['gid']);
                }
                $fieldmap[$fieldname] = array("fieldname" => $fieldname, 'type' => $arow['type'], 'sid' => $surveyid, "gid" => $arow['gid'], "qid" => $arow['qid'], "aid" => $abrow['title'], "scale_id" => 1);
                if ($style == "full") {
                    $fieldmap[$fieldname]['title'] = $arow['title'];
                    $fieldmap[$fieldname]['question'] = $arow['question'];
                    $fieldmap[$fieldname]['subquestion'] = $abrow['question'];
                    $fieldmap[$fieldname]['group_name'] = $arow['group_name'];
                    $fieldmap[$fieldname]['scale'] = gT('Scale 2');
                    $fieldmap[$fieldname]['mandatory'] = $arow['mandatory'];
                    $fieldmap[$fieldname]['hasconditions'] = $conditions;
                    $fieldmap[$fieldname]['usedinconditions'] = $usedinconditions;
                    $fieldmap[$fieldname]['questionSeq'] = $questionSeq;
                    $fieldmap[$fieldname]['groupSeq'] = $groupSeq;
                    // TODO SQrelevance for different scales? $fieldmap[$fieldname]['SQrelevance']=$abrow['relevance'];
                }
            }
        } elseif ($arow['type'] == "R") {
            //MULTI ENTRY
            $data = Answer::model()->findAllByAttributes(array('qid' => $arow['qid'], 'language' => $sLanguage));
            $data = count($data);
            $slots = $data;
            for ($i = 1; $i <= $slots; $i++) {
                $fieldname = "{$arow['sid']}X{$arow['gid']}X{$arow['qid']}{$i}";
                if (isset($fieldmap[$fieldname])) {
                    $aDuplicateQIDs[$arow['qid']] = array('fieldname' => $fieldname, 'question' => $arow['question'], 'gid' => $arow['gid']);
                }
                $fieldmap[$fieldname] = array("fieldname" => $fieldname, 'type' => $arow['type'], 'sid' => $surveyid, "gid" => $arow['gid'], "qid" => $arow['qid'], "aid" => $i);
                if ($style == "full") {
                    $fieldmap[$fieldname]['title'] = $arow['title'];
                    $fieldmap[$fieldname]['question'] = $arow['question'];
                    $fieldmap[$fieldname]['subquestion'] = sprintf(gT('Rank %s'), $i);
                    $fieldmap[$fieldname]['group_name'] = $arow['group_name'];
                    $fieldmap[$fieldname]['mandatory'] = $arow['mandatory'];
                    $fieldmap[$fieldname]['hasconditions'] = $conditions;
                    $fieldmap[$fieldname]['usedinconditions'] = $usedinconditions;
                    $fieldmap[$fieldname]['questionSeq'] = $questionSeq;
                    $fieldmap[$fieldname]['groupSeq'] = $groupSeq;
                }
            }
        } elseif ($arow['type'] == "|") {
            $qidattributes = getQuestionAttributeValues($arow['qid']);
            $fieldname = "{$arow['sid']}X{$arow['gid']}X{$arow['qid']}";
            $fieldmap[$fieldname] = array("fieldname" => $fieldname, 'type' => $arow['type'], 'sid' => $surveyid, "gid" => $arow['gid'], "qid" => $arow['qid'], "aid" => '');
            if ($style == "full") {
                $fieldmap[$fieldname]['title'] = $arow['title'];
                $fieldmap[$fieldname]['question'] = $arow['question'];
                $fieldmap[$fieldname]['max_files'] = $qidattributes['max_num_of_files'];
                $fieldmap[$fieldname]['group_name'] = $arow['group_name'];
                $fieldmap[$fieldname]['mandatory'] = $arow['mandatory'];
                $fieldmap[$fieldname]['hasconditions'] = $conditions;
                $fieldmap[$fieldname]['usedinconditions'] = $usedinconditions;
                $fieldmap[$fieldname]['questionSeq'] = $questionSeq;
                $fieldmap[$fieldname]['groupSeq'] = $groupSeq;
            }
            $fieldname = "{$arow['sid']}X{$arow['gid']}X{$arow['qid']}" . "_filecount";
            $fieldmap[$fieldname] = array("fieldname" => $fieldname, 'type' => $arow['type'], 'sid' => $surveyid, "gid" => $arow['gid'], "qid" => $arow['qid'], "aid" => "filecount");
            if ($style == "full") {
                $fieldmap[$fieldname]['title'] = $arow['title'];
                $fieldmap[$fieldname]['question'] = "filecount - " . $arow['question'];
                $fieldmap[$fieldname]['group_name'] = $arow['group_name'];
                $fieldmap[$fieldname]['mandatory'] = $arow['mandatory'];
                $fieldmap[$fieldname]['hasconditions'] = $conditions;
                $fieldmap[$fieldname]['usedinconditions'] = $usedinconditions;
                $fieldmap[$fieldname]['questionSeq'] = $questionSeq;
                $fieldmap[$fieldname]['groupSeq'] = $groupSeq;
            }
        } else {
            //MULTI ENTRY
            $abrows = getSubQuestions($surveyid, $arow['qid'], $sLanguage);
            foreach ($abrows as $abrow) {
                $fieldname = "{$arow['sid']}X{$arow['gid']}X{$arow['qid']}{$abrow['title']}";
                if (isset($fieldmap[$fieldname])) {
                    $aDuplicateQIDs[$arow['qid']] = array('fieldname' => $fieldname, 'question' => $arow['question'], 'gid' => $arow['gid']);
                }
                $fieldmap[$fieldname] = array("fieldname" => $fieldname, 'type' => $arow['type'], 'sid' => $surveyid, 'gid' => $arow['gid'], 'qid' => $arow['qid'], 'aid' => $abrow['title'], 'sqid' => $abrow['qid']);
                if ($style == "full") {
                    $fieldmap[$fieldname]['title'] = $arow['title'];
                    $fieldmap[$fieldname]['question'] = $arow['question'];
                    $fieldmap[$fieldname]['subquestion'] = $abrow['question'];
                    $fieldmap[$fieldname]['group_name'] = $arow['group_name'];
                    $fieldmap[$fieldname]['mandatory'] = $arow['mandatory'];
                    $fieldmap[$fieldname]['hasconditions'] = $conditions;
                    $fieldmap[$fieldname]['usedinconditions'] = $usedinconditions;
                    $fieldmap[$fieldname]['questionSeq'] = $questionSeq;
                    $fieldmap[$fieldname]['groupSeq'] = $groupSeq;
                    $fieldmap[$fieldname]['preg'] = $arow['preg'];
                    // get SQrelevance from DB
                    $fieldmap[$fieldname]['SQrelevance'] = $abrow['relevance'];
                    if (isset($defaultValues[$arow['qid'] . '~' . $abrow['qid']])) {
                        $fieldmap[$fieldname]['defaultvalue'] = $defaultValues[$arow['qid'] . '~' . $abrow['qid']];
                    }
                }
                if ($arow['type'] == "P") {
                    $fieldname = "{$arow['sid']}X{$arow['gid']}X{$arow['qid']}{$abrow['title']}comment";
                    if (isset($fieldmap[$fieldname])) {
                        $aDuplicateQIDs[$arow['qid']] = array('fieldname' => $fieldname, 'question' => $arow['question'], 'gid' => $arow['gid']);
                    }
                    $fieldmap[$fieldname] = array("fieldname" => $fieldname, 'type' => $arow['type'], 'sid' => $surveyid, "gid" => $arow['gid'], "qid" => $arow['qid'], "aid" => $abrow['title'] . "comment");
                    if ($style == "full") {
                        $fieldmap[$fieldname]['title'] = $arow['title'];
                        $fieldmap[$fieldname]['question'] = $arow['question'];
                        $fieldmap[$fieldname]['subquestion'] = gT('Comment');
                        $fieldmap[$fieldname]['group_name'] = $arow['group_name'];
                        $fieldmap[$fieldname]['mandatory'] = $arow['mandatory'];
                        $fieldmap[$fieldname]['hasconditions'] = $conditions;
                        $fieldmap[$fieldname]['usedinconditions'] = $usedinconditions;
                        $fieldmap[$fieldname]['questionSeq'] = $questionSeq;
                        $fieldmap[$fieldname]['groupSeq'] = $groupSeq;
                    }
                }
            }
            if ($arow['other'] == "Y" && ($arow['type'] == "M" || $arow['type'] == "P")) {
                $fieldname = "{$arow['sid']}X{$arow['gid']}X{$arow['qid']}other";
                if (isset($fieldmap[$fieldname])) {
                    $aDuplicateQIDs[$arow['qid']] = array('fieldname' => $fieldname, 'question' => $arow['question'], 'gid' => $arow['gid']);
                }
                $fieldmap[$fieldname] = array("fieldname" => $fieldname, 'type' => $arow['type'], 'sid' => $surveyid, "gid" => $arow['gid'], "qid" => $arow['qid'], "aid" => "other");
                if ($style == "full") {
                    $fieldmap[$fieldname]['title'] = $arow['title'];
                    $fieldmap[$fieldname]['question'] = $arow['question'];
                    $fieldmap[$fieldname]['subquestion'] = gT('Other');
                    $fieldmap[$fieldname]['group_name'] = $arow['group_name'];
                    $fieldmap[$fieldname]['mandatory'] = $arow['mandatory'];
                    $fieldmap[$fieldname]['hasconditions'] = $conditions;
                    $fieldmap[$fieldname]['usedinconditions'] = $usedinconditions;
                    $fieldmap[$fieldname]['questionSeq'] = $questionSeq;
                    $fieldmap[$fieldname]['groupSeq'] = $groupSeq;
                    $fieldmap[$fieldname]['other'] = $arow['other'];
                }
                if ($arow['type'] == "P") {
                    $fieldname = "{$arow['sid']}X{$arow['gid']}X{$arow['qid']}othercomment";
                    if (isset($fieldmap[$fieldname])) {
                        $aDuplicateQIDs[$arow['qid']] = array('fieldname' => $fieldname, 'question' => $arow['question'], 'gid' => $arow['gid']);
                    }
                    $fieldmap[$fieldname] = array("fieldname" => $fieldname, 'type' => $arow['type'], 'sid' => $surveyid, "gid" => $arow['gid'], "qid" => $arow['qid'], "aid" => "othercomment");
                    if ($style == "full") {
                        $fieldmap[$fieldname]['title'] = $arow['title'];
                        $fieldmap[$fieldname]['question'] = $arow['question'];
                        $fieldmap[$fieldname]['subquestion'] = gT('Other comment');
                        $fieldmap[$fieldname]['group_name'] = $arow['group_name'];
                        $fieldmap[$fieldname]['mandatory'] = $arow['mandatory'];
                        $fieldmap[$fieldname]['hasconditions'] = $conditions;
                        $fieldmap[$fieldname]['usedinconditions'] = $usedinconditions;
                        $fieldmap[$fieldname]['questionSeq'] = $questionSeq;
                        $fieldmap[$fieldname]['groupSeq'] = $groupSeq;
                        $fieldmap[$fieldname]['other'] = $arow['other'];
                    }
                }
            }
        }
        if (isset($fieldmap[$fieldname])) {
            //set question relevance (uses last SQ's relevance field for question relevance)
            $fieldmap[$fieldname]['relevance'] = $arow['relevance'];
            $fieldmap[$fieldname]['grelevance'] = $arow['grelevance'];
            $fieldmap[$fieldname]['questionSeq'] = $questionSeq;
            $fieldmap[$fieldname]['groupSeq'] = $groupSeq;
            $fieldmap[$fieldname]['preg'] = $arow['preg'];
            $fieldmap[$fieldname]['other'] = $arow['other'];
            $fieldmap[$fieldname]['help'] = $arow['help'];
            // Set typeName
        } else {
            --$questionSeq;
            // didn't generate a valid $fieldmap entry, so decrement the question counter to ensure they are sequential
        }
        if (isset($fieldmap[$fieldname]['typename'])) {
            $fieldmap[$fieldname]['typename'] = $typename[$fieldname] = $arow['typename'];
        }
    }
    App()->setLanguage($sOldLanguage);
    if (isset($fieldmap)) {
        if ($questionid == false) {
            // If the fieldmap was randomized, the master will contain the proper order.  Copy that fieldmap with the new language settings.
            if (isset(Yii::app()->session['survey_' . $surveyid]['fieldmap-' . $surveyid . '-randMaster'])) {
                $masterFieldmap = Yii::app()->session['survey_' . $surveyid]['fieldmap-' . $surveyid . '-randMaster'];
                $mfieldmap = Yii::app()->session['survey_' . $surveyid][$masterFieldmap];
                foreach ($mfieldmap as $fieldname => $mf) {
                    if (isset($fieldmap[$fieldname])) {
                        // This array holds the keys of translatable attributes
                        $translatable = array_flip(array('question', 'subquestion', 'subquestion1', 'subquestion2', 'group_name', 'answerList', 'defaultValue', 'help'));
                        // We take all translatable attributes from the new fieldmap
                        $newText = array_intersect_key($fieldmap[$fieldname], $translatable);
                        // And merge them with the other values from the random fieldmap like questionSeq, groupSeq etc.
                        $mf = $newText + $mf;
                    }
                    $mfieldmap[$fieldname] = $mf;
                }
                $fieldmap = $mfieldmap;
            }
            Yii::app()->session['fieldmap-' . $surveyid . $sLanguage] = $fieldmap;
        }
        return $fieldmap;
    }
}
Exemple #14
0
 /**
  * Database::index()
  *
  * @param mixed $sa
  * @return
  */
 function index($sa = null)
 {
     $sAction = Yii::app()->request->getPost('action');
     $clang = $this->getController()->lang;
     $iSurveyID = returnGlobal('sid');
     $iQuestionGroupID = returnGlobal('gid');
     $iQuestionID = returnGlobal('qid');
     $sDBOutput = '';
     if (Yii::app()->getConfig('filterxsshtml') && !Permission::model()->hasGlobalPermission('superadmin', 'read')) {
         $oPurifier = new CHtmlPurifier();
         $oPurifier->options = array('URI.AllowedSchemes' => array('http' => true, 'https' => true));
         $bXSSFilter = true;
     } else {
         $bXSSFilter = false;
     }
     if ($sAction == "updatedefaultvalues" && Permission::model()->hasSurveyPermission($iSurveyID, 'surveycontent', 'update')) {
         $aSurveyLanguages = Survey::model()->findByPk($iSurveyID)->additionalLanguages;
         $sBaseLanguage = Survey::model()->findByPk($iSurveyID)->language;
         array_unshift($aSurveyLanguages, $sBaseLanguage);
         Question::model()->updateAll(array('same_default' => Yii::app()->request->getPost('samedefault') ? 1 : 0), 'sid=:sid ANd qid=:qid', array(':sid' => $iSurveyID, ':qid' => $iQuestionID));
         $arQuestion = Question::model()->findByAttributes(array('qid' => $iQuestionID));
         $sQuestionType = $arQuestion['type'];
         $aQuestionTypeList = getQuestionTypeList('', 'array');
         if ($aQuestionTypeList[$sQuestionType]['answerscales'] > 0 && $aQuestionTypeList[$sQuestionType]['subquestions'] == 0) {
             for ($iScaleID = 0; $iScaleID < $aQuestionTypeList[$sQuestionType]['answerscales']; $iScaleID++) {
                 foreach ($aSurveyLanguages as $sLanguage) {
                     if (!is_null(Yii::app()->request->getPost('defaultanswerscale_' . $iScaleID . '_' . $sLanguage))) {
                         $this->_updateDefaultValues($iQuestionID, 0, $iScaleID, '', $sLanguage, Yii::app()->request->getPost('defaultanswerscale_' . $iScaleID . '_' . $sLanguage), true);
                     }
                     if (!is_null(Yii::app()->request->getPost('other_' . $iScaleID . '_' . $sLanguage))) {
                         $this->_updateDefaultValues($iQuestionID, 0, $iScaleID, 'other', $sLanguage, Yii::app()->request->getPost('other_' . $iScaleID . '_' . $sLanguage), true);
                     }
                 }
             }
         }
         if ($aQuestionTypeList[$sQuestionType]['subquestions'] > 0) {
             foreach ($aSurveyLanguages as $sLanguage) {
                 $arQuestions = Question::model()->findAllByAttributes(array('sid' => $iSurveyID, 'gid' => $iQuestionGroupID, 'parent_qid' => $iQuestionID, 'language' => $sLanguage, 'scale_id' => 0));
                 for ($iScaleID = 0; $iScaleID < $aQuestionTypeList[$sQuestionType]['subquestions']; $iScaleID++) {
                     foreach ($arQuestions as $aSubquestionrow) {
                         if (!is_null(Yii::app()->request->getPost('defaultanswerscale_' . $iScaleID . '_' . $sLanguage . '_' . $aSubquestionrow['qid']))) {
                             $this->_updateDefaultValues($iQuestionID, $aSubquestionrow['qid'], $iScaleID, '', $sLanguage, Yii::app()->request->getPost('defaultanswerscale_' . $iScaleID . '_' . $sLanguage . '_' . $aSubquestionrow['qid']), true);
                         }
                     }
                 }
             }
         }
         if ($aQuestionTypeList[$sQuestionType]['answerscales'] == 0 && $aQuestionTypeList[$sQuestionType]['subquestions'] == 0) {
             foreach ($aSurveyLanguages as $sLanguage) {
                 if (!is_null(Yii::app()->request->getPost('defaultanswerscale_0_' . $sLanguage . '_0'))) {
                     $this->_updateDefaultValues($iQuestionID, 0, 0, '', $sLanguage, Yii::app()->request->getPost('defaultanswerscale_0_' . $sLanguage . '_0'), true);
                 }
             }
         }
         Yii::app()->session['flashmessage'] = $clang->gT("Default value settings were successfully saved.");
         LimeExpressionManager::SetDirtyFlag();
         if ($sDBOutput != '') {
             echo $sDBOutput;
         } else {
             $this->getController()->redirect(array('admin/survey/sa/view/surveyid/' . $iSurveyID . '/gid/' . $iQuestionGroupID . '/qid/' . $iQuestionID));
         }
     }
     if ($sAction == "updateansweroptions" && Permission::model()->hasSurveyPermission($iSurveyID, 'surveycontent', 'update')) {
         Yii::app()->loadHelper('database');
         $aSurveyLanguages = Survey::model()->findByPk($iSurveyID)->additionalLanguages;
         $sBaseLanguage = Survey::model()->findByPk($iSurveyID)->language;
         array_unshift($aSurveyLanguages, $sBaseLanguage);
         $arQuestion = Question::model()->findByAttributes(array('qid' => $iQuestionID));
         $sQuestionType = $arQuestion['type'];
         // Checked)
         $aQuestionTypeList = getQuestionTypeList('', 'array');
         $iScaleCount = $aQuestionTypeList[$sQuestionType]['answerscales'];
         //First delete all answers
         Answer::model()->deleteAllByAttributes(array('qid' => $iQuestionID));
         LimeExpressionManager::RevertUpgradeConditionsToRelevance($iSurveyID);
         for ($iScaleID = 0; $iScaleID < $iScaleCount; $iScaleID++) {
             $iMaxCount = (int) Yii::app()->request->getPost('answercount_' . $iScaleID);
             for ($iSortOrderID = 1; $iSortOrderID < $iMaxCount; $iSortOrderID++) {
                 $sCode = sanitize_paranoid_string(Yii::app()->request->getPost('code_' . $iSortOrderID . '_' . $iScaleID));
                 if (Yii::app()->request->getPost('oldcode_' . $iSortOrderID . '_' . $iScaleID)) {
                     $sOldCode = sanitize_paranoid_string(Yii::app()->request->getPost('oldcode_' . $iSortOrderID . '_' . $iScaleID));
                     if ($sCode !== $sOldCode) {
                         Condition::model()->updateAll(array('value' => $sCode), 'cqid=:cqid AND value=:value', array(':cqid' => $iQuestionID, ':value' => $sOldCode));
                     }
                 }
                 $iAssessmentValue = (int) Yii::app()->request->getPost('assessment_' . $iSortOrderID . '_' . $iScaleID);
                 foreach ($aSurveyLanguages as $sLanguage) {
                     $sAnswerText = Yii::app()->request->getPost('answer_' . $sLanguage . '_' . $iSortOrderID . '_' . $iScaleID);
                     if ($bXSSFilter) {
                         $sAnswerText = $oPurifier->purify($sAnswerText);
                     } else {
                         $sAnswerText = html_entity_decode($sAnswerText, ENT_QUOTES, "UTF-8");
                     }
                     // Fix bug with FCKEditor saving strange BR types
                     $sAnswerText = fixCKeditorText($sAnswerText);
                     // Now we insert the answers
                     $iInsertCount = Answer::model()->insertRecords(array('code' => $sCode, 'answer' => $sAnswerText, 'qid' => $iQuestionID, 'sortorder' => $iSortOrderID, 'language' => $sLanguage, 'assessment_value' => $iAssessmentValue, 'scale_id' => $iScaleID));
                     if (!$iInsertCount) {
                         Yii::app()->setFlashMessage($clang->gT("Failed to update answers"), 'error');
                     }
                 }
                 // foreach ($alllanguages as $language)
                 if (isset($sOldCode) && $sCode !== $sOldCode) {
                     Condition::model()->updateAll(array('value' => $sCode), 'cqid=:cqid AND value=:value', array(':cqid' => $iQuestionID, ':value' => $sOldCode));
                 }
             }
             // for ($sortorderid=0;$sortorderid<$maxcount;$sortorderid++)
         }
         //  for ($scale_id=0;
         LimeExpressionManager::UpgradeConditionsToRelevance($iSurveyID);
         if (!Yii::app()->request->getPost('bFullPOST')) {
             Yii::app()->setFlashMessage($clang->gT("Not all answer options were saved. This usually happens due to server limitations ( PHP setting max_input_vars) - please contact your system administrator."));
         } else {
             Yii::app()->session['flashmessage'] = $clang->gT("Answer options were successfully saved.");
         }
         LimeExpressionManager::SetDirtyFlag();
         if ($sDBOutput != '') {
             echo $sDBOutput;
         } else {
             $this->getController()->redirect(array('/admin/questions/sa/answeroptions/surveyid/' . $iSurveyID . '/gid/' . $iQuestionGroupID . '/qid/' . $iQuestionID));
         }
     }
     if ($sAction == "updatesubquestions" && Permission::model()->hasSurveyPermission($iSurveyID, 'surveycontent', 'update')) {
         Yii::app()->loadHelper('database');
         $aSurveyLanguages = Survey::model()->findByPk($iSurveyID)->additionalLanguages;
         $sBaseLanguage = Survey::model()->findByPk($iSurveyID)->language;
         array_unshift($aSurveyLanguages, $sBaseLanguage);
         $arQuestion = Question::model()->findByAttributes(array('qid' => $iQuestionID));
         $sQuestionType = $arQuestion['type'];
         // Checked
         $aQuestionTypeList = getQuestionTypeList('', 'array');
         $iScaleCount = $aQuestionTypeList[$sQuestionType]['subquestions'];
         $clang = $this->getController()->lang;
         // First delete any deleted ids
         $aDeletedQIDs = explode(' ', trim(Yii::app()->request->getPost('deletedqids')));
         LimeExpressionManager::RevertUpgradeConditionsToRelevance($iSurveyID);
         $aDeletedQIDs = array_unique($aDeletedQIDs, SORT_NUMERIC);
         foreach ($aDeletedQIDs as $iDeletedQID) {
             $iDeletedQID = (int) $iDeletedQID;
             if ($iDeletedQID > 0) {
                 // don't remove undefined
                 $iInsertCount = Question::model()->deleteAllByAttributes(array('qid' => $iDeletedQID));
                 if (!$iInsertCount) {
                     Yii::app()->setFlashMessage($clang->gT("Failed to delete answer"), 'error');
                 }
             }
         }
         //Determine ids by evaluating the hidden field
         $aRows = array();
         $aCodes = array();
         $aOldCodes = array();
         foreach ($_POST as $sPOSTKey => $sPOSTValue) {
             $sPOSTKey = explode('_', $sPOSTKey);
             if ($sPOSTKey[0] == 'answer') {
                 $aRows[$sPOSTKey[3]][$sPOSTKey[1]][$sPOSTKey[2]] = $sPOSTValue;
             }
             if ($sPOSTKey[0] == 'code') {
                 $aCodes[$sPOSTKey[2]][] = $sPOSTValue;
             }
             if ($sPOSTKey[0] == 'oldcode') {
                 $aOldCodes[$sPOSTKey[2]][] = $sPOSTValue;
             }
         }
         $aInsertQID = array();
         for ($iScaleID = 0; $iScaleID < $iScaleCount; $iScaleID++) {
             foreach ($aSurveyLanguages as $sLanguage) {
                 $iPosition = 0;
                 foreach ($aRows[$iScaleID][$sLanguage] as $subquestionkey => $subquestionvalue) {
                     if (substr($subquestionkey, 0, 3) != 'new') {
                         $oSubQuestion = Question::model()->find("qid=:qid AND language=:language", array(":qid" => $subquestionkey, ':language' => $sLanguage));
                         $oSubQuestion->question_order = $iPosition + 1;
                         $oSubQuestion->title = $aCodes[$iScaleID][$iPosition];
                         $oSubQuestion->question = $subquestionvalue;
                         $oSubQuestion->scale_id = $iScaleID;
                     } else {
                         if (!isset($aInsertQID[$iScaleID][$iPosition])) {
                             $oSubQuestion = new Question();
                             $oSubQuestion->sid = $iSurveyID;
                             $oSubQuestion->gid = $iQuestionGroupID;
                             $oSubQuestion->question_order = $iPosition + 1;
                             $oSubQuestion->title = $aCodes[$iScaleID][$iPosition];
                             $oSubQuestion->question = $subquestionvalue;
                             $oSubQuestion->parent_qid = $iQuestionID;
                             $oSubQuestion->language = $sLanguage;
                             $oSubQuestion->scale_id = $iScaleID;
                         } else {
                             $oSubQuestion = Question::model()->find("qid=:qid AND language=:language", array(":qid" => $aInsertQID[$iScaleID][$iPosition], ':language' => $sLanguage));
                             if (!$oSubQuestion) {
                                 $oSubQuestion = new Question();
                             }
                             $oSubQuestion->sid = $iSurveyID;
                             $oSubQuestion->qid = $aInsertQID[$iScaleID][$iPosition];
                             $oSubQuestion->gid = $iQuestionGroupID;
                             $oSubQuestion->question_order = $iPosition + 1;
                             $oSubQuestion->title = $aCodes[$iScaleID][$iPosition];
                             $oSubQuestion->question = $subquestionvalue;
                             $oSubQuestion->parent_qid = $iQuestionID;
                             $oSubQuestion->language = $sLanguage;
                             $oSubQuestion->scale_id = $iScaleID;
                         }
                     }
                     $bSubQuestionResult = $oSubQuestion->save();
                     if ($bSubQuestionResult) {
                         if (substr($subquestionkey, 0, 3) != 'new' && isset($aOldCodes[$iScaleID][$iPosition]) && $aCodes[$iScaleID][$iPosition] !== $aOldCodes[$iScaleID][$iPosition]) {
                             Condition::model()->updateAll(array('cfieldname' => '+' . $iSurveyID . 'X' . $iQuestionGroupID . 'X' . $iQuestionID . $aCodes[$iScaleID][$iPosition], 'value' => $aCodes[$iScaleID][$iPosition]), 'cqid=:cqid AND cfieldname=:cfieldname AND value=:value', array(':cqid' => $iQuestionID, ':cfieldname' => $iSurveyID . 'X' . $iQuestionGroupID . 'X' . $iQuestionID, ':value' => $aOldCodes[$iScaleID][$iPosition]));
                         }
                         if (!isset($aInsertQID[$iScaleID][$iPosition])) {
                             $aInsertQID[$iScaleID][$iPosition] = $oSubQuestion->qid;
                         }
                     } else {
                         $aErrors = $oSubQuestion->getErrors();
                         if (count($aErrors)) {
                             //$sErrorMessage=$clang->gT("Question could not be updated with this errors:");
                             foreach ($aErrors as $sAttribute => $aStringErrors) {
                                 foreach ($aStringErrors as $sStringErrors) {
                                     Yii::app()->setFlashMessage(sprintf($clang->gT("Error on %s for subquestion %s: %s"), $sAttribute, $aCodes[$iScaleID][$iPosition], $sStringErrors), 'error');
                                 }
                             }
                         } else {
                             Yii::app()->setFlashMessage(sprintf($clang->gT("Subquestions %s could not be updated."), $aCodes[$iScaleID][$iPosition]), 'error');
                         }
                     }
                     $iPosition++;
                 }
             }
         }
         LimeExpressionManager::UpgradeConditionsToRelevance($iSurveyID);
         // Do it only if there are no error ?
         if (!isset($aErrors) || !count($aErrors)) {
             if (!Yii::app()->request->getPost('bFullPOST')) {
                 Yii::app()->session['flashmessage'] = $clang->gT("Not all subquestions were saved. This usually happens due to server limitations ( PHP setting max_input_vars) - please contact your system administrator.");
             } else {
                 Yii::app()->session['flashmessage'] = $clang->gT("Subquestions were successfully saved.");
             }
         }
         //$action='editsubquestions';
         LimeExpressionManager::SetDirtyFlag();
         if ($sDBOutput != '') {
             echo $sDBOutput;
         } else {
             $this->getController()->redirect(array('/admin/questions/sa/subquestions/surveyid/' . $iSurveyID . '/gid/' . $iQuestionGroupID . '/qid/' . $iQuestionID));
         }
     }
     if (in_array($sAction, array('insertquestion', 'copyquestion')) && Permission::model()->hasSurveyPermission($iSurveyID, 'surveycontent', 'create')) {
         $sBaseLanguage = Survey::model()->findByPk($iSurveyID)->language;
         if (strlen(Yii::app()->request->getPost('title')) < 1) {
             Yii::app()->setFlashMessage($clang->gT("The question could not be added. You must enter at least a question code."), 'error');
         } else {
             if (Yii::app()->request->getPost('questionposition', "") != "") {
                 $iQuestionOrder = intval(Yii::app()->request->getPost('questionposition'));
                 //Need to renumber all questions on or after this
                 $sQuery = "UPDATE {{questions}} SET question_order=question_order+1 WHERE gid=:gid AND question_order >= :order";
                 Yii::app()->db->createCommand($sQuery)->bindValues(array(':gid' => $iQuestionGroupID, ':order' => $iQuestionOrder))->query();
             } else {
                 $iQuestionOrder = getMaxQuestionOrder($iQuestionGroupID, $iSurveyID);
                 $iQuestionOrder++;
             }
             $_POST['title'] = html_entity_decode(Yii::app()->request->getPost('title'), ENT_QUOTES, "UTF-8");
             $_POST['question_' . $sBaseLanguage] = html_entity_decode(Yii::app()->request->getPost('question_' . $sBaseLanguage), ENT_QUOTES, "UTF-8");
             $_POST['help_' . $sBaseLanguage] = html_entity_decode(Yii::app()->request->getPost('help_' . $sBaseLanguage), ENT_QUOTES, "UTF-8");
             $_POST['title'] = fixCKeditorText(Yii::app()->request->getPost('title'));
             $_POST['question_' . $sBaseLanguage] = fixCKeditorText(Yii::app()->request->getPost('question_' . $sBaseLanguage));
             $_POST['help_' . $sBaseLanguage] = fixCKeditorText(Yii::app()->request->getPost('help_' . $sBaseLanguage));
             $iQuestionID = 0;
             $oQuestion = new Question();
             $oQuestion->sid = $iSurveyID;
             $oQuestion->gid = $iQuestionGroupID;
             $oQuestion->type = Yii::app()->request->getPost('type');
             $oQuestion->title = Yii::app()->request->getPost('title');
             $oQuestion->question = Yii::app()->request->getPost('question_' . $sBaseLanguage);
             $oQuestion->preg = Yii::app()->request->getPost('preg');
             $oQuestion->help = Yii::app()->request->getPost('help_' . $sBaseLanguage);
             $oQuestion->other = Yii::app()->request->getPost('other');
             $oQuestion->mandatory = Yii::app()->request->getPost('mandatory');
             $oQuestion->relevance = Yii::app()->request->getPost('relevance');
             $oQuestion->question_order = $iQuestionOrder;
             $oQuestion->language = $sBaseLanguage;
             $oQuestion->save();
             if ($oQuestion) {
                 $iQuestionID = $oQuestion->qid;
             }
             $aErrors = $oQuestion->getErrors();
             if (count($aErrors)) {
                 foreach ($aErrors as $sAttribute => $aStringErrors) {
                     foreach ($aStringErrors as $sStringErrors) {
                         Yii::app()->setFlashMessage(sprintf($clang->gT("Question could not be created with error on %s: %s"), $sAttribute, $sStringErrors), 'error');
                     }
                 }
             }
             // Add other languages
             if ($iQuestionID) {
                 $addlangs = Survey::model()->findByPk($iSurveyID)->additionalLanguages;
                 foreach ($addlangs as $alang) {
                     if ($alang != "") {
                         $langqid = 0;
                         $oQuestion = new Question();
                         $oQuestion->qid = $iQuestionID;
                         $oQuestion->sid = $iSurveyID;
                         $oQuestion->gid = $iQuestionGroupID;
                         $oQuestion->type = Yii::app()->request->getPost('type');
                         $oQuestion->title = Yii::app()->request->getPost('title');
                         $oQuestion->question = Yii::app()->request->getPost('question_' . $alang);
                         $oQuestion->preg = Yii::app()->request->getPost('preg');
                         $oQuestion->help = Yii::app()->request->getPost('help_' . $alang);
                         $oQuestion->other = Yii::app()->request->getPost('other');
                         $oQuestion->mandatory = Yii::app()->request->getPost('mandatory');
                         $oQuestion->relevance = Yii::app()->request->getPost('relevance');
                         $oQuestion->question_order = $iQuestionOrder;
                         $oQuestion->language = $alang;
                         switchMSSQLIdentityInsert('questions', true);
                         // Not sure for this one ?
                         $oQuestion->save();
                         switchMSSQLIdentityInsert('questions', false);
                         if ($oQuestion) {
                             $langqid = $oQuestion->qid;
                         }
                         $aErrors = $oQuestion->getErrors();
                         if (count($aErrors)) {
                             foreach ($aErrors as $sAttribute => $aStringErrors) {
                                 foreach ($aStringErrors as $sStringErrors) {
                                     Yii::app()->setFlashMessage(sprintf($clang->gT("Question in language %s could not be created with error on %s: %s"), $alang, $sAttribute, $sStringErrors), 'error');
                                 }
                             }
                         }
                         #                            if (!$langqid)
                         #                            {
                         #                                Yii::app()->setFlashMessage($clang->gT("Question in language %s could not be created."),'error');
                         #                            }
                     }
                 }
             }
             if (!$iQuestionID) {
                 Yii::app()->setFlashMessage($clang->gT("Question could not be created."), 'error');
             } else {
                 if ($sAction == 'copyquestion') {
                     if (returnGlobal('copysubquestions') == "Y") {
                         $aSQIDMappings = array();
                         $r1 = Question::model()->getSubQuestions(returnGlobal('oldqid'));
                         while ($qr1 = $r1->read()) {
                             $qr1['parent_qid'] = $iQuestionID;
                             if (isset($aSQIDMappings[$qr1['qid']])) {
                                 $qr1['qid'] = $aSQIDMappings[$qr1['qid']];
                             } else {
                                 $oldqid = $qr1['qid'];
                                 unset($qr1['qid']);
                             }
                             $qr1['gid'] = $iQuestionGroupID;
                             $iInsertID = Question::model()->insertRecords($qr1);
                             if (!isset($qr1['qid'])) {
                                 $aSQIDMappings[$oldqid] = $iInsertID;
                             }
                         }
                     }
                     if (returnGlobal('copyanswers') == "Y") {
                         $r1 = Answer::model()->getAnswers(returnGlobal('oldqid'));
                         while ($qr1 = $r1->read()) {
                             Answer::model()->insertRecords(array('qid' => $iQuestionID, 'code' => $qr1['code'], 'answer' => $qr1['answer'], 'assessment_value' => $qr1['assessment_value'], 'sortorder' => $qr1['sortorder'], 'language' => $qr1['language'], 'scale_id' => $qr1['scale_id']));
                         }
                     }
                     if (returnGlobal('copyattributes') == "Y") {
                         $oOldAttributes = QuestionAttribute::model()->findAll("qid=:qid", array("qid" => returnGlobal('oldqid')));
                         foreach ($oOldAttributes as $oOldAttribute) {
                             $attribute = new QuestionAttribute();
                             $attribute->qid = $iQuestionID;
                             $attribute->value = $oOldAttribute->value;
                             $attribute->attribute = $oOldAttribute->attribute;
                             $attribute->language = $oOldAttribute->language;
                             $attribute->save();
                         }
                     }
                 } else {
                     $qattributes = questionAttributes();
                     $validAttributes = $qattributes[Yii::app()->request->getPost('type')];
                     $aLanguages = array_merge(array(Survey::model()->findByPk($iSurveyID)->language), Survey::model()->findByPk($iSurveyID)->additionalLanguages);
                     foreach ($validAttributes as $validAttribute) {
                         if ($validAttribute['i18n']) {
                             foreach ($aLanguages as $sLanguage) {
                                 $value = Yii::app()->request->getPost($validAttribute['name'] . '_' . $sLanguage);
                                 $iInsertCount = QuestionAttribute::model()->findAllByAttributes(array('attribute' => $validAttribute['name'], 'qid' => $iQuestionID, 'language' => $sLanguage));
                                 if (count($iInsertCount) > 0) {
                                     if ($value != '') {
                                         QuestionAttribute::model()->updateAll(array('value' => $value), 'attribute=:attribute AND qid=:qid AND language=:language', array(':attribute' => $validAttribute['name'], ':qid' => $iQuestionID, ':language' => $sLanguage));
                                     } else {
                                         QuestionAttribute::model()->deleteAll('attribute=:attribute AND qid=:qid AND language=:language', array(':attribute' => $validAttribute['name'], ':qid' => $iQuestionID, ':language' => $sLanguage));
                                     }
                                 } elseif ($value != '') {
                                     $attribute = new QuestionAttribute();
                                     $attribute->qid = $iQuestionID;
                                     $attribute->value = $value;
                                     $attribute->attribute = $validAttribute['name'];
                                     $attribute->language = $sLanguage;
                                     $attribute->save();
                                 }
                             }
                         } else {
                             $value = Yii::app()->request->getPost($validAttribute['name']);
                             if ($validAttribute['name'] == 'multiflexible_step' && trim($value) != '') {
                                 $value = floatval($value);
                                 if ($value == 0) {
                                     $value = 1;
                                 }
                             }
                             $iInsertCount = QuestionAttribute::model()->findAllByAttributes(array('attribute' => $validAttribute['name'], 'qid' => $iQuestionID));
                             if (count($iInsertCount) > 0) {
                                 if ($value != $validAttribute['default'] && trim($value) != "") {
                                     QuestionAttribute::model()->updateAll(array('value' => $value), 'attribute=:attribute AND qid=:qid', array(':attribute' => $validAttribute['name'], ':qid' => $iQuestionID));
                                 } else {
                                     QuestionAttribute::model()->deleteAll('attribute=:attribute AND qid=:qid', array(':attribute' => $validAttribute['name'], ':qid' => $iQuestionID));
                                 }
                             } elseif ($value != $validAttribute['default'] && trim($value) != "") {
                                 $attribute = new QuestionAttribute();
                                 $attribute->qid = $iQuestionID;
                                 $attribute->value = $value;
                                 $attribute->attribute = $validAttribute['name'];
                                 $attribute->save();
                             }
                         }
                     }
                 }
                 Question::model()->updateQuestionOrder($iQuestionGroupID, $iSurveyID);
                 Yii::app()->session['flashmessage'] = $clang->gT("Question was successfully added.");
             }
         }
         LimeExpressionManager::SetDirtyFlag();
         // so refreshes syntax highlighting
         if ($sDBOutput != '') {
             echo $sDBOutput;
         } else {
             $this->getController()->redirect(array('admin/survey/sa/view/surveyid/' . $iSurveyID . '/gid/' . $iQuestionGroupID . '/qid/' . $iQuestionID));
         }
     }
     if ($sAction == "updatequestion" && Permission::model()->hasSurveyPermission($iSurveyID, 'surveycontent', 'update')) {
         LimeExpressionManager::RevertUpgradeConditionsToRelevance($iSurveyID);
         $cqr = Question::model()->findByAttributes(array('qid' => $iQuestionID));
         $oldtype = $cqr['type'];
         $oldgid = $cqr['gid'];
         // Remove invalid question attributes on saving
         $qattributes = questionAttributes();
         $criteria = new CDbCriteria();
         $criteria->compare('qid', $iQuestionID);
         if (isset($qattributes[Yii::app()->request->getPost('type')])) {
             $validAttributes = $qattributes[Yii::app()->request->getPost('type')];
             foreach ($validAttributes as $validAttribute) {
                 $criteria->compare('attribute', '<>' . $validAttribute['name']);
             }
         }
         QuestionAttribute::model()->deleteAll($criteria);
         $aLanguages = array_merge(array(Survey::model()->findByPk($iSurveyID)->language), Survey::model()->findByPk($iSurveyID)->additionalLanguages);
         //now save all valid attributes
         $validAttributes = $qattributes[Yii::app()->request->getPost('type')];
         foreach ($validAttributes as $validAttribute) {
             if ($validAttribute['i18n']) {
                 foreach ($aLanguages as $sLanguage) {
                     // TODO sanitise XSS
                     $value = Yii::app()->request->getPost($validAttribute['name'] . '_' . $sLanguage);
                     $iInsertCount = QuestionAttribute::model()->findAllByAttributes(array('attribute' => $validAttribute['name'], 'qid' => $iQuestionID, 'language' => $sLanguage));
                     if (count($iInsertCount) > 0) {
                         if ($value != '') {
                             QuestionAttribute::model()->updateAll(array('value' => $value), 'attribute=:attribute AND qid=:qid AND language=:language', array(':attribute' => $validAttribute['name'], ':qid' => $iQuestionID, ':language' => $sLanguage));
                         } else {
                             QuestionAttribute::model()->deleteAll('attribute=:attribute AND qid=:qid AND language=:language', array(':attribute' => $validAttribute['name'], ':qid' => $iQuestionID, ':language' => $sLanguage));
                         }
                     } elseif ($value != '') {
                         $attribute = new QuestionAttribute();
                         $attribute->qid = $iQuestionID;
                         $attribute->value = $value;
                         $attribute->attribute = $validAttribute['name'];
                         $attribute->language = $sLanguage;
                         $attribute->save();
                     }
                 }
             } else {
                 $value = Yii::app()->request->getPost($validAttribute['name']);
                 if ($validAttribute['name'] == 'multiflexible_step' && trim($value) != '') {
                     $value = floatval($value);
                     if ($value == 0) {
                         $value = 1;
                     }
                 }
                 $iInsertCount = QuestionAttribute::model()->findAllByAttributes(array('attribute' => $validAttribute['name'], 'qid' => $iQuestionID));
                 if (count($iInsertCount) > 0) {
                     if ($value != $validAttribute['default'] && trim($value) != "") {
                         QuestionAttribute::model()->updateAll(array('value' => $value), 'attribute=:attribute AND qid=:qid', array(':attribute' => $validAttribute['name'], ':qid' => $iQuestionID));
                     } else {
                         QuestionAttribute::model()->deleteAll('attribute=:attribute AND qid=:qid', array(':attribute' => $validAttribute['name'], ':qid' => $iQuestionID));
                     }
                 } elseif ($value != $validAttribute['default'] && trim($value) != "") {
                     $attribute = new QuestionAttribute();
                     $attribute->qid = $iQuestionID;
                     $attribute->value = $value;
                     $attribute->attribute = $validAttribute['name'];
                     $attribute->save();
                 }
             }
         }
         $aQuestionTypeList = getQuestionTypeList('', 'array');
         // These are the questions types that have no answers and therefore we delete the answer in that case
         $iAnswerScales = $aQuestionTypeList[Yii::app()->request->getPost('type')]['answerscales'];
         $iSubquestionScales = $aQuestionTypeList[Yii::app()->request->getPost('type')]['subquestions'];
         // These are the questions types that have the other option therefore we set everything else to 'No Other'
         if (Yii::app()->request->getPost('type') != "L" && Yii::app()->request->getPost('type') != "!" && Yii::app()->request->getPost('type') != "P" && Yii::app()->request->getPost('type') != "M") {
             $_POST['other'] = 'N';
         }
         // These are the questions types that have no validation - so zap it accordingly
         if (Yii::app()->request->getPost('type') == "!" || Yii::app()->request->getPost('type') == "L" || Yii::app()->request->getPost('type') == "M" || Yii::app()->request->getPost('type') == "P" || Yii::app()->request->getPost('type') == "F" || Yii::app()->request->getPost('type') == "H" || Yii::app()->request->getPost('type') == "X" || Yii::app()->request->getPost('type') == "") {
             $_POST['preg'] = '';
         }
         // These are the questions types that have no mandatory property - so zap it accordingly
         if (Yii::app()->request->getPost('type') == "X" || Yii::app()->request->getPost('type') == "|") {
             $_POST['mandatory'] = 'N';
         }
         if ($oldtype != Yii::app()->request->getPost('type')) {
             // TMSW Condition->Relevance:  Do similar check via EM, but do allow such a change since will be easier to modify relevance
             //Make sure there are no conditions based on this question, since we are changing the type
             $ccresult = Condition::model()->findAllByAttributes(array('cqid' => $iQuestionID));
             $cccount = count($ccresult);
             foreach ($ccresult as $ccr) {
                 $qidarray[] = $ccr['qid'];
             }
             if (isset($qidarray) && $qidarray) {
                 $qidlist = implode(", ", $qidarray);
             }
         }
         if (isset($cccount) && $cccount) {
             Yii::app()->setFlashMessage($clang->gT("Question could not be updated. There are conditions for other questions that rely on the answers to this question and changing the type will cause problems. You must delete these conditions  before you can change the type of this question."), 'error');
         } else {
             if (isset($iQuestionGroupID) && $iQuestionGroupID != "") {
                 //                    $array_result=checkMoveQuestionConstraintsForConditions(sanitize_int($surveyid),sanitize_int($qid), sanitize_int($gid));
                 //                    // If there is no blocking conditions that could prevent this move
                 //
                 //                    if (is_null($array_result['notAbove']) && is_null($array_result['notBelow']))
                 //                    {
                 $aSurveyLanguages = Survey::model()->findByPk($iSurveyID)->additionalLanguages;
                 $sBaseLanguage = Survey::model()->findByPk($iSurveyID)->language;
                 array_push($aSurveyLanguages, $sBaseLanguage);
                 if ($bXSSFilter) {
                     $_POST['title'] = $oPurifier->purify($_POST['title']);
                 } else {
                     $_POST['title'] = html_entity_decode(Yii::app()->request->getPost('title'), ENT_QUOTES, "UTF-8");
                 }
                 // Fix bug with FCKEditor saving strange BR types
                 $_POST['title'] = fixCKeditorText(Yii::app()->request->getPost('title'));
                 foreach ($aSurveyLanguages as $qlang) {
                     if ($bXSSFilter) {
                         $_POST['question_' . $qlang] = $oPurifier->purify($_POST['question_' . $qlang]);
                         $_POST['help_' . $qlang] = $oPurifier->purify($_POST['help_' . $qlang]);
                     } else {
                         $_POST['question_' . $qlang] = html_entity_decode(Yii::app()->request->getPost('question_' . $qlang), ENT_QUOTES, "UTF-8");
                         $_POST['help_' . $qlang] = html_entity_decode(Yii::app()->request->getPost('help_' . $qlang), ENT_QUOTES, "UTF-8");
                     }
                     // Fix bug with FCKEditor saving strange BR types : in rules ?
                     $_POST['question_' . $qlang] = fixCKeditorText(Yii::app()->request->getPost('question_' . $qlang));
                     $_POST['help_' . $qlang] = fixCKeditorText(Yii::app()->request->getPost('help_' . $qlang));
                     if (isset($qlang) && $qlang != "") {
                         $udata = array('type' => Yii::app()->request->getPost('type'), 'title' => Yii::app()->request->getPost('title'), 'question' => Yii::app()->request->getPost('question_' . $qlang), 'preg' => Yii::app()->request->getPost('preg'), 'help' => Yii::app()->request->getPost('help_' . $qlang), 'gid' => $iQuestionGroupID, 'other' => Yii::app()->request->getPost('other'), 'mandatory' => Yii::app()->request->getPost('mandatory'), 'relevance' => Yii::app()->request->getPost('relevance'));
                         if ($oldgid != $iQuestionGroupID) {
                             if (getGroupOrder($iSurveyID, $oldgid) > getGroupOrder($iSurveyID, $iQuestionGroupID)) {
                                 // TMSW Condition->Relevance:  What is needed here?
                                 // Moving question to a 'upper' group
                                 // insert question at the end of the destination group
                                 // this prevent breaking conditions if the target qid is in the dest group
                                 $insertorder = getMaxQuestionOrder($iQuestionGroupID, $iSurveyID) + 1;
                                 $udata = array_merge($udata, array('question_order' => $insertorder));
                             } else {
                                 // Moving question to a 'lower' group
                                 // insert question at the beginning of the destination group
                                 shiftOrderQuestions($iSurveyID, $iQuestionGroupID, 1);
                                 // makes 1 spare room for new question at top of dest group
                                 $udata = array_merge($udata, array('question_order' => 0));
                             }
                         }
                         //$condn = array('sid' => $surveyid, 'qid' => $qid, 'language' => $qlang);
                         $oQuestion = Question::model()->findByPk(array("qid" => $iQuestionID, 'language' => $qlang));
                         foreach ($udata as $k => $v) {
                             $oQuestion->{$k} = $v;
                         }
                         $uqresult = $oQuestion->save();
                         //($uqquery); // or safeDie ("Error Update Question: ".$uqquery."<br />");  // Checked)
                         if (!$uqresult) {
                             $bOnError = true;
                             $aErrors = $oQuestion->getErrors();
                             if (count($aErrors)) {
                                 foreach ($aErrors as $sAttribute => $aStringErrors) {
                                     foreach ($aStringErrors as $sStringErrors) {
                                         Yii::app()->setFlashMessage(sprintf($clang->gT("Question could not be updated with error on %s: %s"), $sAttribute, $sStringErrors), 'error');
                                     }
                                 }
                             } else {
                                 Yii::app()->setFlashMessage($clang->gT("Question could not be updated."), 'error');
                             }
                         }
                     }
                 }
                 // Update the group ID on subquestions, too
                 if ($oldgid != $iQuestionGroupID) {
                     Question::model()->updateAll(array('gid' => $iQuestionGroupID), 'qid=:qid and parent_qid>0', array(':qid' => $iQuestionID));
                     // if the group has changed then fix the sortorder of old and new group
                     Question::model()->updateQuestionOrder($oldgid, $iSurveyID);
                     Question::model()->updateQuestionOrder($iQuestionGroupID, $iSurveyID);
                     // If some questions have conditions set on this question's answers
                     // then change the cfieldname accordingly
                     fixMovedQuestionConditions($iQuestionID, $oldgid, $iQuestionGroupID);
                 }
                 if ($oldtype != Yii::app()->request->getPost('type')) {
                     Question::model()->updateAll(array('type' => Yii::app()->request->getPost('type')), 'parent_qid=:qid', array(':qid' => $iQuestionID));
                 }
                 Answer::model()->deleteAllByAttributes(array('qid' => $iQuestionID), 'scale_id >= :scale_id', array(':scale_id' => $iAnswerScales));
                 // Remove old subquestion scales
                 Question::model()->deleteAllByAttributes(array('parent_qid' => $iQuestionID), 'scale_id >= :scale_id', array(':scale_id' => $iSubquestionScales));
                 if (!isset($bOnError) || !$bOnError) {
                     // This really a quick hack and need a better system
                     Yii::app()->setFlashMessage($clang->gT("Question was successfully saved."));
                 }
                 //                    }
                 //                    else
                 //                    {
                 //
                 //                        // There are conditions constraints: alert the user
                 //                        $errormsg="";
                 //                        if (!is_null($array_result['notAbove']))
                 //                        {
                 //                            $errormsg.=$clang->gT("This question relies on other question's answers and can't be moved above groupId:","js")
                 //                            . " " . $array_result['notAbove'][0][0] . " " . $clang->gT("in position","js")." ".$array_result['notAbove'][0][1]."\\n"
                 //                            . $clang->gT("See conditions:")."\\n";
                 //
                 //                            foreach ($array_result['notAbove'] as $notAboveCond)
                 //                            {
                 //                                $errormsg.="- cid:". $notAboveCond[3]."\\n";
                 //                            }
                 //
                 //                        }
                 //                        if (!is_null($array_result['notBelow']))
                 //                        {
                 //                            $errormsg.=$clang->gT("Some questions rely on this question's answers. You can't move this question below groupId:","js")
                 //                            . " " . $array_result['notBelow'][0][0] . " " . $clang->gT("in position","js")." ".$array_result['notBelow'][0][1]."\\n"
                 //                            . $clang->gT("See conditions:")."\\n";
                 //
                 //                            foreach ($array_result['notBelow'] as $notBelowCond)
                 //                            {
                 //                                $errormsg.="- cid:". $notBelowCond[3]."\\n";
                 //                            }
                 //                        }
                 //
                 //                        $databaseoutput .= "<script type=\"text/javascript\">\n<!--\n alert(\"$errormsg\")\n //-->\n</script>\n";
                 //                        $gid= $oldgid; // group move impossible ==> keep display on oldgid
                 //                    }
             } else {
                 Yii::app()->setFlashMessage($clang->gT("Question could not be updated"), 'error');
             }
         }
         LimeExpressionManager::UpgradeConditionsToRelevance($iSurveyID);
         if ($sDBOutput != '') {
             echo $sDBOutput;
         } else {
             if (Yii::app()->request->getPost('redirection') == "edit") {
                 $this->getController()->redirect(array('admin/questions/sa/editquestion/surveyid/' . $iSurveyID . '/gid/' . $iQuestionGroupID . '/qid/' . $iQuestionID));
             } else {
                 $this->getController()->redirect(array('admin/survey/sa/view/surveyid/' . $iSurveyID . '/gid/' . $iQuestionGroupID . '/qid/' . $iQuestionID));
             }
         }
     }
     if ($sAction == "updatesurveylocalesettings" && Permission::model()->hasSurveyPermission($iSurveyID, 'surveylocale', 'update')) {
         $languagelist = Survey::model()->findByPk($iSurveyID)->additionalLanguages;
         $languagelist[] = Survey::model()->findByPk($iSurveyID)->language;
         Yii::app()->loadHelper('database');
         foreach ($languagelist as $langname) {
             if ($langname) {
                 $url = Yii::app()->request->getPost('url_' . $langname);
                 if ($url == 'http://') {
                     $url = "";
                 }
                 $short_title = html_entity_decode(Yii::app()->request->getPost('short_title_' . $langname), ENT_QUOTES, "UTF-8");
                 $description = html_entity_decode(Yii::app()->request->getPost('description_' . $langname), ENT_QUOTES, "UTF-8");
                 $welcome = html_entity_decode(Yii::app()->request->getPost('welcome_' . $langname), ENT_QUOTES, "UTF-8");
                 $endtext = html_entity_decode(Yii::app()->request->getPost('endtext_' . $langname), ENT_QUOTES, "UTF-8");
                 $sURLDescription = html_entity_decode(Yii::app()->request->getPost('urldescrip_' . $langname), ENT_QUOTES, "UTF-8");
                 $sURL = html_entity_decode(Yii::app()->request->getPost('url_' . $langname), ENT_QUOTES, "UTF-8");
                 // Fix bug with FCKEditor saving strange BR types
                 $short_title = Yii::app()->request->getPost('short_title_' . $langname);
                 $description = Yii::app()->request->getPost('description_' . $langname);
                 $welcome = Yii::app()->request->getPost('welcome_' . $langname);
                 $endtext = Yii::app()->request->getPost('endtext_' . $langname);
                 $short_title = fixCKeditorText($short_title);
                 $description = fixCKeditorText($description);
                 $welcome = fixCKeditorText($welcome);
                 $endtext = fixCKeditorText($endtext);
                 $data = array('surveyls_title' => $short_title, 'surveyls_description' => $description, 'surveyls_welcometext' => $welcome, 'surveyls_endtext' => $endtext, 'surveyls_url' => $sURL, 'surveyls_urldescription' => $sURLDescription, 'surveyls_dateformat' => Yii::app()->request->getPost('dateformat_' . $langname), 'surveyls_numberformat' => Yii::app()->request->getPost('numberformat_' . $langname));
                 $SurveyLanguageSetting = SurveyLanguageSetting::model()->findByPk(array('surveyls_survey_id' => $iSurveyID, 'surveyls_language' => $langname));
                 $SurveyLanguageSetting->attributes = $data;
                 $SurveyLanguageSetting->save();
                 // save the change to database
             }
         }
         Yii::app()->session['flashmessage'] = $clang->gT("Survey text elements successfully saved.");
         if ($sDBOutput != '') {
             echo $sDBOutput;
         } else {
             $this->getController()->redirect(array('admin/survey/sa/view/surveyid/' . $iSurveyID));
         }
     }
     if (($sAction == "updatesurveysettingsandeditlocalesettings" || $sAction == "updatesurveysettings") && Permission::model()->hasSurveyPermission($iSurveyID, 'surveysettings', 'update')) {
         // Save plugin settings.
         $pluginSettings = App()->request->getPost('plugin', array());
         foreach ($pluginSettings as $plugin => $settings) {
             $settingsEvent = new PluginEvent('newSurveySettings');
             $settingsEvent->set('settings', $settings);
             $settingsEvent->set('survey', $iSurveyID);
             App()->getPluginManager()->dispatchEvent($settingsEvent, $plugin);
         }
         Yii::app()->loadHelper('surveytranslator');
         Yii::app()->loadHelper('database');
         $formatdata = getDateFormatData(Yii::app()->session['dateformat']);
         $expires = $_POST['expires'];
         if (trim($expires) == "") {
             $expires = null;
         } else {
             Yii::app()->loadLibrary('Date_Time_Converter');
             $datetimeobj = new date_time_converter($expires, $formatdata['phpdate'] . ' H:i');
             //new Date_Time_Converter($expires, $formatdata['phpdate'].' H:i');
             $expires = $datetimeobj->convert("Y-m-d H:i:s");
         }
         $startdate = $_POST['startdate'];
         if (trim($startdate) == "") {
             $startdate = null;
         } else {
             Yii::app()->loadLibrary('Date_Time_Converter');
             $datetimeobj = new date_time_converter($startdate, $formatdata['phpdate'] . ' H:i');
             //new Date_Time_Converter($startdate,$formatdata['phpdate'].' H:i');
             $startdate = $datetimeobj->convert("Y-m-d H:i:s");
         }
         //make sure only numbers are passed within the $_POST variable
         $tokenlength = (int) $_POST['tokenlength'];
         //token length has to be at least 5, otherwise set it to default (15)
         if ($tokenlength < 5) {
             $tokenlength = 15;
         }
         if ($tokenlength > 36) {
             $tokenlength = 36;
         }
         cleanLanguagesFromSurvey($iSurveyID, Yii::app()->request->getPost('languageids'));
         fixLanguageConsistency($iSurveyID, Yii::app()->request->getPost('languageids'));
         $template = Yii::app()->request->getPost('template');
         if (!Permission::model()->hasGlobalPermission('superadmin', 'read') && !Permission::model()->hasGlobalPermission('templates', 'read') && !hasTemplateManageRights(Yii::app()->session['loginID'], $template)) {
             $template = "default";
         }
         $aURLParams = json_decode(Yii::app()->request->getPost('allurlparams'), true);
         SurveyURLParameter::model()->deleteAllByAttributes(array('sid' => $iSurveyID));
         if (isset($aURLParams)) {
             foreach ($aURLParams as $aURLParam) {
                 $aURLParam['parameter'] = trim($aURLParam['parameter']);
                 if ($aURLParam['parameter'] == '' || !preg_match('/^[a-zA-Z_][a-zA-Z0-9_]*$/', $aURLParam['parameter']) || $aURLParam['parameter'] == 'sid' || $aURLParam['parameter'] == 'newtest' || $aURLParam['parameter'] == 'token' || $aURLParam['parameter'] == 'lang') {
                     continue;
                     // this parameter name seems to be invalid - just ignore it
                 }
                 unset($aURLParam['act']);
                 unset($aURLParam['title']);
                 unset($aURLParam['id']);
                 if ($aURLParam['targetqid'] == '') {
                     $aURLParam['targetqid'] = NULL;
                 }
                 if ($aURLParam['targetsqid'] == '') {
                     $aURLParam['targetsqid'] = NULL;
                 }
                 $aURLParam['sid'] = $iSurveyID;
                 $param = new SurveyURLParameter();
                 foreach ($aURLParam as $k => $v) {
                     $param->{$k} = $v;
                 }
                 $param->save();
             }
         }
         $updatearray = array('admin' => Yii::app()->request->getPost('admin'), 'expires' => $expires, 'startdate' => $startdate, 'anonymized' => Yii::app()->request->getPost('anonymized'), 'faxto' => Yii::app()->request->getPost('faxto'), 'format' => Yii::app()->request->getPost('format'), 'savetimings' => Yii::app()->request->getPost('savetimings'), 'template' => $template, 'assessments' => Yii::app()->request->getPost('assessments'), 'language' => Yii::app()->request->getPost('language'), 'additional_languages' => Yii::app()->request->getPost('languageids'), 'datestamp' => Yii::app()->request->getPost('datestamp'), 'ipaddr' => Yii::app()->request->getPost('ipaddr'), 'refurl' => Yii::app()->request->getPost('refurl'), 'publicgraphs' => Yii::app()->request->getPost('publicgraphs'), 'usecookie' => Yii::app()->request->getPost('usecookie'), 'allowregister' => Yii::app()->request->getPost('allowregister'), 'allowsave' => Yii::app()->request->getPost('allowsave'), 'navigationdelay' => Yii::app()->request->getPost('navigationdelay'), 'printanswers' => Yii::app()->request->getPost('printanswers'), 'publicstatistics' => Yii::app()->request->getPost('publicstatistics'), 'autoredirect' => Yii::app()->request->getPost('autoredirect'), 'showxquestions' => Yii::app()->request->getPost('showxquestions'), 'showgroupinfo' => Yii::app()->request->getPost('showgroupinfo'), 'showqnumcode' => Yii::app()->request->getPost('showqnumcode'), 'shownoanswer' => Yii::app()->request->getPost('shownoanswer'), 'showwelcome' => Yii::app()->request->getPost('showwelcome'), 'allowprev' => Yii::app()->request->getPost('allowprev'), 'questionindex' => Yii::app()->request->getPost('questionindex'), 'nokeyboard' => Yii::app()->request->getPost('nokeyboard'), 'showprogress' => Yii::app()->request->getPost('showprogress'), 'listpublic' => Yii::app()->request->getPost('public'), 'htmlemail' => Yii::app()->request->getPost('htmlemail'), 'sendconfirmation' => Yii::app()->request->getPost('sendconfirmation'), 'tokenanswerspersistence' => Yii::app()->request->getPost('tokenanswerspersistence'), 'alloweditaftercompletion' => Yii::app()->request->getPost('alloweditaftercompletion'), 'usecaptcha' => Yii::app()->request->getPost('usecaptcha'), 'emailresponseto' => trim(Yii::app()->request->getPost('emailresponseto')), 'emailnotificationto' => trim(Yii::app()->request->getPost('emailnotificationto')), 'googleanalyticsapikey' => trim(Yii::app()->request->getPost('googleanalyticsapikey')), 'googleanalyticsstyle' => trim(Yii::app()->request->getPost('googleanalyticsstyle')), 'tokenlength' => $tokenlength);
         $warning = '';
         // make sure we only update admin email if it is valid
         if (Yii::app()->request->getPost('adminemail', '') == '' || validateEmailAddress(Yii::app()->request->getPost('adminemail'))) {
             $updatearray['adminemail'] = Yii::app()->request->getPost('adminemail');
         } else {
             $warning .= $clang->gT("Warning! Notification email was not updated because it was not valid.") . '<br/>';
         }
         // make sure we only update bounce email if it is valid
         if (Yii::app()->request->getPost('bounce_email', '') == '' || validateEmailAddress(Yii::app()->request->getPost('bounce_email'))) {
             $updatearray['bounce_email'] = Yii::app()->request->getPost('bounce_email');
         } else {
             $warning .= $clang->gT("Warning! Bounce email was not updated because it was not valid.") . '<br/>';
         }
         // use model
         $Survey = Survey::model()->findByPk($iSurveyID);
         foreach ($updatearray as $k => $v) {
             $Survey->{$k} = $v;
         }
         $Survey->save();
         #            Survey::model()->updateByPk($surveyid, $updatearray);
         $sqlstring = "surveyls_survey_id=:sid AND surveyls_language <> :base ";
         $params = array(':sid' => $iSurveyID, ':base' => Survey::model()->findByPk($iSurveyID)->language);
         $i = 100000;
         foreach (Survey::model()->findByPk($iSurveyID)->additionalLanguages as $langname) {
             if ($langname) {
                 $sqlstring .= "AND surveyls_language <> :{$i} ";
                 $params[':' . $i] = $langname;
             }
             $i++;
         }
         SurveyLanguageSetting::model()->deleteAll($sqlstring, $params);
         $usresult = true;
         foreach (Survey::model()->findByPk($iSurveyID)->additionalLanguages as $langname) {
             if ($langname) {
                 $oLanguageSettings = SurveyLanguageSetting::model()->find('surveyls_survey_id=:surveyid AND surveyls_language=:langname', array(':surveyid' => $iSurveyID, ':langname' => $langname));
                 if (!$oLanguageSettings) {
                     $oLanguageSettings = new SurveyLanguageSetting();
                     $languagedetails = getLanguageDetails($langname);
                     $insertdata = array('surveyls_survey_id' => $iSurveyID, 'surveyls_language' => $langname, 'surveyls_title' => '', 'surveyls_dateformat' => $languagedetails['dateformat']);
                     foreach ($insertdata as $k => $v) {
                         $oLanguageSettings->{$k} = $v;
                     }
                     $usresult = $oLanguageSettings->save();
                 }
             }
         }
         if ($usresult) {
             Yii::app()->session['flashmessage'] = $warning . $clang->gT("Survey settings were successfully saved.");
         } else {
             Yii::app()->session['flashmessage'] = $clang->gT("Error:") . '<br>' . $clang->gT("Survey could not be updated.");
         }
         if (Yii::app()->request->getPost('action') == "updatesurveysettingsandeditlocalesettings") {
             $this->getController()->redirect(array('admin/survey/sa/editlocalsettings/surveyid/' . $iSurveyID));
         } else {
             $this->getController()->redirect(array('admin/survey/sa/view/surveyid/' . $iSurveyID));
         }
     }
     if (!$sAction) {
         $this->getController()->redirect(array("/admin"), "refresh");
     }
 }
Exemple #15
0
 /**
  * Function responsible to activate survey.
  *
  * @access public
  * @param int $iSurveyID
  * @return void
  */
 public function activate($iSurveyID)
 {
     if (!Permission::model()->hasSurveyPermission($iSurveyID, 'surveyactivation', 'update')) {
         die;
     }
     $iSurveyID = (int) $iSurveyID;
     $aData = array();
     $aData['aSurveysettings'] = getSurveyInfo($iSurveyID);
     $aData['surveyid'] = $iSurveyID;
     // Die if this is not possible
     if (!isset($aData['aSurveysettings']['active']) || $aData['aSurveysettings']['active'] == 'Y') {
         $this->getController()->error('Survey not active');
     }
     $qtypes = getQuestionTypeList('', 'array');
     Yii::app()->loadHelper("admin/activate");
     if (empty($_POST['ok'])) {
         if (isset($_GET['fixnumbering']) && $_GET['fixnumbering']) {
             fixNumbering($_GET['fixnumbering'], $iSurveyID);
         }
         // Check consistency for groups and questions
         $failedgroupcheck = checkGroup($iSurveyID);
         $failedcheck = checkQuestions($iSurveyID, $iSurveyID, $qtypes);
         $aData['failedcheck'] = $failedcheck;
         $aData['failedgroupcheck'] = $failedgroupcheck;
         $aData['aSurveysettings'] = getSurveyInfo($iSurveyID);
         $this->_renderWrappedTemplate('survey', 'activateSurvey_view', $aData);
     } else {
         $survey = Survey::model()->findByAttributes(array('sid' => $iSurveyID));
         if (!is_null($survey)) {
             $survey->anonymized = Yii::app()->request->getPost('anonymized');
             $survey->datestamp = Yii::app()->request->getPost('datestamp');
             $survey->ipaddr = Yii::app()->request->getPost('ipaddr');
             $survey->refurl = Yii::app()->request->getPost('refurl');
             $survey->savetimings = Yii::app()->request->getPost('savetimings');
             $survey->save();
             Survey::model()->resetCache();
             // Make sure the saved values will be picked up
         }
         $aResult = activateSurvey($iSurveyID);
         if (isset($aResult['error'])) {
             $aViewUrls['output'] = "<br />\n<div class='messagebox ui-corner-all'>\n" . "<div class='header ui-widget-header'>" . gT("Activate Survey") . " ({$iSurveyID})</div>\n";
             if ($aResult['error'] == 'surveytablecreation') {
                 $aViewUrls['output'] .= "<div class='warningheader'>" . gT("Survey table could not be created.") . "</div>\n";
             } else {
                 $aViewUrls['output'] .= "<div class='warningheader'>" . gT("Timings table could not be created.") . "</div>\n";
             }
             $aViewUrls['output'] .= "<p>" . gT("Database error!!") . "\n <font color='red'>" . "</font>\n" . "<pre>" . var_export($aResult['error'], true) . "</pre>\n\n                <a href='" . Yii::app()->getController()->createUrl("admin/survey/sa/view/surveyid/" . $iSurveyID) . "'>" . gT("Main Admin Screen") . "</a>\n</div>";
         } else {
             $aViewUrls['output'] = "<br />\n<div class='messagebox ui-corner-all'>\n" . "<div class='header ui-widget-header'>" . gT("Activate Survey") . " ({$iSurveyID})</div>\n" . "<div class='successheader'>" . gT("Survey has been activated. Results table has been successfully created.") . "</div><br /><br />\n";
             if (isset($aResult['warning'])) {
                 $aViewUrls['output'] .= "<div class='warningheader'>" . gT("The required directory for saving the uploaded files couldn't be created. Please check file premissions on the /upload/surveys directory.") . "</div>";
             }
             if ($survey->allowregister == 'Y') {
                 $aViewUrls['output'] .= gT("This survey allows public registration. A token table must also be created.") . "<br /><br />\n" . "<input type='submit' value='" . gT("Initialise tokens") . "' onclick=\"" . convertGETtoPOST(Yii::app()->getController()->createUrl("admin/tokens/sa/index/surveyid/" . $iSurveyID)) . "\" />\n";
             } else {
                 $aViewUrls['output'] .= gT("This survey is now active, and responses can be recorded.") . "<br /><br />\n" . "<strong>" . gT("Open-access mode") . ":</strong> " . gT("No invitation code is needed to complete the survey.") . "<br />" . gT("You can switch to the closed-access mode by initialising a token table with the button below.") . "<br /><br />\n" . "<input type='submit' value='" . gT("Switch to closed-access mode") . "' onclick=\"" . convertGETtoPOST(Yii::app()->getController()->createUrl("admin/tokens/sa/index/surveyid/" . $iSurveyID)) . "\" />\n" . "<input type='submit' value='" . gT("No, thanks.") . "' onclick=\"" . convertGETtoPOST(Yii::app()->getController()->createUrl("admin/survey/sa/view/surveyid/" . $iSurveyID)) . "\" />\n";
             }
             $aViewUrls['output'] .= "</div><br />&nbsp;\n";
         }
         $this->_renderWrappedTemplate('survey', $aViewUrls, $aData);
     }
 }
                                                <?php 
$modulename = isset($eqrow['modulename']) ? $eqrow['modulename'] : false;
?>

                                                <input type="hidden" id="question_type" name="type" value="<?php 
echo $eqrow['type'];
?>
" />
                                                <input type="hidden" id="question_module_name" name="module_name" value="<?php 
echo $modulename;
?>
" />

                                                <?php 
foreach (getQuestionTypeList($eqrow['type'], 'array') as $key => $questionType) {
    if (!isset($groups[$questionType['group']])) {
        $groups[$questionType['group']] = array();
    }
    $groups[$questionType['group']][$key] = $questionType['description'];
}
?>

                                                <?php 
if (isset($selectormodeclass) && $selectormodeclass != "none" && $activated != "Y") {
    ?>

                                                    <div class="col-sm-8 btn-group" id="question_type_button" style="z-index: 1000">
                                                        <button type="button" class="btn btn-default dropdown-toggle " <?php 
    if ($activated == "Y") {
        echo " disabled ";
/**
* This function builds all the required session variables when a survey is first started and
* it loads any answer defaults from command line or from the table defaultvalues
* It is called from the related format script (group.php, question.php, survey.php)
* if the survey has just started.
*/
function buildsurveysession($surveyid, $preview = false)
{
    Yii::trace('start', 'survey.buildsurveysession');
    global $secerror, $clienttoken;
    global $tokensexist;
    //global $surveyid;
    global $move, $rooturl;
    $clang = Yii::app()->lang;
    $sLangCode = $clang->langcode;
    $languagechanger = makeLanguageChangerSurvey($sLangCode);
    if (!$preview) {
        $preview = Yii::app()->getConfig('previewmode');
    }
    $thissurvey = getSurveyInfo($surveyid, $sLangCode);
    $_SESSION['survey_' . $surveyid]['templatename'] = validateTemplateDir($thissurvey['template']);
    $_SESSION['survey_' . $surveyid]['templatepath'] = getTemplatePath($_SESSION['survey_' . $surveyid]['templatename']) . DIRECTORY_SEPARATOR;
    $sTemplatePath = $_SESSION['survey_' . $surveyid]['templatepath'];
    $loadsecurity = returnGlobal('loadsecurity', true);
    // NO TOKEN REQUIRED BUT CAPTCHA ENABLED FOR SURVEY ACCESS
    if ($tokensexist == 0 && isCaptchaEnabled('surveyaccessscreen', $thissurvey['usecaptcha']) && !isset($_SESSION['survey_' . $surveyid]['captcha_surveyaccessscreen']) && !$preview) {
        // IF CAPTCHA ANSWER IS NOT CORRECT OR NOT SET
        if (!isset($loadsecurity) || !isset($_SESSION['survey_' . $surveyid]['secanswer']) || $loadsecurity != $_SESSION['survey_' . $surveyid]['secanswer']) {
            sendCacheHeaders();
            doHeader();
            // No or bad answer to required security question
            $redata = compact(array_keys(get_defined_vars()));
            echo templatereplace(file_get_contents($sTemplatePath . "startpage.pstpl"), array(), $redata, 'frontend_helper[875]');
            //echo makedropdownlist();
            echo templatereplace(file_get_contents($sTemplatePath . "survey.pstpl"), array(), $redata, 'frontend_helper[877]');
            if (isset($loadsecurity)) {
                // was a bad answer
                echo "<font color='#FF0000'>" . $clang->gT("The answer to the security question is incorrect.") . "</font><br />";
            }
            echo "<p class='captcha'>" . $clang->gT("Please confirm access to survey by answering the security question below and click continue.") . "</p>" . CHtml::form(array("/survey/index/sid/{$surveyid}"), 'post', array('class' => 'captcha')) . "\n            <table align='center'>\n            <tr>\n            <td align='right' valign='middle'>\n            <input type='hidden' name='sid' value='" . $surveyid . "' id='sid' />\n            <input type='hidden' name='lang' value='" . $sLangCode . "' id='lang' />";
            // In case we this is a direct Reload previous answers URL, then add hidden fields
            if (isset($_GET['loadall']) && isset($_GET['scid']) && isset($_GET['loadname']) && isset($_GET['loadpass'])) {
                echo "\n                <input type='hidden' name='loadall' value='" . htmlspecialchars($_GET['loadall']) . "' id='loadall' />\n                <input type='hidden' name='scid' value='" . returnGlobal('scid', true) . "' id='scid' />\n                <input type='hidden' name='loadname' value='" . htmlspecialchars($_GET['loadname']) . "' id='loadname' />\n                <input type='hidden' name='loadpass' value='" . htmlspecialchars($_GET['loadpass']) . "' id='loadpass' />";
            }
            echo "\n            </td>\n            </tr>";
            if (function_exists("ImageCreate") && isCaptchaEnabled('surveyaccessscreen', $thissurvey['usecaptcha'])) {
                echo "<tr>\n                <td align='center' valign='middle'><label for='captcha'>" . $clang->gT("Security question:") . "</label></td><td align='left' valign='middle'><table><tr><td valign='middle'><img src='" . Yii::app()->getController()->createUrl('/verification/image/sid/' . $surveyid) . "' alt='captcha' /></td>\n                <td valign='middle'><input id='captcha' type='text' size='5' maxlength='3' name='loadsecurity' value='' /></td></tr></table>\n                </td>\n                </tr>";
            }
            echo "<tr><td colspan='2' align='center'><input class='submit' type='submit' value='" . $clang->gT("Continue") . "' /></td></tr>\n            </table>\n            </form>";
            echo templatereplace(file_get_contents($sTemplatePath . "endpage.pstpl"), array(), $redata, 'frontend_helper[1567]');
            doFooter();
            exit;
        } else {
            $_SESSION['survey_' . $surveyid]['captcha_surveyaccessscreen'] = true;
        }
    }
    //BEFORE BUILDING A NEW SESSION FOR THIS SURVEY, LET'S CHECK TO MAKE SURE THE SURVEY SHOULD PROCEED!
    // TOKEN REQUIRED BUT NO TOKEN PROVIDED
    if ($tokensexist == 1 && !$clienttoken && !$preview) {
        if ($thissurvey['nokeyboard'] == 'Y') {
            includeKeypad();
            $kpclass = "text-keypad";
        } else {
            $kpclass = "";
        }
        // DISPLAY REGISTER-PAGE if needed
        // DISPLAY CAPTCHA if needed
        sendCacheHeaders();
        doHeader();
        $redata = compact(array_keys(get_defined_vars()));
        echo templatereplace(file_get_contents($sTemplatePath . "startpage.pstpl"), array(), $redata, 'frontend_helper[1594]');
        //echo makedropdownlist();
        echo templatereplace(file_get_contents($sTemplatePath . "survey.pstpl"), array(), $redata, 'frontend_helper[1596]');
        if (isset($thissurvey) && $thissurvey['allowregister'] == "Y") {
            echo templatereplace(file_get_contents($sTemplatePath . "register.pstpl"), array(), $redata, 'frontend_helper[1599]');
        } else {
            // ->renderPartial('entertoken_view');
            if (isset($secerror)) {
                echo "<span class='error'>" . $secerror . "</span><br />";
            }
            echo '<div id="wrapper"><p id="tokenmessage">' . $clang->gT("This is a controlled survey. You need a valid token to participate.") . "<br />";
            echo $clang->gT("If you have been issued a token, please enter it in the box below and click continue.") . "</p>\n            <script type='text/javascript'>var focus_element='#token';</script>" . CHtml::form(array("/survey/index/sid/{$surveyid}"), 'post', array('id' => 'tokenform', 'autocomplete' => 'off')) . "\n            <ul>\n            <li>";
            ?>
            <label for='token'><?php 
            $clang->eT("Token:");
            ?>
</label><input class='text <?php 
            echo $kpclass;
            ?>
' id='token' type='password' name='token' value='' />
            <?php 
            echo "<input type='hidden' name='sid' value='" . $surveyid . "' id='sid' />\n            <input type='hidden' name='lang' value='" . $sLangCode . "' id='lang' />";
            if (isset($_GET['newtest']) && $_GET['newtest'] == "Y") {
                echo "  <input type='hidden' name='newtest' value='Y' id='newtest' />";
            }
            // If this is a direct Reload previous answers URL, then add hidden fields
            if (isset($_GET['loadall']) && isset($_GET['scid']) && isset($_GET['loadname']) && isset($_GET['loadpass'])) {
                echo "\n                <input type='hidden' name='loadall' value='" . htmlspecialchars($_GET['loadall']) . "' id='loadall' />\n                <input type='hidden' name='scid' value='" . returnGlobal('scid', true) . "' id='scid' />\n                <input type='hidden' name='loadname' value='" . htmlspecialchars($_GET['loadname']) . "' id='loadname' />\n                <input type='hidden' name='loadpass' value='" . htmlspecialchars($_GET['loadpass']) . "' id='loadpass' />";
            }
            echo "</li>";
            if (function_exists("ImageCreate") && isCaptchaEnabled('surveyaccessscreen', $thissurvey['usecaptcha'])) {
                echo "<li>\n                <label for='captchaimage'>" . $clang->gT("Security Question") . "</label><img id='captchaimage' src='" . Yii::app()->getController()->createUrl('/verification/image/sid/' . $surveyid) . "' alt='captcha' /><input type='text' size='5' maxlength='3' name='loadsecurity' value='' />\n                </li>";
            }
            echo "<li>\n            <input class='submit button' type='submit' value='" . $clang->gT("Continue") . "' />\n            </li>\n            </ul>\n            </form></div>";
        }
        echo templatereplace(file_get_contents($sTemplatePath . "endpage.pstpl"), array(), $redata, 'frontend_helper[1645]');
        doFooter();
        exit;
    } elseif ($tokensexist == 1 && $clienttoken && !isCaptchaEnabled('surveyaccessscreen', $thissurvey['usecaptcha'])) {
        //check if token actually does exist
        // check also if it is allowed to change survey after completion
        if ($thissurvey['alloweditaftercompletion'] == 'Y') {
            $oTokenEntry = Token::model($surveyid)->findByAttributes(array('token' => $clienttoken));
        } else {
            $oTokenEntry = Token::model($surveyid)->usable()->incomplete()->findByAttributes(array('token' => $clienttoken));
        }
        if (!isset($oTokenEntry)) {
            //TOKEN DOESN'T EXIST OR HAS ALREADY BEEN USED. EXPLAIN PROBLEM AND EXIT
            killSurveySession($surveyid);
            sendCacheHeaders();
            doHeader();
            $redata = compact(array_keys(get_defined_vars()));
            echo templatereplace(file_get_contents($sTemplatePath . "startpage.pstpl"), array(), $redata, 'frontend_helper[1676]');
            echo templatereplace(file_get_contents($sTemplatePath . "survey.pstpl"), array(), $redata, 'frontend_helper[1677]');
            echo '<div id="wrapper"><p id="tokenmessage">' . $clang->gT("This is a controlled survey. You need a valid token to participate.") . "<br /><br />\n" . "\t" . $clang->gT("The token you have provided is either not valid, or has already been used.") . "<br /><br />\n" . "\t" . sprintf($clang->gT("For further information please contact %s"), $thissurvey['adminname']) . " (<a href='mailto:{$thissurvey['adminemail']}'>" . "{$thissurvey['adminemail']}</a>)</p></div>\n";
            echo templatereplace(file_get_contents($sTemplatePath . "endpage.pstpl"), array(), $redata, 'frontend_helper[1684]');
            doFooter();
            exit;
        }
    } elseif ($tokensexist == 1 && $clienttoken && isCaptchaEnabled('surveyaccessscreen', $thissurvey['usecaptcha'])) {
        // IF CAPTCHA ANSWER IS CORRECT
        if (isset($loadsecurity) && isset($_SESSION['survey_' . $surveyid]['secanswer']) && $loadsecurity == $_SESSION['survey_' . $surveyid]['secanswer']) {
            if ($thissurvey['alloweditaftercompletion'] == 'Y') {
                $oTokenEntry = Token::model($surveyid)->findByAttributes(array('token' => $clienttoken));
            } else {
                $oTokenEntry = Token::model($surveyid)->incomplete()->findByAttributes(array('token' => $clienttoken));
            }
            if (!isset($oTokenEntry)) {
                sendCacheHeaders();
                doHeader();
                //TOKEN DOESN'T EXIST OR HAS ALREADY BEEN USED. EXPLAIN PROBLEM AND EXIT
                $redata = compact(array_keys(get_defined_vars()));
                echo templatereplace(file_get_contents($sTemplatePath . "startpage.pstpl"), array(), $redata, 'frontend_helper[1719]');
                echo templatereplace(file_get_contents($sTemplatePath . "survey.pstpl"), array(), $redata, 'frontend_helper[1720]');
                echo "\t<div id='wrapper'>\n" . "\t<p id='tokenmessage'>\n" . "\t" . $clang->gT("This is a controlled survey. You need a valid token to participate.") . "<br /><br />\n" . "\t" . $clang->gT("The token you have provided is either not valid, or has already been used.") . "<br/><br />\n" . "\t" . sprintf($clang->gT("For further information please contact %s"), $thissurvey['adminname']) . " (<a href='mailto:{$thissurvey['adminemail']}'>" . "{$thissurvey['adminemail']}</a>)\n" . "\t</p>\n" . "\t</div>\n";
                echo templatereplace(file_get_contents($sTemplatePath . "endpage.pstpl"), array(), $redata, 'frontend_helper[1731]');
                doFooter();
                exit;
            }
        } else {
            if (!isset($move) || is_null($move)) {
                unset($_SESSION['survey_' . $surveyid]['srid']);
                $gettoken = $clienttoken;
                sendCacheHeaders();
                doHeader();
                // No or bad answer to required security question
                $redata = compact(array_keys(get_defined_vars()));
                echo templatereplace(file_get_contents($sTemplatePath . "startpage.pstpl"), array(), $redata, 'frontend_helper[1745]');
                echo templatereplace(file_get_contents($sTemplatePath . "survey.pstpl"), array(), $redata, 'frontend_helper[1746]');
                // If token wasn't provided and public registration
                // is enabled then show registration form
                if (!isset($gettoken) && isset($thissurvey) && $thissurvey['allowregister'] == "Y") {
                    echo templatereplace(file_get_contents($sTemplatePath . "register.pstpl"), array(), $redata, 'frontend_helper[1751]');
                } else {
                    // only show CAPTCHA
                    echo '<div id="wrapper"><p id="tokenmessage">';
                    if (isset($loadsecurity)) {
                        // was a bad answer
                        echo "<span class='error'>" . $clang->gT("The answer to the security question is incorrect.") . "</span><br />";
                    }
                    echo $clang->gT("This is a controlled survey. You need a valid token to participate.") . "<br /><br />";
                    // IF TOKEN HAS BEEN GIVEN THEN AUTOFILL IT
                    // AND HIDE ENTRY FIELD
                    if (!isset($gettoken)) {
                        echo $clang->gT("If you have been issued a token, please enter it in the box below and click continue.") . "</p>\n                        <form id='tokenform' method='get' action='" . Yii::app()->getController()->createUrl("/survey/index") . "'>\n                        <ul>\n                        <li>\n                        <input type='hidden' name='sid' value='" . $surveyid . "' id='sid' />\n                        <input type='hidden' name='lang' value='" . $sLangCode . "' id='lang' />";
                        if (isset($_GET['loadall']) && isset($_GET['scid']) && isset($_GET['loadname']) && isset($_GET['loadpass'])) {
                            echo "<input type='hidden' name='loadall' value='" . htmlspecialchars($_GET['loadall']) . "' id='loadall' />\n                            <input type='hidden' name='scid' value='" . returnGlobal('scid', true) . "' id='scid' />\n                            <input type='hidden' name='loadname' value='" . htmlspecialchars($_GET['loadname']) . "' id='loadname' />\n                            <input type='hidden' name='loadpass' value='" . htmlspecialchars($_GET['loadpass']) . "' id='loadpass' />";
                        }
                        echo '<label for="token">' . $clang->gT("Token") . "</label><input class='text' type='password' id='token' name='token'></li>";
                    } else {
                        echo $clang->gT("Please confirm the token by answering the security question below and click continue.") . "</p>\n                    <form id='tokenform' method='get' action='" . Yii::app()->getController()->createUrl("/survey/index") . "'>\n                    <ul>\n                    <li>\n                    <input type='hidden' name='sid' value='" . $surveyid . "' id='sid' />\n                    <input type='hidden' name='lang' value='" . $sLangCode . "' id='lang' />";
                        if (isset($_GET['loadall']) && isset($_GET['scid']) && isset($_GET['loadname']) && isset($_GET['loadpass'])) {
                            echo "<input type='hidden' name='loadall' value='" . htmlspecialchars($_GET['loadall']) . "' id='loadall' />\n                        <input type='hidden' name='scid' value='" . returnGlobal('scid', true) . "' id='scid' />\n                        <input type='hidden' name='loadname' value='" . htmlspecialchars($_GET['loadname']) . "' id='loadname' />\n                        <input type='hidden' name='loadpass' value='" . htmlspecialchars($_GET['loadpass']) . "' id='loadpass' />";
                        }
                        echo '<label for="token">' . $clang->gT("Token:") . "</label><span id='token'>{$gettoken}</span>" . "<input type='hidden' name='token' value='{$gettoken}'></li>";
                    }
                    if (function_exists("ImageCreate") && isCaptchaEnabled('surveyaccessscreen', $thissurvey['usecaptcha'])) {
                        echo "<li>\n                    <label for='captchaimage'>" . $clang->gT("Security Question") . "</label><img id='captchaimage' src='" . Yii::app()->getController()->createUrl('/verification/image/sid/' . $surveyid) . "' alt='captcha' /><input type='text' size='5' maxlength='3' name='loadsecurity' value='' />\n                    </li>";
                    }
                    echo "<li><input class='submit' type='submit' value='" . $clang->gT("Continue") . "' /></li>\n                </ul>\n                </form>\n                </id>";
                }
                echo '</div>' . templatereplace(file_get_contents($sTemplatePath . "endpage.pstpl"), array(), $redata, 'frontend_helper[1817]');
                doFooter();
                exit;
            }
        }
    }
    //RESET ALL THE SESSION VARIABLES AND START AGAIN
    unset($_SESSION['survey_' . $surveyid]['grouplist']);
    unset($_SESSION['survey_' . $surveyid]['fieldarray']);
    unset($_SESSION['survey_' . $surveyid]['insertarray']);
    unset($_SESSION['survey_' . $surveyid]['fieldnamesInfo']);
    unset($_SESSION['survey_' . $surveyid]['fieldmap-' . $surveyid . '-randMaster']);
    unset($_SESSION['survey_' . $surveyid]['groupReMap']);
    $_SESSION['survey_' . $surveyid]['fieldnamesInfo'] = array();
    // Multi lingual support order : by REQUEST, if not by Token->language else by survey default language
    if (returnGlobal('lang', true)) {
        $language_to_set = returnGlobal('lang', true);
    } elseif (isset($oTokenEntry) && $oTokenEntry) {
        // If survey have token : we have a $oTokenEntry
        // Can use $oTokenEntry = Token::model($surveyid)->findByAttributes(array('token'=>$clienttoken)); if we move on another function : this par don't validate the token validity
        $language_to_set = $oTokenEntry->language;
    } else {
        $language_to_set = $thissurvey['language'];
    }
    if (!isset($_SESSION['survey_' . $surveyid]['s_lang'])) {
        SetSurveyLanguage($surveyid, $language_to_set);
    }
    UpdateGroupList($surveyid, $_SESSION['survey_' . $surveyid]['s_lang']);
    $sQuery = "SELECT count(*)\n" . " FROM {{groups}} INNER JOIN {{questions}} ON {{groups}}.gid = {{questions}}.gid\n" . " WHERE {{questions}}.sid=" . $surveyid . "\n" . " AND {{groups}}.language='" . $_SESSION['survey_' . $surveyid]['s_lang'] . "'\n" . " AND {{questions}}.language='" . $_SESSION['survey_' . $surveyid]['s_lang'] . "'\n" . " AND {{questions}}.parent_qid=0\n";
    $totalquestions = Yii::app()->db->createCommand($sQuery)->queryScalar();
    // Fix totalquestions by substracting Test Display questions
    $iNumberofQuestions = dbExecuteAssoc("SELECT count(*)\n" . " FROM {{questions}}" . " WHERE type in ('X','*')\n" . " AND sid={$surveyid}" . " AND language='" . $_SESSION['survey_' . $surveyid]['s_lang'] . "'" . " AND parent_qid=0")->read();
    $_SESSION['survey_' . $surveyid]['totalquestions'] = $totalquestions - (int) reset($iNumberofQuestions);
    //2. SESSION VARIABLE: totalsteps
    //The number of "pages" that will be presented in this survey
    //The number of pages to be presented will differ depending on the survey format
    switch ($thissurvey['format']) {
        case "A":
            $_SESSION['survey_' . $surveyid]['totalsteps'] = 1;
            break;
        case "G":
            if (isset($_SESSION['survey_' . $surveyid]['grouplist'])) {
                $_SESSION['survey_' . $surveyid]['totalsteps'] = count($_SESSION['survey_' . $surveyid]['grouplist']);
            }
            break;
        case "S":
            $_SESSION['survey_' . $surveyid]['totalsteps'] = $totalquestions;
    }
    if ($totalquestions == 0) {
        sendCacheHeaders();
        doHeader();
        $redata = compact(array_keys(get_defined_vars()));
        echo templatereplace(file_get_contents($sTemplatePath . "startpage.pstpl"), array(), $redata, 'frontend_helper[1914]');
        echo templatereplace(file_get_contents($sTemplatePath . "survey.pstpl"), array(), $redata, 'frontend_helper[1915]');
        echo "\t<div id='wrapper'>\n" . "\t<p id='tokenmessage'>\n" . "\t" . $clang->gT("This survey does not yet have any questions and cannot be tested or completed.") . "<br /><br />\n" . "\t" . sprintf($clang->gT("For further information please contact %s"), $thissurvey['adminname']) . " (<a href='mailto:{$thissurvey['adminemail']}'>" . "{$thissurvey['adminemail']}</a>)<br /><br />\n" . "\t</p>\n" . "\t</div>\n";
        echo templatereplace(file_get_contents($sTemplatePath . "endpage.pstpl"), array(), $redata, 'frontend_helper[1925]');
        doFooter();
        exit;
    }
    //Perform a case insensitive natural sort on group name then question title of a multidimensional array
    //    usort($arows, 'groupOrderThenQuestionOrder');
    //3. SESSION VARIABLE - insertarray
    //An array containing information about used to insert the data into the db at the submit stage
    //4. SESSION VARIABLE - fieldarray
    //See rem at end..
    if ($tokensexist == 1 && $clienttoken) {
        $_SESSION['survey_' . $surveyid]['token'] = $clienttoken;
    }
    if ($thissurvey['anonymized'] == "N") {
        $_SESSION['survey_' . $surveyid]['insertarray'][] = "token";
    }
    $qtypes = getQuestionTypeList('', 'array');
    $fieldmap = createFieldMap($surveyid, 'full', true, false, $_SESSION['survey_' . $surveyid]['s_lang']);
    // Randomization groups for groups
    $aRandomGroups = array();
    $aGIDCompleteMap = array();
    // first find all groups and their groups IDS
    $criteria = new CDbCriteria();
    $criteria->addColumnCondition(array('sid' => $surveyid, 'language' => $_SESSION['survey_' . $surveyid]['s_lang']));
    $criteria->addCondition("randomization_group != ''");
    $oData = QuestionGroup::model()->findAll($criteria);
    foreach ($oData as $aGroup) {
        $aRandomGroups[$aGroup['randomization_group']][] = $aGroup['gid'];
    }
    // Shuffle each group and create a map for old GID => new GID
    foreach ($aRandomGroups as $sGroupName => $aGIDs) {
        $aShuffledIDs = $aGIDs;
        shuffle($aShuffledIDs);
        $aGIDCompleteMap = $aGIDCompleteMap + array_combine($aGIDs, $aShuffledIDs);
    }
    $_SESSION['survey_' . $surveyid]['groupReMap'] = $aGIDCompleteMap;
    $randomized = false;
    // So we can trigger reorder once for group and question randomization
    // Now adjust the grouplist
    if (count($aRandomGroups) > 0 && !$preview) {
        $randomized = true;
        // So we can trigger reorder once for group and question randomization
        // Now adjust the grouplist
        Yii::import('application.helpers.frontend_helper', true);
        // make sure frontend helper is loaded
        UpdateGroupList($surveyid, $_SESSION['survey_' . $surveyid]['s_lang']);
        // ... and the fieldmap
        // First create a fieldmap with GID as key
        foreach ($fieldmap as $aField) {
            if (isset($aField['gid'])) {
                $GroupFieldMap[$aField['gid']][] = $aField;
            } else {
                $GroupFieldMap['other'][] = $aField;
            }
        }
        // swap it
        foreach ($GroupFieldMap as $iOldGid => $fields) {
            $iNewGid = $iOldGid;
            if (isset($aGIDCompleteMap[$iOldGid])) {
                $iNewGid = $aGIDCompleteMap[$iOldGid];
            }
            $newGroupFieldMap[$iNewGid] = $GroupFieldMap[$iNewGid];
        }
        $GroupFieldMap = $newGroupFieldMap;
        // and convert it back to a fieldmap
        unset($fieldmap);
        foreach ($GroupFieldMap as $aGroupFields) {
            foreach ($aGroupFields as $aField) {
                if (isset($aField['fieldname'])) {
                    $fieldmap[$aField['fieldname']] = $aField;
                    // isset() because of the shuffled flag above
                }
            }
        }
        unset($GroupFieldMap);
    }
    // Randomization groups for questions
    // Find all defined randomization groups through question attribute values
    $randomGroups = array();
    if (in_array(Yii::app()->db->getDriverName(), array('mssql', 'sqlsrv', 'dblib'))) {
        $rgquery = "SELECT attr.qid, CAST(value as varchar(255)) as value FROM {{question_attributes}} as attr right join {{questions}} as quests on attr.qid=quests.qid WHERE attribute='random_group' and CAST(value as varchar(255)) <> '' and sid={$surveyid} GROUP BY attr.qid, CAST(value as varchar(255))";
    } else {
        $rgquery = "SELECT attr.qid, value FROM {{question_attributes}} as attr right join {{questions}} as quests on attr.qid=quests.qid WHERE attribute='random_group' and value <> '' and sid={$surveyid} GROUP BY attr.qid, value";
    }
    $rgresult = dbExecuteAssoc($rgquery);
    foreach ($rgresult->readAll() as $rgrow) {
        // Get the question IDs for each randomization group
        $randomGroups[$rgrow['value']][] = $rgrow['qid'];
    }
    // If we have randomization groups set, then lets cycle through each group and
    // replace questions in the group with a randomly chosen one from the same group
    if (count($randomGroups) > 0 && !$preview) {
        $randomized = true;
        // So we can trigger reorder once for group and question randomization
        $copyFieldMap = array();
        $oldQuestOrder = array();
        $newQuestOrder = array();
        $randGroupNames = array();
        foreach ($randomGroups as $key => $value) {
            $oldQuestOrder[$key] = $randomGroups[$key];
            $newQuestOrder[$key] = $oldQuestOrder[$key];
            // We shuffle the question list to get a random key->qid which will be used to swap from the old key
            shuffle($newQuestOrder[$key]);
            $randGroupNames[] = $key;
        }
        // Loop through the fieldmap and swap each question as they come up
        foreach ($fieldmap as $fieldkey => $fieldval) {
            $found = 0;
            foreach ($randomGroups as $gkey => $gval) {
                // We found a qid that is in the randomization group
                if (isset($fieldval['qid']) && in_array($fieldval['qid'], $oldQuestOrder[$gkey])) {
                    // Get the swapped question
                    $idx = array_search($fieldval['qid'], $oldQuestOrder[$gkey]);
                    foreach ($fieldmap as $key => $field) {
                        if (isset($field['qid']) && $field['qid'] == $newQuestOrder[$gkey][$idx]) {
                            $field['random_gid'] = $fieldval['gid'];
                            // It is possible to swap to another group
                            $copyFieldMap[$key] = $field;
                        }
                    }
                    $found = 1;
                    break;
                } else {
                    $found = 2;
                }
            }
            if ($found == 2) {
                $copyFieldMap[$fieldkey] = $fieldval;
            }
            reset($randomGroups);
        }
        $fieldmap = $copyFieldMap;
    }
    if ($randomized === true) {
        // reset the sequencing counts
        $gseq = -1;
        $_gid = -1;
        $qseq = -1;
        $_qid = -1;
        $copyFieldMap = array();
        foreach ($fieldmap as $key => $val) {
            if ($val['gid'] != '') {
                if (isset($val['random_gid'])) {
                    $gid = $val['random_gid'];
                } else {
                    $gid = $val['gid'];
                }
                if ($gid != $_gid) {
                    $_gid = $gid;
                    ++$gseq;
                }
            }
            if ($val['qid'] != '' && $val['qid'] != $_qid) {
                $_qid = $val['qid'];
                ++$qseq;
            }
            if ($val['gid'] != '' && $val['qid'] != '') {
                $val['groupSeq'] = $gseq;
                $val['questionSeq'] = $qseq;
            }
            $copyFieldMap[$key] = $val;
        }
        $fieldmap = $copyFieldMap;
        unset($copyFieldMap);
        $_SESSION['survey_' . $surveyid]['fieldmap-' . $surveyid . $_SESSION['survey_' . $surveyid]['s_lang']] = $fieldmap;
        $_SESSION['survey_' . $surveyid]['fieldmap-' . $surveyid . '-randMaster'] = 'fieldmap-' . $surveyid . $_SESSION['survey_' . $surveyid]['s_lang'];
    }
    // TMSW Condition->Relevance:  don't need hasconditions, or usedinconditions
    $_SESSION['survey_' . $surveyid]['fieldmap'] = $fieldmap;
    foreach ($fieldmap as $field) {
        if (isset($field['qid']) && $field['qid'] != '') {
            $_SESSION['survey_' . $surveyid]['fieldnamesInfo'][$field['fieldname']] = $field['sid'] . 'X' . $field['gid'] . 'X' . $field['qid'];
            $_SESSION['survey_' . $surveyid]['insertarray'][] = $field['fieldname'];
            //fieldarray ARRAY CONTENTS -
            //            [0]=questions.qid,
            //            [1]=fieldname,
            //            [2]=questions.title,
            //            [3]=questions.question
            //                     [4]=questions.type,
            //            [5]=questions.gid,
            //            [6]=questions.mandatory,
            //            [7]=conditionsexist,
            //            [8]=usedinconditions
            //            [8]=usedinconditions
            //            [9]=used in group.php for question count
            //            [10]=new group id for question in randomization group (GroupbyGroup Mode)
            if (!isset($_SESSION['survey_' . $surveyid]['fieldarray'][$field['sid'] . 'X' . $field['gid'] . 'X' . $field['qid']])) {
                //JUST IN CASE : PRECAUTION!
                //following variables are set only if $style=="full" in createFieldMap() in common_helper.
                //so, if $style = "short", set some default values here!
                if (isset($field['title'])) {
                    $title = $field['title'];
                } else {
                    $title = "";
                }
                if (isset($field['question'])) {
                    $question = $field['question'];
                } else {
                    $question = "";
                }
                if (isset($field['mandatory'])) {
                    $mandatory = $field['mandatory'];
                } else {
                    $mandatory = 'N';
                }
                if (isset($field['hasconditions'])) {
                    $hasconditions = $field['hasconditions'];
                } else {
                    $hasconditions = 'N';
                }
                if (isset($field['usedinconditions'])) {
                    $usedinconditions = $field['usedinconditions'];
                } else {
                    $usedinconditions = 'N';
                }
                $_SESSION['survey_' . $surveyid]['fieldarray'][$field['sid'] . 'X' . $field['gid'] . 'X' . $field['qid']] = array($field['qid'], $field['sid'] . 'X' . $field['gid'] . 'X' . $field['qid'], $title, $question, $field['type'], $field['gid'], $mandatory, $hasconditions, $usedinconditions);
            }
            if (isset($field['random_gid'])) {
                $_SESSION['survey_' . $surveyid]['fieldarray'][$field['sid'] . 'X' . $field['gid'] . 'X' . $field['qid']][10] = $field['random_gid'];
            }
        }
    }
    // Prefill questions/answers from command line params
    $reservedGetValues = array('token', 'sid', 'gid', 'qid', 'lang', 'newtest', 'action');
    $startingValues = array();
    if (isset($_GET)) {
        foreach ($_GET as $k => $v) {
            if (!in_array($k, $reservedGetValues) && isset($_SESSION['survey_' . $surveyid]['fieldmap'][$k])) {
                $startingValues[$k] = $v;
            } else {
                // Search question codes to use those for prefilling.
                foreach ($_SESSION['survey_' . $surveyid]['fieldmap'] as $sgqa => $details) {
                    if ($details['title'] == $k) {
                        $startingValues[$sgqa] = $v;
                    }
                }
            }
        }
    }
    $_SESSION['survey_' . $surveyid]['startingValues'] = $startingValues;
    if (isset($_SESSION['survey_' . $surveyid]['fieldarray'])) {
        $_SESSION['survey_' . $surveyid]['fieldarray'] = array_values($_SESSION['survey_' . $surveyid]['fieldarray']);
    }
    //Check if a passthru label and value have been included in the query url
    $oResult = SurveyURLParameter::model()->getParametersForSurvey($surveyid);
    foreach ($oResult->readAll() as $aRow) {
        if (isset($_GET[$aRow['parameter']]) && !$preview) {
            $_SESSION['survey_' . $surveyid]['urlparams'][$aRow['parameter']] = $_GET[$aRow['parameter']];
            if ($aRow['targetqid'] != '') {
                foreach ($fieldmap as $sFieldname => $aField) {
                    if ($aRow['targetsqid'] != '') {
                        if ($aField['qid'] == $aRow['targetqid'] && $aField['sqid'] == $aRow['targetsqid']) {
                            $_SESSION['survey_' . $surveyid]['startingValues'][$sFieldname] = $_GET[$aRow['parameter']];
                            $_SESSION['survey_' . $surveyid]['startingValues'][$aRow['parameter']] = $_GET[$aRow['parameter']];
                        }
                    } else {
                        if ($aField['qid'] == $aRow['targetqid']) {
                            $_SESSION['survey_' . $surveyid]['startingValues'][$sFieldname] = $_GET[$aRow['parameter']];
                            $_SESSION['survey_' . $surveyid]['startingValues'][$aRow['parameter']] = $_GET[$aRow['parameter']];
                        }
                    }
                }
            }
        }
    }
    Yii::trace('end', 'survey.buildsurveysession');
}
Exemple #18
0
 /**
  * Load edit/new question screen depending on $action.
  *
  * @access public
  * @param string $action
  * @param int $surveyid
  * @param int $gid
  * @param int $qid
  * @return void
  */
 public function index($sa, $surveyid, $gid, $qid = null)
 {
     $action = $sa;
     $surveyid = sanitize_int($surveyid);
     $gid = sanitize_int($gid);
     if (isset($qid)) {
         $qid = sanitize_int($qid);
     }
     $aViewUrls = array();
     $aData['surveyid'] = $surveyid;
     $aData['gid'] = $gid;
     $aData['qid'] = $qid;
     $aData['display']['menu_bars']['surveysummary'] = 'viewgroup';
     $aData['display']['menu_bars']['gid_action'] = 'addquestion';
     Yii::app()->session['FileManagerContext'] = "create:question:{$surveyid}";
     if (hasSurveyPermission($surveyid, 'surveycontent', 'read')) {
         $clang = $this->getController()->lang;
         $surveyinfo = getSurveyInfo($surveyid);
         Yii::app()->loadHelper('admin/htmleditor');
         Yii::app()->loadHelper('surveytranslator');
         if (isset($_POST['sortorder'])) {
             $postsortorder = sanitize_int($_POST['sortorder']);
         }
         $aData['adding'] = $adding = $action == 'addquestion';
         $aData['copying'] = $copying = $action == 'copyquestion';
         $questlangs = Survey::model()->findByPk($surveyid)->additionalLanguages;
         $baselang = Survey::model()->findByPk($surveyid)->language;
         $questlangs[] = $baselang;
         $questlangs = array_flip($questlangs);
         // Prepare selector Mode TODO: with and without image
         if (!$adding) {
             Yii::app()->session['FileManagerContext'] = "edit:question:{$surveyid}";
             $aData['display']['menu_bars']['qid_action'] = 'editquestion';
             $egresult = Questions::model()->findAllByAttributes(array('sid' => $surveyid, 'gid' => $gid, 'qid' => $qid));
             foreach ($egresult as $esrow) {
                 if (!array_key_exists($esrow->language, $questlangs)) {
                     // Language Exists, BUT ITS NOT ON THE SURVEY ANYMORE.
                     $esrow->delete();
                 } else {
                     $questlangs[$esrow->language] = 99;
                 }
                 if ($esrow->language == $baselang) {
                     $esrow = $esrow->attributes;
                     $basesettings = array('question_order' => $esrow['question_order'], 'other' => $esrow['other'], 'mandatory' => $esrow['mandatory'], 'type' => $esrow['type'], 'title' => $esrow['title'], 'preg' => $esrow['preg'], 'question' => $esrow['question'], 'help' => $esrow['help']);
                 }
             }
             if (!$egresult) {
                 $this->getController()->error('Invalid question id');
             }
             while (list($key, $value) = each($questlangs)) {
                 if ($value != 99) {
                     Questions::model()->insert(array('qid' => $qid, 'sid' => $surveyid, 'gid' => $gid, 'type' => $basesettings['type'], 'title' => $basesettings['title'], 'question' => $basesettings['question'], 'preg' => $basesettings['preg'], 'help' => $basesettings['help'], 'other' => $basesettings['other'], 'mandatory' => $basesettings['mandatory'], 'question_order' => $basesettings['question_order'], 'language' => $key));
                 }
             }
             $eqresult = Questions::model()->with('groups')->together()->findByAttributes(array('sid' => $surveyid, 'gid' => $gid, 'qid' => $qid, 'language' => $baselang));
         } else {
             // This is needed to properly color-code content if it contains replacements
             LimeExpressionManager::StartProcessingPage(false, Yii::app()->baseUrl, true);
             // so can click on syntax highlighting to edit questions
         }
         $qtypelist = getQuestionTypeList('', 'array');
         $qDescToCode = 'qDescToCode = {';
         $qCodeToInfo = 'qCodeToInfo = {';
         foreach ($qtypelist as $qtype => $qdesc) {
             $qDescToCode .= " '{$qdesc['description']}' : '{$qtype}', \n";
             $qCodeToInfo .= " '{$qtype}' : '" . ls_json_encode($qdesc) . "', \n";
         }
         $aData['qTypeOutput'] = "{$qDescToCode} 'null':'null' }; \n {$qCodeToInfo} 'null':'null' };";
         if (!$adding) {
             $eqrow = array_merge($eqresult->attributes, $eqresult->groups->attributes);
             // Todo: handler in case that record is not found
             if ($copying) {
                 $eqrow['title'] = '';
             }
         } else {
             $eqrow['language'] = $baselang;
             $eqrow['title'] = '';
             $eqrow['question'] = '';
             $eqrow['help'] = '';
             $eqrow['type'] = 'T';
             $eqrow['lid'] = 0;
             $eqrow['lid1'] = 0;
             $eqrow['gid'] = $gid;
             $eqrow['other'] = 'N';
             $eqrow['mandatory'] = 'N';
             $eqrow['preg'] = '';
             $eqrow['relevance'] = 1;
             $eqrow['group_name'] = '';
         }
         $aData['eqrow'] = $eqrow;
         $aData['surveyid'] = $surveyid;
         $aData['gid'] = $gid;
         if (!$adding) {
             $criteria = new CDbCriteria();
             $criteria->addColumnCondition(array('sid' => $surveyid, 'gid' => $gid, 'qid' => $qid));
             $criteria->params[':lang'] = $baselang;
             $criteria->addCondition('language != :lang');
             $aqresult = Questions::model()->findAll($criteria);
             $aData['aqresult'] = $aqresult;
         }
         $aData['clang'] = $clang;
         $aData['action'] = $action;
         $sumresult1 = Survey::model()->findByPk($surveyid);
         if (is_null($sumresult1)) {
             $this->getController()->error('Invalid Survey ID');
         }
         $surveyinfo = $sumresult1->attributes;
         $surveyinfo = array_map('flattenText', $surveyinfo);
         $aData['activated'] = $activated = $surveyinfo['active'];
         if ($activated != "Y") {
             // Prepare selector Class for javascript function : TODO with or without picture
             $selectormodeclass = 'full';
             if (Yii::app()->session['questionselectormode'] == 'none') {
                 $selectormodeclass = 'none';
             }
             $aData['selectormodeclass'] = $selectormodeclass;
         }
         if (!$adding) {
             $qattributes = questionAttributes();
         } else {
             $qattributes = array();
         }
         if ($adding) {
             // Get the questions for this group
             $baselang = Survey::model()->findByPk($surveyid)->language;
             $oqresult = Questions::model()->findAllByAttributes(array('sid' => $surveyid, 'gid' => $gid, 'language' => $baselang, 'parent_qid' => 0), array('order' => 'question_order'));
             $aData['oqresult'] = $oqresult;
         }
         $this->getController()->_js_admin_includes(Yii::app()->getConfig('adminscripts') . 'questions.js');
         $aViewUrls['editQuestion_view'][] = $aData;
         $aViewUrls['questionJavascript_view'][] = array('type' => $eqrow['type']);
     } else {
         include 'accessDenied.php';
     }
     $this->_renderWrappedTemplate('survey/Question', $aViewUrls, $aData);
 }
 /**
  * Shows admin menu for question
  * @param int Survey id
  * @param int Group id
  * @param int Question id
  * @param string action
  */
 function _questionbar($iSurveyID, $gid, $qid, $action = null)
 {
     $clang = $this->getController()->lang;
     $baselang = Survey::model()->findByPk($iSurveyID)->language;
     //Show Question Details
     //Count answer-options for this question
     $qrr = Answers::model()->findAllByAttributes(array('qid' => $qid, 'language' => $baselang));
     $aData['qct'] = $qct = count($qrr);
     //Count sub-questions for this question
     $sqrq = Questions::model()->findAllByAttributes(array('parent_qid' => $qid, 'language' => $baselang));
     $aData['sqct'] = $sqct = count($sqrq);
     $qrrow = Questions::model()->findByAttributes(array('qid' => $qid, 'gid' => $gid, 'sid' => $iSurveyID, 'language' => $baselang));
     $questionsummary = "<div class='menubar'>\n";
     // Check if other questions in the Survey are dependent upon this question
     $condarray = getQuestDepsForConditions($iSurveyID, "all", "all", $qid, "by-targqid", "outsidegroup");
     $sumresult1 = Survey::model()->findByPk($iSurveyID);
     if (is_null($sumresult1)) {
         Yii::app()->session['flashmessage'] = $clang->gT("Invalid survey ID");
         $this->getController()->redirect($this->getController()->createUrl("admin/index"));
     }
     //  if surveyid is invalid then die to prevent errors at a later time
     $surveyinfo = $sumresult1->attributes;
     $surveyinfo = array_map('flattenText', $surveyinfo);
     $aData['activated'] = $surveyinfo['active'];
     $qrrow = $qrrow->attributes;
     if (hasSurveyPermission($iSurveyID, 'surveycontent', 'read')) {
         if (count(Survey::model()->findByPk($iSurveyID)->additionalLanguages) != 0) {
             Yii::app()->loadHelper('surveytranslator');
             $tmp_survlangs = Survey::model()->findByPk($iSurveyID)->additionalLanguages;
             $baselang = Survey::model()->findByPk($iSurveyID)->language;
             $tmp_survlangs[] = $baselang;
             rsort($tmp_survlangs);
             $aData['tmp_survlangs'] = $tmp_survlangs;
         }
     }
     $aData['qtypes'] = $qtypes = getQuestionTypeList('', 'array');
     if ($action == 'editansweroptions' || $action == "editsubquestions" || $action == "editquestion" || $action == "editdefaultvalues" || $action == "editdefaultvalues" || $action == "copyquestion") {
         $qshowstyle = "style='display: none'";
     } else {
         $qshowstyle = "";
     }
     $aData['qshowstyle'] = $qshowstyle;
     $aData['action'] = $action;
     $aData['surveyid'] = $iSurveyID;
     $aData['qid'] = $qid;
     $aData['gid'] = $gid;
     $aData['clang'] = $clang;
     $aData['qrrow'] = $qrrow;
     $aData['baselang'] = $baselang;
     $aAttributesWithValues = Questions::model()->getAdvancedSettingsWithValues($qid, $qrrow['type'], $iSurveyID, $baselang);
     $DisplayArray = array();
     foreach ($aAttributesWithValues as $aAttribute) {
         if ($aAttribute['i18n'] == false && isset($aAttribute['value']) && $aAttribute['value'] != $aAttribute['default'] || $aAttribute['i18n'] == true && isset($aAttribute['value'][$baselang]) && $aAttribute['value'][$baselang] != $aAttribute['default']) {
             if ($aAttribute['inputtype'] == 'singleselect') {
                 $aAttribute['value'] = $aAttribute['options'][$aAttribute['value']];
             }
             /*
             if ($aAttribute['name']=='relevance')
             {
             $sRelevance = $aAttribute['value'];
             if ($sRelevance !== '' && $sRelevance !== '1' && $sRelevance !== '0')
             {
             LimeExpressionManager::ProcessString("{" . $sRelevance . "}");    // tests Relevance equation so can pretty-print it
             $aAttribute['value']= LimeExpressionManager::GetLastPrettyPrintExpression();
             }
             }
             */
             $DisplayArray[] = $aAttribute;
         }
     }
     $aData['advancedsettings'] = $DisplayArray;
     $aData['condarray'] = $condarray;
     $aData['sImageURL'] = Yii::app()->getConfig('adminimageurl');
     $aData['iIconSize'] = Yii::app()->getConfig('adminthemeiconsize');
     $questionsummary .= $this->getController()->render('/admin/survey/Question/questionbar_view', $aData, true);
     $finaldata['display'] = $questionsummary;
     $this->getController()->render('/survey_view', $finaldata);
 }