Exemplo n.º 1
0
/**
* fixes the numbering of questions
* This can happen if question 1 have subquestion code 1 and have question 11 in same survey and group (then same SGQA)
* @param int $fixnumbering
* @todo can call this function (no $_GET, but getParam) AND do it with Yii
*/
function fixNumbering($iQuestionID, $iSurveyID)
{
    Yii::app()->loadHelper("database");
    LimeExpressionManager::RevertUpgradeConditionsToRelevance($iSurveyID);
    //Fix a question id - requires renumbering a question
    $iQuestionID = (int) $iQuestionID;
    $iMaxQID = Question::model()->getMaxId('qid', true);
    // Always refresh as we insert new qid's
    $iNewQID = $iMaxQID + 1;
    // Not sure we can do this in MSSQL ?
    $sQuery = "UPDATE {{questions}} SET qid={$iNewQID} WHERE qid={$iQuestionID}";
    Yii::app()->db->createCommand($sQuery)->query();
    // Update subquestions
    $sQuery = "UPDATE {{questions}} SET parent_qid={$iNewQID} WHERE parent_qid={$iQuestionID}";
    Yii::app()->db->createCommand($sQuery)->query();
    //Update conditions.. firstly conditions FOR this question
    $sQuery = "UPDATE {{conditions}} SET qid={$iNewQID} WHERE qid={$iQuestionID}";
    Yii::app()->db->createCommand($sQuery)->query();
    //Update default values
    $sQuery = "UPDATE {{defaultvalues}} SET qid={$iNewQID} WHERE qid={$iQuestionID}";
    Yii::app()->db->createCommand($sQuery)->query();
    $sQuery = "UPDATE {{defaultvalues}} SET sqid={$iNewQID} WHERE sqid={$iQuestionID}";
    Yii::app()->db->createCommand($sQuery)->query();
    //Update quotas
    $sQuery = "UPDATE {{quota_members}} SET qid={$iNewQID} WHERE qid={$iQuestionID}";
    Yii::app()->db->createCommand($sQuery)->query();
    //Update url params
    $sQuery = "UPDATE {{survey_url_parameters}} SET targetqid={$iNewQID} WHERE targetqid={$iQuestionID}";
    Yii::app()->db->createCommand($sQuery)->query();
    $sQuery = "UPDATE {{survey_url_parameters}} SET targetsqid={$iNewQID} WHERE targetsqid={$iQuestionID}";
    Yii::app()->db->createCommand($sQuery)->query();
    //Now conditions based upon this question
    $sQuery = "SELECT cqid, cfieldname FROM {{conditions}} WHERE cqid={$iQuestionID}";
    $sResult = Yii::app()->db->createCommand($sQuery)->query();
    foreach ($sResult->readAll() as $row) {
        $aSwitcher[] = array("cqid" => $row['cqid'], "cfieldname" => $row['cfieldname']);
    }
    if (isset($aSwitcher)) {
        foreach ($aSwitcher as $aSwitch) {
            $sQuery = "UPDATE {{conditions}}\n            SET cqid={$iNewQID},\n            cfieldname='" . str_replace("X" . $iQuestionID, "X" . $iNewQID, $aSwitch['cfieldname']) . "'\n            WHERE cqid={$iQuestionID}";
            $sResult = db_execute_assosc($sQuery);
        }
    }
    //Now question_attributes
    $sQuery = "UPDATE {{question_attributes}} SET qid={$iNewQID} WHERE qid={$iQuestionID}";
    Yii::app()->db->createCommand($sQuery)->query();
    //Now answers
    $sQuery = "UPDATE {{answers}} SET qid={$iNewQID} WHERE qid={$iQuestionID}";
    Yii::app()->db->createCommand($sQuery)->query();
    LimeExpressionManager::UpgradeConditionsToRelevance($iSurveyID);
}
Exemplo n.º 2
0
/**
* fixes the numbering of questions
* @param <type> $fixnumbering
*/
function fixNumbering($fixnumbering, $iSurveyID)
{
    Yii::app()->loadHelper("database");
    LimeExpressionManager::RevertUpgradeConditionsToRelevance($iSurveyID);
    //Fix a question id - requires renumbering a question
    $oldqid = $fixnumbering;
    $query = "SELECT qid FROM {{questions}} ORDER BY qid DESC";
    $result = dbSelectLimitAssoc($query, 1);
    foreach ($result->readAll() as $row) {
        $lastqid = $row['qid'];
    }
    $newqid = $lastqid + 1;
    $query = "UPDATE {{questions}} SET qid={$newqid} WHERE qid={$oldqid}";
    $result = db_execute_assosc($query);
    // Update subquestions
    $query = "UPDATE {{questions}} SET parent_qid={$newqid} WHERE parent_qid={$oldqid}";
    $result = db_execute_assosc($query);
    //Update conditions.. firstly conditions FOR this question
    $query = "UPDATE {{conditions}} SET qid={$newqid} WHERE qid={$oldqid}";
    $result = db_execute_assosc($query);
    //Now conditions based upon this question
    $query = "SELECT cqid, cfieldname FROM {{conditions}} WHERE cqid={$oldqid}";
    $result = dbExecuteAssoc($query);
    foreach ($result->readAll() as $row) {
        $switcher[] = array("cqid" => $row['cqid'], "cfieldname" => $row['cfieldname']);
    }
    if (isset($switcher)) {
        foreach ($switcher as $switch) {
            $query = "UPDATE {{conditions}}\n            SET cqid={$newqid},\n            cfieldname='" . str_replace("X" . $oldqid, "X" . $newqid, $switch['cfieldname']) . "'\n            WHERE cqid={$oldqid}";
            $result = db_execute_assosc($query);
        }
    }
    // TMSW Conditions->Relevance:  (1) Call LEM->ConvertConditionsToRelevance()when done. (2) Should relevance for old conditions be removed first?
    //Now question_attributes
    $query = "UPDATE {{question_attributes}} SET qid={$newqid} WHERE qid={$oldqid}";
    $result = db_execute_assosc($query);
    //Now answers
    $query = "UPDATE {{answers}} SET qid={$newqid} WHERE qid={$oldqid}";
    $result = db_execute_assosc($query);
    LimeExpressionManager::UpgradeConditionsToRelevance($iSurveyID);
}
Exemplo n.º 3
0
/**
* fixes the numbering of questions
* @global $dbprefix $dbprefix
* @global $connect $connect
* @global $clang $clang
* @param <type> $fixnumbering
*/
function fixNumbering($fixnumbering)
{
    global $dbprefix, $connect, $clang, $surveyid;
    LimeExpressionManager::RevertUpgradeConditionsToRelevance($surveyid);
    //Fix a question id - requires renumbering a question
    $oldqid = sanitize_int($fixnumbering);
    $query = "SELECT qid FROM {$dbprefix}questions ORDER BY qid DESC";
    $result = db_select_limit_assoc($query, 1) or safe_die($query . "<br />" . $connect->ErrorMsg());
    while ($row = $result->FetchRow()) {
        $lastqid = $row['qid'];
    }
    $newqid = $lastqid + 1;
    $query = "UPDATE {$dbprefix}questions SET qid={$newqid} WHERE qid={$oldqid}";
    $result = $connect->Execute($query) or safe_die($query . "<br />" . $connect->ErrorMsg());
    // Update subquestions
    $query = "UPDATE {$dbprefix}questions SET parent_qid={$newqid} WHERE parent_qid={$oldqid}";
    $result = $connect->Execute($query) or safe_die($query . "<br />" . $connect->ErrorMsg());
    //Update conditions.. firstly conditions FOR this question
    $query = "UPDATE {$dbprefix}conditions SET qid={$newqid} WHERE qid={$oldqid}";
    $result = $connect->Execute($query) or safe_die($query . "<br />" . $connect->ErrorMsg());
    //Now conditions based upon this question
    $query = "SELECT cqid, cfieldname FROM {$dbprefix}conditions WHERE cqid={$oldqid}";
    $result = db_execute_assoc($query) or safe_die($query . "<br />" . $connect->ErrorMsg());
    while ($row = $result->FetchRow()) {
        $switcher[] = array("cqid" => $row['cqid'], "cfieldname" => $row['cfieldname']);
    }
    if (isset($switcher)) {
        foreach ($switcher as $switch) {
            $query = "UPDATE {$dbprefix}conditions\n            SET cqid={$newqid},\n            cfieldname='" . str_replace("X" . $oldqid, "X" . $newqid, $switch['cfieldname']) . "'\n            WHERE cqid={$oldqid}";
            $result = $connect->Execute($query) or safe_die($query . "<br />" . $connect->ErrorMsg());
        }
    }
    //Now question_attributes
    $query = "UPDATE {$dbprefix}question_attributes SET qid={$newqid} WHERE qid={$oldqid}";
    $result = $connect->Execute($query) or safe_die($query . "<br />" . $connect->ErrorMsg());
    //Now answers
    $query = "UPDATE {$dbprefix}answers SET qid={$newqid} WHERE qid={$oldqid}";
    $result = $connect->Execute($query) or safe_die($query . "<br />" . $connect->ErrorMsg());
    LimeExpressionManager::UpgradeConditionsToRelevance($surveyid);
}
Exemplo n.º 4
0
 /**
  * Action to delete a question group.
  *
  * @access public
  * @return void
  */
 public function delete($iSurveyId, $iGroupId)
 {
     $iSurveyId = sanitize_int($iSurveyId);
     if (Permission::model()->hasSurveyPermission($iSurveyId, 'surveycontent', 'delete')) {
         LimeExpressionManager::RevertUpgradeConditionsToRelevance($iSurveyId);
         $iGroupId = sanitize_int($iGroupId);
         $iGroupsDeleted = QuestionGroup::deleteWithDependency($iGroupId, $iSurveyId);
         if ($iGroupsDeleted > 0) {
             fixSortOrderGroups($iSurveyId);
             Yii::app()->setFlashMessage(gT('The question group was deleted.'));
         } else {
             Yii::app()->setFlashMessage(gT('Group could not be deleted'), 'error');
         }
         LimeExpressionManager::UpgradeConditionsToRelevance($iSurveyId);
         $this->getController()->redirect(array('admin/survey/sa/view/surveyid/' . $iSurveyId));
     }
 }
Exemplo n.º 5
0
 /**
  * Action to delete a question group.
  *
  * @access public
  * @return void
  */
 public function delete($iSurveyId, $iGroupId)
 {
     $iSurveyId = sanitize_int($iSurveyId);
     if (hasSurveyPermission($iSurveyId, 'surveycontent', 'delete')) {
         LimeExpressionManager::RevertUpgradeConditionsToRelevance($iSurveyId);
         $iGroupId = sanitize_int($iGroupId);
         $clang = $this->getController()->lang;
         $iGroupsDeleted = Groups::deleteWithDependency($iGroupId, $iSurveyId);
         if ($iGroupsDeleted !== 1) {
             fixSortOrderGroups($iSurveyId);
             Yii::app()->user->setFlash('flashmessage', $clang->gT('The question group was deleted.'));
         } else {
             Yii::app()->user->setFlash('flashmessage', $clang->gT('Group could not be deleted'));
         }
         $this->getController()->redirect($this->getController()->createUrl('admin/survey/sa/view/surveyid/' . $iSurveyId));
         LimeExpressionManager::UpgradeConditionsToRelevance($iSurveyId);
     }
 }
Exemplo n.º 6
0
 /**
  * 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");
 }
Exemplo n.º 7
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");
     }
 }
Exemplo n.º 8
0
/**
* This function imports a LimeSurvey .lss survey XML file
*
* @param mixed $sFullFilepath  The full filepath of the uploaded file
*/
function XMLImportSurvey($sFullFilepath, $sXMLdata = NULL, $sNewSurveyName = NULL, $iDesiredSurveyId = NULL, $bTranslateInsertansTags = true)
{
    Yii::app()->loadHelper('database');
    $clang = Yii::app()->lang;
    $aGIDReplacements = array();
    if ($sXMLdata == NULL) {
        $xml = simplexml_load_file($sFullFilepath);
    } else {
        $xml = simplexml_load_string($sXMLdata);
    }
    if ($xml->LimeSurveyDocType != 'Survey') {
        $results['error'] = $clang->gT("This is not a valid LimeSurvey survey structure XML file.");
        return $results;
    }
    $iDBVersion = (int) $xml->DBVersion;
    $aQIDReplacements = array();
    $aQuotaReplacements = array();
    $results['defaultvalues'] = 0;
    $results['answers'] = 0;
    $results['surveys'] = 0;
    $results['questions'] = 0;
    $results['subquestions'] = 0;
    $results['question_attributes'] = 0;
    $results['groups'] = 0;
    $results['assessments'] = 0;
    $results['quota'] = 0;
    $results['quotals'] = 0;
    $results['quotamembers'] = 0;
    $results['survey_url_parameters'] = 0;
    $results['importwarnings'] = array();
    $aLanguagesSupported = array();
    foreach ($xml->languages->language as $language) {
        $aLanguagesSupported[] = (string) $language;
    }
    $results['languages'] = count($aLanguagesSupported);
    // Import surveys table ====================================================
    foreach ($xml->surveys->rows->row as $row) {
        $insertdata = array();
        foreach ($row as $key => $value) {
            $insertdata[(string) $key] = (string) $value;
        }
        $iOldSID = $results['oldsid'] = $insertdata['sid'];
        if ($iDesiredSurveyId != NULL) {
            $insertdata['wishSID'] = GetNewSurveyID($iDesiredSurveyId);
        }
        if ($iDBVersion <= 143) {
            if (isset($insertdata['private'])) {
                $insertdata['anonymized'] = $insertdata['private'];
            }
            unset($insertdata['private']);
            unset($insertdata['notification']);
        }
        unset($insertdata['expires']);
        unset($insertdata['startdate']);
        //Make sure it is not set active
        $insertdata['active'] = 'N';
        //Set current user to be the owner
        $insertdata['owner_id'] = Yii::app()->session['loginID'];
        if (isset($insertdata['bouncetime']) && $insertdata['bouncetime'] == '') {
            $insertdata['bouncetime'] = NULL;
        }
        if (isset($insertdata['showXquestions'])) {
            $insertdata['showxquestions'] = $insertdata['showXquestions'];
            unset($insertdata['showXquestions']);
        }
        $iNewSID = $results['newsid'] = Survey::model()->insertNewSurvey($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data [1]<br />");
        $results['surveys']++;
    }
    // Import survey languagesettings table ===================================================================================
    foreach ($xml->surveys_languagesettings->rows->row as $row) {
        $insertdata = array();
        foreach ($row as $key => $value) {
            $insertdata[(string) $key] = (string) $value;
        }
        if (!in_array($insertdata['surveyls_language'], $aLanguagesSupported)) {
            continue;
        }
        $insertdata['surveyls_survey_id'] = $iNewSID;
        if ($bTranslateInsertansTags) {
            if ($sNewSurveyName == NULL) {
                $insertdata['surveyls_title'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['surveyls_title']);
            } else {
                $insertdata['surveyls_title'] = translateLinks('survey', $iOldSID, $iNewSID, $sNewSurveyName);
            }
            if (isset($insertdata['surveyls_description'])) {
                $insertdata['surveyls_description'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['surveyls_description']);
            }
            if (isset($insertdata['surveyls_welcometext'])) {
                $insertdata['surveyls_welcometext'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['surveyls_welcometext']);
            }
            if (isset($insertdata['surveyls_urldescription'])) {
                $insertdata['surveyls_urldescription'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['surveyls_urldescription']);
            }
            if (isset($insertdata['surveyls_email_invite'])) {
                $insertdata['surveyls_email_invite'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['surveyls_email_invite']);
            }
            if (isset($insertdata['surveyls_email_remind'])) {
                $insertdata['surveyls_email_remind'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['surveyls_email_remind']);
            }
            if (isset($insertdata['surveyls_email_register'])) {
                $insertdata['surveyls_email_register'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['surveyls_email_register']);
            }
            if (isset($insertdata['surveyls_email_confirm'])) {
                $insertdata['surveyls_email_confirm'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['surveyls_email_confirm']);
            }
        }
        $result = Surveys_languagesettings::model()->insertNewSurvey($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data [2]<br />");
    }
    // Import groups table ===================================================================================
    if (isset($xml->groups->rows->row)) {
        foreach ($xml->groups->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            if (!in_array($insertdata['language'], $aLanguagesSupported)) {
                continue;
            }
            $iOldSID = $insertdata['sid'];
            $insertdata['sid'] = $iNewSID;
            $oldgid = $insertdata['gid'];
            unset($insertdata['gid']);
            // save the old qid
            // now translate any links
            if ($bTranslateInsertansTags) {
                $insertdata['group_name'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['group_name']);
                $insertdata['description'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['description']);
            }
            // Insert the new group
            if (isset($aGIDReplacements[$oldgid])) {
                switchMSSQLIdentityInsert('groups', true);
                $insertdata['gid'] = $aGIDReplacements[$oldgid];
            }
            $newgid = Groups::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data [3]<br />");
            $results['groups']++;
            if (!isset($aGIDReplacements[$oldgid])) {
                $aGIDReplacements[$oldgid] = $newgid;
                // add old and new qid to the mapping array
            } else {
                switchMSSQLIdentityInsert('groups', false);
            }
        }
    }
    // Import questions table ===================================================================================
    // We have to run the question table data two times - first to find all main questions
    // then for subquestions (because we need to determine the new qids for the main questions first)
    if (isset($xml->questions)) {
        foreach ($xml->questions->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            if (!in_array($insertdata['language'], $aLanguagesSupported) || $insertdata['gid'] == 0) {
                continue;
            }
            $iOldSID = $insertdata['sid'];
            $insertdata['sid'] = $iNewSID;
            $insertdata['gid'] = $aGIDReplacements[$insertdata['gid']];
            $oldqid = $insertdata['qid'];
            unset($insertdata['qid']);
            // save the old qid
            // now translate any links
            if ($bTranslateInsertansTags) {
                $insertdata['question'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['question']);
                $insertdata['help'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['help']);
            }
            // Insert the new question
            if (isset($aQIDReplacements[$oldqid])) {
                $insertdata['qid'] = $aQIDReplacements[$oldqid];
                switchMSSQLIdentityInsert('questions', true);
            }
            if ($insertdata) {
                XSSFilterArray($insertdata);
            }
            $newqid = Questions::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data [4]<br />");
            if (!isset($aQIDReplacements[$oldqid])) {
                $aQIDReplacements[$oldqid] = $newqid;
                $results['questions']++;
            } else {
                switchMSSQLIdentityInsert('questions', false);
            }
        }
    }
    // Import subquestions -------------------------------------------------------
    if (isset($xml->subquestions)) {
        foreach ($xml->subquestions->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            if (!in_array($insertdata['language'], $aLanguagesSupported) || $insertdata['gid'] == 0) {
                continue;
            }
            if (!isset($insertdata['mandatory']) || trim($insertdata['mandatory']) == '') {
                $insertdata['mandatory'] = 'N';
            }
            $insertdata['sid'] = $iNewSID;
            $insertdata['gid'] = $aGIDReplacements[(int) $insertdata['gid']];
            $oldsqid = (int) $insertdata['qid'];
            unset($insertdata['qid']);
            // save the old qid
            $insertdata['parent_qid'] = $aQIDReplacements[(int) $insertdata['parent_qid']];
            // remap the parent_qid
            // now translate any links
            if ($bTranslateInsertansTags) {
                $insertdata['question'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['question']);
                if (isset($insertdata['help'])) {
                    $insertdata['help'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['help']);
                }
            }
            if (isset($aQIDReplacements[$oldsqid])) {
                $insertdata['qid'] = $aQIDReplacements[$oldsqid];
                switchMSSQLIdentityInsert('questions', true);
            }
            if ($insertdata) {
                XSSFilterArray($insertdata);
            }
            $newsqid = Questions::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data [5]<br />");
            if (!isset($insertdata['qid'])) {
                $aQIDReplacements[$oldsqid] = $newsqid;
                // add old and new qid to the mapping array
            } else {
                switchMSSQLIdentityInsert('questions', false);
            }
            $results['subquestions']++;
        }
    }
    // Import answers ------------------------------------------------------------
    if (isset($xml->answers)) {
        foreach ($xml->answers->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            if (!in_array($insertdata['language'], $aLanguagesSupported) || !isset($aQIDReplacements[(int) $insertdata['qid']])) {
                continue;
            }
            $insertdata['qid'] = $aQIDReplacements[(int) $insertdata['qid']];
            // remap the parent_qid
            // now translate any links
            if ($bTranslateInsertansTags) {
                $insertdata['answer'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['answer']);
            }
            if ($insertdata) {
                XSSFilterArray($insertdata);
            }
            $result = Answers::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data<br />");
            $results['answers']++;
        }
    }
    // Import questionattributes -------------------------------------------------
    if (isset($xml->question_attributes)) {
        $aAllAttributes = questionAttributes(true);
        foreach ($xml->question_attributes->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            unset($insertdata['qaid']);
            if (!isset($aQIDReplacements[(int) $insertdata['qid']])) {
                continue;
            }
            $insertdata['qid'] = $aQIDReplacements[(int) $insertdata['qid']];
            // remap the qid
            if ($iDBVersion < 148 && isset($aAllAttributes[$insertdata['attribute']]['i18n']) && $aAllAttributes[$insertdata['attribute']]['i18n']) {
                foreach ($aLanguagesSupported as $sLanguage) {
                    $insertdata['language'] = $sLanguage;
                    if ($insertdata) {
                        XSSFilterArray($insertdata);
                    }
                    $result = Question_attributes::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data<br />");
                }
            } else {
                $result = Question_attributes::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data<br />");
            }
            $results['question_attributes']++;
        }
    }
    // Import defaultvalues ------------------------------------------------------
    if (isset($xml->defaultvalues)) {
        $results['defaultvalues'] = 0;
        foreach ($xml->defaultvalues->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            $insertdata['qid'] = $aQIDReplacements[(int) $insertdata['qid']];
            // remap the qid
            if (isset($aQIDReplacements[(int) $insertdata['sqid']])) {
                $insertdata['sqid'] = $aQIDReplacements[(int) $insertdata['sqid']];
            }
            // remap the subquestion id
            if ($insertdata) {
                XSSFilterArray($insertdata);
            }
            // now translate any links
            $result = Defaultvalues::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data<br />");
            $results['defaultvalues']++;
        }
    }
    $aOldNewFieldmap = reverseTranslateFieldNames($iOldSID, $iNewSID, $aGIDReplacements, $aQIDReplacements);
    // Import conditions ---------------------------------------------------------
    if (isset($xml->conditions)) {
        $results['conditions'] = 0;
        foreach ($xml->conditions->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            // replace the qid for the new one (if there is no new qid in the $aQIDReplacements array it mean that this condition is orphan -> error, skip this record)
            if (isset($aQIDReplacements[$insertdata['qid']])) {
                $insertdata['qid'] = $aQIDReplacements[$insertdata['qid']];
                // remap the qid
            } else {
                continue;
            }
            // a problem with this answer record -> don't consider
            if ($insertdata['cqid'] != 0) {
                if (isset($aQIDReplacements[$insertdata['cqid']])) {
                    $oldcqid = $insertdata['cqid'];
                    //Save for cfield transformation
                    $insertdata['cqid'] = $aQIDReplacements[$insertdata['cqid']];
                    // remap the qid
                } else {
                    continue;
                }
                // a problem with this answer record -> don't consider
                list($oldcsid, $oldcgid, $oldqidanscode) = explode("X", $insertdata["cfieldname"], 3);
                // replace the gid for the new one in the cfieldname(if there is no new gid in the $aGIDReplacements array it means that this condition is orphan -> error, skip this record)
                if (!isset($aGIDReplacements[$oldcgid])) {
                    continue;
                }
            }
            unset($insertdata["cid"]);
            // recreate the cfieldname with the new IDs
            if ($insertdata['cqid'] != 0) {
                if (preg_match("/^\\+/", $oldcsid)) {
                    $newcfieldname = '+' . $iNewSID . "X" . $aGIDReplacements[$oldcgid] . "X" . $insertdata["cqid"] . substr($oldqidanscode, strlen($oldcqid));
                } else {
                    $newcfieldname = $iNewSID . "X" . $aGIDReplacements[$oldcgid] . "X" . $insertdata["cqid"] . substr($oldqidanscode, strlen($oldcqid));
                }
            } else {
                // The cfieldname is a not a previous question cfield but a {XXXX} replacement field
                $newcfieldname = $insertdata["cfieldname"];
            }
            $insertdata["cfieldname"] = $newcfieldname;
            if (trim($insertdata["method"]) == '') {
                $insertdata["method"] = '==';
            }
            // Now process the value and replace @sgqa@ codes
            if (preg_match("/^@(.*)@\$/", $insertdata["value"], $cfieldnameInCondValue)) {
                if (isset($aOldNewFieldmap[$cfieldnameInCondValue[1]])) {
                    $newvalue = '@' . $aOldNewFieldmap[$cfieldnameInCondValue[1]] . '@';
                    $insertdata["value"] = $newvalue;
                }
            }
            // now translate any links
            $result = Conditions::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data<br />");
            $results['conditions']++;
        }
    }
    // TMSW Conditions->Relevance:  Call  LEM->ConvertConditionsToRelevance
    // Import assessments --------------------------------------------------------
    if (isset($xml->assessments)) {
        foreach ($xml->assessments->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            if ($insertdata['gid'] > 0) {
                $insertdata['gid'] = $aGIDReplacements[(int) $insertdata['gid']];
                // remap the qid
            }
            $insertdata['sid'] = $iNewSID;
            // remap the survey id
            // now translate any links
            $result = Assessment::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data<br />");
            $results['assessments']++;
        }
    }
    // Import quota --------------------------------------------------------------
    if (isset($xml->quota)) {
        foreach ($xml->quota->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            $insertdata['sid'] = $iNewSID;
            // remap the survey id
            $oldid = $insertdata['id'];
            unset($insertdata['id']);
            // now translate any links
            $result = Quota::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data<br />");
            $aQuotaReplacements[$oldid] = Yii::app()->db->getCommandBuilder()->getLastInsertID('{{quota}}');
            $results['quota']++;
        }
    }
    // Import quota_members ------------------------------------------------------
    if (isset($xml->quota_members)) {
        foreach ($xml->quota_members->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            $insertdata['sid'] = $iNewSID;
            // remap the survey id
            $insertdata['qid'] = $aQIDReplacements[(int) $insertdata['qid']];
            // remap the qid
            $insertdata['quota_id'] = $aQuotaReplacements[(int) $insertdata['quota_id']];
            // remap the qid
            unset($insertdata['id']);
            // now translate any links
            $result = Quota_members::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data<br />");
            $results['quotamembers']++;
        }
    }
    // Import quota_languagesettings----------------------------------------------
    if (isset($xml->quota_languagesettings)) {
        foreach ($xml->quota_languagesettings->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            $insertdata['quotals_quota_id'] = $aQuotaReplacements[(int) $insertdata['quotals_quota_id']];
            // remap the qid
            unset($insertdata['quotals_id']);
            $result = Quota_languagesettings::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data<br />");
            $results['quotals']++;
        }
    }
    // Import survey_url_parameters ----------------------------------------------
    if (isset($xml->survey_url_parameters)) {
        foreach ($xml->survey_url_parameters->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            $insertdata['sid'] = $iNewSID;
            // remap the survey id
            if (isset($insertdata['targetsqid']) && $insertdata['targetsqid'] != '') {
                $insertdata['targetsqid'] = $aSQIDReplacements[(int) $insertdata['targetsqid']];
                // remap the qid
            }
            if (isset($insertdata['targetqid']) && $insertdata['targetqid'] != '') {
                $insertdata['targetqid'] = $aQIDReplacements[(int) $insertdata['targetqid']];
                // remap the qid
            }
            unset($insertdata['id']);
            $result = Survey_url_parameters::model()->insertRecord($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data<br />");
            $results['survey_url_parameters']++;
        }
    }
    // Set survey rights
    Survey_permissions::model()->giveAllSurveyPermissions(Yii::app()->session['loginID'], $iNewSID);
    $aOldNewFieldmap = reverseTranslateFieldNames($iOldSID, $iNewSID, $aGIDReplacements, $aQIDReplacements);
    $results['FieldReMap'] = $aOldNewFieldmap;
    LimeExpressionManager::SetSurveyId($iNewSID);
    translateInsertansTags($iNewSID, $iOldSID, $aOldNewFieldmap);
    LimeExpressionManager::RevertUpgradeConditionsToRelevance($iNewSID);
    LimeExpressionManager::UpgradeConditionsToRelevance($iNewSID);
    return $results;
}
<?php

$data = LimeExpressionManager::UpgradeConditionsToRelevance();
if (is_null($data)) {
    echo "No conditions found in database";
} else {
    echo "Found and converted conditions for " . count($data) . " question(s)<br/>";
    echo "<pre>";
    print_r($data);
    echo "</pre>";
}
Exemplo n.º 10
0
/**
* This function imports a LimeSurvey .lsg question group XML file
*
* @param mixed $sFullFilepath  The full filepath of the uploaded file
* @param mixed $newsid The new survey id - the group will always be added after the last group in the survey
*/
function XMLImportGroup($sFullFilepath, $newsid)
{
    global $connect, $dbprefix, $clang;
    $aLanguagesSupported = array();
    // this array will keep all the languages supported for the survey
    $sBaseLanguage = GetBaseLanguageFromSurveyID($newsid);
    $aLanguagesSupported[] = $sBaseLanguage;
    // adds the base language to the list of supported languages
    $aLanguagesSupported = array_merge($aLanguagesSupported, GetAdditionalLanguagesFromSurveyID($newsid));
    $xml = @simplexml_load_file($sFullFilepath);
    if ($xml == false || $xml->LimeSurveyDocType != 'Group') {
        safe_die('This is not a valid LimeSurvey group structure XML file.');
    }
    $dbversion = (double) $xml->DBVersion;
    $aQIDReplacements = array();
    $results['defaultvalues'] = 0;
    $results['answers'] = 0;
    $results['question_attributes'] = 0;
    $results['subquestions'] = 0;
    $results['conditions'] = 0;
    $results['groups'] = 0;
    $importlanguages = array();
    foreach ($xml->languages->language as $language) {
        $importlanguages[] = (string) $language;
    }
    if (!in_array($sBaseLanguage, $importlanguages)) {
        $results['fatalerror'] = $clang->gT("The languages of the imported group file must at least include the base language of this survey.");
        return $results;
    }
    // First get an overview of fieldnames - it's not useful for the moment but might be with newer versions
    /*
        $fieldnames=array();
        foreach ($xml->questions->fields->fieldname as $fieldname )
        {
            $fieldnames[]=(string)$fieldname;
        };*/
    // Import group table ===================================================================================
    $tablename = $dbprefix . 'groups';
    $newgrouporder = $connect->GetOne("SELECT MAX(group_order) AS maxqo FROM " . db_table_name('groups') . " WHERE sid={$newsid}");
    if (is_null($newgrouporder)) {
        $newgrouporder = 0;
    } else {
        $newgrouporder++;
    }
    foreach ($xml->groups->rows->row as $row) {
        $insertdata = array();
        foreach ($row as $key => $value) {
            $insertdata[(string) $key] = (string) $value;
        }
        $oldsid = $insertdata['sid'];
        $insertdata['sid'] = $newsid;
        $insertdata['group_order'] = $newgrouporder;
        $oldgid = $insertdata['gid'];
        unset($insertdata['gid']);
        // save the old qid
        // now translate any links
        $insertdata['group_name'] = translink('survey', $oldsid, $newsid, $insertdata['group_name']);
        $insertdata['description'] = translink('survey', $oldsid, $newsid, $insertdata['description']);
        // Insert the new question
        if (isset($aGIDReplacements[$oldgid])) {
            $insertdata['gid'] = $aGIDReplacements[$oldgid];
            db_switchIDInsert('groups', true);
        }
        $query = $connect->GetInsertSQL($tablename, $insertdata);
        $result = $connect->Execute($query) or safe_die($clang->gT("Error") . ": Failed to insert data<br />{$query}<br />\n" . $connect->ErrorMsg());
        $results['groups']++;
        if (!isset($aGIDReplacements[$oldgid])) {
            $newgid = $connect->Insert_ID($tablename, "gid");
            // save this for later
            $aGIDReplacements[$oldgid] = $newgid;
            // add old and new qid to the mapping array
        } else {
            db_switchIDInsert('groups', false);
        }
    }
    // Import questions table ===================================================================================
    // We have to run the question table data two times - first to find all main questions
    // then for subquestions (because we need to determine the new qids for the main questions first)
    $tablename = $dbprefix . 'questions';
    $results['questions'] = 0;
    if (isset($xml->questions)) {
        foreach ($xml->questions->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            $oldsid = $insertdata['sid'];
            $insertdata['sid'] = $newsid;
            if (!isset($aGIDReplacements[$insertdata['gid']]) || trim($insertdata['title']) == '') {
                continue;
            }
            // Skip questions with invalid group id
            $insertdata['gid'] = $aGIDReplacements[$insertdata['gid']];
            $oldqid = $insertdata['qid'];
            unset($insertdata['qid']);
            // save the old qid
            // now translate any links
            $insertdata['title'] = translink('survey', $oldsid, $newsid, $insertdata['title']);
            $insertdata['question'] = translink('survey', $oldsid, $newsid, $insertdata['question']);
            $insertdata['help'] = translink('survey', $oldsid, $newsid, $insertdata['help']);
            // Insert the new question
            if (isset($aQIDReplacements[$oldqid])) {
                $insertdata['qid'] = $aQIDReplacements[$oldqid];
                db_switchIDInsert('questions', true);
            }
            $query = $connect->GetInsertSQL($tablename, $insertdata);
            $result = $connect->Execute($query) or safe_die($clang->gT("Error") . ": Failed to insert data<br />{$query}<br />\n" . $connect->ErrorMsg());
            if (!isset($aQIDReplacements[$oldqid])) {
                $newqid = $connect->Insert_ID($tablename, "qid");
                // save this for later
                $aQIDReplacements[$oldqid] = $newqid;
                // add old and new qid to the mapping array
                $results['questions']++;
            } else {
                db_switchIDInsert('questions', false);
            }
        }
    }
    // Import subquestions --------------------------------------------------------------
    if (isset($xml->subquestions)) {
        foreach ($xml->subquestions->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            $insertdata['sid'] = $newsid;
            if (!isset($aGIDReplacements[$insertdata['gid']])) {
                continue;
            }
            // Skip questions with invalid group id
            $insertdata['gid'] = $aGIDReplacements[(int) $insertdata['gid']];
            $oldsqid = (int) $insertdata['qid'];
            unset($insertdata['qid']);
            // save the old qid
            if (!isset($aQIDReplacements[(int) $insertdata['parent_qid']])) {
                continue;
            }
            // Skip subquestions with invalid parent_qids
            $insertdata['parent_qid'] = $aQIDReplacements[(int) $insertdata['parent_qid']];
            // remap the parent_qid
            // now translate any links
            $insertdata['title'] = translink('survey', $oldsid, $newsid, $insertdata['title']);
            $insertdata['question'] = translink('survey', $oldsid, $newsid, $insertdata['question']);
            $insertdata['help'] = isset($insertdata['help']) ? translink('survey', $oldsid, $newsid, $insertdata['help']) : '';
            if (isset($aQIDReplacements[$oldsqid])) {
                $insertdata['qid'] = $aQIDReplacements[$oldsqid];
                db_switchIDInsert('questions', true);
            }
            $query = $connect->GetInsertSQL($tablename, $insertdata);
            $result = $connect->Execute($query) or safe_die($clang->gT("Error") . ": Failed to insert data<br />{$query}<br />\n" . $connect->ErrorMsg());
            $newsqid = $connect->Insert_ID($tablename, "qid");
            // save this for later
            if (!isset($insertdata['qid'])) {
                $aQIDReplacements[$oldsqid] = $newsqid;
                // add old and new qid to the mapping array
            } else {
                db_switchIDInsert('questions', false);
            }
            $results['subquestions']++;
        }
    }
    // Import answers --------------------------------------------------------------
    if (isset($xml->answers)) {
        $tablename = $dbprefix . 'answers';
        foreach ($xml->answers->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            if (!isset($aQIDReplacements[(int) $insertdata['qid']])) {
                continue;
            }
            // Skip questions with invalid group id
            $insertdata['qid'] = $aQIDReplacements[(int) $insertdata['qid']];
            // remap the parent_qid
            // now translate any links
            $query = $connect->GetInsertSQL($tablename, $insertdata);
            $result = $connect->Execute($query) or safe_die($clang->gT("Error") . ": Failed to insert data<br />{$query}<br />\n" . $connect->ErrorMsg());
            $results['answers']++;
        }
    }
    // Import questionattributes --------------------------------------------------------------
    if (isset($xml->question_attributes)) {
        $tablename = $dbprefix . 'question_attributes';
        foreach ($xml->question_attributes->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            unset($insertdata['qaid']);
            if (!isset($aQIDReplacements[(int) $insertdata['qid']])) {
                continue;
            }
            // Skip questions with invalid group id
            $insertdata['qid'] = $aQIDReplacements[(int) $insertdata['qid']];
            // remap the parent_qid
            // now translate any links
            $query = $connect->GetInsertSQL($tablename, $insertdata);
            $result = $connect->Execute($query) or safe_die($clang->gT("Error") . ": Failed to insert data<br />{$query}<br />\n" . $connect->ErrorMsg());
            $results['question_attributes']++;
        }
    }
    // Import defaultvalues --------------------------------------------------------------
    if (isset($xml->defaultvalues)) {
        $tablename = $dbprefix . 'defaultvalues';
        $results['defaultvalues'] = 0;
        foreach ($xml->defaultvalues->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            $insertdata['qid'] = $aQIDReplacements[(int) $insertdata['qid']];
            // remap the qid
            if (!isset($aQIDReplacements[(int) $insertdata['sqid']]) || is_null($aQIDReplacements[(int) $insertdata['sqid']])) {
                $insertdata['sqid'] = 0;
                // defaults for non-array types
            } else {
                $insertdata['sqid'] = $aQIDReplacements[(int) $insertdata['sqid']];
                // remap the subqeustion id
            }
            // now translate any links
            $query = $connect->GetInsertSQL($tablename, $insertdata);
            $result = $connect->Execute($query) or safe_die($clang->gT("Error") . ": Failed to insert data<br />" . $query . "<br />\n" . $connect->ErrorMsg());
            $results['defaultvalues']++;
        }
    }
    // Import conditions --------------------------------------------------------------
    if (isset($xml->conditions)) {
        $tablename = $dbprefix . 'conditions';
        foreach ($xml->conditions->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            // replace the qid for the new one (if there is no new qid in the $aQIDReplacements array it mean that this condition is orphan -> error, skip this record)
            if (isset($aQIDReplacements[$insertdata['qid']])) {
                $insertdata['qid'] = $aQIDReplacements[$insertdata['qid']];
                // remap the qid
            } else {
                continue;
            }
            // a problem with this answer record -> don't consider
            if (isset($aQIDReplacements[$insertdata['cqid']])) {
                $insertdata['cqid'] = $aQIDReplacements[$insertdata['cqid']];
                // remap the qid
            } else {
                continue;
            }
            // a problem with this answer record -> don't consider
            list($oldcsid, $oldcgid, $oldqidanscode) = explode("X", $insertdata["cfieldname"], 3);
            if ($oldcgid != $oldgid) {
                // this means that the condition is in another group (so it should not have to be been exported -> skip it
                continue;
            }
            unset($insertdata["cid"]);
            // recreate the cfieldname with the new IDs
            if (preg_match("/^\\+/", $oldcsid)) {
                $newcfieldname = '+' . $newsid . "X" . $newgid . "X" . $insertdata["cqid"] . substr($oldqidanscode, strlen($oldqid));
            } else {
                $newcfieldname = $newsid . "X" . $newgid . "X" . $insertdata["cqid"] . substr($oldqidanscode, strlen($oldqid));
            }
            $insertdata["cfieldname"] = $newcfieldname;
            if (trim($insertdata["method"]) == '') {
                $insertdata["method"] = '==';
            }
            // now translate any links
            $query = $connect->GetInsertSQL($tablename, $insertdata);
            $result = $connect->Execute($query) or safe_die($clang->gT("Error") . ": Failed to insert data<br />\$query<br />\n" . $connect->ErrorMsg());
            $results['conditions']++;
        }
    }
    LimeExpressionManager::RevertUpgradeConditionsToRelevance($newsid);
    LimeExpressionManager::UpgradeConditionsToRelevance($newsid);
    $results['newgid'] = $newgid;
    $results['labelsets'] = 0;
    $results['labels'] = 0;
    return $results;
}
Exemplo n.º 11
0
/**
* This function imports a LimeSurvey .lss survey XML file
*
* @param mixed $sFullFilepath  The full filepath of the uploaded file
*/
function XMLImportSurvey($sFullFilepath, $sXMLdata = NULL, $sNewSurveyName = NULL, $iDesiredSurveyId = NULL, $bTranslateInsertansTags = true)
{
    global $connect, $dbprefix, $clang, $timeadjust;
    $iDesiredSurveyId = intval($iDesiredSurveyId);
    $results['error'] = false;
    if ($sXMLdata == NULL) {
        $xml = simplexml_load_file($sFullFilepath);
    } else {
        $xml = simplexml_load_string($sXMLdata);
    }
    if ($xml->LimeSurveyDocType != 'Survey') {
        $results['error'] = $clang->gT("This is not a valid LimeSurvey survey structure XML file.");
        return $results;
    } else {
        //$results['error'] = $clang->gT("This is VALID LimeSurvey survey structure XML file.");
        //echo $clang->gT("This is VALID LimeSurvey survey structure XML file.");
        //return $results;
    }
    $dbversion = (double) $xml->DBVersion;
    $aQIDReplacements = array();
    $aQuotaReplacements = array();
    $results['defaultvalues'] = 0;
    $results['answers'] = 0;
    $results['surveys'] = 0;
    $results['questions'] = 0;
    $results['subquestions'] = 0;
    $results['question_attributes'] = 0;
    $results['groups'] = 0;
    $results['assessments'] = 0;
    $results['quota'] = 0;
    $results['quotals'] = 0;
    $results['quotamembers'] = 0;
    $results['importwarnings'] = array();
    $aLanguagesSupported = array();
    foreach ($xml->languages->language as $language) {
        $aLanguagesSupported[] = (string) $language;
    }
    $results['languages'] = count($aLanguagesSupported);
    // First get an overview of fieldnames - it's not useful for the moment but might be with newer versions
    /*
        $fieldnames=array();
        foreach ($xml->questions->fields->fieldname as $fieldname )
        {
            $fieldnames[]=(string)$fieldname;
        };*/
    // Import surveys table ===================================================================================
    $tablename = $dbprefix . 'surveys';
    foreach ($xml->surveys->rows->row as $row) {
        $insertdata = array();
        foreach ($row as $key => $value) {
            $insertdata[(string) $key] = (string) $value;
        }
        $oldsid = $insertdata['sid'];
        if ($iDesiredSurveyId != NULL) {
            $newsid = GetNewSurveyID($iDesiredSurveyId);
        } else {
            $newsid = GetNewSurveyID($oldsid);
        }
        if ($dbversion <= 143) {
            $insertdata['anonymized'] = $insertdata['private'];
            unset($insertdata['private']);
            unset($insertdata['notification']);
        }
        $insertdata['startdate'] = NULL;
        //Now insert the new SID and change some values
        $insertdata['sid'] = $newsid;
        //Make sure it is not set active
        $insertdata['active'] = 'N';
        //Set current user to be the owner
        $insertdata['owner_id'] = $_SESSION['loginID'];
        //Change creation date to import date
        $insertdata['datecreated'] = $connect->BindTimeStamp(date_shift(date("Y-m-d H:i:s"), "Y-m-d", $timeadjust));
        db_switchIDInsert('surveys', true);
        $query = $connect->GetInsertSQL($tablename, $insertdata);
        $result = $connect->Execute($query) or safe_die($clang->gT("Error") . ": Failed to insert data<br />{$query}<br />\n" . $connect->ErrorMsg());
        $results['surveys']++;
        db_switchIDInsert('surveys', false);
    }
    $results['newsid'] = $newsid;
    // Import survey languagesettings table ===================================================================================
    $tablename = $dbprefix . 'surveys_languagesettings';
    foreach ($xml->surveys_languagesettings->rows->row as $row) {
        $insertdata = array();
        foreach ($row as $key => $value) {
            $insertdata[(string) $key] = (string) $value;
        }
        $insertdata['surveyls_survey_id'] = $newsid;
        if ($sNewSurveyName == NULL) {
            $insertdata['surveyls_title'] = translink('survey', $oldsid, $newsid, $insertdata['surveyls_title']);
        } else {
            $insertdata['surveyls_title'] = translink('survey', $oldsid, $newsid, $sNewSurveyName);
        }
        $insertdata['surveyls_description'] = translink('survey', $oldsid, $newsid, $insertdata['surveyls_description']);
        $insertdata['surveyls_welcometext'] = translink('survey', $oldsid, $newsid, $insertdata['surveyls_welcometext']);
        $insertdata['surveyls_urldescription'] = translink('survey', $oldsid, $newsid, $insertdata['surveyls_urldescription']);
        $insertdata['surveyls_email_invite'] = translink('survey', $oldsid, $newsid, $insertdata['surveyls_email_invite']);
        $insertdata['surveyls_email_remind'] = translink('survey', $oldsid, $newsid, $insertdata['surveyls_email_remind']);
        $insertdata['surveyls_email_register'] = translink('survey', $oldsid, $newsid, $insertdata['surveyls_email_register']);
        $insertdata['surveyls_email_confirm'] = translink('survey', $oldsid, $newsid, $insertdata['surveyls_email_confirm']);
        $query = $connect->GetInsertSQL($tablename, $insertdata);
        $result = $connect->Execute($query) or safe_die($clang->gT("Error") . ": Failed to insert data<br />{$query}<br />\n" . $connect->ErrorMsg());
    }
    // Import groups table ===================================================================================
    $tablename = $dbprefix . 'groups';
    foreach ($xml->groups->rows->row as $row) {
        $insertdata = array();
        foreach ($row as $key => $value) {
            $insertdata[(string) $key] = (string) $value;
        }
        $oldsid = $insertdata['sid'];
        $insertdata['sid'] = $newsid;
        $oldgid = $insertdata['gid'];
        unset($insertdata['gid']);
        // save the old qid
        // now translate any links
        $insertdata['group_name'] = translink('survey', $oldsid, $newsid, $insertdata['group_name']);
        $insertdata['description'] = translink('survey', $oldsid, $newsid, $insertdata['description']);
        // Insert the new group
        if (isset($aGIDReplacements[$oldgid])) {
            db_switchIDInsert('groups', true);
            $insertdata['gid'] = $aGIDReplacements[$oldgid];
        }
        $query = $connect->GetInsertSQL($tablename, $insertdata);
        $result = $connect->Execute($query) or safe_die($clang->gT("Error") . ": Failed to insert data<br />{$query}<br />\n" . $connect->ErrorMsg());
        $results['groups']++;
        if (!isset($aGIDReplacements[$oldgid])) {
            $newgid = $connect->Insert_ID($tablename, "gid");
            // save this for later
            $aGIDReplacements[$oldgid] = $newgid;
            // add old and new qid to the mapping array
        } else {
            db_switchIDInsert('groups', false);
        }
    }
    // Import questions table ===================================================================================
    // We have to run the question table data two times - first to find all main questions
    // then for subquestions (because we need to determine the new qids for the main questions first)
    if (isset($xml->questions)) {
        $tablename = $dbprefix . 'questions';
        foreach ($xml->questions->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            $oldsid = $insertdata['sid'];
            $insertdata['sid'] = $newsid;
            $insertdata['gid'] = $aGIDReplacements[$insertdata['gid']];
            $oldqid = $insertdata['qid'];
            unset($insertdata['qid']);
            // save the old qid
            // now translate any links
            $insertdata['title'] = translink('survey', $oldsid, $newsid, $insertdata['title']);
            $insertdata['question'] = translink('survey', $oldsid, $newsid, $insertdata['question']);
            $insertdata['help'] = translink('survey', $oldsid, $newsid, $insertdata['help']);
            // Insert the new question
            if (isset($aQIDReplacements[$oldqid])) {
                $insertdata['qid'] = $aQIDReplacements[$oldqid];
                db_switchIDInsert('questions', true);
            }
            $query = $connect->GetInsertSQL($tablename, $insertdata);
            $result = $connect->Execute($query) or safe_die($clang->gT("Error") . ": Failed to insert data<br />{$query}<br />\n" . $connect->ErrorMsg());
            if (!isset($aQIDReplacements[$oldqid])) {
                $newqid = $connect->Insert_ID($tablename, "qid");
                // save this for later
                $aQIDReplacements[$oldqid] = $newqid;
                // add old and new qid to the mapping array
                $results['questions']++;
            } else {
                db_switchIDInsert('questions', false);
            }
        }
    }
    // Import subquestions --------------------------------------------------------------
    if (isset($xml->subquestions)) {
        $tablename = $dbprefix . 'questions';
        foreach ($xml->subquestions->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            $insertdata['sid'] = $newsid;
            $insertdata['gid'] = $aGIDReplacements[(int) $insertdata['gid']];
            $oldsqid = (int) $insertdata['qid'];
            unset($insertdata['qid']);
            // save the old qid
            $insertdata['parent_qid'] = $aQIDReplacements[(int) $insertdata['parent_qid']];
            // remap the parent_qid
            // now translate any links
            $insertdata['title'] = translink('survey', $oldsid, $newsid, $insertdata['title']);
            $insertdata['question'] = translink('survey', $oldsid, $newsid, $insertdata['question']);
            $insertdata['help'] = translink('survey', $oldsid, $newsid, $insertdata['help']);
            if (isset($aQIDReplacements[$oldsqid])) {
                $insertdata['qid'] = $aQIDReplacements[$oldsqid];
                db_switchIDInsert('questions', true);
            }
            $query = $connect->GetInsertSQL($tablename, $insertdata);
            $result = $connect->Execute($query) or safe_die($clang->gT("Error") . ": Failed to insert data<br />{$query}<br />\n" . $connect->ErrorMsg());
            $newsqid = $connect->Insert_ID($tablename, "qid");
            // save this for later
            if (!isset($insertdata['qid'])) {
                $aQIDReplacements[$oldsqid] = $newsqid;
                // add old and new qid to the mapping array
            } else {
                db_switchIDInsert('questions', false);
            }
            $results['subquestions']++;
        }
    }
    // Import answers --------------------------------------------------------------
    if (isset($xml->answers)) {
        $tablename = $dbprefix . 'answers';
        foreach ($xml->answers->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            $insertdata['qid'] = $aQIDReplacements[(int) $insertdata['qid']];
            // remap the parent_qid
            // now translate any links
            $insertdata['answer'] = translink('survey', $oldsid, $newsid, $insertdata['answer']);
            $query = $connect->GetInsertSQL($tablename, $insertdata);
            $result = $connect->Execute($query) or safe_die($clang->gT("Error") . ": Failed to insert data<br />{$query}<br />\n" . $connect->ErrorMsg());
            $results['answers']++;
        }
    }
    // Import questionattributes --------------------------------------------------------------
    if (isset($xml->question_attributes)) {
        $tablename = $dbprefix . 'question_attributes';
        foreach ($xml->question_attributes->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            unset($insertdata['qaid']);
            $insertdata['qid'] = $aQIDReplacements[(int) $insertdata['qid']];
            // remap the parent_qid
            // now translate any links
            $query = $connect->GetInsertSQL($tablename, $insertdata);
            $result = $connect->Execute($query) or safe_die($clang->gT("Error") . ": Failed to insert data<br />{$query}<br />\n" . $connect->ErrorMsg());
            $results['question_attributes']++;
        }
    }
    // Import defaultvalues --------------------------------------------------------------
    if (isset($xml->defaultvalues)) {
        $tablename = $dbprefix . 'defaultvalues';
        $results['defaultvalues'] = 0;
        foreach ($xml->defaultvalues->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            $insertdata['qid'] = $aQIDReplacements[(int) $insertdata['qid']];
            // remap the qid
            if (isset($aQIDReplacements[(int) $insertdata['sqid']])) {
                $insertdata['sqid'] = $aQIDReplacements[(int) $insertdata['sqid']];
            }
            // remap the subquestion id
            // now translate any links
            $query = $connect->GetInsertSQL($tablename, $insertdata);
            $result = $connect->Execute($query) or safe_die($clang->gT("Error") . ": Failed to insert data<br />{$query}<br />\n" . $connect->ErrorMsg());
            $results['defaultvalues']++;
        }
    }
    $aOldNewFieldmap = aReverseTranslateFieldnames($oldsid, $newsid, $aGIDReplacements, $aQIDReplacements);
    // Import conditions --------------------------------------------------------------
    if (isset($xml->conditions)) {
        $tablename = $dbprefix . 'conditions';
        $results['conditions'] = 0;
        foreach ($xml->conditions->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            // replace the qid for the new one (if there is no new qid in the $aQIDReplacements array it mean that this condition is orphan -> error, skip this record)
            if (isset($aQIDReplacements[$insertdata['qid']])) {
                $insertdata['qid'] = $aQIDReplacements[$insertdata['qid']];
                // remap the qid
            } else {
                continue;
            }
            // a problem with this answer record -> don't consider
            if ($insertdata['cqid'] != 0) {
                if (isset($aQIDReplacements[$insertdata['cqid']])) {
                    $oldcqid = $insertdata['cqid'];
                    //Save for cfield transformation
                    $insertdata['cqid'] = $aQIDReplacements[$insertdata['cqid']];
                    // remap the qid
                } else {
                    continue;
                }
                // a problem with this answer record -> don't consider
                list($oldcsid, $oldcgid, $oldqidanscode) = explode("X", $insertdata["cfieldname"], 3);
                // replace the gid for the new one in the cfieldname(if there is no new gid in the $aGIDReplacements array it means that this condition is orphan -> error, skip this record)
                if (!isset($aGIDReplacements[$oldcgid])) {
                    continue;
                }
            }
            unset($insertdata["cid"]);
            // recreate the cfieldname with the new IDs
            if ($insertdata['cqid'] != 0) {
                if (preg_match("/^\\+/", $oldcsid)) {
                    $newcfieldname = '+' . $newsid . "X" . $aGIDReplacements[$oldcgid] . "X" . $insertdata["cqid"] . substr($oldqidanscode, strlen($oldcqid));
                } else {
                    $newcfieldname = $newsid . "X" . $aGIDReplacements[$oldcgid] . "X" . $insertdata["cqid"] . substr($oldqidanscode, strlen($oldcqid));
                }
            } else {
                // The cfieldname is a not a previous question cfield but a {XXXX} replacement field
                $newcfieldname = $insertdata["cfieldname"];
            }
            $insertdata["cfieldname"] = $newcfieldname;
            if (trim($insertdata["method"]) == '') {
                $insertdata["method"] = '==';
            }
            // Now process the value and replace @sgqa@ codes TIBO
            if (preg_match("/^@(.*)@\$/", $insertdata["value"], $cfieldnameInCondValue)) {
                if (isset($aOldNewFieldmap[$cfieldnameInCondValue[1]])) {
                    $newvalue = '@' . $aOldNewFieldmap[$cfieldnameInCondValue[1]] . '@';
                    $insertdata["value"] = $newvalue;
                }
            }
            // now translate any links
            $query = $connect->GetInsertSQL($tablename, $insertdata);
            $result = $connect->Execute($query) or safe_die($clang->gT("Error") . ": Failed to insert data<br />{$query}<br />\n" . $connect->ErrorMsg());
            $results['conditions']++;
        }
    }
    // Import assessments --------------------------------------------------------------
    if (isset($xml->assessments)) {
        $tablename = $dbprefix . 'assessments';
        foreach ($xml->assessments->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            if ($insertdata['gid'] > 0) {
                $insertdata['gid'] = $aGIDReplacements[(int) $insertdata['gid']];
                // remap the qid
            }
            $insertdata['sid'] = $newsid;
            // remap the survey id
            unset($insertdata['id']);
            // now translate any links
            $query = $connect->GetInsertSQL($tablename, $insertdata);
            $result = $connect->Execute($query) or safe_die($clang->gT("Error") . ": Failed to insert data<br />{$query}<br />\n" . $connect->ErrorMsg());
            $results['assessments']++;
        }
    }
    // Import quota --------------------------------------------------------------
    if (isset($xml->quota)) {
        $tablename = $dbprefix . 'quota';
        foreach ($xml->quota->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            $insertdata['sid'] = $newsid;
            // remap the survey id
            $oldid = $insertdata['id'];
            unset($insertdata['id']);
            // now translate any links
            $query = $connect->GetInsertSQL($tablename, $insertdata);
            $result = $connect->Execute($query) or safe_die($clang->gT("Error") . ": Failed to insert data<br />{$query}<br />\n" . $connect->ErrorMsg());
            $aQuotaReplacements[$oldid] = $connect->Insert_ID(db_table_name_nq('quota'), "id");
            $results['quota']++;
        }
    }
    // Import quota_members --------------------------------------------------------------
    if (isset($xml->quota_members)) {
        $tablename = $dbprefix . 'quota_members';
        foreach ($xml->quota_members->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            $insertdata['sid'] = $newsid;
            // remap the survey id
            $insertdata['qid'] = $aQIDReplacements[(int) $insertdata['qid']];
            // remap the qid
            $insertdata['quota_id'] = $aQuotaReplacements[(int) $insertdata['quota_id']];
            // remap the qid
            unset($insertdata['id']);
            // now translate any links
            $query = $connect->GetInsertSQL($tablename, $insertdata);
            $result = $connect->Execute($query) or safe_die($clang->gT("Error") . ": Failed to insert data<br />{$query}<br />\n" . $connect->ErrorMsg());
            $results['quotamembers']++;
        }
    }
    // Import quota_languagesettings --------------------------------------------------------------
    if (isset($xml->quota_languagesettings)) {
        $tablename = $dbprefix . 'quota_languagesettings';
        foreach ($xml->quota_languagesettings->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            $insertdata['quotals_quota_id'] = $aQuotaReplacements[(int) $insertdata['quotals_quota_id']];
            // remap the qid
            unset($insertdata['quotals_id']);
            // now translate any links
            $query = $connect->GetInsertSQL($tablename, $insertdata);
            $result = $connect->Execute($query) or safe_die($clang->gT("Error") . ": Failed to insert data<br />{$query}<br />\n" . $connect->ErrorMsg());
            $results['quotals']++;
        }
    }
    // Set survey rights
    GiveAllSurveyPermissions($_SESSION['loginID'], $newsid);
    if ($bTranslateInsertansTags) {
        TranslateInsertansTags($newsid, $oldsid, $aOldNewFieldmap);
    }
    LimeExpressionManager::RevertUpgradeConditionsToRelevance($newsid);
    LimeExpressionManager::UpgradeConditionsToRelevance($newsid);
    LimeExpressionManager::SetSurveyId($newsid);
    return $results;
}
function db_upgrade_all($oldversion)
{
    /// This function does anything necessary to upgrade
    /// older versions to match current functionality
    global $modifyoutput, $usertemplaterootdir, $standardtemplaterootdir;
    Yii::app()->loadHelper('database');
    $usertemplaterootdir = Yii::app()->getConfig('usertemplaterootdir');
    $standardtemplaterootdir = Yii::app()->getConfig('standardtemplaterootdir');
    $clang = Yii::app()->lang;
    echo str_pad($clang->gT('The LimeSurvey database is being upgraded') . ' (' . date('Y-m-d H:i:s') . ')', 14096) . ".<br /><br />" . $clang->gT('Please be patient...') . "<br /><br />\n";
    $sDBDriverName = setsDBDriverName();
    setVarchar($sDBDriverName);
    $sVarchar = Yii::app()->getConfig('varchar');
    $sAutoIncrement = Yii::app()->getConfig('autoincrement');
    $oTransaction = Yii::app()->db->beginTransaction();
    try {
        if ($oldversion < 111) {
            // Language upgrades from version 110 to 111 because the language names did change
            $aOldNewLanguages = array('german_informal' => 'german-informal', 'cns' => 'cn-Hans', 'cnt' => 'cn-Hant', 'pt_br' => 'pt-BR', 'gr' => 'el', 'jp' => 'ja', 'si' => 'sl', 'se' => 'sv', 'vn' => 'vi');
            foreach ($aOldNewLanguages as $sOldLanguageCode => $sNewLanguageCode) {
                alterLanguageCode($sOldLanguageCode, $sNewLanguageCode);
            }
            Yii::app()->db->createCommand()->update('{{settings_global}}', array('stg_value' => 111), "stg_name='DBVersion'");
        }
        if ($oldversion < 112) {
            // New size of the username field (it was previously 20 chars wide)
            Yii::app()->db->createCommand()->alterColumn('{{users}}', 'users_name', "{$sVarchar}(64) NOT NULL");
            Yii::app()->db->createCommand()->update('{{settings_global}}', array('stg_value' => 112), "stg_name='DBVersion'");
        }
        if ($oldversion < 113) {
            //Fixes the collation for the complete DB, tables and columns
            if ($sDBDriverName == 'mysql') {
                $databasename = getDBConnectionStringProperty('dbname');
                fixMySQLCollations();
                modifyDatabase("", "ALTER DATABASE `{$databasename}` DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;");
                echo $modifyoutput;
                flush();
                @ob_flush();
            }
            Yii::app()->db->createCommand()->update('{{settings_global}}', array('stg_value' => 113), "stg_name='DBVersion'");
        }
        if ($oldversion < 114) {
            Yii::app()->db->createCommand()->alterColumn('{{saved_control}}', 'email', "{$sVarchar}(320) NOT NULL");
            Yii::app()->db->createCommand()->alterColumn('{{surveys}}', 'adminemail', "{$sVarchar}(320) NOT NULL");
            Yii::app()->db->createCommand()->alterColumn('{{users}}', 'email', "{$sVarchar}(320) NOT NULL");
            Yii::app()->db->createCommand()->insert('{{settings_global}}', array('stg_name' => 'SessionName', 'stg_value' => randomChars(64, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ!"$%&/()=?`+*~#",;.:abcdefghijklmnopqrstuvwxyz123456789')));
            Yii::app()->db->createCommand()->update('{{settings_global}}', array('stg_value' => 114), "stg_name='DBVersion'");
        }
        if ($oldversion < 126) {
            addColumn('{{surveys}}', 'printanswers', "{$sVarchar}(1) default 'N'");
            addColumn('{{surveys}}', 'listpublic', "{$sVarchar}(1) default 'N'");
            upgradeSurveyTables126();
            upgradeTokenTables126();
            // Create quota table
            createTable('{{quota}}', array('id' => 'pk', 'sid' => 'integer', 'qlimit' => 'integer', 'name' => 'string', 'action' => 'integer', 'active' => 'integer NOT NULL DEFAULT 1'));
            // Create quota_members table
            createTable('{{quota_members}}', array('id' => 'pk', 'sid' => 'integer', 'qid' => 'integer', 'quota_id' => 'integer', 'code' => $sVarchar . '(5)'));
            Yii::app()->db->createCommand()->createIndex('sid', '{{quota_members}}', 'sid,qid,quota_id,code', true);
            // Create templates_rights table
            createTable('{{templates_rights}}', array('uid' => 'integer NOT NULL', 'folder' => 'string NOT NULL', 'use' => 'integer', 'PRIMARY KEY (uid, folder)'));
            // Create templates table
            createTable('{{templates}}', array('folder' => 'string NOT NULL', 'creator' => 'integer NOT NULL', 'PRIMARY KEY (folder)'));
            // Rename Norwegian language codes
            alterLanguageCode('no', 'nb');
            addColumn('{{surveys}}', 'htmlemail', "{$sVarchar}(1) default 'N'");
            addColumn('{{surveys}}', 'tokenanswerspersistence', "{$sVarchar}(1) default 'N'");
            addColumn('{{surveys}}', 'usecaptcha', "{$sVarchar}(1) default 'N'");
            addColumn('{{surveys}}', 'bounce_email', 'text');
            addColumn('{{users}}', 'htmleditormode', "{$sVarchar}(7) default 'default'");
            addColumn('{{users}}', 'superadmin', "integer NOT NULL default '0'");
            addColumn('{{questions}}', 'lid1', "integer NOT NULL default '0'");
            alterColumn('{{conditions}}', 'value', "string", false, '');
            alterColumn('{{labels}}', 'title', "text");
            Yii::app()->db->createCommand()->update('{{users}}', array('superadmin' => 1), "create_survey=1 AND create_user=1 AND move_user=1 AND delete_user=1 AND configurator=1");
            Yii::app()->db->createCommand()->update('{{conditions}}', array('method' => '=='), "(method is null) or method='' or method='0'");
            dropColumn('{{users}}', 'move_user');
            Yii::app()->db->createCommand()->update('{{settings_global}}', array('stg_value' => 126), "stg_name='DBVersion'");
        }
        if ($oldversion < 127) {
            modifyDatabase("", "create index answers_idx2 on {{answers}} (sortorder)");
            echo $modifyoutput;
            modifyDatabase("", "create index assessments_idx2 on {{assessments}} (sid)");
            echo $modifyoutput;
            modifyDatabase("", "create index assessments_idx3 on {{assessments}} (gid)");
            echo $modifyoutput;
            modifyDatabase("", "create index conditions_idx2 on {{conditions}} (qid)");
            echo $modifyoutput;
            modifyDatabase("", "create index conditions_idx3 on {{conditions}} (cqid)");
            echo $modifyoutput;
            modifyDatabase("", "create index groups_idx2 on {{groups}} (sid)");
            echo $modifyoutput;
            modifyDatabase("", "create index question_attributes_idx2 on {{question_attributes}} (qid)");
            echo $modifyoutput;
            modifyDatabase("", "create index questions_idx2 on {{questions}} (sid)");
            echo $modifyoutput;
            modifyDatabase("", "create index questions_idx3 on {{questions}} (gid)");
            echo $modifyoutput;
            modifyDatabase("", "create index questions_idx4 on {{questions}} (type)");
            echo $modifyoutput;
            modifyDatabase("", "create index quota_idx2 on {{quota}} (sid)");
            echo $modifyoutput;
            modifyDatabase("", "create index saved_control_idx2 on {{saved_control}} (sid)");
            echo $modifyoutput;
            modifyDatabase("", "create index user_in_groups_idx1 on {{user_in_groups}} (ugid, uid)");
            echo $modifyoutput;
            Yii::app()->db->createCommand()->update('{{settings_global}}', array('stg_value' => 127), "stg_name='DBVersion'");
        }
        if ($oldversion < 128) {
            upgradeTokens128();
            Yii::app()->db->createCommand()->update('{{settings_global}}', array('stg_value' => 128), "stg_name='DBVersion'");
        }
        if ($oldversion < 129) {
            addColumn('{{surveys}}', 'startdate', "datetime");
            addColumn('{{surveys}}', 'usestartdate', "{$sVarchar}(1) NOT NULL default 'N'");
            Yii::app()->db->createCommand()->update('{{settings_global}}', array('stg_value' => 129), "stg_name='DBVersion'");
        }
        if ($oldversion < 130) {
            addColumn('{{conditions}}', 'scenario', "integer NOT NULL default '1'");
            Yii::app()->db->createCommand()->update('{{conditions}}', array('scenario' => '1'), "(scenario is null) or scenario=0");
            Yii::app()->db->createCommand()->update('{{settings_global}}', array('stg_value' => 130), "stg_name='DBVersion'");
        }
        if ($oldversion < 131) {
            addColumn('{{surveys}}', 'publicstatistics', "{$sVarchar}(1) NOT NULL default 'N'");
            Yii::app()->db->createCommand()->update('{{settings_global}}', array('stg_value' => 131), "stg_name='DBVersion'");
        }
        if ($oldversion < 132) {
            addColumn('{{surveys}}', 'publicgraphs', "{$sVarchar}(1) NOT NULL default 'N'");
            Yii::app()->db->createCommand()->update('{{settings_global}}', array('stg_value' => 132), "stg_name='DBVersion'");
        }
        if ($oldversion < 133) {
            addColumn('{{users}}', 'one_time_pw', 'binary');
            // Add new assessment setting
            addColumn('{{surveys}}', 'assessments', "{$sVarchar}(1) NOT NULL default 'N'");
            // add new assessment value fields to answers & labels
            addColumn('{{answers}}', 'assessment_value', "integer NOT NULL default '0'");
            addColumn('{{labels}}', 'assessment_value', "integer NOT NULL default '0'");
            // copy any valid codes from code field to assessment field
            switch ($sDBDriverName) {
                case 'mysql':
                    Yii::app()->db->createCommand("UPDATE {{answers}} SET assessment_value=CAST(`code` as SIGNED) where `code` REGEXP '^-?[0-9]+\$'")->execute();
                    Yii::app()->db->createCommand("UPDATE {{labels}} SET assessment_value=CAST(`code` as SIGNED) where `code` REGEXP '^-?[0-9]+\$'")->execute();
                    // copy assessment link to message since from now on we will have HTML assignment messages
                    Yii::app()->db->createCommand("UPDATE {{assessments}} set message=concat(replace(message,'/''',''''),'<br /><a href=\"',link,'\">',link,'</a>')")->execute();
                    break;
                case 'mssql':
                    try {
                        Yii::app()->db->createCommand("UPDATE {{answers}} SET assessment_value=CAST([code] as int) WHERE ISNUMERIC([code])=1")->execute();
                        Yii::app()->db->createCommand("UPDATE {{labels}} SET assessment_value=CAST([code] as int) WHERE ISNUMERIC([code])=1")->execute();
                    } catch (Exception $e) {
                    }
                    // copy assessment link to message since from now on we will have HTML assignment messages
                    alterColumn('{{assessments}}', 'link', "varchar(max)", false);
                    alterColumn('{{assessments}}', 'message', "varchar(max)", false);
                    Yii::app()->db->createCommand("UPDATE {{assessments}} set message=replace(message,'/''','''')+'<br /><a href=\"'+link+'\">'+link+'</a>'")->execute();
                    break;
                case 'pgsql':
                    Yii::app()->db->createCommand("UPDATE {{answers}} SET assessment_value=CAST(code as integer) where code ~ '^[0-9]+'")->execute();
                    Yii::app()->db->createCommand("UPDATE {{labels}} SET assessment_value=CAST(code as integer) where code ~ '^[0-9]+'")->execute();
                    // copy assessment link to message since from now on we will have HTML assignment messages
                    Yii::app()->db->createCommand("UPDATE {{assessments}} set message=replace(message,'/''','''')||'<br /><a href=\"'||link||'\">'||link||'</a>'")->execute();
                    break;
                default:
                    die('Unkown database type');
            }
            // activate assessment where assessment rules exist
            Yii::app()->db->createCommand("UPDATE {{surveys}} SET assessments='Y' where sid in (SELECT sid FROM {{assessments}} group by sid)")->execute();
            // add language field to assessment table
            addColumn('{{assessments}}', 'language', "{$sVarchar}(20) NOT NULL default 'en'");
            // update language field with default language of that particular survey
            Yii::app()->db->createCommand("UPDATE {{assessments}} SET language=(select language from {{surveys}} where sid={{assessments}}.sid)")->execute();
            // drop the old link field
            dropColumn('{{assessments}}', 'link');
            // Add new fields to survey language settings
            addColumn('{{surveys_languagesettings}}', 'surveyls_url', "string");
            addColumn('{{surveys_languagesettings}}', 'surveyls_endtext', 'text');
            // copy old URL fields ot language specific entries
            Yii::app()->db->createCommand("UPDATE {{surveys_languagesettings}} set surveyls_url=(select url from {{surveys}} where sid={{surveys_languagesettings}}.surveyls_survey_id)")->execute();
            // drop old URL field
            dropColumn('{{surveys}}', 'url');
            Yii::app()->db->createCommand()->update('{{settings_global}}', array('stg_value' => 133), "stg_name='DBVersion'");
        }
        if ($oldversion < 134) {
            // Add new tokens setting
            addColumn('{{surveys}}', 'usetokens', "{$sVarchar}(1) NOT NULL default 'N'");
            addColumn('{{surveys}}', 'attributedescriptions', 'text');
            dropColumn('{{surveys}}', 'attribute1');
            dropColumn('{{surveys}}', 'attribute2');
            upgradeTokenTables134();
            Yii::app()->db->createCommand()->update('{{settings_global}}', array('stg_value' => 134), "stg_name='DBVersion'");
        }
        if ($oldversion < 135) {
            alterColumn('{{question_attributes}}', 'value', 'text');
            Yii::app()->db->createCommand()->update('{{settings_global}}', array('stg_value' => 135), "stg_name='DBVersion'");
        }
        if ($oldversion < 136) {
            addColumn('{{quota}}', 'autoload_url', "integer NOT NULL default 0");
            // Create quota table
            $fields = array('quotals_id' => 'pk', 'quotals_quota_id' => 'integer NOT NULL DEFAULT 0', 'quotals_language' => "{$sVarchar}(45) NOT NULL default 'en'", 'quotals_name' => 'string', 'quotals_message' => 'text NOT NULL', 'quotals_url' => 'string', 'quotals_urldescrip' => 'string');
            createTable('{{quota_languagesettings}}', $fields);
            Yii::app()->db->createCommand()->update('{{settings_global}}', array('stg_value' => 136), "stg_name='DBVersion'");
        }
        if ($oldversion < 137) {
            addColumn('{{surveys_languagesettings}}', 'surveyls_dateformat', "integer NOT NULL default 1");
            addColumn('{{users}}', 'dateformat', "integer NOT NULL default 1");
            Yii::app()->db->createCommand()->update('{{surveys}}', array('startdate' => NULL), "usestartdate='N'");
            Yii::app()->db->createCommand()->update('{{surveys}}', array('expires' => NULL), "useexpiry='N'");
            dropColumn('{{surveys}}', 'useexpiry');
            dropColumn('{{surveys}}', 'usestartdate');
            Yii::app()->db->createCommand()->update('{{settings_global}}', array('stg_value' => 137), "stg_name='DBVersion'");
        }
        if ($oldversion < 138) {
            alterColumn('{{quota_members}}', 'code', "{$sVarchar}(11)");
            Yii::app()->db->createCommand()->update('{{settings_global}}', array('stg_value' => 138), "stg_name='DBVersion'");
        }
        if ($oldversion < 139) {
            upgradeSurveyTables139();
            Yii::app()->db->createCommand()->update('{{settings_global}}', array('stg_value' => 139), "stg_name='DBVersion'");
        }
        if ($oldversion < 140) {
            addColumn('{{surveys}}', 'emailresponseto', 'text');
            Yii::app()->db->createCommand()->update('{{settings_global}}', array('stg_value' => 140), "stg_name='DBVersion'");
        }
        if ($oldversion < 141) {
            addColumn('{{surveys}}', 'tokenlength', 'integer NOT NULL default 15');
            Yii::app()->db->createCommand()->update('{{settings_global}}', array('stg_value' => 141), "stg_name='DBVersion'");
        }
        if ($oldversion < 142) {
            upgradeQuestionAttributes142();
            Yii::app()->db->createCommand()->alterColumn('{{surveys}}', 'expires', "datetime");
            Yii::app()->db->createCommand()->alterColumn('{{surveys}}', 'startdate', "datetime");
            Yii::app()->db->createCommand()->update('{{question_attributes}}', array('value' => 0), "value='false'");
            Yii::app()->db->createCommand()->update('{{question_attributes}}', array('value' => 1), "value='true'");
            Yii::app()->db->createCommand()->update('{{settings_global}}', array('stg_value' => 142), "stg_name='DBVersion'");
        }
        if ($oldversion < 143) {
            addColumn('{{questions}}', 'parent_qid', 'integer NOT NULL default 0');
            addColumn('{{answers}}', 'scale_id', 'integer NOT NULL default 0');
            addColumn('{{questions}}', 'scale_id', 'integer NOT NULL default 0');
            addColumn('{{questions}}', 'same_default', 'integer NOT NULL default 0');
            dropPrimaryKey('answers');
            addPrimaryKey('answers', array('qid', 'code', 'language', 'scale_id'));
            $fields = array('qid' => "integer NOT NULL default 0", 'scale_id' => 'integer NOT NULL default 0', 'sqid' => 'integer  NOT NULL default 0', 'language' => $sVarchar . '(20) NOT NULL', 'specialtype' => $sVarchar . "(20) NOT NULL default ''", 'defaultvalue' => 'text');
            createTable('{{defaultvalues}}', $fields);
            addPrimaryKey('defaultvalues', array('qid', 'specialtype', 'language', 'scale_id', 'sqid'));
            // -Move all 'answers' that are subquestions to the questions table
            // -Move all 'labels' that are answers to the answers table
            // -Transscribe the default values where applicable
            // -Move default values from answers to questions
            upgradeTables143();
            dropColumn('{{answers}}', 'default_value');
            dropColumn('{{questions}}', 'lid');
            dropColumn('{{questions}}', 'lid1');
            $fields = array('sesskey' => "{$sVarchar}(64) NOT NULL DEFAULT ''", 'expiry' => "datetime NOT NULL", 'expireref' => "{$sVarchar}(250) DEFAULT ''", 'created' => "datetime NOT NULL", 'modified' => "datetime NOT NULL", 'sessdata' => 'text');
            createTable('{{sessions}}', $fields);
            addPrimaryKey('sessions', array('sesskey'));
            Yii::app()->db->createCommand()->createIndex('sess2_expiry', '{{sessions}}', 'expiry');
            Yii::app()->db->createCommand()->createIndex('sess2_expireref', '{{sessions}}', 'expireref');
            // Move all user templates to the new user template directory
            echo sprintf($clang->gT("Moving user templates to new location at %s..."), $usertemplaterootdir) . "<br />";
            $myDirectory = opendir($standardtemplaterootdir);
            $aFailedTemplates = array();
            // get each entry
            while ($entryName = readdir($myDirectory)) {
                if (!in_array($entryName, array('.', '..', '.svn')) && is_dir($standardtemplaterootdir . DIRECTORY_SEPARATOR . $entryName) && !isStandardTemplate($entryName)) {
                    if (!rename($standardtemplaterootdir . DIRECTORY_SEPARATOR . $entryName, $usertemplaterootdir . DIRECTORY_SEPARATOR . $entryName)) {
                        $aFailedTemplates[] = $entryName;
                    }
                }
            }
            if (count($aFailedTemplates) > 0) {
                echo "The following templates at {$standardtemplaterootdir} could not be moved to the new location at {$usertemplaterootdir}:<br /><ul>";
                foreach ($aFailedTemplates as $sFailedTemplate) {
                    echo "<li>{$sFailedTemplate}</li>";
                }
                echo "</ul>Please move these templates manually after the upgrade has finished.<br />";
            }
            // close directory
            closedir($myDirectory);
            Yii::app()->db->createCommand()->update('{{settings_global}}', array('stg_value' => 143), "stg_name='DBVersion'");
        }
        if ($oldversion < 145) {
            addColumn('{{surveys}}', 'savetimings', "{$sVarchar}(1) NULL default 'N'");
            addColumn('{{surveys}}', 'showXquestions', "{$sVarchar}(1) NULL default 'Y'");
            addColumn('{{surveys}}', 'showgroupinfo', "{$sVarchar}(1) NULL default 'B'");
            addColumn('{{surveys}}', 'shownoanswer', "{$sVarchar}(1) NULL default 'Y'");
            addColumn('{{surveys}}', 'showqnumcode', "{$sVarchar}(1) NULL default 'X'");
            addColumn('{{surveys}}', 'bouncetime', 'integer');
            addColumn('{{surveys}}', 'bounceprocessing', "{$sVarchar}(1) NULL default 'N'");
            addColumn('{{surveys}}', 'bounceaccounttype', "{$sVarchar}(4)");
            addColumn('{{surveys}}', 'bounceaccounthost', "{$sVarchar}(200)");
            addColumn('{{surveys}}', 'bounceaccountpass', "{$sVarchar}(100)");
            addColumn('{{surveys}}', 'bounceaccountencryption', "{$sVarchar}(3)");
            addColumn('{{surveys}}', 'bounceaccountuser', "{$sVarchar}(200)");
            addColumn('{{surveys}}', 'showwelcome', "{$sVarchar}(1) default 'Y'");
            addColumn('{{surveys}}', 'showprogress', "{$sVarchar}(1) default 'Y'");
            addColumn('{{surveys}}', 'allowjumps', "{$sVarchar}(1) default 'N'");
            addColumn('{{surveys}}', 'navigationdelay', "integer default 0");
            addColumn('{{surveys}}', 'nokeyboard', "{$sVarchar}(1) default 'N'");
            addColumn('{{surveys}}', 'alloweditaftercompletion', "{$sVarchar}(1) default 'N'");
            $fields = array('sid' => "integer NOT NULL", 'uid' => "integer NOT NULL", 'permission' => $sVarchar . '(20) NOT NULL', 'create_p' => "integer NOT NULL default 0", 'read_p' => "integer NOT NULL default 0", 'update_p' => "integer NOT NULL default 0", 'delete_p' => "integer NOT NULL default 0", 'import_p' => "integer NOT NULL default 0", 'export_p' => "integer NOT NULL default 0");
            createTable('{{survey_permissions}}', $fields);
            addPrimaryKey('survey_permissions', array('sid', 'uid', 'permission'));
            upgradeSurveyPermissions145();
            // drop the old survey rights table
            Yii::app()->db->createCommand()->dropTable('{{surveys_rights}}');
            // Add new fields for email templates
            addColumn('{{surveys_languagesettings}}', 'email_admin_notification_subj', "string");
            addColumn('{{surveys_languagesettings}}', 'email_admin_responses_subj', "string");
            addColumn('{{surveys_languagesettings}}', 'email_admin_notification', "text");
            addColumn('{{surveys_languagesettings}}', 'email_admin_responses', "text");
            //Add index to questions table to speed up subquestions
            Yii::app()->db->createCommand()->createIndex('parent_qid_idx', '{{questions}}', 'parent_qid');
            addColumn('{{surveys}}', 'emailnotificationto', "text");
            upgradeSurveys145();
            dropColumn('{{surveys}}', 'notification');
            alterColumn('{{conditions}}', 'method', "{$sVarchar}(5)", false, '');
            Yii::app()->db->createCommand()->renameColumn('{{surveys}}', 'private', 'anonymized');
            Yii::app()->db->createCommand()->update('{{surveys}}', array('anonymized' => 'N'), "anonymized is NULL");
            alterColumn('{{surveys}}', 'anonymized', "{$sVarchar}(1)", false, 'N');
            //now we clean up things that were not properly set in previous DB upgrades
            Yii::app()->db->createCommand()->update('{{answers}}', array('answer' => ''), "answer is NULL");
            Yii::app()->db->createCommand()->update('{{assessments}}', array('scope' => ''), "scope is NULL");
            Yii::app()->db->createCommand()->update('{{assessments}}', array('name' => ''), "name is NULL");
            Yii::app()->db->createCommand()->update('{{assessments}}', array('message' => ''), "message is NULL");
            Yii::app()->db->createCommand()->update('{{assessments}}', array('minimum' => ''), "minimum is NULL");
            Yii::app()->db->createCommand()->update('{{assessments}}', array('maximum' => ''), "maximum is NULL");
            Yii::app()->db->createCommand()->update('{{groups}}', array('group_name' => ''), "group_name is NULL");
            Yii::app()->db->createCommand()->update('{{labels}}', array('code' => ''), "code is NULL");
            Yii::app()->db->createCommand()->update('{{labelsets}}', array('label_name' => ''), "label_name is NULL");
            Yii::app()->db->createCommand()->update('{{questions}}', array('type' => 'T'), "type is NULL");
            Yii::app()->db->createCommand()->update('{{questions}}', array('title' => ''), "title is NULL");
            Yii::app()->db->createCommand()->update('{{questions}}', array('question' => ''), "question is NULL");
            Yii::app()->db->createCommand()->update('{{questions}}', array('other' => 'N'), "other is NULL");
            alterColumn('{{answers}}', 'answer', "text", false);
            alterColumn('{{answers}}', 'assessment_value', 'integer', false, '0');
            alterColumn('{{assessments}}', 'scope', "{$sVarchar}(5)", false, '');
            alterColumn('{{assessments}}', 'name', "text", false);
            alterColumn('{{assessments}}', 'message', "text", false);
            alterColumn('{{assessments}}', 'minimum', "{$sVarchar}(50)", false, '');
            alterColumn('{{assessments}}', 'maximum', "{$sVarchar}(50)", false, '');
            // change the primary index to include language
            if ($sDBDriverName == 'mysql') {
                Yii::app()->db->createCommand("ALTER TABLE {{assessments}} DROP PRIMARY KEY, ADD PRIMARY KEY (`id`, `language`)")->execute();
            } else {
                dropPrimaryKey('assessments');
                addPrimaryKey('assessments', array('id', 'language'));
            }
            alterColumn('{{conditions}}', 'cfieldname', "{$sVarchar}(50)", false, '');
            dropPrimaryKey('defaultvalues');
            alterColumn('{{defaultvalues}}', 'specialtype', "{$sVarchar}(20)", false, '');
            addPrimaryKey('defaultvalues', array('qid', 'specialtype', 'language', 'scale_id', 'sqid'));
            alterColumn('{{groups}}', 'group_name', "{$sVarchar}(100)", false, '');
            alterColumn('{{labels}}', 'code', "{$sVarchar}(5)", false, '');
            alterColumn('{{labels}}', 'language', "{$sVarchar}(20)", false, 'en');
            alterColumn('{{labelsets}}', 'label_name', "{$sVarchar}(100)", false, '');
            alterColumn('{{questions}}', 'parent_qid', 'integer', false, '0');
            alterColumn('{{questions}}', 'title', "{$sVarchar}(20)", false, '');
            alterColumn('{{questions}}', 'question', "text", false);
            alterColumn('{{questions}}', 'type', "{$sVarchar}(1)", false, 'T');
            try {
                Yii::app()->db->createCommand()->createIndex('questions_idx4', '{{questions}}', 'type');
            } catch (Exception $e) {
            }
            alterColumn('{{questions}}', 'other', "{$sVarchar}(1)", false, 'N');
            alterColumn('{{questions}}', 'mandatory', "{$sVarchar}(1)");
            alterColumn('{{question_attributes}}', 'attribute', "{$sVarchar}(50)");
            alterColumn('{{quota}}', 'qlimit', 'integer');
            Yii::app()->db->createCommand()->update('{{saved_control}}', array('identifier' => ''), "identifier is NULL");
            alterColumn('{{saved_control}}', 'identifier', "text", false);
            Yii::app()->db->createCommand()->update('{{saved_control}}', array('access_code' => ''), "access_code is NULL");
            alterColumn('{{saved_control}}', 'access_code', "text", false);
            alterColumn('{{saved_control}}', 'email', "{$sVarchar}(320)");
            Yii::app()->db->createCommand()->update('{{saved_control}}', array('ip' => ''), "ip is NULL");
            alterColumn('{{saved_control}}', 'ip', "text", false);
            Yii::app()->db->createCommand()->update('{{saved_control}}', array('saved_thisstep' => ''), "saved_thisstep is NULL");
            alterColumn('{{saved_control}}', 'saved_thisstep', "text", false);
            Yii::app()->db->createCommand()->update('{{saved_control}}', array('status' => ''), "status is NULL");
            alterColumn('{{saved_control}}', 'status', "{$sVarchar}(1)", false, '');
            Yii::app()->db->createCommand()->update('{{saved_control}}', array('saved_date' => '1980-01-01 00:00:00'), "saved_date is NULL");
            alterColumn('{{saved_control}}', 'saved_date', "datetime", false);
            Yii::app()->db->createCommand()->update('{{settings_global}}', array('stg_value' => ''), "stg_value is NULL");
            alterColumn('{{settings_global}}', 'stg_value', "string", false, '');
            alterColumn('{{surveys}}', 'admin', "{$sVarchar}(50)");
            Yii::app()->db->createCommand()->update('{{surveys}}', array('active' => 'N'), "active is NULL");
            alterColumn('{{surveys}}', 'active', "{$sVarchar}(1)", false, 'N');
            alterColumn('{{surveys}}', 'startdate', "datetime");
            alterColumn('{{surveys}}', 'adminemail', "{$sVarchar}(320)");
            alterColumn('{{surveys}}', 'anonymized', "{$sVarchar}(1)", false, 'N');
            alterColumn('{{surveys}}', 'faxto', "{$sVarchar}(20)");
            alterColumn('{{surveys}}', 'format', "{$sVarchar}(1)");
            alterColumn('{{surveys}}', 'language', "{$sVarchar}(50)");
            alterColumn('{{surveys}}', 'additional_languages', "string");
            alterColumn('{{surveys}}', 'printanswers', "{$sVarchar}(1)", true, 'N');
            alterColumn('{{surveys}}', 'publicstatistics', "{$sVarchar}(1)", true, 'N');
            alterColumn('{{surveys}}', 'publicgraphs', "{$sVarchar}(1)", true, 'N');
            alterColumn('{{surveys}}', 'assessments', "{$sVarchar}(1)", true, 'N');
            alterColumn('{{surveys}}', 'usetokens', "{$sVarchar}(1)", true, 'N');
            alterColumn('{{surveys}}', 'bounce_email', "{$sVarchar}(320)");
            alterColumn('{{surveys}}', 'tokenlength', 'integer', true, 15);
            Yii::app()->db->createCommand()->update('{{surveys_languagesettings}}', array('surveyls_title' => ''), "surveyls_title is NULL");
            alterColumn('{{surveys_languagesettings}}', 'surveyls_title', "{$sVarchar}(200)", false);
            alterColumn('{{surveys_languagesettings}}', 'surveyls_endtext', "text");
            alterColumn('{{surveys_languagesettings}}', 'surveyls_url', "string");
            alterColumn('{{surveys_languagesettings}}', 'surveyls_urldescription', "string");
            alterColumn('{{surveys_languagesettings}}', 'surveyls_email_invite_subj', "string");
            alterColumn('{{surveys_languagesettings}}', 'surveyls_email_remind_subj', "string");
            alterColumn('{{surveys_languagesettings}}', 'surveyls_email_register_subj', "string");
            alterColumn('{{surveys_languagesettings}}', 'surveyls_email_confirm_subj', "string");
            alterColumn('{{surveys_languagesettings}}', 'surveyls_dateformat', 'integer', false, 1);
            Yii::app()->db->createCommand()->update('{{users}}', array('users_name' => ''), "users_name is NULL");
            Yii::app()->db->createCommand()->update('{{users}}', array('full_name' => ''), "full_name is NULL");
            alterColumn('{{users}}', 'users_name', "{$sVarchar}(64)", false, '');
            alterColumn('{{users}}', 'full_name', "{$sVarchar}(50)", false);
            alterColumn('{{users}}', 'lang', "{$sVarchar}(20)");
            alterColumn('{{users}}', 'email', "{$sVarchar}(320)");
            alterColumn('{{users}}', 'superadmin', 'integer', false, 0);
            alterColumn('{{users}}', 'htmleditormode', "{$sVarchar}(7)", true, 'default');
            alterColumn('{{users}}', 'dateformat', 'integer', false, 1);
            try {
                Yii::app()->db->createCommand()->dropIndex('email', '{{users}}');
            } catch (Exception $e) {
                // do nothing
            }
            Yii::app()->db->createCommand()->update('{{user_groups}}', array('name' => ''), "name is NULL");
            Yii::app()->db->createCommand()->update('{{user_groups}}', array('description' => ''), "description is NULL");
            alterColumn('{{user_groups}}', 'name', "{$sVarchar}(20)", false);
            alterColumn('{{user_groups}}', 'description', "text", false);
            try {
                Yii::app()->db->createCommand()->dropIndex('user_in_groups_idx1', '{{user_in_groups}}');
            } catch (Exception $e) {
            }
            try {
                addPrimaryKey('user_in_groups', array('ugid', 'uid'));
            } catch (Exception $e) {
            }
            addColumn('{{surveys_languagesettings}}', 'surveyls_numberformat', "integer NOT NULL DEFAULT 0");
            createTable('{{failed_login_attempts}}', array('id' => "pk", 'ip' => $sVarchar . '(37) NOT NULL', 'last_attempt' => $sVarchar . '(20) NOT NULL', 'number_attempts' => "integer NOT NULL"));
            upgradeTokens145();
            Yii::app()->db->createCommand()->update('{{settings_global}}', array('stg_value' => 145), "stg_name='DBVersion'");
        }
        if ($oldversion < 146) {
            upgradeSurveyTimings146();
            // Fix permissions for new feature quick-translation
            try {
                setTransactionBookmark();
                Yii::app()->db->createCommand("INSERT into {{survey_permissions}} (sid,uid,permission,read_p,update_p) SELECT sid,owner_id,'translations','1','1' from {{surveys}}")->execute();
                echo $modifyoutput;
                flush();
                @ob_flush();
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            Yii::app()->db->createCommand()->update('{{settings_global}}', array('stg_value' => 146), "stg_name='DBVersion'");
        }
        if ($oldversion < 147) {
            addColumn('{{users}}', 'templateeditormode', "{$sVarchar}(7) NOT NULL default 'default'");
            addColumn('{{users}}', 'questionselectormode', "{$sVarchar}(7) NOT NULL default 'default'");
            Yii::app()->db->createCommand()->update('{{settings_global}}', array('stg_value' => 147), "stg_name='DBVersion'");
        }
        if ($oldversion < 148) {
            addColumn('{{users}}', 'participant_panel', "integer NOT NULL default 0");
            createTable('{{participants}}', array('participant_id' => $sVarchar . '(50) NOT NULL', 'firstname' => $sVarchar . '(40) default NULL', 'lastname' => $sVarchar . '(40) default NULL', 'email' => $sVarchar . '(80) default NULL', 'language' => $sVarchar . '(40) default NULL', 'blacklisted' => $sVarchar . '(1) NOT NULL', 'owner_uid' => "integer NOT NULL"));
            addPrimaryKey('participants', array('participant_id'));
            createTable('{{participant_attribute}}', array('participant_id' => $sVarchar . '(50) NOT NULL', 'attribute_id' => "integer NOT NULL", 'value' => $sVarchar . '(50) NOT NULL'));
            addPrimaryKey('participant_attribute', array('participant_id', 'attribute_id'));
            createTable('{{participant_attribute_names}}', array('attribute_id' => $sAutoIncrement, 'attribute_type' => $sVarchar . '(4) NOT NULL', 'visible' => $sVarchar . '(5) NOT NULL', 'PRIMARY KEY (attribute_id,attribute_type)'));
            createTable('{{participant_attribute_names_lang}}', array('attribute_id' => 'integer NOT NULL', 'attribute_name' => $sVarchar . '(30) NOT NULL', 'lang' => $sVarchar . '(20) NOT NULL'));
            addPrimaryKey('participant_attribute_names_lang', array('attribute_id', 'lang'));
            createTable('{{participant_attribute_values}}', array('attribute_id' => 'integer NOT NULL', 'value_id' => 'pk', 'value' => $sVarchar . '(20) NOT NULL'));
            createTable('{{participant_shares}}', array('participant_id' => $sVarchar . '(50) NOT NULL', 'share_uid' => 'integer NOT NULL', 'date_added' => 'datetime NOT NULL', 'can_edit' => $sVarchar . '(5) NOT NULL'));
            addPrimaryKey('participant_shares', array('participant_id', 'share_uid'));
            createTable('{{survey_links}}', array('participant_id' => $sVarchar . '(50) NOT NULL', 'token_id' => 'integer NOT NULL', 'survey_id' => 'integer NOT NULL', 'date_created' => 'datetime NOT NULL'));
            addPrimaryKey('survey_links', array('participant_id', 'token_id', 'survey_id'));
            // Add language field to question_attributes table
            addColumn('{{question_attributes}}', 'language', "{$sVarchar}(20)");
            upgradeQuestionAttributes148();
            upgradeTokens148();
            fixSubquestions();
            Yii::app()->db->createCommand()->update('{{settings_global}}', array('stg_value' => 148), "stg_name='DBVersion'");
        }
        if ($oldversion < 149) {
            $fields = array('id' => 'integer', 'sid' => 'integer', 'parameter' => $sVarchar . '(50)', 'targetqid' => 'integer', 'targetsqid' => 'integer');
            createTable('{{survey_url_parameters}}', $fields);
            Yii::app()->db->createCommand()->update('{{settings_global}}', array('stg_value' => 149), "stg_name='DBVersion'");
        }
        if ($oldversion < 150) {
            addColumn('{{questions}}', 'relevance', 'TEXT');
            Yii::app()->db->createCommand()->update('{{settings_global}}', array('stg_value' => 150), "stg_name='DBVersion'");
        }
        if ($oldversion < 151) {
            addColumn('{{groups}}', 'randomization_group', "{$sVarchar}(20) NOT NULL default ''");
            Yii::app()->db->createCommand()->update('{{settings_global}}', array('stg_value' => 151), "stg_name='DBVersion'");
        }
        if ($oldversion < 152) {
            Yii::app()->db->createCommand()->createIndex('question_attributes_idx3', '{{question_attributes}}', 'attribute');
            Yii::app()->db->createCommand()->update('{{settings_global}}', array('stg_value' => 152), "stg_name='DBVersion'");
        }
        if ($oldversion < 153) {
            createTable('{{expression_errors}}', array('id' => 'pk', 'errortime' => $sVarchar . '(50)', 'sid' => 'integer', 'gid' => 'integer', 'qid' => 'integer', 'gseq' => 'integer', 'qseq' => 'integer', 'type' => $sVarchar . '(50)', 'eqn' => 'text', 'prettyprint' => 'text'));
            Yii::app()->db->createCommand()->update('{{settings_global}}', array('stg_value' => 153), "stg_name='DBVersion'");
        }
        if ($oldversion < 154) {
            Yii::app()->db->createCommand()->addColumn('{{groups}}', 'grelevance', "text");
            Yii::app()->db->createCommand()->update('{{settings_global}}', array('stg_value' => 154), "stg_name='DBVersion'");
        }
        if ($oldversion < 155) {
            addColumn('{{surveys}}', 'googleanalyticsstyle', "{$sVarchar}(1)");
            addColumn('{{surveys}}', 'googleanalyticsapikey', "{$sVarchar}(25)");
            try {
                setTransactionBookmark();
                Yii::app()->db->createCommand()->renameColumn('{{surveys}}', 'showXquestions', 'showxquestions');
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            Yii::app()->db->createCommand()->update('{{settings_global}}', array('stg_value' => 155), "stg_name='DBVersion'");
        }
        if ($oldversion < 156) {
            try {
                Yii::app()->db->createCommand()->dropTable('{{survey_url_parameters}}');
            } catch (Exception $e) {
                // do nothing
            }
            createTable('{{survey_url_parameters}}', array('id' => 'pk', 'sid' => 'integer NOT NULL', 'parameter' => $sVarchar . '(50) NOT NULL', 'targetqid' => 'integer', 'targetsqid' => 'integer'));
            Yii::app()->db->createCommand()->dropTable('{{sessions}}');
            if ($sDBDriverName == 'mysql') {
                createTable('{{sessions}}', array('id' => $sVarchar . '(32) NOT NULL', 'expire' => 'integer', 'data' => 'longtext'));
            } else {
                createTable('{{sessions}}', array('id' => $sVarchar . '(32) NOT NULL', 'expire' => 'integer', 'data' => 'text'));
            }
            addPrimaryKey('sessions', array('id'));
            addColumn('{{surveys_languagesettings}}', 'surveyls_attributecaptions', "TEXT");
            addColumn('{{surveys}}', 'sendconfirmation', "{$sVarchar}(1) default 'Y'");
            upgradeSurveys156();
            // If a survey has an deleted owner, re-own the survey to the superadmin
            Yii::app()->db->schema->refresh();
            Survey::model()->refreshMetaData();
            $surveys = Survey::model();
            $surveys = $surveys->with(array('owner'))->findAll();
            foreach ($surveys as $row) {
                if (!isset($row->owner->attributes)) {
                    Survey::model()->updateByPk($row->sid, array('owner_id' => 1));
                }
            }
            Yii::app()->db->createCommand()->update('{{settings_global}}', array('stg_value' => 156), "stg_name='DBVersion'");
            $oTransaction->commit();
            $oTransaction = Yii::app()->db->beginTransaction();
        }
        if ($oldversion < 157) {
            // MySQL DB corrections
            try {
                setTransactionBookmark();
                Yii::app()->db->createCommand()->dropIndex('questions_idx4', '{{questions}}');
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            alterColumn('{{answers}}', 'assessment_value', 'integer', false, '0');
            dropPrimaryKey('answers');
            alterColumn('{{answers}}', 'scale_id', 'integer', false, '0');
            addPrimaryKey('answers', array('qid', 'code', 'language', 'scale_id'));
            alterColumn('{{conditions}}', 'method', "{$sVarchar}(5)", false, '');
            alterColumn('{{participants}}', 'owner_uid', 'integer', false);
            alterColumn('{{participant_attribute_names}}', 'visible', $sVarchar . '(5)', false);
            alterColumn('{{questions}}', 'type', "{$sVarchar}(1)", false, 'T');
            alterColumn('{{questions}}', 'other', "{$sVarchar}(1)", false, 'N');
            alterColumn('{{questions}}', 'mandatory', "{$sVarchar}(1)");
            alterColumn('{{questions}}', 'scale_id', 'integer', false, '0');
            alterColumn('{{questions}}', 'parent_qid', 'integer', false, '0');
            alterColumn('{{questions}}', 'same_default', 'integer', false, '0');
            alterColumn('{{quota}}', 'qlimit', 'integer');
            alterColumn('{{quota}}', 'action', 'integer');
            alterColumn('{{quota}}', 'active', 'integer', false, '1');
            alterColumn('{{quota}}', 'autoload_url', 'integer', false, '0');
            alterColumn('{{saved_control}}', 'status', "{$sVarchar}(1)", false, '');
            try {
                setTransactionBookmark();
                alterColumn('{{sessions}}', 'id', "{$sVarchar}(32)", false);
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            alterColumn('{{surveys}}', 'active', "{$sVarchar}(1)", false, 'N');
            alterColumn('{{surveys}}', 'anonymized', "{$sVarchar}(1)", false, 'N');
            alterColumn('{{surveys}}', 'format', "{$sVarchar}(1)");
            alterColumn('{{surveys}}', 'savetimings', "{$sVarchar}(1)", false, 'N');
            alterColumn('{{surveys}}', 'datestamp', "{$sVarchar}(1)", false, 'N');
            alterColumn('{{surveys}}', 'usecookie', "{$sVarchar}(1)", false, 'N');
            alterColumn('{{surveys}}', 'allowregister', "{$sVarchar}(1)", false, 'N');
            alterColumn('{{surveys}}', 'allowsave', "{$sVarchar}(1)", false, 'Y');
            alterColumn('{{surveys}}', 'autonumber_start', 'integer', false, '0');
            alterColumn('{{surveys}}', 'autoredirect', "{$sVarchar}(1)", false, 'N');
            alterColumn('{{surveys}}', 'allowprev', "{$sVarchar}(1)", false, 'N');
            alterColumn('{{surveys}}', 'printanswers', "{$sVarchar}(1)", false, 'N');
            alterColumn('{{surveys}}', 'ipaddr', "{$sVarchar}(1)", false, 'N');
            alterColumn('{{surveys}}', 'refurl', "{$sVarchar}(1)", false, 'N');
            alterColumn('{{surveys}}', 'publicstatistics', "{$sVarchar}(1)", false, 'N');
            alterColumn('{{surveys}}', 'publicgraphs', "{$sVarchar}(1)", false, 'N');
            alterColumn('{{surveys}}', 'listpublic', "{$sVarchar}(1)", false, 'N');
            alterColumn('{{surveys}}', 'htmlemail', "{$sVarchar}(1)", false, 'N');
            alterColumn('{{surveys}}', 'sendconfirmation', "{$sVarchar}(1)", false, 'Y');
            alterColumn('{{surveys}}', 'tokenanswerspersistence', "{$sVarchar}(1)", false, 'N');
            alterColumn('{{surveys}}', 'assessments', "{$sVarchar}(1)", false, 'N');
            alterColumn('{{surveys}}', 'usecaptcha', "{$sVarchar}(1)", false, 'N');
            alterColumn('{{surveys}}', 'usetokens', "{$sVarchar}(1)", false, 'N');
            alterColumn('{{surveys}}', 'tokenlength', 'integer', false, '15');
            alterColumn('{{surveys}}', 'showxquestions', "{$sVarchar}(1)", true, 'Y');
            alterColumn('{{surveys}}', 'showgroupinfo', "{$sVarchar}(1) ", true, 'B');
            alterColumn('{{surveys}}', 'shownoanswer', "{$sVarchar}(1) ", true, 'Y');
            alterColumn('{{surveys}}', 'showqnumcode', "{$sVarchar}(1) ", true, 'X');
            alterColumn('{{surveys}}', 'bouncetime', 'integer');
            alterColumn('{{surveys}}', 'showwelcome', "{$sVarchar}(1)", true, 'Y');
            alterColumn('{{surveys}}', 'showprogress', "{$sVarchar}(1)", true, 'Y');
            alterColumn('{{surveys}}', 'allowjumps', "{$sVarchar}(1)", true, 'N');
            alterColumn('{{surveys}}', 'navigationdelay', 'integer', false, '0');
            alterColumn('{{surveys}}', 'nokeyboard', "{$sVarchar}(1)", true, 'N');
            alterColumn('{{surveys}}', 'alloweditaftercompletion', "{$sVarchar}(1)", true, 'N');
            alterColumn('{{surveys}}', 'googleanalyticsstyle', "{$sVarchar}(1)");
            alterColumn('{{surveys_languagesettings}}', 'surveyls_dateformat', 'integer', false, 1);
            try {
                setTransactionBookmark();
                alterColumn('{{survey_permissions}}', 'sid', "integer", false);
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            try {
                setTransactionBookmark();
                alterColumn('{{survey_permissions}}', 'uid', "integer", false);
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            alterColumn('{{survey_permissions}}', 'create_p', 'integer', false, '0');
            alterColumn('{{survey_permissions}}', 'read_p', 'integer', false, '0');
            alterColumn('{{survey_permissions}}', 'update_p', 'integer', false, '0');
            alterColumn('{{survey_permissions}}', 'delete_p', 'integer', false, '0');
            alterColumn('{{survey_permissions}}', 'import_p', 'integer', false, '0');
            alterColumn('{{survey_permissions}}', 'export_p', 'integer', false, '0');
            alterColumn('{{survey_url_parameters}}', 'targetqid', 'integer');
            alterColumn('{{survey_url_parameters}}', 'targetsqid', 'integer');
            alterColumn('{{templates_rights}}', 'use', 'integer', false);
            alterColumn('{{users}}', 'create_survey', 'integer', false, '0');
            alterColumn('{{users}}', 'create_user', 'integer', false, '0');
            alterColumn('{{users}}', 'participant_panel', 'integer', false, '0');
            alterColumn('{{users}}', 'delete_user', 'integer', false, '0');
            alterColumn('{{users}}', 'superadmin', 'integer', false, '0');
            alterColumn('{{users}}', 'configurator', 'integer', false, '0');
            alterColumn('{{users}}', 'manage_template', 'integer', false, '0');
            alterColumn('{{users}}', 'manage_label', 'integer', false, '0');
            alterColumn('{{users}}', 'dateformat', 'integer', false, 1);
            alterColumn('{{users}}', 'participant_panel', 'integer', false, '0');
            alterColumn('{{users}}', 'parent_id', 'integer', false);
            try {
                setTransactionBookmark();
                alterColumn('{{surveys_languagesettings}}', 'surveyls_survey_id', "integer", false);
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            alterColumn('{{user_groups}}', 'owner_id', "integer", false);
            alterColumn('{{user_in_groups}}', 'ugid', "integer", false);
            alterColumn('{{user_in_groups}}', 'uid', "integer", false);
            // Additional corrections for Postgres
            try {
                setTransactionBookmark();
                Yii::app()->db->createCommand()->createIndex('questions_idx3', '{{questions}}', 'gid');
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            try {
                setTransactionBookmark();
                Yii::app()->db->createCommand()->createIndex('conditions_idx3', '{{conditions}}', 'cqid');
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            try {
                setTransactionBookmark();
                Yii::app()->db->createCommand()->createIndex('questions_idx4', '{{questions}}', 'type');
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            try {
                setTransactionBookmark();
                Yii::app()->db->createCommand()->dropIndex('user_in_groups_idx1', '{{user_in_groups}}');
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            try {
                setTransactionBookmark();
                Yii::app()->db->createCommand()->dropIndex('{{user_name_key}}', '{{users}}');
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            try {
                setTransactionBookmark();
                Yii::app()->db->createCommand()->createIndex('users_name', '{{users}}', 'users_name', true);
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            try {
                setTransactionBookmark();
                addPrimaryKey('user_in_groups', array('ugid', 'uid'));
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            alterColumn('{{participant_attribute}}', 'value', "{$sVarchar}(50)", false);
            try {
                setTransactionBookmark();
                alterColumn('{{participant_attribute_names}}', 'attribute_type', "{$sVarchar}(4)", false);
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            try {
                setTransactionBookmark();
                dropColumn('{{participant_attribute_names_lang}}', 'id');
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            try {
                setTransactionBookmark();
                addPrimaryKey('participant_attribute_names_lang', array('attribute_id', 'lang'));
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            try {
                setTransactionBookmark();
                Yii::app()->db->createCommand()->renameColumn('{{participant_shares}}', 'shared_uid', 'share_uid');
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            alterColumn('{{participant_shares}}', 'date_added', "datetime", false);
            alterColumn('{{participants}}', 'firstname', "{$sVarchar}(40)");
            alterColumn('{{participants}}', 'lastname', "{$sVarchar}(40)");
            alterColumn('{{participants}}', 'email', "{$sVarchar}(80)");
            alterColumn('{{participants}}', 'language', "{$sVarchar}(40)");
            alterColumn('{{quota_languagesettings}}', 'quotals_name', "string");
            try {
                setTransactionBookmark();
                alterColumn('{{survey_permissions}}', 'sid', 'integer', false);
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            try {
                setTransactionBookmark();
                alterColumn('{{survey_permissions}}', 'uid', 'integer', false);
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            alterColumn('{{users}}', 'htmleditormode', "{$sVarchar}(7)", true, 'default');
            // Sometimes the survey_links table was deleted before this step, if so
            // we recreate it (copied from line 663)
            if (!tableExists('{survey_links}')) {
                createTable('{{survey_links}}', array('participant_id' => $sVarchar . '(50) NOT NULL', 'token_id' => 'integer NOT NULL', 'survey_id' => 'integer NOT NULL', 'date_created' => 'datetime NOT NULL'));
                addPrimaryKey('survey_links', array('participant_id', 'token_id', 'survey_id'));
            }
            alterColumn('{{survey_links}}', 'date_created', "datetime", true);
            alterColumn('{{saved_control}}', 'identifier', "text", false);
            alterColumn('{{saved_control}}', 'email', "{$sVarchar}(320)");
            alterColumn('{{surveys}}', 'adminemail', "{$sVarchar}(320)");
            alterColumn('{{surveys}}', 'bounce_email', "{$sVarchar}(320)");
            alterColumn('{{users}}', 'email', "{$sVarchar}(320)");
            try {
                setTransactionBookmark();
                Yii::app()->db->createCommand()->dropIndex('assessments_idx', '{{assessments}}');
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            try {
                setTransactionBookmark();
                Yii::app()->db->createCommand()->createIndex('assessments_idx3', '{{assessments}}', 'gid');
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            try {
                setTransactionBookmark();
                Yii::app()->db->createCommand()->dropIndex('ixcode', '{{labels}}');
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            try {
                setTransactionBookmark();
                Yii::app()->db->createCommand()->dropIndex('{{labels_ixcode_idx}}', '{{labels}}');
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            try {
                setTransactionBookmark();
                Yii::app()->db->createCommand()->createIndex('labels_code_idx', '{{labels}}', 'code');
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            if ($sDBDriverName == 'pgsql') {
                try {
                    setTransactionBookmark();
                    Yii::app()->db->createCommand("ALTER TABLE ONLY {{user_groups}} ADD PRIMARY KEY (ugid); ")->execute;
                } catch (Exception $e) {
                    rollBackToTransactionBookmark();
                }
                try {
                    setTransactionBookmark();
                    Yii::app()->db->createCommand("ALTER TABLE ONLY {{users}} ADD PRIMARY KEY (uid); ")->execute;
                } catch (Exception $e) {
                    rollBackToTransactionBookmark();
                }
            }
            // Additional corrections for MSSQL
            alterColumn('{{answers}}', 'answer', "text", false);
            alterColumn('{{assessments}}', 'name', "text", false);
            alterColumn('{{assessments}}', 'message', "text", false);
            alterColumn('{{defaultvalues}}', 'defaultvalue', "text");
            alterColumn('{{expression_errors}}', 'eqn', "text");
            alterColumn('{{expression_errors}}', 'prettyprint', "text");
            alterColumn('{{groups}}', 'description', "text");
            alterColumn('{{groups}}', 'grelevance', "text");
            alterColumn('{{labels}}', 'title', "text");
            alterColumn('{{question_attributes}}', 'value', "text");
            alterColumn('{{questions}}', 'preg', "text");
            alterColumn('{{questions}}', 'help', "text");
            alterColumn('{{questions}}', 'relevance', "text");
            alterColumn('{{questions}}', 'question', "text", false);
            alterColumn('{{quota_languagesettings}}', 'quotals_quota_id', "integer", false);
            alterColumn('{{quota_languagesettings}}', 'quotals_message', "text", false);
            alterColumn('{{saved_control}}', 'refurl', "text");
            alterColumn('{{saved_control}}', 'access_code', "text", false);
            alterColumn('{{saved_control}}', 'ip', "text", false);
            alterColumn('{{saved_control}}', 'saved_thisstep', "text", false);
            alterColumn('{{saved_control}}', 'saved_date', "datetime", false);
            alterColumn('{{surveys}}', 'attributedescriptions', "text");
            alterColumn('{{surveys}}', 'emailresponseto', "text");
            alterColumn('{{surveys}}', 'emailnotificationto', "text");
            alterColumn('{{surveys_languagesettings}}', 'surveyls_description', "text");
            alterColumn('{{surveys_languagesettings}}', 'surveyls_welcometext', "text");
            alterColumn('{{surveys_languagesettings}}', 'surveyls_email_invite', "text");
            alterColumn('{{surveys_languagesettings}}', 'surveyls_email_remind', "text");
            alterColumn('{{surveys_languagesettings}}', 'surveyls_email_register', "text");
            alterColumn('{{surveys_languagesettings}}', 'surveyls_email_confirm', "text");
            alterColumn('{{surveys_languagesettings}}', 'surveyls_attributecaptions', "text");
            alterColumn('{{surveys_languagesettings}}', 'email_admin_notification', "text");
            alterColumn('{{surveys_languagesettings}}', 'email_admin_responses', "text");
            alterColumn('{{surveys_languagesettings}}', 'surveyls_endtext', "text");
            alterColumn('{{user_groups}}', 'description', "text", false);
            alterColumn('{{conditions}}', 'value', 'string', false, '');
            alterColumn('{{participant_shares}}', 'can_edit', "{$sVarchar}(5)", false);
            alterColumn('{{users}}', 'password', "binary", false);
            dropColumn('{{users}}', 'one_time_pw');
            addColumn('{{users}}', 'one_time_pw', 'binary');
            Yii::app()->db->createCommand()->update('{{question_attributes}}', array('value' => '1'), "attribute = 'random_order' and value = '2'");
            Yii::app()->db->createCommand()->update('{{settings_global}}', array('stg_value' => 157), "stg_name='DBVersion'");
        }
        if ($oldversion < 158) {
            LimeExpressionManager::UpgradeConditionsToRelevance();
            Yii::app()->db->createCommand()->update('{{settings_global}}', array('stg_value' => 158), "stg_name='DBVersion'");
        }
        if ($oldversion < 159) {
            alterColumn('{{failed_login_attempts}}', 'ip', "{$sVarchar}(40)", false);
            Yii::app()->db->createCommand()->update('{{settings_global}}', array('stg_value' => 159), "stg_name='DBVersion'");
        }
        if ($oldversion < 160) {
            alterLanguageCode('it', 'it-informal');
            alterLanguageCode('it-formal', 'it');
            Yii::app()->db->createCommand()->update('{{settings_global}}', array('stg_value' => 160), "stg_name='DBVersion'");
        }
        if ($oldversion < 161) {
            addColumn('{{survey_links}}', 'date_invited', 'datetime NULL default NULL');
            addColumn('{{survey_links}}', 'date_completed', 'datetime NULL default NULL');
            Yii::app()->db->createCommand()->update('{{settings_global}}', array('stg_value' => 161), "stg_name='DBVersion'");
        }
        if ($oldversion < 162) {
            /* Fix participant db types */
            alterColumn('{{participant_attribute}}', 'value', "text", false);
            alterColumn('{{participant_attribute_names_lang}}', 'attribute_name', "{$sVarchar}(255)", false);
            alterColumn('{{participant_attribute_values}}', 'value', "text", false);
            Yii::app()->db->createCommand()->update('{{settings_global}}', array('stg_value' => 162), "stg_name='DBVersion'");
        }
        if ($oldversion < 163) {
            //Replace  by <script type="text/javascript" src="{TEMPLATEURL}template.js"></script> by {TEMPLATEJS}
            $replacedTemplate = replaceTemplateJS();
            Yii::app()->db->createCommand()->update('{{settings_global}}', array('stg_value' => 163), "stg_name='DBVersion'");
        }
        if ($oldversion < 164) {
            // fix survey tables for missing or incorrect token field
            upgradeSurveyTables164();
            Yii::app()->db->createCommand()->update('{{settings_global}}', array('stg_value' => 164), "stg_name='DBVersion'");
            // Not updating settings table as upgrade process takes care of that step now
        }
        $oTransaction->commit();
    } catch (Exception $e) {
        $oTransaction->rollback();
        echo '<br /><br />' . $clang->gT('An non-recoverable error happened during the update. Error details:') . "<p>" . htmlspecialchars($e->getMessage()) . '</p><br />';
        return false;
    }
    fixLanguageConsistencyAllSurveys();
    echo '<br /><br />' . sprintf($clang->gT('Database update finished (%s)'), date('Y-m-d H:i:s')) . '<br /><br />';
    return true;
}
Exemplo n.º 13
0
 /**
  * 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");
     }
 }
Exemplo n.º 14
0
function db_upgrade($oldversion)
{
    /// This function does anything necessary to upgrade
    /// older versions to match current functionality
    global $modifyoutput, $databasename, $databasetabletype, $connect, $clang;
    if ($oldversion < 111) {
        // Language upgrades from version 110 to 111 since the language names did change
        $oldnewlanguages = array('german_informal' => 'german-informal', 'cns' => 'cn-Hans', 'cnt' => 'cn-Hant', 'pt_br' => 'pt-BR', 'gr' => 'el', 'jp' => 'ja', 'si' => 'sl', 'se' => 'sv', 'vn' => 'vi');
        foreach ($oldnewlanguages as $oldlang => $newlang) {
            modify_database("", "update `prefix_answers` set `language`='{$newlang}' where language='{$oldlang}'");
            echo $modifyoutput;
            flush();
            @ob_flush();
            modify_database("", "update `prefix_questions` set `language`='{$newlang}' where language='{$oldlang}'");
            echo $modifyoutput;
            flush();
            @ob_flush();
            modify_database("", "update `prefix_groups` set `language`='{$newlang}' where language='{$oldlang}'");
            echo $modifyoutput;
            flush();
            @ob_flush();
            modify_database("", "update `prefix_labels` set `language`='{$newlang}' where language='{$oldlang}'");
            echo $modifyoutput;
            flush();
            @ob_flush();
            modify_database("", "update `prefix_surveys` set `language`='{$newlang}' where language='{$oldlang}'");
            echo $modifyoutput;
            flush();
            @ob_flush();
            modify_database("", "update `prefix_surveys_languagesettings` set `surveyls_language`='{$newlang}' where surveyls_language='{$oldlang}'");
            echo $modifyoutput;
            flush();
            @ob_flush();
            modify_database("", "update `prefix_users` set `lang`='{$newlang}' where lang='{$oldlang}'");
            echo $modifyoutput;
            flush();
            @ob_flush();
        }
        $resultdata = db_execute_assoc("select * from " . db_table_name("labelsets"));
        while ($datarow = $resultdata->FetchRow()) {
            $toreplace = $datarow['languages'];
            $toreplace = str_replace('german_informal', 'german-informal', $toreplace);
            $toreplace = str_replace('cns', 'cn-Hans', $toreplace);
            $toreplace = str_replace('cnt', 'cn-Hant', $toreplace);
            $toreplace = str_replace('pt_br', 'pt-BR', $toreplace);
            $toreplace = str_replace('gr', 'el', $toreplace);
            $toreplace = str_replace('jp', 'ja', $toreplace);
            $toreplace = str_replace('si', 'sl', $toreplace);
            $toreplace = str_replace('se', 'sv', $toreplace);
            $toreplace = str_replace('vn', 'vi', $toreplace);
            modify_database("", "update  `prefix_labelsets` set `languages`='{$toreplace}' where lid=" . $datarow['lid']);
            echo $modifyoutput;
            flush();
            @ob_flush();
        }
        $resultdata = db_execute_assoc("select * from " . db_table_name("surveys"));
        while ($datarow = $resultdata->FetchRow()) {
            $toreplace = $datarow['additional_languages'];
            $toreplace = str_replace('german_informal', 'german-informal', $toreplace);
            $toreplace = str_replace('cns', 'cn-Hans', $toreplace);
            $toreplace = str_replace('cnt', 'cn-Hant', $toreplace);
            $toreplace = str_replace('pt_br', 'pt-BR', $toreplace);
            $toreplace = str_replace('gr', 'el', $toreplace);
            $toreplace = str_replace('jp', 'ja', $toreplace);
            $toreplace = str_replace('si', 'sl', $toreplace);
            $toreplace = str_replace('se', 'sv', $toreplace);
            $toreplace = str_replace('vn', 'vi', $toreplace);
            modify_database("", "update  `prefix_surveys` set `additional_languages`='{$toreplace}' where sid=" . $datarow['sid']);
            echo $modifyoutput;
            flush();
            @ob_flush();
        }
        modify_database("", "update `prefix_settings_global` set `stg_value`='111' where stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        @ob_flush();
    }
    if ($oldversion < 112) {
        //The size of the users_name field is now 64 char (20 char before version 112)
        modify_database("", "ALTER TABLE `prefix_users` CHANGE `users_name` `users_name` VARCHAR( 64 ) NOT NULL");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "update `prefix_settings_global` set `stg_value`='112' where stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        @ob_flush();
    }
    if ($oldversion < 113) {
        //Fixes the collation for the complete DB, tables and columns
        echo "<strong>Attention:</strong>The following upgrades will update your MySQL Database collations. This may take some time.<br />If for any reason you should get a timeout just re-run the upgrade procedure. The updating will continue where it left off.<br /><br />";
        flush();
        @ob_flush();
        fix_mysql_collation();
        modify_database("", "ALTER DATABASE `{$databasename}` DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "update `prefix_settings_global` set `stg_value`='113' where stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        @ob_flush();
    }
    if ($oldversion < 114) {
        modify_database("", "ALTER TABLE `prefix_saved_control` CHANGE `email` `email` VARCHAR(320) NOT NULL");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_surveys` CHANGE `adminemail` `adminemail` VARCHAR(320) NOT NULL");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_users` CHANGE `email` `email` VARCHAR(320) NOT NULL");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", 'INSERT INTO `prefix_settings_global` VALUES (\'SessionName\', \'$sessionname\');');
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "update `prefix_settings_global` set `stg_value`='114' where stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        @ob_flush();
    }
    if ($oldversion < 126) {
        //Adds new "public" field
        modify_database("", "ALTER TABLE `prefix_surveys` ADD `printanswers` CHAR(1) default 'N' AFTER allowsave");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_surveys` ADD `listpublic` CHAR(1) default 'N' AFTER `datecreated`");
        echo $modifyoutput;
        flush();
        @ob_flush();
        upgrade_survey_tables117();
        upgrade_survey_tables118();
        // 119
        modify_database("", "CREATE TABLE `prefix_quota` (\r\n \t\t\t\t            `id` int(11) NOT NULL auto_increment,\r\n  \t\t\t\t\t\t\t`sid` int(11) default NULL,\r\n  \t\t\t\t\t\t\t`qlimit` int(8) default NULL,\r\n  \t\t\t\t\t\t\t`name` varchar(255) collate utf8_unicode_ci default NULL,\r\n  \t\t\t\t\t\t\t`action` int(2) default NULL,\r\n  \t\t\t\t\t\t\t`active` int(1) NOT NULL default '1',\r\n  \t\t\t\t\t\t\tPRIMARY KEY  (`id`)\r\n\t\t\t\t\t\t\t)   CHARACTER SET utf8 COLLATE utf8_unicode_ci;");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "CREATE TABLE `prefix_quota_members` (\r\n   \t\t \t\t\t\t   `id` int(11) NOT NULL auto_increment,\r\n\t\t\t\t\t\t   `sid` int(11) default NULL,\r\n  \t\t\t\t\t\t   `qid` int(11) default NULL,\r\n  \t\t\t\t\t\t   `quota_id` int(11) default NULL,\r\n  \t\t\t\t\t\t   `code` varchar(5) collate utf8_unicode_ci default NULL,\r\n  \t\t\t\t\t\t   PRIMARY KEY  (`id`),\r\n  \t\t\t\t\t\t   UNIQUE KEY `sid` (`sid`,`qid`,`quota_id`,`code`)\r\n\t\t\t\t\t\t   )    CHARACTER SET utf8 COLLATE utf8_unicode_ci;");
        echo $modifyoutput;
        flush();
        @ob_flush();
        // Rename Norwegian language code from NO to NB
        $oldnewlanguages = array('no' => 'nb');
        foreach ($oldnewlanguages as $oldlang => $newlang) {
            modify_database("", "update `prefix_answers` set `language`='{$newlang}' where language='{$oldlang}'");
            echo $modifyoutput;
            flush();
            @ob_flush();
            modify_database("", "update `prefix_questions` set `language`='{$newlang}' where language='{$oldlang}'");
            echo $modifyoutput;
            flush();
            @ob_flush();
            modify_database("", "update `prefix_groups` set `language`='{$newlang}' where language='{$oldlang}'");
            echo $modifyoutput;
            flush();
            @ob_flush();
            modify_database("", "update `prefix_labels` set `language`='{$newlang}' where language='{$oldlang}'");
            echo $modifyoutput;
            flush();
            @ob_flush();
            modify_database("", "update `prefix_surveys` set `language`='{$newlang}' where language='{$oldlang}'");
            echo $modifyoutput;
            flush();
            @ob_flush();
            modify_database("", "update `prefix_surveys_languagesettings` set `surveyls_language`='{$newlang}' where surveyls_language='{$oldlang}'");
            echo $modifyoutput;
            flush();
            @ob_flush();
            modify_database("", "update `prefix_users` set `lang`='{$newlang}' where lang='{$oldlang}'");
            echo $modifyoutput;
            flush();
            @ob_flush();
        }
        $resultdata = db_execute_assoc("select * from " . db_table_name("labelsets"));
        while ($datarow = $resultdata->FetchRow()) {
            $toreplace = $datarow['languages'];
            $toreplace2 = str_replace('no', 'nb', $toreplace);
            if ($toreplace2 != $toreplace) {
                modify_database("", "update  `prefix_labelsets` set `languages`='{$toreplace}' where lid=" . $datarow['lid']);
                echo $modifyoutput;
                flush();
                @ob_flush();
            }
        }
        $resultdata = db_execute_assoc("select * from " . db_table_name("surveys"));
        while ($datarow = $resultdata->FetchRow()) {
            $toreplace = $datarow['additional_languages'];
            $toreplace2 = str_replace('no', 'nb', $toreplace);
            if ($toreplace2 != $toreplace) {
                modify_database("", "update `prefix_surveys` set `additional_languages`='{$toreplace}' where sid=" . $datarow['sid']);
                echo $modifyoutput;
                flush();
                @ob_flush();
            }
        }
        modify_database("", "ALTER TABLE `prefix_surveys` ADD `htmlemail` CHAR(1) default 'N'");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_surveys` ADD `tokenanswerspersistence` CHAR(1) default 'N'");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_surveys` ADD `usecaptcha` CHAR(1) default 'N'");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_users` ADD `htmleditormode` CHAR(7) default 'default'");
        echo $modifyoutput;
        flush();
        @ob_flush();
        //122
        modify_database("", "CREATE TABLE `prefix_templates_rights` (\r\n\t\t\t\t\t\t   `uid` int(11) NOT NULL,\r\n\t\t\t\t\t\t   `folder` varchar(255) NOT NULL,\r\n\t\t\t\t\t\t   `use` int(1) NOT NULL,\r\n\t\t\t\t\t\t   PRIMARY KEY  (`uid`,`folder`)\r\n\t\t\t\t\t\t   )  CHARACTER SET utf8 COLLATE utf8_unicode_ci;");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "CREATE TABLE `prefix_templates` (\r\n\t\t\t\t\t\t   `folder` varchar(255) NOT NULL,\r\n\t\t\t\t\t\t   `creator` int(11) NOT NULL,\r\n\t\t\t\t\t\t   PRIMARY KEY  (`folder`)\r\n\t\t\t\t\t\t   )  CHARACTER SET utf8 COLLATE utf8_unicode_ci;");
        echo $modifyoutput;
        flush();
        @ob_flush();
        //123
        modify_database("", "ALTER TABLE `prefix_conditions` CHANGE `value` `value` VARCHAR(255) NOT NULL default ''");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_labels` CHANGE `title` `title` text");
        echo $modifyoutput;
        flush();
        @ob_flush();
        //124
        modify_database("", "ALTER TABLE `prefix_surveys` ADD `bounce_email` text");
        echo $modifyoutput;
        flush();
        @ob_flush();
        //125
        upgrade_token_tables125();
        modify_database("", "ALTER TABLE `prefix_users` ADD `superadmin` tinyint(1) NOT NULL default '0'");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "UPDATE `prefix_users` SET `superadmin`=1 where (create_survey=1 AND create_user=1 AND move_user=1 AND delete_user=1 AND configurator=1)");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_users` DROP COLUMN `move_user`");
        echo $modifyoutput;
        flush();
        @ob_flush();
        //126
        modify_database("", "ALTER TABLE `prefix_questions` ADD `lid1` integer NOT NULL default '0'");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "UPDATE `prefix_conditions` SET `method`='==' where (`method` is null) or `method`='' or `method`='0'");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "update `prefix_settings_global` set `stg_value`='126' where stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        @ob_flush();
    }
    if ($oldversion < 127) {
        modify_database("", "create index `assessments_idx2` on `prefix_assessments` (`sid`)");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "create index `assessments_idx3` on `prefix_assessments` (`gid`)");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "create index `conditions_idx2` on `prefix_conditions` (`qid`)");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "create index `groups_idx2` on `prefix_groups` (`sid`)");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "create index `questions_idx2` on `prefix_questions` (`sid`)");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "create index `questions_idx3` on `prefix_questions` (`gid`)");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "create index `question_attributes_idx2` on `prefix_question_attributes` (`qid`)");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "create index `quota_idx2` on `prefix_quota` (`sid`)");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "create index `saved_control_idx2` on `prefix_saved_control` (`sid`)");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "create index `user_in_groups_idx1` on `prefix_user_in_groups`  (`ugid`, `uid`)");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "create index `answers_idx2` on `prefix_answers` (`sortorder`)");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "create index `conditions_idx3` on `prefix_conditions` (`cqid`)");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "create index `questions_idx4` on `prefix_questions` (`type`)");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "update `prefix_settings_global` set `stg_value`='127' where stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        @ob_flush();
    }
    if ($oldversion < 128) {
        //128
        upgrade_token_tables128();
        modify_database("", "update `prefix_settings_global` set `stg_value`='128' where stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        @ob_flush();
    }
    if ($oldversion < 129) {
        //129
        modify_database("", "ALTER TABLE `prefix_surveys` ADD `startdate` DATETIME");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_surveys` ADD `usestartdate` varchar(1) NOT NULL default 'N'");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "update `prefix_settings_global` set `stg_value`='129' where stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        @ob_flush();
    }
    if ($oldversion < 130) {
        modify_database("", "ALTER TABLE `prefix_conditions` ADD `scenario` integer NOT NULL default '1' AFTER `qid`");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "UPDATE `prefix_conditions` SET `scenario`=1 where (`scenario` is null) or `scenario`='' or `scenario`=0");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "update `prefix_settings_global` set `stg_value`='130' where stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        @ob_flush();
    }
    if ($oldversion < 131) {
        modify_database("", "ALTER TABLE `prefix_surveys` ADD `publicstatistics` varchar(1) NOT NULL default 'N'");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "update `prefix_settings_global` set `stg_value`='131' where stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        @ob_flush();
    }
    if ($oldversion < 132) {
        modify_database("", "ALTER TABLE `prefix_surveys` ADD `publicgraphs` varchar(1) NOT NULL default 'N'");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "update `prefix_settings_global` set `stg_value`='132' where stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        @ob_flush();
    }
    if ($oldversion < 133) {
        modify_database("", "ALTER TABLE `prefix_users` ADD `one_time_pw` blob");
        echo $modifyoutput;
        flush();
        @ob_flush();
        // Add new assessment setting
        modify_database("", "ALTER TABLE `prefix_surveys` ADD `assessments` varchar(1) NOT NULL default 'N'");
        echo $modifyoutput;
        flush();
        @ob_flush();
        // add new assessment value fields to answers & labels
        modify_database("", "ALTER TABLE `prefix_answers` ADD `assessment_value` int(11) NOT NULL default '0'");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_labels` ADD `assessment_value` int(11) NOT NULL default '0'");
        echo $modifyoutput;
        flush();
        @ob_flush();
        // copy any valid codes from code field to assessment field
        modify_database("", "update `prefix_answers` set `assessment_value`=CAST(`code` as SIGNED) where `code` REGEXP '^-?[0-9]+\$'");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "update `prefix_labels` set `assessment_value`=CAST(`code` as SIGNED) where `code` REGEXP '^-?[0-9]+\$'");
        echo $modifyoutput;
        flush();
        @ob_flush();
        // activate assessment where assesment rules exist
        modify_database("", "update `prefix_surveys` set `assessments`='Y' where `sid` in (SELECT `sid` FROM `prefix_assessments` group by `sid`)");
        echo $modifyoutput;
        flush();
        @ob_flush();
        // add language field to assessment table
        modify_database("", "ALTER TABLE `prefix_assessments` ADD `language` varchar(20) NOT NULL default 'en'");
        echo $modifyoutput;
        flush();
        @ob_flush();
        // update language field with default language of that particular survey
        modify_database("", "update `prefix_assessments` set `language`=(select `language` from `prefix_surveys` where `sid`=`prefix_assessments`.`sid`)");
        echo $modifyoutput;
        flush();
        @ob_flush();
        // copy assessment link to message since from now on we will have HTML assignment messages
        modify_database("", "update `prefix_assessments` set `message`=concat(replace(`message`,'/''',''''),'<br /><a href=\"',`link`,'\">',`link`,'</a>')");
        echo $modifyoutput;
        flush();
        @ob_flush();
        // drop the old link field
        modify_database("", "ALTER TABLE `prefix_assessments` DROP COLUMN `link`");
        echo $modifyoutput;
        flush();
        @ob_flush();
        // change the primary index to include language
        modify_database("", "ALTER TABLE `prefix_assessments` DROP PRIMARY KEY, ADD PRIMARY KEY  USING BTREE(`id`, `language`)");
        echo $modifyoutput;
        flush();
        @ob_flush();
        // Add new fields to survey language settings
        modify_database("", "ALTER TABLE `prefix_surveys_languagesettings` ADD `surveyls_url` varchar(255)");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_surveys_languagesettings` ADD `surveyls_endtext` text");
        echo $modifyoutput;
        flush();
        @ob_flush();
        // copy old URL fields ot language specific entries
        modify_database("", "update `prefix_surveys_languagesettings` set `surveyls_url`=(select `url` from `prefix_surveys` where `sid`=`prefix_surveys_languagesettings`.`surveyls_survey_id`)");
        echo $modifyoutput;
        flush();
        @ob_flush();
        // drop old URL field
        modify_database("", "ALTER TABLE `prefix_surveys` DROP COLUMN `url`");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "update `prefix_settings_global` set `stg_value`='133' where stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        @ob_flush();
    }
    if ($oldversion < 134) {
        // Add new tokens setting
        modify_database("", "ALTER TABLE `prefix_surveys` ADD `usetokens` varchar(1) NOT NULL default 'N'");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_surveys` ADD `attributedescriptions` TEXT;");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_surveys` DROP COLUMN `attribute1`");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_surveys` DROP COLUMN `attribute2`");
        echo $modifyoutput;
        flush();
        @ob_flush();
        upgrade_token_tables134();
        modify_database("", "update `prefix_settings_global` set `stg_value`='134' where stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        @ob_flush();
    }
    if ($oldversion < 135) {
        modify_database("", "ALTER TABLE `prefix_question_attributes` MODIFY `value` text");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "UPDATE `prefix_settings_global` SET `stg_value`='135' WHERE stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        @ob_flush();
    }
    if ($oldversion < 136) {
        modify_database("", "ALTER TABLE `prefix_quota` ADD `autoload_url` int(1) NOT NULL default '0'");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "CREATE TABLE `prefix_quota_languagesettings` (\r\n\t\t\t\t\t\t\t\t         `quotals_id` int(11) NOT NULL auto_increment,\r\n\t\t\t\t\t\t\t\t\t\t `quotals_quota_id` int(11) NOT NULL default '0',\r\n\t\t\t\t\t\t\t\t\t\t `quotals_language` varchar(45) NOT NULL default 'en',\r\n\t\t\t\t\t\t\t\t\t\t `quotals_name` varchar(255) collate utf8_unicode_ci default NULL,\r\n\t\t\t\t\t\t\t\t\t\t `quotals_message` text NOT NULL,\r\n\t\t\t\t\t\t\t\t\t\t `quotals_url` varchar(255),\r\n\t\t\t\t\t\t\t\t\t\t `quotals_urldescrip` varchar(255),\r\n\t\t\t\t\t\t\t\t\t\t PRIMARY KEY (`quotals_id`)\r\n\t\t\t\t\t\t\t\t\t\t )   CHARACTER SET utf8 COLLATE utf8_unicode_ci;");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "UPDATE `prefix_settings_global` SET `stg_value`='136' WHERE stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        @ob_flush();
    }
    if ($oldversion < 137) {
        modify_database("", "ALTER TABLE `prefix_surveys_languagesettings` ADD `surveyls_dateformat` int(1) NOT NULL default '1'");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_users` ADD `dateformat` int(1) NOT NULL default '1'");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "UPDATE `prefix_surveys` set `startdate`=null where `usestartdate`='N'");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "UPDATE `prefix_surveys` set `expires`=null where `useexpiry`='N'");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_surveys` DROP COLUMN `useexpiry`");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_surveys` DROP COLUMN `usestartdate`");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "UPDATE `prefix_settings_global` SET `stg_value`='137' WHERE stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        @ob_flush();
    }
    if ($oldversion < 138) {
        modify_database("", "ALTER TABLE `prefix_quota_members` CHANGE `code` `code` VARCHAR(11) collate utf8_unicode_ci default NULL");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "UPDATE `prefix_settings_global` SET `stg_value`='138' WHERE stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        @ob_flush();
    }
    if ($oldversion < 139) {
        upgrade_survey_tables139();
        modify_database("", "UPDATE `prefix_settings_global` SET `stg_value`='139' WHERE stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        @ob_flush();
    }
    if ($oldversion < 140) {
        modify_database("", "ALTER TABLE `prefix_surveys` ADD `emailresponseto` text DEFAULT NULL");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "UPDATE `prefix_settings_global` SET `stg_value`='140' WHERE stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        @ob_flush();
    }
    if ($oldversion < 141) {
        modify_database("", "ALTER TABLE `prefix_surveys` ADD `tokenlength` tinyint(2) NOT NULL default '15'");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "UPDATE `prefix_settings_global` SET `stg_value`='141' WHERE stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        @ob_flush();
    }
    if ($oldversion < 142) {
        upgrade_question_attributes142();
        modify_database("", "ALTER TABLE `prefix_surveys` CHANGE `expires` `expires` datetime");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_surveys` CHANGE `startdate` `startdate` datetime");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "UPDATE `prefix_question_attributes` SET `value`='0' WHERE `value`='false'");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "UPDATE `prefix_question_attributes` SET `value`='1' WHERE `value`='true'");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "UPDATE `prefix_settings_global` SET `stg_value`='142' WHERE stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        @ob_flush();
    }
    if ($oldversion < 143) {
        modify_database("", "ALTER TABLE `prefix_questions` ADD `parent_qid` integer NOT NULL default '0'");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_answers` ADD `scale_id` tinyint NOT NULL default '0'");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_questions` ADD `scale_id` tinyint NOT NULL default '0'");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_questions` ADD `same_default` tinyint NOT NULL default '0' COMMENT 'Saves if user set to use the same default value across languages in default options dialog'");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_answers` DROP PRIMARY KEY, ADD PRIMARY KEY (`qid`,`code`,`language`,`scale_id`)");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "CREATE TABLE `prefix_defaultvalues` (\r\n                              `qid` int(11) NOT NULL default '0',\r\n                              `scale_id` int(11) NOT NULL default '0',\r\n                              `sqid` int(11) NOT NULL default '0',\r\n                              `language` varchar(20) NOT NULL,\r\n                              `specialtype` varchar(20) NOT NULL default '',\r\n                              `defaultvalue` text,\r\n                              PRIMARY KEY  (`qid` , `scale_id`, `language`, `specialtype`, `sqid` )\r\n                            )  CHARACTER SET utf8 COLLATE utf8_unicode_ci;");
        echo $modifyoutput;
        flush();
        @ob_flush();
        // -Move all 'answers' that are subquestions to the questions table
        // -Move all 'labels' that are answers to the answers table
        // -Transscribe the default values where applicable
        // -Move default values from answers to questions
        upgrade_tables143();
        modify_database("", "ALTER TABLE `prefix_answers` DROP COLUMN `default_value`");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_questions` DROP COLUMN `lid`");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_questions` DROP COLUMN `lid1`");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "CREATE TABLE prefix_sessions(\r\n                              sesskey VARCHAR( 64 ) NOT NULL DEFAULT '',\r\n                              expiry DATETIME NOT NULL ,\r\n                              expireref VARCHAR( 250 ) DEFAULT '',\r\n                              created DATETIME NOT NULL ,\r\n                              modified DATETIME NOT NULL ,\r\n                              sessdata LONGTEXT,\r\n                              PRIMARY KEY ( sesskey ) ,\r\n                              INDEX sess2_expiry( expiry ),\r\n                              INDEX sess2_expireref( expireref ))  CHARACTER SET utf8 COLLATE utf8_unicode_ci;");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "UPDATE `prefix_settings_global` SET `stg_value`='143' WHERE stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        @ob_flush();
    }
    if ($oldversion < 145) {
        modify_database("", "ALTER TABLE `prefix_surveys` ADD `savetimings` CHAR(1) NULL default 'N' AFTER `format`");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_surveys` ADD `showxquestions` CHAR(1) NULL default 'Y'");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_surveys` ADD `showgroupinfo` CHAR(1) NULL default 'B'");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_surveys` ADD `shownoanswer` CHAR(1) NULL default 'Y'");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_surveys` ADD `showqnumcode` CHAR(1) NULL default 'X'");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_surveys` ADD `bouncetime` BIGINT(20) NULL ");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_surveys` ADD `bounceprocessing` VARCHAR(1) NULL default 'N'");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_surveys` ADD `bounceaccounttype` VARCHAR(4) NULL");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_surveys` ADD `bounceaccounthost` VARCHAR(200) NULL");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_surveys` ADD `bounceaccountpass` VARCHAR(100) NULL");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_surveys` ADD `bounceaccountencryption` VARCHAR(3) NULL");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_surveys` ADD `bounceaccountuser` VARCHAR(200) NULL");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_surveys` ADD `showwelcome` CHAR(1) NULL default 'Y'");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_surveys` ADD `showprogress` char(1) default 'Y'");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_surveys` ADD `allowjumps` char(1) default 'N'");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_surveys` ADD `navigationdelay` tinyint(2) default '0'");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_surveys` ADD `nokeyboard` char(1) default 'N'");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_surveys` ADD `alloweditaftercompletion` char(1) default 'N'");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "CREATE TABLE `prefix_survey_permissions` (\r\n                                `sid` int(10) unsigned NOT NULL,\r\n                                `uid` int(10) unsigned NOT NULL,\r\n                                `permission` varchar(20) NOT NULL,\r\n                                `create_p` tinyint(1) NOT NULL default '0',\r\n                                `read_p` tinyint(1) NOT NULL default '0',\r\n                                `update_p` tinyint(1) NOT NULL default '0',\r\n                                `delete_p` tinyint(1) NOT NULL default '0',\r\n                                `import_p` tinyint(1) NOT NULL default '0',\r\n                                `export_p` tinyint(1) NOT NULL default '0',\r\n                                PRIMARY KEY (sid, uid, permission)\r\n                            )  CHARACTER SET utf8 COLLATE utf8_unicode_ci;");
        echo $modifyoutput;
        flush();
        @ob_flush();
        upgrade_surveypermissions_table145();
        // drop the old survey rights table
        modify_database("", "DROP TABLE `prefix_surveys_rights`");
        echo $modifyoutput;
        flush();
        @ob_flush();
        // Add new fields for email templates
        modify_database("", "ALTER TABLE `prefix_surveys_languagesettings` ADD\r\n                             (`email_admin_notification_subj`  VARCHAR(255) NULL,\r\n                              `email_admin_notification` TEXT NULL,\r\n                              `email_admin_responses_subj` VARCHAR(255) NULL,\r\n                              `email_admin_responses` TEXT NULL)");
        //Add index to questions table to speed up subquestions
        modify_database("", "create INDEX parent_qid_idx on prefix_questions( parent_qid );");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_surveys` ADD `emailnotificationto` text DEFAULT NULL AFTER `emailresponseto`");
        echo $modifyoutput;
        flush();
        @ob_flush();
        upgrade_survey_table145();
        modify_database("", "ALTER TABLE `prefix_surveys` DROP COLUMN `notification`");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_conditions` CHANGE `method` `method` CHAR( 5 ) NOT NULL default '';");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "UPDATE `prefix_surveys` set `private`='N' where `private` is NULL;");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_surveys` CHANGE `private` `anonymized` char(1) collate utf8_unicode_ci NOT NULL default 'N';");
        echo $modifyoutput;
        flush();
        @ob_flush();
        //now we clean up things that were not properly set in previous DB upgrades
        modify_database("", "UPDATE `prefix_answers` SET `answer`='' where `answer` is null;");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_answers` CHANGE `answer` `answer` text collate utf8_unicode_ci NOT NULL;");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_answers` CHANGE `assessment_value` `assessment_value` int(11) NOT NULL default '0' AFTER `answer`;");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "UPDATE `prefix_assessments` SET `scope`='' where `scope` is null;");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_assessments` CHANGE `scope` `scope` varchar(5) collate utf8_unicode_ci NOT NULL default '';");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "UPDATE `prefix_assessments` SET `name`='' where `name` is null;");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_assessments` CHANGE `name` `name` text collate utf8_unicode_ci NOT NULL;");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "UPDATE `prefix_assessments` SET `message`='' where `message` is null;");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_assessments` CHANGE `message` `message` text collate utf8_unicode_ci NOT NULL;");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "UPDATE `prefix_assessments` SET `minimum`='' where `minimum` is null;");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_assessments` CHANGE `minimum` `minimum` varchar(50) collate utf8_unicode_ci NOT NULL default '';");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "UPDATE `prefix_assessments` SET `maximum`='' where `maximum` is null;");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_assessments` CHANGE `maximum` `maximum` varchar(50) collate utf8_unicode_ci NOT NULL default '';");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_assessments` CHANGE `id` `id` int(11) NOT NULL;");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_assessments` DROP PRIMARY KEY;");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_assessments` ADD PRIMARY KEY (`id`,`language`);");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_assessments` CHANGE `id` `id` int(11) NOT NULL auto_increment;");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_conditions` CHANGE `cfieldname` `cfieldname` varchar(50) collate utf8_unicode_ci NOT NULL default '';");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_defaultvalues` CHANGE `specialtype` `specialtype` varchar(20) collate utf8_unicode_ci NOT NULL default '' AFTER `qid`;");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "UPDATE `prefix_groups` SET `group_name`='' where `group_name` is null;");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_groups` CHANGE `group_name` `group_name` varchar(100) collate utf8_unicode_ci NOT NULL default '';");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "UPDATE `prefix_labels` SET `code`='' where `code` is null;");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_labels` CHANGE `code` `code` varchar(5) collate utf8_unicode_ci NOT NULL default '';");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_labels` CHANGE `language` `language` varchar(20) collate utf8_unicode_ci NOT NULL default 'en' AFTER `assessment_value`;");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "UPDATE `prefix_labelsets` SET `label_name`='' WHERE `label_name` is null;");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_labelsets` CHANGE `label_name` `label_name` varchar(100) collate utf8_unicode_ci NOT NULL default '';");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_questions` CHANGE `parent_qid` `parent_qid` int(11) NOT NULL default '0' AFTER `qid`;");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "UPDATE `prefix_questions` SET `type`='T' where `type` is null;");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_questions` CHANGE `type` `type` char(1) collate utf8_unicode_ci NOT NULL default 'T';");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "UPDATE `prefix_questions` SET `title`='' where `type` is null;");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_questions` CHANGE `title` `title` varchar(20) collate utf8_unicode_ci NOT NULL default '';");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "UPDATE `prefix_questions` SET `question`='' where `question` is null;");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_questions` CHANGE `question` `question` text collate utf8_unicode_ci NOT NULL;");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "UPDATE `prefix_questions` SET `other`='N' where `other` is null;");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_questions` CHANGE `other` `other` char(1) collate utf8_unicode_ci NOT NULL default 'N';");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_questions` CHANGE `mandatory` `mandatory` char(1) collate utf8_unicode_ci default NULL;");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_question_attributes` CHANGE `attribute` `attribute` varchar(50) collate utf8_unicode_ci default NULL;");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_quota` CHANGE `qlimit` `qlimit` int(8) default NULL AFTER `name`;");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "UPDATE `prefix_saved_control` SET `identifier`='' where `identifier` is null;");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_saved_control` CHANGE `identifier` `identifier` text collate utf8_unicode_ci NOT NULL;");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "UPDATE `prefix_saved_control` SET `access_code`='' where `access_code` is null;");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_saved_control` CHANGE `access_code` `access_code` text collate utf8_unicode_ci NOT NULL;");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_saved_control` CHANGE `email` `email` varchar(320) collate utf8_unicode_ci default NULL;");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "UPDATE `prefix_saved_control` SET `ip`='' where `ip` is null;");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_saved_control` CHANGE `ip` `ip` text collate utf8_unicode_ci NOT NULL;");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "UPDATE `prefix_saved_control` SET `saved_thisstep`='' where `access_code` is null;");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_saved_control` CHANGE `saved_thisstep` `saved_thisstep` text collate utf8_unicode_ci NOT NULL;");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "UPDATE `prefix_saved_control` SET `status`='' where `access_code` is null;");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_saved_control` CHANGE `status` `status` char(1) collate utf8_unicode_ci NOT NULL default '';");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "UPDATE `prefix_saved_control` SET `saved_date`='0000-00-00 00:00:00' where `saved_date` is null;");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_saved_control` CHANGE `saved_date` `saved_date` datetime NOT NULL;");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "UPDATE `prefix_settings_global` SET `stg_value`='' where `stg_value` is null;");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_settings_global` CHANGE `stg_value` `stg_value` varchar(255) collate utf8_unicode_ci NOT NULL default ''");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_surveys` CHANGE `admin` `admin` varchar(50) collate utf8_unicode_ci default NULL");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "UPDATE `prefix_surveys` SET `active`='N' where `active` is null;");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_surveys` CHANGE `active` `active` char(1) collate utf8_unicode_ci NOT NULL default 'N';");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_surveys` CHANGE `startdate` `startdate` datetime default NULL AFTER `expires`");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_surveys` CHANGE `adminemail` `adminemail` varchar(320) collate utf8_unicode_ci default NULL");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_surveys` CHANGE `anonymized` `anonymized` char(1) collate utf8_unicode_ci NOT NULL default 'N'");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_surveys` CHANGE `faxto` `faxto` varchar(20) collate utf8_unicode_ci default NULL");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_surveys` CHANGE `format` `format` char(1) collate utf8_unicode_ci default NULL");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_surveys` CHANGE `language` `language` varchar(50) collate utf8_unicode_ci default NULL");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_surveys` CHANGE `additional_languages` `additional_languages` varchar(255) collate utf8_unicode_ci default NULL");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_surveys` CHANGE `printanswers` `printanswers` char(1) collate utf8_unicode_ci default 'N' AFTER `allowprev`");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_surveys` CHANGE `publicstatistics` `publicstatistics` char(1) collate utf8_unicode_ci default 'N' after `datecreated`");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_surveys` CHANGE `publicgraphs` `publicgraphs` char(1) collate utf8_unicode_ci default 'N' AFTER `publicstatistics`");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_surveys` CHANGE `assessments` `assessments` char(1) collate utf8_unicode_ci default 'N' AFTER `tokenanswerspersistence`");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_surveys` CHANGE `usetokens` `usetokens` char(1) collate utf8_unicode_ci default 'N' AFTER `usecaptcha`");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_surveys` CHANGE `bounce_email` `bounce_email` varchar(320) collate utf8_unicode_ci default NULL");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_surveys` CHANGE `tokenlength` `tokenlength` tinyint(2) default '15'");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "UPDATE `prefix_surveys_languagesettings` SET `surveyls_title`='' where `surveyls_title` is null;");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_surveys_languagesettings` CHANGE `surveyls_title` `surveyls_title` varchar(200) collate utf8_unicode_ci NOT NULL");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_surveys_languagesettings` CHANGE `surveyls_endtext` `surveyls_endtext` text collate utf8_unicode_ci AFTER `surveyls_welcometext`");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_surveys_languagesettings` CHANGE `surveyls_url` `surveyls_url` varchar(255) collate utf8_unicode_ci default NULL   AFTER `surveyls_endtext`");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_surveys_languagesettings` CHANGE `surveyls_urldescription` `surveyls_urldescription` varchar(255) collate utf8_unicode_ci default NULL");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_surveys_languagesettings` CHANGE `surveyls_email_invite_subj` `surveyls_email_invite_subj` varchar(255) collate utf8_unicode_ci default NULL");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_surveys_languagesettings` CHANGE `surveyls_email_remind_subj` `surveyls_email_remind_subj` varchar(255) collate utf8_unicode_ci default NULL");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_surveys_languagesettings` CHANGE `surveyls_email_register_subj` `surveyls_email_register_subj` varchar(255) collate utf8_unicode_ci default NULL");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_surveys_languagesettings` CHANGE `surveyls_email_confirm_subj` `surveyls_email_confirm_subj` varchar(255) collate utf8_unicode_ci default NULL");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_surveys_languagesettings` CHANGE `surveyls_dateformat` `surveyls_dateformat` int(10) unsigned NOT NULL default '1'");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "UPDATE `prefix_users` SET `users_name`='' where `users_name` is null;");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_users` CHANGE `users_name` `users_name` varchar(64) collate utf8_unicode_ci NOT NULL default ''");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "UPDATE `prefix_users` SET `full_name`='' where `full_name` is null;");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_users` CHANGE `full_name` `full_name` varchar(50) collate utf8_unicode_ci NOT NULL");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_users` CHANGE `lang` `lang` varchar(20) collate utf8_unicode_ci default NULL");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_users` CHANGE `email` `email` varchar(320) collate utf8_unicode_ci default NULL");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_users` CHANGE `superadmin` `superadmin` tinyint(1) NOT NULL default '0' AFTER `delete_user`");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_users` CHANGE `htmleditormode` `htmleditormode` varchar(7) collate utf8_unicode_ci default 'default'");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_users` CHANGE `dateformat` `dateformat` int(10) unsigned NOT NULL default '1'");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_users` DROP INDEX `email`;");
        modify_database("", "UPDATE `prefix_user_groups` SET `name`='' where `name` is null;");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_user_groups` CHANGE `name` `name` varchar(20) collate utf8_unicode_ci NOT NULL");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "UPDATE `prefix_user_groups` SET `description`='' where `description` is null;");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_user_groups` CHANGE `description` `description` text collate utf8_unicode_ci NOT NULL");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_user_in_groups` DROP INDEX `user_in_groups_idx1`");
        // Don't show output because this key might not exist
        modify_database("", "ALTER TABLE `prefix_user_in_groups` ADD PRIMARY KEY (`ugid`, `uid`)");
        // Don't show output because this might already be set
        modify_database("", "ALTER TABLE  `prefix_surveys_languagesettings` ADD  `surveyls_numberformat` int(11) NOT NULL DEFAULT 0 AFTER  `surveyls_dateformat`");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "CREATE TABLE `prefix_failed_login_attempts` (\r\n                              `id` int(11) NOT NULL AUTO_INCREMENT,\r\n                              `ip` varchar(37) NOT NULL,\r\n                              `last_attempt` varchar(20) NOT NULL,\r\n                              `number_attempts` int(11) NOT NULL,\r\n                              PRIMARY KEY (`id`)\r\n                            )  CHARACTER SET utf8 COLLATE utf8_unicode_ci;");
        echo $modifyoutput;
        flush();
        @ob_flush();
        upgrade_token_tables145();
        modify_database("", "UPDATE `prefix_settings_global` SET `stg_value`='145' WHERE stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        @ob_flush();
    }
    if ($oldversion < 146) {
        upgrade_timing_tables146();
        // Fix permissions for new feature quick-translation
        modify_database("", "INSERT into prefix_survey_permissions (sid,`uid`,permission,`read_p`,`update_p`) SELECT sid,owner_id,'translations','1','1' from prefix_surveys");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "UPDATE `prefix_settings_global` SET `stg_value`='146' WHERE stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        @ob_flush();
    }
    if ($oldversion < 147) {
        modify_database("", "ALTER TABLE `prefix_users` ADD `templateeditormode` VARCHAR( 7 )NOT NULL DEFAULT 'default' AFTER `htmleditormode`");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_users` ADD `questionselectormode` VARCHAR( 7 )NOT NULL DEFAULT 'default' AFTER `templateeditormode`");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "UPDATE `prefix_settings_global` SET `stg_value`='147' WHERE stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        @ob_flush();
    }
    if ($oldversion < 148) {
        modify_database("", "ALTER TABLE `prefix_users` ADD `participant_panel` tinyint(1) NOT NULL default '0'");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "CREATE TABLE `prefix_participants` (`participant_id` varchar(50) NOT NULL,\r\n                                                                `firstname` varchar(40) default NULL,\r\n                                                                `lastname` varchar(40) default NULL,\r\n                                                                `email` varchar(80) collate utf8_unicode_ci default NULL,\r\n                                                                `language` varchar(40) default NULL,\r\n                                                                `blacklisted` varchar(1) NOT NULL,\r\n                                                                `owner_uid` int(20) NOT NULL ,\r\n                                                                PRIMARY KEY  (`participant_id`)\r\n                                                                )   CHARACTER SET utf8 COLLATE utf8_unicode_ci;");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "CREATE TABLE `prefix_participant_attribute` (\r\n        `participant_id` varchar(50) NOT NULL,\r\n        `attribute_id` int(11) NOT NULL,\r\n        `value` varchar(50) NOT NULL,\r\n        PRIMARY KEY  (`participant_id`,`attribute_id`)\r\n        )   CHARACTER SET utf8 COLLATE utf8_unicode_ci;");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "CREATE TABLE `prefix_participant_attribute_names` (\r\n        `attribute_id` int(11) NOT NULL AUTO_INCREMENT,\r\n        `attribute_type` varchar(4) NOT NULL,\r\n        `visible` char(5) NOT NULL,\r\n        PRIMARY KEY  (`attribute_id`,`attribute_type`)\r\n        )   CHARACTER SET utf8 COLLATE utf8_unicode_ci;");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "CREATE TABLE `prefix_participant_attribute_names_lang` (\r\n        `attribute_id` int(11) NOT NULL,\r\n        `attribute_name` varchar(30) NOT NULL,\r\n        `lang` varchar(20) NOT NULL,\r\n        PRIMARY KEY  (`attribute_id`,`lang`)\r\n        )   CHARACTER SET utf8 COLLATE utf8_unicode_ci;");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "CREATE TABLE `prefix_participant_attribute_values` (\r\n        `attribute_id` int(11) NOT NULL,\r\n        `value_id` int(11) NOT NULL AUTO_INCREMENT,\r\n        `value` varchar(20) NOT NULL,\r\n        PRIMARY KEY  (`value_id`)\r\n        )   CHARACTER SET utf8 COLLATE utf8_unicode_ci;");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "CREATE TABLE `prefix_participant_shares` (\r\n        `participant_id` varchar(50) NOT NULL,\r\n        `share_uid` int(11) NOT NULL,\r\n        `date_added` datetime NOT NULL,\r\n        `can_edit` varchar(5) NOT NULL,\r\n        PRIMARY KEY  (`participant_id`,`share_uid`)\r\n        )   CHARACTER SET utf8 COLLATE utf8_unicode_ci;");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "CREATE TABLE `prefix_survey_links` (\r\n        `participant_id` varchar(50) NOT NULL,\r\n        `token_id` int(11) NOT NULL,\r\n        `survey_id` int(11) NOT NULL,\r\n        `date_created` datetime NOT NULL,\r\n        PRIMARY KEY  (`participant_id`,`token_id`,`survey_id`)\r\n        )   CHARACTER SET utf8 COLLATE utf8_unicode_ci;");
        echo $modifyoutput;
        flush();
        @ob_flush();
        // add question_attributes field to assessment table
        modify_database("", "ALTER TABLE `prefix_question_attributes` ADD `language` varchar(20)");
        echo $modifyoutput;
        flush();
        @ob_flush();
        upgrade_question_attributes148();
        fixSubquestions();
        modify_database("", "UPDATE `prefix_settings_global` SET `stg_value`='148' WHERE stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        @ob_flush();
    }
    if ($oldversion < 149) {
        modify_database("", "CREATE TABLE `prefix_survey_url_parameters` (\r\n        `id` int(9) NOT NULL AUTO_INCREMENT,\r\n        `sid` int(10) NOT NULL,\r\n        `parameter` varchar(50) NOT NULL,\r\n        `targetqid` int(10) NULL,\r\n        `targetsqid` int(10) NULL,\r\n        PRIMARY KEY (`id`)\r\n        ) ENGINE=MYISAM CHARACTER SET utf8 COLLATE utf8_unicode_ci;");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "update `prefix_settings_global` set `stg_value`='149' where stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        @ob_flush();
    }
    if ($oldversion < 150) {
        modify_database("", "ALTER TABLE `prefix_questions` ADD `relevance` TEXT;");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "update `prefix_settings_global` set `stg_value`='150' where stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        @ob_flush();
    }
    if ($oldversion < 151) {
        modify_database("", "ALTER TABLE `prefix_groups` ADD `randomization_group` VARCHAR(20) NOT NULL DEFAULT '';");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "update `prefix_settings_global` set `stg_value`='151' where stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        @ob_flush();
    }
    if ($oldversion < 152) {
        modify_database("", "CREATE INDEX `question_attributes_idx3` ON `prefix_question_attributes` (`attribute`);");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "update `prefix_settings_global` set `stg_value`='152' where stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        @ob_flush();
    }
    if ($oldversion < 153) {
        modify_database("", "CREATE TABLE `prefix_expression_errors` (\r\n        `id` int(9) NOT NULL AUTO_INCREMENT,\r\n        `errortime` varchar(50) DEFAULT NULL,\r\n        `sid` int(11) DEFAULT NULL,\r\n        `gid` int(11) DEFAULT NULL,\r\n        `qid` int(11) DEFAULT NULL,\r\n        `gseq` int(11) DEFAULT NULL,\r\n        `qseq` int(11) DEFAULT NULL,\r\n        `type` varchar(50) ,\r\n        `eqn` text,\r\n        `prettyprint` text,\r\n        PRIMARY KEY (`id`)\r\n        ) ENGINE=MYISAM CHARACTER SET utf8 COLLATE utf8_unicode_ci;");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "update `prefix_settings_global` set `stg_value`='153' where stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        @ob_flush();
    }
    if ($oldversion < 154) {
        modify_database("", "ALTER TABLE `prefix_groups` ADD `grelevance` text DEFAULT NULL;");
        echo $modifyoutput;
        flush();
        @ob_flush();
        LimeExpressionManager::UpgradeConditionsToRelevance();
        modify_database("", "update `prefix_settings_global` set `stg_value`='154' where stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        @ob_flush();
    }
    if ($oldversion < 155) {
        modify_database("", "ALTER TABLE `prefix_surveys` ADD `googleanalyticsstyle` char(1) DEFAULT NULL;");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_surveys` ADD `googleanalyticsapikey` varchar(25) DEFAULT NULL;");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE `prefix_surveys` CHANGE `showXquestions` `showxquestions` char(1) collate utf8_unicode_ci NOT NULL default 'Y';");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "UPDATE `prefix_settings_global` SET stg_value='155' WHERE stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        ob_flush();
    }
    fixLanguageConsistencyAllSurveys();
    echo '<br /><br />' . sprintf($clang->gT('Database update finished (%s)'), date('Y-m-d H:i:s')) . '<br />';
    return true;
}
Exemplo n.º 15
0
/**
 * @param integer $iOldDBVersion
 */
function db_upgrade_all($iOldDBVersion)
{
    /// This function does anything necessary to upgrade
    /// older versions to match current functionality
    global $modifyoutput;
    Yii::app()->loadHelper('database');
    $sUserTemplateRootDir = Yii::app()->getConfig('usertemplaterootdir');
    $sStandardTemplateRootDir = Yii::app()->getConfig('standardtemplaterootdir');
    $oDB = Yii::app()->getDb();
    Yii::app()->setConfig('Updating', true);
    $oDB->schemaCachingDuration = 0;
    // Deactivate schema caching
    $oTransaction = $oDB->beginTransaction();
    try {
        if ($iOldDBVersion < 111) {
            // Language upgrades from version 110 to 111 because the language names did change
            $aOldNewLanguages = array('german_informal' => 'german-informal', 'cns' => 'cn-Hans', 'cnt' => 'cn-Hant', 'pt_br' => 'pt-BR', 'gr' => 'el', 'jp' => 'ja', 'si' => 'sl', 'se' => 'sv', 'vn' => 'vi');
            foreach ($aOldNewLanguages as $sOldLanguageCode => $sNewLanguageCode) {
                alterLanguageCode($sOldLanguageCode, $sNewLanguageCode);
            }
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 111), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 112) {
            // New size of the username field (it was previously 20 chars wide)
            $oDB->createCommand()->alterColumn('{{users}}', 'users_name', "string(64) NOT NULL");
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 112), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 113) {
            //Fixes the collation for the complete DB, tables and columns
            if (Yii::app()->db->driverName == 'mysql') {
                $sDatabaseName = getDBConnectionStringProperty('dbname');
                fixMySQLCollations();
                modifyDatabase("", "ALTER DATABASE `{$sDatabaseName}` DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;");
                echo $modifyoutput;
                flush();
                @ob_flush();
            }
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 113), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 114) {
            $oDB->createCommand()->alterColumn('{{saved_control}}', 'email', "string(320) NOT NULL");
            $oDB->createCommand()->alterColumn('{{surveys}}', 'adminemail', "string(320) NOT NULL");
            $oDB->createCommand()->alterColumn('{{users}}', 'email', "string(320) NOT NULL");
            $oDB->createCommand()->insert('{{settings_global}}', array('stg_name' => 'SessionName', 'stg_value' => randomChars(64, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ!"$%&/()=?`+*~#",;.:abcdefghijklmnopqrstuvwxyz123456789')));
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 114), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 126) {
            addColumn('{{surveys}}', 'printanswers', "string(1) default 'N'");
            addColumn('{{surveys}}', 'listpublic', "string(1) default 'N'");
            upgradeSurveyTables126();
            upgradeTokenTables126();
            // Create quota table
            $oDB->createCommand()->createTable('{{quota}}', array('id' => 'pk', 'sid' => 'integer', 'qlimit' => 'integer', 'name' => 'string', 'action' => 'integer', 'active' => 'integer NOT NULL DEFAULT 1'));
            // Create quota_members table
            $oDB->createCommand()->createTable('{{quota_members}}', array('id' => 'pk', 'sid' => 'integer', 'qid' => 'integer', 'quota_id' => 'integer', 'code' => 'string(5)'));
            $oDB->createCommand()->createIndex('sid', '{{quota_members}}', 'sid,qid,quota_id,code', true);
            // Create templates_rights table
            $oDB->createCommand()->createTable('{{templates_rights}}', array('uid' => 'integer NOT NULL', 'folder' => 'string NOT NULL', 'use' => 'integer', 'PRIMARY KEY (uid, folder)'));
            // Create templates table
            $oDB->createCommand()->createTable('{{templates}}', array('folder' => 'string NOT NULL', 'creator' => 'integer NOT NULL', 'PRIMARY KEY (folder)'));
            // Rename Norwegian language codes
            alterLanguageCode('no', 'nb');
            addColumn('{{surveys}}', 'htmlemail', "string(1) default 'N'");
            addColumn('{{surveys}}', 'tokenanswerspersistence', "string(1) default 'N'");
            addColumn('{{surveys}}', 'usecaptcha', "string(1) default 'N'");
            addColumn('{{surveys}}', 'bounce_email', 'text');
            addColumn('{{users}}', 'htmleditormode', "string(7) default 'default'");
            addColumn('{{users}}', 'superadmin', "integer NOT NULL default '0'");
            addColumn('{{questions}}', 'lid1', "integer NOT NULL default '0'");
            alterColumn('{{conditions}}', 'value', "string", false, '');
            alterColumn('{{labels}}', 'title', "text");
            $oDB->createCommand()->update('{{users}}', array('superadmin' => 1), "create_survey=1 AND create_user=1 AND move_user=1 AND delete_user=1 AND configurator=1");
            $oDB->createCommand()->update('{{conditions}}', array('method' => '=='), "(method is null) or method='' or method='0'");
            dropColumn('{{users}}', 'move_user');
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 126), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 127) {
            modifyDatabase("", "create index answers_idx2 on {{answers}} (sortorder)");
            echo $modifyoutput;
            modifyDatabase("", "create index assessments_idx2 on {{assessments}} (sid)");
            echo $modifyoutput;
            modifyDatabase("", "create index assessments_idx3 on {{assessments}} (gid)");
            echo $modifyoutput;
            modifyDatabase("", "create index conditions_idx2 on {{conditions}} (qid)");
            echo $modifyoutput;
            modifyDatabase("", "create index conditions_idx3 on {{conditions}} (cqid)");
            echo $modifyoutput;
            modifyDatabase("", "create index groups_idx2 on {{groups}} (sid)");
            echo $modifyoutput;
            modifyDatabase("", "create index question_attributes_idx2 on {{question_attributes}} (qid)");
            echo $modifyoutput;
            modifyDatabase("", "create index questions_idx2 on {{questions}} (sid)");
            echo $modifyoutput;
            modifyDatabase("", "create index questions_idx3 on {{questions}} (gid)");
            echo $modifyoutput;
            modifyDatabase("", "create index questions_idx4 on {{questions}} (type)");
            echo $modifyoutput;
            modifyDatabase("", "create index quota_idx2 on {{quota}} (sid)");
            echo $modifyoutput;
            modifyDatabase("", "create index saved_control_idx2 on {{saved_control}} (sid)");
            echo $modifyoutput;
            modifyDatabase("", "create index user_in_groups_idx1 on {{user_in_groups}} (ugid, uid)");
            echo $modifyoutput;
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 127), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 128) {
            upgradeTokens128();
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 128), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 129) {
            addColumn('{{surveys}}', 'startdate', "datetime");
            addColumn('{{surveys}}', 'usestartdate', "string(1) NOT NULL default 'N'");
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 129), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 130) {
            addColumn('{{conditions}}', 'scenario', "integer NOT NULL default '1'");
            $oDB->createCommand()->update('{{conditions}}', array('scenario' => '1'), "(scenario is null) or scenario=0");
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 130), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 131) {
            addColumn('{{surveys}}', 'publicstatistics', "string(1) NOT NULL default 'N'");
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 131), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 132) {
            addColumn('{{surveys}}', 'publicgraphs', "string(1) NOT NULL default 'N'");
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 132), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 133) {
            addColumn('{{users}}', 'one_time_pw', 'binary');
            // Add new assessment setting
            addColumn('{{surveys}}', 'assessments', "string(1) NOT NULL default 'N'");
            // add new assessment value fields to answers & labels
            addColumn('{{answers}}', 'assessment_value', "integer NOT NULL default '0'");
            addColumn('{{labels}}', 'assessment_value', "integer NOT NULL default '0'");
            // copy any valid codes from code field to assessment field
            switch (Yii::app()->db->driverName) {
                case 'mysql':
                case 'mysqli':
                    $oDB->createCommand("UPDATE {{answers}} SET assessment_value=CAST(`code` as SIGNED) where `code` REGEXP '^-?[0-9]+\$'")->execute();
                    $oDB->createCommand("UPDATE {{labels}} SET assessment_value=CAST(`code` as SIGNED) where `code` REGEXP '^-?[0-9]+\$'")->execute();
                    // copy assessment link to message since from now on we will have HTML assignment messages
                    $oDB->createCommand("UPDATE {{assessments}} set message=concat(replace(message,'/''',''''),'<br /><a href=\"',link,'\">',link,'</a>')")->execute();
                    break;
                case 'sqlsrv':
                case 'dblib':
                case 'mssql':
                    try {
                        $oDB->createCommand("UPDATE {{answers}} SET assessment_value=CAST([code] as int) WHERE ISNUMERIC([code])=1")->execute();
                        $oDB->createCommand("UPDATE {{labels}} SET assessment_value=CAST([code] as int) WHERE ISNUMERIC([code])=1")->execute();
                    } catch (Exception $e) {
                    }
                    // copy assessment link to message since from now on we will have HTML assignment messages
                    alterColumn('{{assessments}}', 'link', "text", false);
                    alterColumn('{{assessments}}', 'message', "text", false);
                    $oDB->createCommand("UPDATE {{assessments}} set message=replace(message,'/''','''')+'<br /><a href=\"'+link+'\">'+link+'</a>'")->execute();
                    break;
                case 'pgsql':
                    $oDB->createCommand("UPDATE {{answers}} SET assessment_value=CAST(code as integer) where code ~ '^[0-9]+'")->execute();
                    $oDB->createCommand("UPDATE {{labels}} SET assessment_value=CAST(code as integer) where code ~ '^[0-9]+'")->execute();
                    // copy assessment link to message since from now on we will have HTML assignment messages
                    $oDB->createCommand("UPDATE {{assessments}} set message=replace(message,'/''','''')||'<br /><a href=\"'||link||'\">'||link||'</a>'")->execute();
                    break;
                default:
                    die('Unknown database type');
            }
            // activate assessment where assessment rules exist
            $oDB->createCommand("UPDATE {{surveys}} SET assessments='Y' where sid in (SELECT sid FROM {{assessments}} group by sid)")->execute();
            // add language field to assessment table
            addColumn('{{assessments}}', 'language', "string(20) NOT NULL default 'en'");
            // update language field with default language of that particular survey
            $oDB->createCommand("UPDATE {{assessments}} SET language=(select language from {{surveys}} where sid={{assessments}}.sid)")->execute();
            // drop the old link field
            dropColumn('{{assessments}}', 'link');
            // Add new fields to survey language settings
            addColumn('{{surveys_languagesettings}}', 'surveyls_url', "string");
            addColumn('{{surveys_languagesettings}}', 'surveyls_endtext', 'text');
            // copy old URL fields ot language specific entries
            $oDB->createCommand("UPDATE {{surveys_languagesettings}} set surveyls_url=(select url from {{surveys}} where sid={{surveys_languagesettings}}.surveyls_survey_id)")->execute();
            // drop old URL field
            dropColumn('{{surveys}}', 'url');
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 133), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 134) {
            // Add new tokens setting
            addColumn('{{surveys}}', 'usetokens', "string(1) NOT NULL default 'N'");
            addColumn('{{surveys}}', 'attributedescriptions', 'text');
            dropColumn('{{surveys}}', 'attribute1');
            dropColumn('{{surveys}}', 'attribute2');
            upgradeTokenTables134();
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 134), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 135) {
            alterColumn('{{question_attributes}}', 'value', 'text');
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 135), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 136) {
            addColumn('{{quota}}', 'autoload_url', "integer NOT NULL default 0");
            // Create quota table
            $aFields = array('quotals_id' => 'pk', 'quotals_quota_id' => 'integer NOT NULL DEFAULT 0', 'quotals_language' => "string(45) NOT NULL default 'en'", 'quotals_name' => 'string', 'quotals_message' => 'text NOT NULL', 'quotals_url' => 'string', 'quotals_urldescrip' => 'string');
            $oDB->createCommand()->createTable('{{quota_languagesettings}}', $aFields);
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 136), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 137) {
            addColumn('{{surveys_languagesettings}}', 'surveyls_dateformat', "integer NOT NULL default 1");
            addColumn('{{users}}', 'dateformat', "integer NOT NULL default 1");
            $oDB->createCommand()->update('{{surveys}}', array('startdate' => NULL), "usestartdate='N'");
            $oDB->createCommand()->update('{{surveys}}', array('expires' => NULL), "useexpiry='N'");
            dropColumn('{{surveys}}', 'useexpiry');
            dropColumn('{{surveys}}', 'usestartdate');
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 137), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 138) {
            alterColumn('{{quota_members}}', 'code', "string(11)");
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 138), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 139) {
            upgradeSurveyTables139();
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 139), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 140) {
            addColumn('{{surveys}}', 'emailresponseto', 'text');
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 140), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 141) {
            addColumn('{{surveys}}', 'tokenlength', 'integer NOT NULL default 15');
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 141), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 142) {
            upgradeQuestionAttributes142();
            $oDB->createCommand()->alterColumn('{{surveys}}', 'expires', "datetime");
            $oDB->createCommand()->alterColumn('{{surveys}}', 'startdate', "datetime");
            $oDB->createCommand()->update('{{question_attributes}}', array('value' => 0), "value='false'");
            $oDB->createCommand()->update('{{question_attributes}}', array('value' => 1), "value='true'");
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 142), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 143) {
            addColumn('{{questions}}', 'parent_qid', 'integer NOT NULL default 0');
            addColumn('{{answers}}', 'scale_id', 'integer NOT NULL default 0');
            addColumn('{{questions}}', 'scale_id', 'integer NOT NULL default 0');
            addColumn('{{questions}}', 'same_default', 'integer NOT NULL default 0');
            dropPrimaryKey('answers');
            addPrimaryKey('answers', array('qid', 'code', 'language', 'scale_id'));
            $aFields = array('qid' => "integer NOT NULL default 0", 'scale_id' => 'integer NOT NULL default 0', 'sqid' => 'integer  NOT NULL default 0', 'language' => 'string(20) NOT NULL', 'specialtype' => "string(20) NOT NULL default ''", 'defaultvalue' => 'text');
            $oDB->createCommand()->createTable('{{defaultvalues}}', $aFields);
            addPrimaryKey('defaultvalues', array('qid', 'specialtype', 'language', 'scale_id', 'sqid'));
            // -Move all 'answers' that are subquestions to the questions table
            // -Move all 'labels' that are answers to the answers table
            // -Transscribe the default values where applicable
            // -Move default values from answers to questions
            upgradeTables143();
            dropColumn('{{answers}}', 'default_value');
            dropColumn('{{questions}}', 'lid');
            dropColumn('{{questions}}', 'lid1');
            $aFields = array('sesskey' => "string(64) NOT NULL DEFAULT ''", 'expiry' => "datetime NOT NULL", 'expireref' => "string(250) DEFAULT ''", 'created' => "datetime NOT NULL", 'modified' => "datetime NOT NULL", 'sessdata' => 'text');
            $oDB->createCommand()->createTable('{{sessions}}', $aFields);
            addPrimaryKey('sessions', array('sesskey'));
            $oDB->createCommand()->createIndex('sess2_expiry', '{{sessions}}', 'expiry');
            $oDB->createCommand()->createIndex('sess2_expireref', '{{sessions}}', 'expireref');
            // Move all user templates to the new user template directory
            echo "<br>" . sprintf(gT("Moving user templates to new location at %s..."), $sUserTemplateRootDir) . "<br />";
            $hTemplateDirectory = opendir($sStandardTemplateRootDir);
            $aFailedTemplates = array();
            // get each entry
            while ($entryName = readdir($hTemplateDirectory)) {
                if (!in_array($entryName, array('.', '..', '.svn')) && is_dir($sStandardTemplateRootDir . DIRECTORY_SEPARATOR . $entryName) && !isStandardTemplate($entryName)) {
                    if (!rename($sStandardTemplateRootDir . DIRECTORY_SEPARATOR . $entryName, $sUserTemplateRootDir . DIRECTORY_SEPARATOR . $entryName)) {
                        $aFailedTemplates[] = $entryName;
                    }
                }
            }
            if (count($aFailedTemplates) > 0) {
                echo "The following templates at {$sStandardTemplateRootDir} could not be moved to the new location at {$sUserTemplateRootDir}:<br /><ul>";
                foreach ($aFailedTemplates as $sFailedTemplate) {
                    echo "<li>{$sFailedTemplate}</li>";
                }
                echo "</ul>Please move these templates manually after the upgrade has finished.<br />";
            }
            // close directory
            closedir($hTemplateDirectory);
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 143), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 145) {
            addColumn('{{surveys}}', 'savetimings', "string(1) NULL default 'N'");
            addColumn('{{surveys}}', 'showXquestions', "string(1) NULL default 'Y'");
            addColumn('{{surveys}}', 'showgroupinfo', "string(1) NULL default 'B'");
            addColumn('{{surveys}}', 'shownoanswer', "string(1) NULL default 'Y'");
            addColumn('{{surveys}}', 'showqnumcode', "string(1) NULL default 'X'");
            addColumn('{{surveys}}', 'bouncetime', 'integer');
            addColumn('{{surveys}}', 'bounceprocessing', "string(1) NULL default 'N'");
            addColumn('{{surveys}}', 'bounceaccounttype', "string(4)");
            addColumn('{{surveys}}', 'bounceaccounthost', "string(200)");
            addColumn('{{surveys}}', 'bounceaccountpass', "string(100)");
            addColumn('{{surveys}}', 'bounceaccountencryption', "string(3)");
            addColumn('{{surveys}}', 'bounceaccountuser', "string(200)");
            addColumn('{{surveys}}', 'showwelcome', "string(1) default 'Y'");
            addColumn('{{surveys}}', 'showprogress', "string(1) default 'Y'");
            addColumn('{{surveys}}', 'allowjumps', "string(1) default 'N'");
            addColumn('{{surveys}}', 'navigationdelay', "integer default 0");
            addColumn('{{surveys}}', 'nokeyboard', "string(1) default 'N'");
            addColumn('{{surveys}}', 'alloweditaftercompletion', "string(1) default 'N'");
            $aFields = array('sid' => "integer NOT NULL", 'uid' => "integer NOT NULL", 'permission' => 'string(20) NOT NULL', 'create_p' => "integer NOT NULL default 0", 'read_p' => "integer NOT NULL default 0", 'update_p' => "integer NOT NULL default 0", 'delete_p' => "integer NOT NULL default 0", 'import_p' => "integer NOT NULL default 0", 'export_p' => "integer NOT NULL default 0");
            $oDB->createCommand()->createTable('{{survey_permissions}}', $aFields);
            addPrimaryKey('survey_permissions', array('sid', 'uid', 'permission'));
            upgradeSurveyPermissions145();
            // drop the old survey rights table
            $oDB->createCommand()->dropTable('{{surveys_rights}}');
            // Add new fields for email templates
            addColumn('{{surveys_languagesettings}}', 'email_admin_notification_subj', "string");
            addColumn('{{surveys_languagesettings}}', 'email_admin_responses_subj', "string");
            addColumn('{{surveys_languagesettings}}', 'email_admin_notification', "text");
            addColumn('{{surveys_languagesettings}}', 'email_admin_responses', "text");
            //Add index to questions table to speed up subquestions
            $oDB->createCommand()->createIndex('parent_qid_idx', '{{questions}}', 'parent_qid');
            addColumn('{{surveys}}', 'emailnotificationto', "text");
            upgradeSurveys145();
            dropColumn('{{surveys}}', 'notification');
            alterColumn('{{conditions}}', 'method', "string(5)", false, '');
            $oDB->createCommand()->renameColumn('{{surveys}}', 'private', 'anonymized');
            $oDB->createCommand()->update('{{surveys}}', array('anonymized' => 'N'), "anonymized is NULL");
            alterColumn('{{surveys}}', 'anonymized', "string(1)", false, 'N');
            //now we clean up things that were not properly set in previous DB upgrades
            $oDB->createCommand()->update('{{answers}}', array('answer' => ''), "answer is NULL");
            $oDB->createCommand()->update('{{assessments}}', array('scope' => ''), "scope is NULL");
            $oDB->createCommand()->update('{{assessments}}', array('name' => ''), "name is NULL");
            $oDB->createCommand()->update('{{assessments}}', array('message' => ''), "message is NULL");
            $oDB->createCommand()->update('{{assessments}}', array('minimum' => ''), "minimum is NULL");
            $oDB->createCommand()->update('{{assessments}}', array('maximum' => ''), "maximum is NULL");
            $oDB->createCommand()->update('{{groups}}', array('group_name' => ''), "group_name is NULL");
            $oDB->createCommand()->update('{{labels}}', array('code' => ''), "code is NULL");
            $oDB->createCommand()->update('{{labelsets}}', array('label_name' => ''), "label_name is NULL");
            $oDB->createCommand()->update('{{questions}}', array('type' => 'T'), "type is NULL");
            $oDB->createCommand()->update('{{questions}}', array('title' => ''), "title is NULL");
            $oDB->createCommand()->update('{{questions}}', array('question' => ''), "question is NULL");
            $oDB->createCommand()->update('{{questions}}', array('other' => 'N'), "other is NULL");
            alterColumn('{{answers}}', 'answer', "text", false);
            alterColumn('{{answers}}', 'assessment_value', 'integer', false, '0');
            alterColumn('{{assessments}}', 'scope', "string(5)", false, '');
            alterColumn('{{assessments}}', 'name', "text", false);
            alterColumn('{{assessments}}', 'message', "text", false);
            alterColumn('{{assessments}}', 'minimum', "string(50)", false, '');
            alterColumn('{{assessments}}', 'maximum', "string(50)", false, '');
            // change the primary index to include language
            if (Yii::app()->db->driverName == 'mysql') {
                modifyPrimaryKey('assessments', array('id', 'language'));
            } else {
                dropPrimaryKey('assessments');
                addPrimaryKey('assessments', array('id', 'language'));
            }
            alterColumn('{{conditions}}', 'cfieldname', "string(50)", false, '');
            dropPrimaryKey('defaultvalues');
            alterColumn('{{defaultvalues}}', 'specialtype', "string(20)", false, '');
            addPrimaryKey('defaultvalues', array('qid', 'specialtype', 'language', 'scale_id', 'sqid'));
            alterColumn('{{groups}}', 'group_name', "string(100)", false, '');
            alterColumn('{{labels}}', 'code', "string(5)", false, '');
            dropPrimaryKey('labels');
            alterColumn('{{labels}}', 'language', "string(20)", false, 'en');
            addPrimaryKey('labels', array('lid', 'sortorder', 'language'));
            alterColumn('{{labelsets}}', 'label_name', "string(100)", false, '');
            alterColumn('{{questions}}', 'parent_qid', 'integer', false, '0');
            alterColumn('{{questions}}', 'title', "string(20)", false, '');
            alterColumn('{{questions}}', 'question', "text", false);
            try {
                setTransactionBookmark();
                $oDB->createCommand()->dropIndex('questions_idx4', '{{questions}}');
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            alterColumn('{{questions}}', 'type', "string(1)", false, 'T');
            try {
                $oDB->createCommand()->createIndex('questions_idx4', '{{questions}}', 'type');
            } catch (Exception $e) {
            }
            alterColumn('{{questions}}', 'other', "string(1)", false, 'N');
            alterColumn('{{questions}}', 'mandatory', "string(1)");
            alterColumn('{{question_attributes}}', 'attribute', "string(50)");
            alterColumn('{{quota}}', 'qlimit', 'integer');
            $oDB->createCommand()->update('{{saved_control}}', array('identifier' => ''), "identifier is NULL");
            alterColumn('{{saved_control}}', 'identifier', "text", false);
            $oDB->createCommand()->update('{{saved_control}}', array('access_code' => ''), "access_code is NULL");
            alterColumn('{{saved_control}}', 'access_code', "text", false);
            alterColumn('{{saved_control}}', 'email', "string(320)");
            $oDB->createCommand()->update('{{saved_control}}', array('ip' => ''), "ip is NULL");
            alterColumn('{{saved_control}}', 'ip', "text", false);
            $oDB->createCommand()->update('{{saved_control}}', array('saved_thisstep' => ''), "saved_thisstep is NULL");
            alterColumn('{{saved_control}}', 'saved_thisstep', "text", false);
            $oDB->createCommand()->update('{{saved_control}}', array('status' => ''), "status is NULL");
            alterColumn('{{saved_control}}', 'status', "string(1)", false, '');
            $oDB->createCommand()->update('{{saved_control}}', array('saved_date' => '1980-01-01 00:00:00'), "saved_date is NULL");
            alterColumn('{{saved_control}}', 'saved_date', "datetime", false);
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => ''), "stg_value is NULL");
            alterColumn('{{settings_global}}', 'stg_value', "string", false, '');
            alterColumn('{{surveys}}', 'admin', "string(50)");
            $oDB->createCommand()->update('{{surveys}}', array('active' => 'N'), "active is NULL");
            alterColumn('{{surveys}}', 'active', "string(1)", false, 'N');
            alterColumn('{{surveys}}', 'startdate', "datetime");
            alterColumn('{{surveys}}', 'adminemail', "string(320)");
            alterColumn('{{surveys}}', 'anonymized', "string(1)", false, 'N');
            alterColumn('{{surveys}}', 'faxto', "string(20)");
            alterColumn('{{surveys}}', 'format', "string(1)");
            alterColumn('{{surveys}}', 'language', "string(50)");
            alterColumn('{{surveys}}', 'additional_languages', "string");
            alterColumn('{{surveys}}', 'printanswers', "string(1)", true, 'N');
            alterColumn('{{surveys}}', 'publicstatistics', "string(1)", true, 'N');
            alterColumn('{{surveys}}', 'publicgraphs', "string(1)", true, 'N');
            alterColumn('{{surveys}}', 'assessments', "string(1)", true, 'N');
            alterColumn('{{surveys}}', 'usetokens', "string(1)", true, 'N');
            alterColumn('{{surveys}}', 'bounce_email', "string(320)");
            alterColumn('{{surveys}}', 'tokenlength', 'integer', true, 15);
            $oDB->createCommand()->update('{{surveys_languagesettings}}', array('surveyls_title' => ''), "surveyls_title is NULL");
            alterColumn('{{surveys_languagesettings}}', 'surveyls_title', "string(200)", false);
            alterColumn('{{surveys_languagesettings}}', 'surveyls_endtext', "text");
            alterColumn('{{surveys_languagesettings}}', 'surveyls_url', "string");
            alterColumn('{{surveys_languagesettings}}', 'surveyls_urldescription', "string");
            alterColumn('{{surveys_languagesettings}}', 'surveyls_email_invite_subj', "string");
            alterColumn('{{surveys_languagesettings}}', 'surveyls_email_remind_subj', "string");
            alterColumn('{{surveys_languagesettings}}', 'surveyls_email_register_subj', "string");
            alterColumn('{{surveys_languagesettings}}', 'surveyls_email_confirm_subj', "string");
            alterColumn('{{surveys_languagesettings}}', 'surveyls_dateformat', 'integer', false, 1);
            $oDB->createCommand()->update('{{users}}', array('users_name' => ''), "users_name is NULL");
            $oDB->createCommand()->update('{{users}}', array('full_name' => ''), "full_name is NULL");
            alterColumn('{{users}}', 'users_name', "string(64)", false, '');
            alterColumn('{{users}}', 'full_name', "string(50)", false);
            alterColumn('{{users}}', 'lang', "string(20)");
            alterColumn('{{users}}', 'email', "string(320)");
            alterColumn('{{users}}', 'superadmin', 'integer', false, 0);
            alterColumn('{{users}}', 'htmleditormode', "string(7)", true, 'default');
            alterColumn('{{users}}', 'dateformat', 'integer', false, 1);
            try {
                setTransactionBookmark();
                $oDB->createCommand()->dropIndex('email', '{{users}}');
            } catch (Exception $e) {
                // do nothing
                rollBackToTransactionBookmark();
            }
            $oDB->createCommand()->update('{{user_groups}}', array('name' => ''), "name is NULL");
            $oDB->createCommand()->update('{{user_groups}}', array('description' => ''), "description is NULL");
            alterColumn('{{user_groups}}', 'name', "string(20)", false);
            alterColumn('{{user_groups}}', 'description', "text", false);
            try {
                $oDB->createCommand()->dropIndex('user_in_groups_idx1', '{{user_in_groups}}');
            } catch (Exception $e) {
            }
            try {
                addPrimaryKey('user_in_groups', array('ugid', 'uid'));
            } catch (Exception $e) {
            }
            addColumn('{{surveys_languagesettings}}', 'surveyls_numberformat', "integer NOT NULL DEFAULT 0");
            $oDB->createCommand()->createTable('{{failed_login_attempts}}', array('id' => "pk", 'ip' => 'string(37) NOT NULL', 'last_attempt' => 'string(20) NOT NULL', 'number_attempts' => "integer NOT NULL"));
            upgradeTokens145();
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 145), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 146) {
            upgradeSurveyTimings146();
            // Fix permissions for new feature quick-translation
            try {
                setTransactionBookmark();
                $oDB->createCommand("INSERT into {{survey_permissions}} (sid,uid,permission,read_p,update_p) SELECT sid,owner_id,'translations','1','1' from {{surveys}}")->execute();
                echo $modifyoutput;
                flush();
                @ob_flush();
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 146), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 147) {
            addColumn('{{users}}', 'templateeditormode', "string(7) NOT NULL default 'default'");
            addColumn('{{users}}', 'questionselectormode', "string(7) NOT NULL default 'default'");
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 147), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 148) {
            addColumn('{{users}}', 'participant_panel', "integer NOT NULL default 0");
            $oDB->createCommand()->createTable('{{participants}}', array('participant_id' => 'string(50) NOT NULL', 'firstname' => 'string(40) default NULL', 'lastname' => 'string(40) default NULL', 'email' => 'string(80) default NULL', 'language' => 'string(40) default NULL', 'blacklisted' => 'string(1) NOT NULL', 'owner_uid' => "integer NOT NULL"));
            addPrimaryKey('participants', array('participant_id'));
            $oDB->createCommand()->createTable('{{participant_attribute}}', array('participant_id' => 'string(50) NOT NULL', 'attribute_id' => "integer NOT NULL", 'value' => 'string(50) NOT NULL'));
            addPrimaryKey('participant_attribute', array('participant_id', 'attribute_id'));
            $oDB->createCommand()->createTable('{{participant_attribute_names}}', array('attribute_id' => 'autoincrement', 'attribute_type' => 'string(4) NOT NULL', 'visible' => 'string(5) NOT NULL', 'PRIMARY KEY (attribute_id,attribute_type)'));
            $oDB->createCommand()->createTable('{{participant_attribute_names_lang}}', array('attribute_id' => 'integer NOT NULL', 'attribute_name' => 'string(30) NOT NULL', 'lang' => 'string(20) NOT NULL'));
            addPrimaryKey('participant_attribute_names_lang', array('attribute_id', 'lang'));
            $oDB->createCommand()->createTable('{{participant_attribute_values}}', array('attribute_id' => 'integer NOT NULL', 'value_id' => 'pk', 'value' => 'string(20) NOT NULL'));
            $oDB->createCommand()->createTable('{{participant_shares}}', array('participant_id' => 'string(50) NOT NULL', 'share_uid' => 'integer NOT NULL', 'date_added' => 'datetime NOT NULL', 'can_edit' => 'string(5) NOT NULL'));
            addPrimaryKey('participant_shares', array('participant_id', 'share_uid'));
            $oDB->createCommand()->createTable('{{survey_links}}', array('participant_id' => 'string(50) NOT NULL', 'token_id' => 'integer NOT NULL', 'survey_id' => 'integer NOT NULL', 'date_created' => 'datetime NOT NULL'));
            addPrimaryKey('survey_links', array('participant_id', 'token_id', 'survey_id'));
            // Add language field to question_attributes table
            addColumn('{{question_attributes}}', 'language', "string(20)");
            upgradeQuestionAttributes148();
            fixSubquestions();
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 148), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 149) {
            $aFields = array('id' => 'integer', 'sid' => 'integer', 'parameter' => 'string(50)', 'targetqid' => 'integer', 'targetsqid' => 'integer');
            $oDB->createCommand()->createTable('{{survey_url_parameters}}', $aFields);
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 149), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 150) {
            addColumn('{{questions}}', 'relevance', 'TEXT');
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 150), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 151) {
            addColumn('{{groups}}', 'randomization_group', "string(20) NOT NULL default ''");
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 151), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 152) {
            $oDB->createCommand()->createIndex('question_attributes_idx3', '{{question_attributes}}', 'attribute');
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 152), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 153) {
            $oDB->createCommand()->createTable('{{expression_errors}}', array('id' => 'pk', 'errortime' => 'string(50)', 'sid' => 'integer', 'gid' => 'integer', 'qid' => 'integer', 'gseq' => 'integer', 'qseq' => 'integer', 'type' => 'string(50)', 'eqn' => 'text', 'prettyprint' => 'text'));
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 153), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 154) {
            $oDB->createCommand()->addColumn('{{groups}}', 'grelevance', "text");
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 154), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 155) {
            addColumn('{{surveys}}', 'googleanalyticsstyle', "string(1)");
            addColumn('{{surveys}}', 'googleanalyticsapikey', "string(25)");
            try {
                setTransactionBookmark();
                $oDB->createCommand()->renameColumn('{{surveys}}', 'showXquestions', 'showxquestions');
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 155), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 156) {
            try {
                $oDB->createCommand()->dropTable('{{survey_url_parameters}}');
            } catch (Exception $e) {
                // do nothing
            }
            $oDB->createCommand()->createTable('{{survey_url_parameters}}', array('id' => 'pk', 'sid' => 'integer NOT NULL', 'parameter' => 'string(50) NOT NULL', 'targetqid' => 'integer', 'targetsqid' => 'integer'));
            $oDB->createCommand()->dropTable('{{sessions}}');
            if (Yii::app()->db->driverName == 'mysql') {
                $oDB->createCommand()->createTable('{{sessions}}', array('id' => 'string(32) NOT NULL', 'expire' => 'integer', 'data' => 'longtext'));
            } else {
                $oDB->createCommand()->createTable('{{sessions}}', array('id' => 'string(32) NOT NULL', 'expire' => 'integer', 'data' => 'text'));
            }
            addPrimaryKey('sessions', array('id'));
            addColumn('{{surveys_languagesettings}}', 'surveyls_attributecaptions', "TEXT");
            addColumn('{{surveys}}', 'sendconfirmation', "string(1) default 'Y'");
            upgradeSurveys156();
            // If a survey has an deleted owner, re-own the survey to the superadmin
            $oDB->schema->refresh();
            Survey::model()->refreshMetaData();
            $surveys = Survey::model();
            $surveys = $surveys->with(array('owner'))->findAll();
            foreach ($surveys as $row) {
                if (!isset($row->owner->attributes)) {
                    Survey::model()->updateByPk($row->sid, array('owner_id' => 1));
                }
            }
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 156), "stg_name='DBVersion'");
            $oTransaction->commit();
            $oTransaction = $oDB->beginTransaction();
        }
        if ($iOldDBVersion < 157) {
            // MySQL DB corrections
            try {
                setTransactionBookmark();
                $oDB->createCommand()->dropIndex('questions_idx4', '{{questions}}');
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            alterColumn('{{answers}}', 'assessment_value', 'integer', false, '0');
            dropPrimaryKey('answers');
            alterColumn('{{answers}}', 'scale_id', 'integer', false, '0');
            addPrimaryKey('answers', array('qid', 'code', 'language', 'scale_id'));
            alterColumn('{{conditions}}', 'method', "string(5)", false, '');
            alterColumn('{{participants}}', 'owner_uid', 'integer', false);
            alterColumn('{{participant_attribute_names}}', 'visible', 'string(5)', false);
            alterColumn('{{questions}}', 'type', "string(1)", false, 'T');
            alterColumn('{{questions}}', 'other', "string(1)", false, 'N');
            alterColumn('{{questions}}', 'mandatory', "string(1)");
            alterColumn('{{questions}}', 'scale_id', 'integer', false, '0');
            alterColumn('{{questions}}', 'parent_qid', 'integer', false, '0');
            alterColumn('{{questions}}', 'same_default', 'integer', false, '0');
            alterColumn('{{quota}}', 'qlimit', 'integer');
            alterColumn('{{quota}}', 'action', 'integer');
            alterColumn('{{quota}}', 'active', 'integer', false, '1');
            alterColumn('{{quota}}', 'autoload_url', 'integer', false, '0');
            alterColumn('{{saved_control}}', 'status', "string(1)", false, '');
            try {
                setTransactionBookmark();
                alterColumn('{{sessions}}', 'id', "string(32)", false);
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            alterColumn('{{surveys}}', 'active', "string(1)", false, 'N');
            alterColumn('{{surveys}}', 'anonymized', "string(1)", false, 'N');
            alterColumn('{{surveys}}', 'format', "string(1)");
            alterColumn('{{surveys}}', 'savetimings', "string(1)", false, 'N');
            alterColumn('{{surveys}}', 'datestamp', "string(1)", false, 'N');
            alterColumn('{{surveys}}', 'usecookie', "string(1)", false, 'N');
            alterColumn('{{surveys}}', 'allowregister', "string(1)", false, 'N');
            alterColumn('{{surveys}}', 'allowsave', "string(1)", false, 'Y');
            alterColumn('{{surveys}}', 'autonumber_start', 'integer', false, '0');
            alterColumn('{{surveys}}', 'autoredirect', "string(1)", false, 'N');
            alterColumn('{{surveys}}', 'allowprev', "string(1)", false, 'N');
            alterColumn('{{surveys}}', 'printanswers', "string(1)", false, 'N');
            alterColumn('{{surveys}}', 'ipaddr', "string(1)", false, 'N');
            alterColumn('{{surveys}}', 'refurl', "string(1)", false, 'N');
            alterColumn('{{surveys}}', 'publicstatistics', "string(1)", false, 'N');
            alterColumn('{{surveys}}', 'publicgraphs', "string(1)", false, 'N');
            alterColumn('{{surveys}}', 'listpublic', "string(1)", false, 'N');
            alterColumn('{{surveys}}', 'htmlemail', "string(1)", false, 'N');
            alterColumn('{{surveys}}', 'sendconfirmation', "string(1)", false, 'Y');
            alterColumn('{{surveys}}', 'tokenanswerspersistence', "string(1)", false, 'N');
            alterColumn('{{surveys}}', 'assessments', "string(1)", false, 'N');
            alterColumn('{{surveys}}', 'usecaptcha', "string(1)", false, 'N');
            alterColumn('{{surveys}}', 'usetokens', "string(1)", false, 'N');
            alterColumn('{{surveys}}', 'tokenlength', 'integer', false, '15');
            alterColumn('{{surveys}}', 'showxquestions', "string(1)", true, 'Y');
            alterColumn('{{surveys}}', 'showgroupinfo', "string(1) ", true, 'B');
            alterColumn('{{surveys}}', 'shownoanswer', "string(1) ", true, 'Y');
            alterColumn('{{surveys}}', 'showqnumcode', "string(1) ", true, 'X');
            alterColumn('{{surveys}}', 'bouncetime', 'integer');
            alterColumn('{{surveys}}', 'showwelcome', "string(1)", true, 'Y');
            alterColumn('{{surveys}}', 'showprogress', "string(1)", true, 'Y');
            alterColumn('{{surveys}}', 'allowjumps', "string(1)", true, 'N');
            alterColumn('{{surveys}}', 'navigationdelay', 'integer', false, '0');
            alterColumn('{{surveys}}', 'nokeyboard', "string(1)", true, 'N');
            alterColumn('{{surveys}}', 'alloweditaftercompletion', "string(1)", true, 'N');
            alterColumn('{{surveys}}', 'googleanalyticsstyle', "string(1)");
            alterColumn('{{surveys_languagesettings}}', 'surveyls_dateformat', 'integer', false, 1);
            try {
                setTransactionBookmark();
                alterColumn('{{survey_permissions}}', 'sid', "integer", false);
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            try {
                setTransactionBookmark();
                alterColumn('{{survey_permissions}}', 'uid', "integer", false);
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            alterColumn('{{survey_permissions}}', 'create_p', 'integer', false, '0');
            alterColumn('{{survey_permissions}}', 'read_p', 'integer', false, '0');
            alterColumn('{{survey_permissions}}', 'update_p', 'integer', false, '0');
            alterColumn('{{survey_permissions}}', 'delete_p', 'integer', false, '0');
            alterColumn('{{survey_permissions}}', 'import_p', 'integer', false, '0');
            alterColumn('{{survey_permissions}}', 'export_p', 'integer', false, '0');
            alterColumn('{{survey_url_parameters}}', 'targetqid', 'integer');
            alterColumn('{{survey_url_parameters}}', 'targetsqid', 'integer');
            alterColumn('{{templates_rights}}', 'use', 'integer', false);
            alterColumn('{{users}}', 'create_survey', 'integer', false, '0');
            alterColumn('{{users}}', 'create_user', 'integer', false, '0');
            alterColumn('{{users}}', 'participant_panel', 'integer', false, '0');
            alterColumn('{{users}}', 'delete_user', 'integer', false, '0');
            alterColumn('{{users}}', 'superadmin', 'integer', false, '0');
            alterColumn('{{users}}', 'configurator', 'integer', false, '0');
            alterColumn('{{users}}', 'manage_template', 'integer', false, '0');
            alterColumn('{{users}}', 'manage_label', 'integer', false, '0');
            alterColumn('{{users}}', 'dateformat', 'integer', false, 1);
            alterColumn('{{users}}', 'participant_panel', 'integer', false, '0');
            alterColumn('{{users}}', 'parent_id', 'integer', false);
            try {
                setTransactionBookmark();
                alterColumn('{{surveys_languagesettings}}', 'surveyls_survey_id', "integer", false);
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            alterColumn('{{user_groups}}', 'owner_id', "integer", false);
            dropPrimaryKey('user_in_groups');
            alterColumn('{{user_in_groups}}', 'ugid', "integer", false);
            alterColumn('{{user_in_groups}}', 'uid', "integer", false);
            // Additional corrections for Postgres
            try {
                setTransactionBookmark();
                $oDB->createCommand()->createIndex('questions_idx3', '{{questions}}', 'gid');
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            try {
                setTransactionBookmark();
                $oDB->createCommand()->createIndex('conditions_idx3', '{{conditions}}', 'cqid');
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            try {
                setTransactionBookmark();
                $oDB->createCommand()->createIndex('questions_idx4', '{{questions}}', 'type');
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            try {
                setTransactionBookmark();
                $oDB->createCommand()->dropIndex('user_in_groups_idx1', '{{user_in_groups}}');
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            try {
                setTransactionBookmark();
                $oDB->createCommand()->dropIndex('{{user_name_key}}', '{{users}}');
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            try {
                setTransactionBookmark();
                $oDB->createCommand()->createIndex('users_name', '{{users}}', 'users_name', true);
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            try {
                setTransactionBookmark();
                addPrimaryKey('user_in_groups', array('ugid', 'uid'));
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            alterColumn('{{participant_attribute}}', 'value', "string(50)", false);
            try {
                setTransactionBookmark();
                alterColumn('{{participant_attribute_names}}', 'attribute_type', "string(4)", false);
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            try {
                setTransactionBookmark();
                dropColumn('{{participant_attribute_names_lang}}', 'id');
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            try {
                setTransactionBookmark();
                addPrimaryKey('participant_attribute_names_lang', array('attribute_id', 'lang'));
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            try {
                setTransactionBookmark();
                $oDB->createCommand()->renameColumn('{{participant_shares}}', 'shared_uid', 'share_uid');
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            alterColumn('{{participant_shares}}', 'date_added', "datetime", false);
            alterColumn('{{participants}}', 'firstname', "string(40)");
            alterColumn('{{participants}}', 'lastname', "string(40)");
            alterColumn('{{participants}}', 'email', "string(80)");
            alterColumn('{{participants}}', 'language', "string(40)");
            alterColumn('{{quota_languagesettings}}', 'quotals_name', "string");
            try {
                setTransactionBookmark();
                alterColumn('{{survey_permissions}}', 'sid', 'integer', false);
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            try {
                setTransactionBookmark();
                alterColumn('{{survey_permissions}}', 'uid', 'integer', false);
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            alterColumn('{{users}}', 'htmleditormode', "string(7)", true, 'default');
            // Sometimes the survey_links table was deleted before this step, if so
            // we recreate it (copied from line 663)
            if (!tableExists('{survey_links}')) {
                $oDB->createCommand()->createTable('{{survey_links}}', array('participant_id' => 'string(50) NOT NULL', 'token_id' => 'integer NOT NULL', 'survey_id' => 'integer NOT NULL', 'date_created' => 'datetime NOT NULL'));
                addPrimaryKey('survey_links', array('participant_id', 'token_id', 'survey_id'));
            }
            alterColumn('{{survey_links}}', 'date_created', "datetime", true);
            alterColumn('{{saved_control}}', 'identifier', "text", false);
            alterColumn('{{saved_control}}', 'email', "string(320)");
            alterColumn('{{surveys}}', 'adminemail', "string(320)");
            alterColumn('{{surveys}}', 'bounce_email', "string(320)");
            alterColumn('{{users}}', 'email', "string(320)");
            try {
                setTransactionBookmark();
                $oDB->createCommand()->dropIndex('assessments_idx', '{{assessments}}');
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            try {
                setTransactionBookmark();
                $oDB->createCommand()->createIndex('assessments_idx3', '{{assessments}}', 'gid');
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            try {
                setTransactionBookmark();
                $oDB->createCommand()->dropIndex('ixcode', '{{labels}}');
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            try {
                setTransactionBookmark();
                $oDB->createCommand()->dropIndex('{{labels_ixcode_idx}}', '{{labels}}');
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            try {
                setTransactionBookmark();
                $oDB->createCommand()->createIndex('labels_code_idx', '{{labels}}', 'code');
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            if (Yii::app()->db->driverName == 'pgsql') {
                try {
                    setTransactionBookmark();
                    $oDB->createCommand("ALTER TABLE ONLY {{user_groups}} ADD PRIMARY KEY (ugid); ")->execute;
                } catch (Exception $e) {
                    rollBackToTransactionBookmark();
                }
                try {
                    setTransactionBookmark();
                    $oDB->createCommand("ALTER TABLE ONLY {{users}} ADD PRIMARY KEY (uid); ")->execute;
                } catch (Exception $e) {
                    rollBackToTransactionBookmark();
                }
            }
            // Additional corrections for MSSQL
            alterColumn('{{answers}}', 'answer', "text", false);
            alterColumn('{{assessments}}', 'name', "text", false);
            alterColumn('{{assessments}}', 'message', "text", false);
            alterColumn('{{defaultvalues}}', 'defaultvalue', "text");
            alterColumn('{{expression_errors}}', 'eqn', "text");
            alterColumn('{{expression_errors}}', 'prettyprint', "text");
            alterColumn('{{groups}}', 'description', "text");
            alterColumn('{{groups}}', 'grelevance', "text");
            alterColumn('{{labels}}', 'title', "text");
            alterColumn('{{question_attributes}}', 'value', "text");
            alterColumn('{{questions}}', 'preg', "text");
            alterColumn('{{questions}}', 'help', "text");
            alterColumn('{{questions}}', 'relevance', "text");
            alterColumn('{{questions}}', 'question', "text", false);
            alterColumn('{{quota_languagesettings}}', 'quotals_quota_id', "integer", false);
            alterColumn('{{quota_languagesettings}}', 'quotals_message', "text", false);
            alterColumn('{{saved_control}}', 'refurl', "text");
            alterColumn('{{saved_control}}', 'access_code', "text", false);
            alterColumn('{{saved_control}}', 'ip', "text", false);
            alterColumn('{{saved_control}}', 'saved_thisstep', "text", false);
            alterColumn('{{saved_control}}', 'saved_date', "datetime", false);
            alterColumn('{{surveys}}', 'attributedescriptions', "text");
            alterColumn('{{surveys}}', 'emailresponseto', "text");
            alterColumn('{{surveys}}', 'emailnotificationto', "text");
            alterColumn('{{surveys_languagesettings}}', 'surveyls_description', "text");
            alterColumn('{{surveys_languagesettings}}', 'surveyls_welcometext', "text");
            alterColumn('{{surveys_languagesettings}}', 'surveyls_email_invite', "text");
            alterColumn('{{surveys_languagesettings}}', 'surveyls_email_remind', "text");
            alterColumn('{{surveys_languagesettings}}', 'surveyls_email_register', "text");
            alterColumn('{{surveys_languagesettings}}', 'surveyls_email_confirm', "text");
            alterColumn('{{surveys_languagesettings}}', 'surveyls_attributecaptions', "text");
            alterColumn('{{surveys_languagesettings}}', 'email_admin_notification', "text");
            alterColumn('{{surveys_languagesettings}}', 'email_admin_responses', "text");
            alterColumn('{{surveys_languagesettings}}', 'surveyls_endtext', "text");
            alterColumn('{{user_groups}}', 'description', "text", false);
            alterColumn('{{conditions}}', 'value', 'string', false, '');
            alterColumn('{{participant_shares}}', 'can_edit', "string(5)", false);
            alterColumn('{{users}}', 'password', "binary", false);
            dropColumn('{{users}}', 'one_time_pw');
            addColumn('{{users}}', 'one_time_pw', 'binary');
            $oDB->createCommand()->update('{{question_attributes}}', array('value' => '1'), "attribute = 'random_order' and value = '2'");
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 157), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 158) {
            LimeExpressionManager::UpgradeConditionsToRelevance();
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 158), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 159) {
            alterColumn('{{failed_login_attempts}}', 'ip', "string(40)", false);
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 159), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 160) {
            alterLanguageCode('it', 'it-informal');
            alterLanguageCode('it-formal', 'it');
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 160), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 161) {
            addColumn('{{survey_links}}', 'date_invited', 'datetime NULL default NULL');
            addColumn('{{survey_links}}', 'date_completed', 'datetime NULL default NULL');
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 161), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 162) {
            /* Fix participant db types */
            alterColumn('{{participant_attribute}}', 'value', "text", false);
            alterColumn('{{participant_attribute_names_lang}}', 'attribute_name', "string(255)", false);
            alterColumn('{{participant_attribute_values}}', 'value', "text", false);
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 162), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 163) {
            //Replace  by <script type="text/javascript" src="{TEMPLATEURL}template.js"></script> by {TEMPLATEJS}
            $replacedTemplate = replaceTemplateJS();
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 163), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 164) {
            upgradeTokens148();
            // this should have bee done in 148 - that's why it is named this way
            // fix survey tables for missing or incorrect token field
            upgradeSurveyTables164();
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 164), "stg_name='DBVersion'");
            // Not updating settings table as upgrade process takes care of that step now
        }
        if ($iOldDBVersion < 165) {
            $oDB->createCommand()->createTable('{{plugins}}', array('id' => 'pk', 'name' => 'string NOT NULL', 'active' => 'boolean'));
            $oDB->createCommand()->createTable('{{plugin_settings}}', array('id' => 'pk', 'plugin_id' => 'integer NOT NULL', 'model' => 'string', 'model_id' => 'integer', 'key' => 'string', 'value' => 'text'));
            alterColumn('{{surveys_languagesettings}}', 'surveyls_url', "text");
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 165), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 166) {
            $oDB->createCommand()->renameTable('{{survey_permissions}}', '{{permissions}}');
            dropPrimaryKey('permissions');
            alterColumn('{{permissions}}', 'permission', "string(100)", false);
            $oDB->createCommand()->renameColumn('{{permissions}}', 'sid', 'entity_id');
            alterColumn('{{permissions}}', 'entity_id', "string(100)", false);
            addColumn('{{permissions}}', 'entity', "string(50)");
            $oDB->createCommand("update {{permissions}} set entity='survey'")->query();
            addColumn('{{permissions}}', 'id', 'pk');
            $oDB->createCommand()->createIndex('idxPermissions', '{{permissions}}', 'entity_id,entity,permission,uid', true);
            upgradePermissions166();
            dropColumn('{{users}}', 'create_survey');
            dropColumn('{{users}}', 'create_user');
            dropColumn('{{users}}', 'delete_user');
            dropColumn('{{users}}', 'superadmin');
            dropColumn('{{users}}', 'configurator');
            dropColumn('{{users}}', 'manage_template');
            dropColumn('{{users}}', 'manage_label');
            dropColumn('{{users}}', 'participant_panel');
            $oDB->createCommand()->dropTable('{{templates_rights}}');
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 166), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 167) {
            addColumn('{{surveys_languagesettings}}', 'attachments', 'text');
            addColumn('{{users}}', 'created', 'datetime');
            addColumn('{{users}}', 'modified', 'datetime');
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 167), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 168) {
            addColumn('{{participants}}', 'created', 'datetime');
            addColumn('{{participants}}', 'modified', 'datetime');
            addColumn('{{participants}}', 'created_by', 'integer');
            $oDB->createCommand('update {{participants}} set created_by=owner_uid')->query();
            alterColumn('{{participants}}', 'created_by', "integer", false);
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 168), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 169) {
            // Add new column for question index options.
            addColumn('{{surveys}}', 'questionindex', 'integer not null default 0');
            // Set values for existing surveys.
            $oDB->createCommand("update {{surveys}} set questionindex = 0 where allowjumps <> 'Y'")->query();
            $oDB->createCommand("update {{surveys}} set questionindex = 1 where allowjumps = 'Y'")->query();
            // Remove old column.
            dropColumn('{{surveys}}', 'allowjumps');
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 169), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 170) {
            // renamed advanced attributes fields dropdown_dates_year_min/max
            $oDB->createCommand()->update('{{question_attributes}}', array('attribute' => 'date_min'), "attribute='dropdown_dates_year_min'");
            $oDB->createCommand()->update('{{question_attributes}}', array('attribute' => 'date_max'), "attribute='dropdown_dates_year_max'");
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 170), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 171) {
            try {
                dropColumn('{{sessions}}', 'data');
            } catch (Exception $e) {
            }
            switch (Yii::app()->db->driverName) {
                case 'mysql':
                case 'mysqli':
                    addColumn('{{sessions}}', 'data', 'longbinary');
                    break;
                case 'sqlsrv':
                case 'dblib':
                case 'mssql':
                    addColumn('{{sessions}}', 'data', 'VARBINARY(MAX)');
                    break;
                case 'pgsql':
                    addColumn('{{sessions}}', 'data', 'BYTEA');
                    break;
                default:
                    die('Unknown database type');
            }
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 171), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 172) {
            switch (Yii::app()->db->driverName) {
                case 'pgsql':
                    // Special treatment for Postgres as it is too dumb to convert a string to a number without explicit being told to do so ... seriously?
                    alterColumn('{{permissions}}', 'entity_id', "INTEGER USING (entity_id::integer)", false);
                    break;
                case 'sqlsrv':
                case 'dblib':
                case 'mssql':
                    try {
                        setTransactionBookmark();
                        $oDB->createCommand()->dropIndex('permissions_idx2', '{{permissions}}');
                    } catch (Exception $e) {
                        rollBackToTransactionBookmark();
                    }
                    try {
                        setTransactionBookmark();
                        $oDB->createCommand()->dropIndex('idxPermissions', '{{permissions}}');
                    } catch (Exception $e) {
                        rollBackToTransactionBookmark();
                    }
                    alterColumn('{{permissions}}', 'entity_id', "INTEGER", false);
                    $oDB->createCommand()->createIndex('permissions_idx2', '{{permissions}}', 'entity_id,entity,permission,uid', true);
                    break;
                default:
                    alterColumn('{{permissions}}', 'entity_id', "INTEGER", false);
            }
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 172), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 173) {
            addColumn('{{participant_attribute_names}}', 'defaultname', "string(50) NOT NULL default ''");
            upgradeCPDBAttributeDefaultNames173();
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 173), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 174) {
            alterColumn('{{participants}}', 'email', "string(254)");
            alterColumn('{{saved_control}}', 'email', "string(254)");
            alterColumn('{{surveys}}', 'adminemail', "string(254)");
            alterColumn('{{surveys}}', 'bounce_email', "string(254)");
            switch (Yii::app()->db->driverName) {
                case 'sqlsrv':
                case 'dblib':
                case 'mssql':
                    dropUniqueKeyMSSQL('email', '{{users}}');
            }
            alterColumn('{{users}}', 'email', "string(254)");
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 174), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 175) {
            switch (Yii::app()->db->driverName) {
                case 'pgsql':
                    // Special treatment for Postgres as it is too dumb to convert a boolean to a number without explicit being told to do so
                    alterColumn('{{plugins}}', 'active', "INTEGER USING (active::integer)", false);
                    break;
                default:
                    alterColumn('{{plugins}}', 'active', "integer", false, '0');
            }
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 175), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 176) {
            upgradeTokens176();
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 176), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 177) {
            if (Yii::app()->getConfig('auth_webserver') === true) {
                // using auth webserver, now activate the plugin with default settings.
                if (!class_exists('Authwebserver', false)) {
                    $plugin = Plugin::model()->findByAttributes(array('name' => 'Authwebserver'));
                    if (!$plugin) {
                        $plugin = new Plugin();
                        $plugin->name = 'Authwebserver';
                        $plugin->active = 1;
                        $plugin->save();
                        $plugin = App()->getPluginManager()->loadPlugin('Authwebserver', $plugin->id);
                        $aPluginSettings = $plugin->getPluginSettings(true);
                        $aDefaultSettings = array();
                        foreach ($aPluginSettings as $key => $settings) {
                            if (is_array($settings) && array_key_exists('current', $settings)) {
                                $aDefaultSettings[$key] = $settings['current'];
                            }
                        }
                        $plugin->saveSettings($aDefaultSettings);
                    } else {
                        $plugin->active = 1;
                        $plugin->save();
                    }
                }
            }
            upgradeSurveys177();
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 177), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 178) {
            if (Yii::app()->db->driverName == 'mysql' || Yii::app()->db->driverName == 'mysqli') {
                modifyPrimaryKey('questions', array('qid', 'language'));
            }
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 178), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 179) {
            upgradeSurveys177();
            // Needs to be run again to make sure
            upgradeTokenTables179();
            alterColumn('{{participants}}', 'email', "string(254)", false);
            alterColumn('{{participants}}', 'firstname', "string(150)", false);
            alterColumn('{{participants}}', 'lastname', "string(150)", false);
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 179), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 180) {
            $aUsers = User::model()->findAll();
            $aPerm = array('entity_id' => 0, 'entity' => 'global', 'uid' => 0, 'permission' => 'auth_db', 'create_p' => 0, 'read_p' => 1, 'update_p' => 0, 'delete_p' => 0, 'import_p' => 0, 'export_p' => 0);
            foreach ($aUsers as $oUser) {
                if (!Permission::model()->hasGlobalPermission('auth_db', 'read', $oUser->uid)) {
                    $oPermission = new Permission();
                    foreach ($aPerm as $k => $v) {
                        $oPermission->{$k} = $v;
                    }
                    $oPermission->uid = $oUser->uid;
                    $oPermission->save();
                }
            }
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 180), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 181) {
            upgradeTokenTables181();
            upgradeSurveyTables181();
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 181), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 183) {
            upgradeSurveyTables183();
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 183), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 184) {
            fixKCFinder184();
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 184), "stg_name='DBVersion'");
        }
        // LS 2.5 table start at 250
        if ($iOldDBVersion < 250) {
            createBoxes250();
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 250), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 251) {
            upgradeSurveyTables251();
            // Update DBVersion
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 251), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 252) {
            Yii::app()->db->createCommand()->addColumn('{{questions}}', 'modulename', 'string');
            // Update DBVersion
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 252), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 253) {
            upgradeSurveyTables253();
            // Update DBVersion
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 253), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 254) {
            upgradeSurveyTables254();
            // Update DBVersion
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 254), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 255) {
            upgradeSurveyTables255();
            // Update DBVersion
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 255), "stg_name='DBVersion'");
        }
        $oTransaction->commit();
        // Activate schema caching
        $oDB->schemaCachingDuration = 3600;
        // Load all tables of the application in the schema
        $oDB->schema->getTables();
        // clear the cache of all loaded tables
        $oDB->schema->refresh();
    } catch (Exception $e) {
        Yii::app()->setConfig('Updating', false);
        $oTransaction->rollback();
        // Activate schema caching
        $oDB->schemaCachingDuration = 3600;
        // Load all tables of the application in the schema
        $oDB->schema->getTables();
        // clear the cache of all loaded tables
        $oDB->schema->refresh();
        echo '<br /><br />' . gT('An non-recoverable error happened during the update. Error details:') . "<p>" . htmlspecialchars($e->getMessage()) . '</p><br />';
        return false;
    }
    fixLanguageConsistencyAllSurveys();
    Yii::app()->setConfig('Updating', false);
    return true;
}
Exemplo n.º 16
0
 function index($subaction, $iSurveyID = null, $gid = null, $qid = null)
 {
     $iSurveyID = sanitize_int($iSurveyID);
     $gid = sanitize_int($gid);
     $qid = sanitize_int($qid);
     $clang = $this->getController()->lang;
     $imageurl = Yii::app()->getConfig("adminimageurl");
     Yii::app()->loadHelper("database");
     if (!empty($_POST['subaction'])) {
         $subaction = Yii::app()->request->getPost('subaction');
     }
     //BEGIN Sanitizing POSTed data
     if (!isset($iSurveyID)) {
         $iSurveyID = returnGlobal('sid');
     }
     if (!isset($qid)) {
         $qid = returnGlobal('qid');
     }
     if (!isset($gid)) {
         $gid = returnGlobal('gid');
     }
     if (!isset($p_scenario)) {
         $p_scenario = returnGlobal('scenario');
     }
     if (!isset($p_cqid)) {
         $p_cqid = returnGlobal('cqid');
         if ($p_cqid == '') {
             $p_cqid = 0;
         }
         // we are not using another question as source of condition
     }
     if (!isset($p_cid)) {
         $p_cid = returnGlobal('cid');
     }
     if (!isset($p_subaction)) {
         if (isset($_POST['subaction'])) {
             $p_subaction = $_POST['subaction'];
         } else {
             $p_subaction = $subaction;
         }
     }
     if (!isset($p_cquestions)) {
         $p_cquestions = returnGlobal('cquestions');
     }
     if (!isset($p_csrctoken)) {
         $p_csrctoken = returnGlobal('csrctoken');
     }
     if (!isset($p_prevquestionsgqa)) {
         $p_prevquestionsgqa = returnGlobal('prevQuestionSGQA');
     }
     if (!isset($p_canswers)) {
         if (isset($_POST['canswers']) && is_array($_POST['canswers'])) {
             foreach ($_POST['canswers'] as $key => $val) {
                 $p_canswers[$key] = preg_replace("/[^_.a-zA-Z0-9]@/", "", $val);
             }
         }
     }
     // this array will be used soon,
     // to explain wich conditions is used to evaluate the question
     if (Yii::app()->getConfig('stringcomparizonoperators') == 1) {
         $method = array("<" => $clang->gT("Less than"), "<=" => $clang->gT("Less than or equal to"), "==" => $clang->gT("equals"), "!=" => $clang->gT("Not equal to"), ">=" => $clang->gT("Greater than or equal to"), ">" => $clang->gT("Greater than"), "RX" => $clang->gT("Regular expression"), "a<b" => $clang->gT("Less than (Strings)"), "a<=b" => $clang->gT("Less than or equal to (Strings)"), "a>=b" => $clang->gT("Greater than or equal to (Strings)"), "a>b" => $clang->gT("Greater than (Strings)"));
     } else {
         $method = array("<" => $clang->gT("Less than"), "<=" => $clang->gT("Less than or equal to"), "==" => $clang->gT("equals"), "!=" => $clang->gT("Not equal to"), ">=" => $clang->gT("Greater than or equal to"), ">" => $clang->gT("Greater than"), "RX" => $clang->gT("Regular expression"));
     }
     if (isset($_POST['method'])) {
         if (!in_array($_POST['method'], array_keys($method))) {
             $p_method = "==";
         } else {
             $p_method = trim($_POST['method']);
         }
     }
     if (isset($_POST['newscenarionum'])) {
         $p_newscenarionum = sanitize_int($_POST['newscenarionum']);
     }
     //END Sanitizing POSTed data
     //include_once("login_check.php");
     include_once "database.php";
     // Caution (lemeur): database.php uses autoUnescape on all entries in $_POST
     // Take care to not use autoUnescape on $_POST variables after this
     $br = CHtml::openTag('br /');
     //MAKE SURE THAT THERE IS A SID
     if (!isset($iSurveyID) || !$iSurveyID) {
         $conditionsoutput = $clang->gT("You have not selected a survey") . str_repeat($br, 2);
         $conditionsoutput .= CHtml::submitButton($clang->gT("Main admin screen"), array('onclick' => "window.open('" . $this->getController()->createUrl("admin/") . "', '_top')")) . $br;
         safeDie($conditionsoutput);
         return;
     }
     if (isset($p_subaction) && $p_subaction == "resetsurveylogic") {
         $clang = $this->getController()->lang;
         $resetsurveylogicoutput = $br;
         $resetsurveylogicoutput .= CHtml::openTag('table', array('class' => 'alertbox'));
         $resetsurveylogicoutput .= CHtml::openTag('tr') . CHtml::openTag('td', array('colspan' => '2'));
         $resetsurveylogicoutput .= CHtml::tag('font', array('size' => '1'), CHtml::tag('strong', array(), $clang->gT("Reset Survey Logic")));
         $resetsurveylogicoutput .= CHtml::closeTag('td') . CHtml::closeTag('tr');
         if (!isset($_GET['ok'])) {
             $button_yes = CHtml::submitButton($clang->gT("Yes"), array('onclick' => "window.open('" . $this->getController()->createUrl("admin/conditions/sa/index/subaction/resetsurveylogic/surveyid/{$iSurveyID}") . "?ok=Y" . "', '_top')"));
             $button_cancel = CHtml::submitButton($clang->gT("Cancel"), array('onclick' => "window.open('" . $this->getController()->createUrl("admin/survey/sa/view/surveyid/{$iSurveyID}") . "', '_top')"));
             $messagebox_content = $clang->gT("You are about to delete all conditions on this survey's questions") . "({$iSurveyID})" . $br . $clang->gT("We recommend that before you proceed, you export the entire survey from the main administration screen.") . $br . $clang->gT("Continue?") . $br . $button_yes . $button_cancel;
             $this->_renderWrappedTemplate('conditions', array('message' => array('title' => $clang->gT("Warning"), 'message' => $messagebox_content)));
             exit;
         } else {
             LimeExpressionManager::RevertUpgradeConditionsToRelevance($iSurveyID);
             Conditions::model()->deleteRecords("qid in (select qid from {{questions}} where sid={$iSurveyID})");
             Yii::app()->session['flashmessage'] = $clang->gT("All conditions in this survey have been deleted.");
             $this->getController()->redirect($this->getController()->createUrl('admin/survey/sa/view/surveyid/' . $iSurveyID));
         }
     }
     // MAKE SURE THAT THERE IS A QID
     if (!isset($qid) || !$qid) {
         $conditionsoutput = $clang->gT("You have not selected a question") . str_repeat($br, 2);
         $conditionsoutput .= CHtml::submitButton($clang->gT("Main admin screen"), array('onclick' => "window.open('" . $this->getController()->createUrl("admin/") . "', '_top')")) . $br;
         safeDie($conditionsoutput);
         return;
     }
     // If we made it this far, then lets develop the menu items
     // add the conditions container table
     $extraGetParams = "";
     if (isset($qid) && isset($gid)) {
         $extraGetParams = "/gid/{$gid}/qid/{$qid}";
     }
     $conditionsoutput_action_error = "";
     // defined during the actions
     $markcidarray = array();
     if (isset($_GET['markcid'])) {
         $markcidarray = explode("-", $_GET['markcid']);
     }
     //BEGIN PROCESS ACTIONS
     // ADD NEW ENTRY IF THIS IS AN ADD
     if (isset($p_subaction) && $p_subaction == "insertcondition") {
         if (!isset($p_canswers) && !isset($_POST['ConditionConst']) && !isset($_POST['prevQuestionSGQA']) && !isset($_POST['tokenAttr']) && !isset($_POST['ConditionRegexp']) || !isset($p_cquestions) && !isset($p_csrctoken)) {
             $conditionsoutput_action_error .= CHtml::script("\n<!--\n alert(\"" . $clang->gT("Your condition could not be added! It did not include the question and/or answer upon which the condition was based. Please ensure you have selected a question and an answer.", "js") . "\")\n //-->\n");
         } else {
             if (isset($p_cquestions) && $p_cquestions != '') {
                 $conditionCfieldname = $p_cquestions;
             } elseif (isset($p_csrctoken) && $p_csrctoken != '') {
                 $conditionCfieldname = $p_csrctoken;
             }
             $condition_data = array('qid' => $qid, 'scenario' => $p_scenario, 'cqid' => $p_cqid, 'cfieldname' => $conditionCfieldname, 'method' => $p_method);
             if (isset($p_canswers)) {
                 foreach ($p_canswers as $ca) {
                     //First lets make sure there isn't already an exact replica of this condition
                     $condition_data['value'] = $ca;
                     $result = Conditions::model()->findAllByAttributes($condition_data);
                     $count_caseinsensitivedupes = count($result);
                     if ($count_caseinsensitivedupes == 0) {
                         $result = Conditions::model()->insertRecords($condition_data);
                     }
                 }
             }
             unset($posted_condition_value);
             // Please note that autoUnescape is already applied in database.php included above
             // so we only need to db_quote _POST variables
             if (isset($_POST['ConditionConst']) && isset($_POST['editTargetTab']) && $_POST['editTargetTab'] == "#CONST") {
                 $posted_condition_value = Yii::app()->request->getPost('ConditionConst');
             } elseif (isset($_POST['prevQuestionSGQA']) && isset($_POST['editTargetTab']) && $_POST['editTargetTab'] == "#PREVQUESTIONS") {
                 $posted_condition_value = Yii::app()->request->getPost('prevQuestionSGQA');
             } elseif (isset($_POST['tokenAttr']) && isset($_POST['editTargetTab']) && $_POST['editTargetTab'] == "#TOKENATTRS") {
                 $posted_condition_value = Yii::app()->request->getPost('tokenAttr');
             } elseif (isset($_POST['ConditionRegexp']) && isset($_POST['editTargetTab']) && $_POST['editTargetTab'] == "#REGEXP") {
                 $posted_condition_value = Yii::app()->request->getPost('ConditionRegexp');
             }
             if (isset($posted_condition_value)) {
                 $condition_data['value'] = $posted_condition_value;
                 $result = Conditions::model()->insertRecords($condition_data);
             }
         }
         LimeExpressionManager::UpgradeConditionsToRelevance(NULL, $qid);
     }
     // UPDATE ENTRY IF THIS IS AN EDIT
     if (isset($p_subaction) && $p_subaction == "updatecondition") {
         if (!isset($p_canswers) && !isset($_POST['ConditionConst']) && !isset($_POST['prevQuestionSGQA']) && !isset($_POST['tokenAttr']) && !isset($_POST['ConditionRegexp']) || !isset($p_cquestions) && !isset($p_csrctoken)) {
             $conditionsoutput_action_error .= CHtml::script("\n<!--\n alert(\"" . $clang->gT("Your condition could not be added! It did not include the question and/or answer upon which the condition was based. Please ensure you have selected a question and an answer.", "js") . "\")\n //-->\n");
         } else {
             if (isset($p_cquestions) && $p_cquestions != '') {
                 $conditionCfieldname = $p_cquestions;
             } elseif (isset($p_csrctoken) && $p_csrctoken != '') {
                 $conditionCfieldname = $p_csrctoken;
             }
             if (isset($p_canswers)) {
                 foreach ($p_canswers as $ca) {
                     // This is an Edit, there will only be ONE VALUE
                     $updated_data = array('qid' => $qid, 'scenario' => $p_scenario, 'cqid' => $p_cqid, 'cfieldname' => $conditionCfieldname, 'method' => $p_method, 'value' => $ca);
                     $result = Conditions::model()->insertRecords($updated_data, TRUE, array('cid' => $p_cid));
                 }
             }
             unset($posted_condition_value);
             // Please note that autoUnescape is already applied in database.php included above
             // so we only need to db_quote _POST variables
             if (isset($_POST['ConditionConst']) && isset($_POST['editTargetTab']) && $_POST['editTargetTab'] == "#CONST") {
                 $posted_condition_value = Yii::app()->request->getPost('ConditionConst');
             } elseif (isset($_POST['prevQuestionSGQA']) && isset($_POST['editTargetTab']) && $_POST['editTargetTab'] == "#PREVQUESTIONS") {
                 $posted_condition_value = Yii::app()->request->getPost('prevQuestionSGQA');
             } elseif (isset($_POST['tokenAttr']) && isset($_POST['editTargetTab']) && $_POST['editTargetTab'] == "#TOKENATTRS") {
                 $posted_condition_value = Yii::app()->request->getPost('tokenAttr');
             } elseif (isset($_POST['ConditionRegexp']) && isset($_POST['editTargetTab']) && $_POST['editTargetTab'] == "#REGEXP") {
                 $posted_condition_value = Yii::app()->request->getPost('ConditionRegexp');
             }
             if (isset($posted_condition_value)) {
                 $updated_data = array('qid' => $qid, 'scenario' => $p_scenario, 'cqid' => $p_cqid, 'cfieldname' => $conditionCfieldname, 'method' => $p_method, 'value' => $posted_condition_value);
                 $result = Conditions::model()->insertRecords($updated_data, TRUE, array('cid' => $p_cid));
             }
         }
         LimeExpressionManager::UpgradeConditionsToRelevance(NULL, $qid);
     }
     // DELETE ENTRY IF THIS IS DELETE
     if (isset($p_subaction) && $p_subaction == "delete") {
         LimeExpressionManager::RevertUpgradeConditionsToRelevance(NULL, $qid);
         // in case deleted the last condition
         $result = Conditions::model()->deleteRecords(array('cid' => $p_cid));
         LimeExpressionManager::UpgradeConditionsToRelevance(NULL, $qid);
     }
     // DELETE ALL CONDITIONS IN THIS SCENARIO
     if (isset($p_subaction) && $p_subaction == "deletescenario") {
         LimeExpressionManager::RevertUpgradeConditionsToRelevance(NULL, $qid);
         // in case deleted the last condition
         $result = Conditions::model()->deleteRecords(array('qid' => $qid, 'scenario' => $p_scenario));
         LimeExpressionManager::UpgradeConditionsToRelevance(NULL, $qid);
     }
     // UPDATE SCENARIO
     if (isset($p_subaction) && $p_subaction == "updatescenario" && isset($p_newscenarionum)) {
         $result = Conditions::model()->insertRecords(array('scenario' => $p_newscenarionum), TRUE, array('qid' => $qid, 'scenario' => $p_scenario));
         LimeExpressionManager::UpgradeConditionsToRelevance(NULL, $qid);
     }
     // DELETE ALL CONDITIONS FOR THIS QUESTION
     if (isset($p_subaction) && $p_subaction == "deleteallconditions") {
         LimeExpressionManager::RevertUpgradeConditionsToRelevance(NULL, $qid);
         // in case deleted the last condition
         $result = Conditions::model()->deleteRecords(array('qid' => $qid));
     }
     // RENUMBER SCENARIOS
     if (isset($p_subaction) && $p_subaction == "renumberscenarios") {
         $query = "SELECT DISTINCT scenario FROM {{conditions}} WHERE qid=:qid ORDER BY scenario";
         $result = Yii::app()->db->createCommand($query)->bindParam(":qid", $qid, PDO::PARAM_INT)->query() or safeDie("Couldn't select scenario<br />{$query}<br />");
         $newindex = 1;
         foreach ($result->readAll() as $srow) {
             // new var $update_result == old var $result2
             $update_result = Conditions::model()->insertRecords(array('scenario' => $newindex), TRUE, array('qid' => $qid, 'scenario' => $srow['scenario']));
             $newindex++;
         }
         LimeExpressionManager::UpgradeConditionsToRelevance(NULL, $qid);
         Yii::app()->session['flashmessage'] = $clang->gT("All conditions scenarios were renumbered.");
     }
     // COPY CONDITIONS IF THIS IS COPY
     if (isset($p_subaction) && $p_subaction == "copyconditions") {
         $qid = returnGlobal('qid');
         $copyconditionsfrom = returnGlobal('copyconditionsfrom');
         $copyconditionsto = returnGlobal('copyconditionsto');
         if (isset($copyconditionsto) && is_array($copyconditionsto) && isset($copyconditionsfrom) && is_array($copyconditionsfrom)) {
             //Get the conditions we are going to copy
             foreach ($copyconditionsfrom as &$entry) {
                 $entry = Yii::app()->db->quoteValue($entry);
             }
             $query = "SELECT * FROM {{conditions}}\n" . "WHERE cid in (";
             $query .= implode(", ", $copyconditionsfrom);
             $query .= ")";
             $result = Yii::app()->db->createCommand($query)->query() or safeDie("Couldn't get conditions for copy<br />{$query}<br />");
             foreach ($result->readAll() as $row) {
                 $proformaconditions[] = array("scenario" => $row['scenario'], "cqid" => $row['cqid'], "cfieldname" => $row['cfieldname'], "method" => $row['method'], "value" => $row['value']);
             }
             // while
             foreach ($copyconditionsto as $copyc) {
                 list($newsid, $newgid, $newqid) = explode("X", $copyc);
                 foreach ($proformaconditions as $pfc) {
                     //TIBO
                     //First lets make sure there isn't already an exact replica of this condition
                     $conditions_data = array('qid' => $newqid, 'scenario' => $pfc['scenario'], 'cqid' => $pfc['cqid'], 'cfieldname' => $pfc['cfieldname'], 'method' => $pfc['method'], 'value' => $pfc['value']);
                     $result = Conditions::model()->findAllByAttributes($conditions_data);
                     $count_caseinsensitivedupes = count($result);
                     $countduplicates = 0;
                     if ($count_caseinsensitivedupes != 0) {
                         foreach ($result as $ccrow) {
                             if ($ccrow['value'] == $pfc['value']) {
                                 $countduplicates++;
                             }
                         }
                     }
                     if ($countduplicates == 0) {
                         $result = Conditions::model()->insertRecords($conditions_data);
                         $conditionCopied = true;
                     } else {
                         $conditionDuplicated = true;
                     }
                 }
             }
             if (isset($conditionCopied) && $conditionCopied === true) {
                 if (isset($conditionDuplicated) && $conditionDuplicated == true) {
                     $CopyConditionsMessage = CHtml::tag('div', array('class' => 'partialheader'), '(' . $clang->gT("Conditions successfully copied (some were skipped because they were duplicates)") . ')');
                 } else {
                     $CopyConditionsMessage = CHtml::tag('div', array('class' => 'successheader'), '(' . $clang->gT("Conditions successfully copied") . ')');
                 }
             } else {
                 $CopyConditionsMessage = CHtml::tag('div', array('class' => 'warningheader'), '(' . $clang->gT("No conditions could be copied (due to duplicates)") . ')');
             }
         }
         LimeExpressionManager::UpgradeConditionsToRelevance($iSurveyID);
         // do for whole survey, since don't know which questions affected.
     }
     //END PROCESS ACTIONS
     $cquestions = array();
     $canswers = array();
     //BEGIN: GATHER INFORMATION
     // 1: Get information for this question
     if (!isset($qid)) {
         $qid = returnGlobal('qid');
     }
     if (!isset($iSurveyID)) {
         $iSurveyID = returnGlobal('sid');
     }
     $thissurvey = getSurveyInfo($iSurveyID);
     $qresult = Questions::model()->with('groups')->findByAttributes(array('qid' => $qid, 'parent_qid' => 0, 'language' => Survey::model()->findByPk($iSurveyID)->language));
     $questiongroupname = $qresult->groups->group_name;
     $questiontitle = $qresult['title'];
     $questiontext = $qresult['question'];
     $questiontype = $qresult['type'];
     // 2: Get all other questions that occur before this question that are pre-determined answer types
     // To avoid natural sort order issues,
     // first get all questions in natural sort order
     // , and find out which number in that order this question is
     $qresult = Questions::model()->with(array('groups' => array('condition' => 'groups.language = :lang', 'params' => array(':lang' => Survey::model()->findByPk($iSurveyID)->language))))->findAllByAttributes(array('parent_qid' => 0, 'sid' => $iSurveyID, 'language' => Survey::model()->findByPk($iSurveyID)->language));
     $qrows = array();
     foreach ($qresult as $k => $v) {
         $qrows[$k] = array_merge($v->attributes, $v->groups->attributes);
     }
     // Perform a case insensitive natural sort on group name then question title (known as "code" in the form) of a multidimensional array
     usort($qrows, 'groupOrderThenQuestionOrder');
     $position = "before";
     // Go through each question until we reach the current one
     foreach ($qrows as $qrow) {
         if ($qrow["qid"] != $qid && $position == "before") {
             // remember all previous questions
             // all question types are supported.
             $questionlist[] = $qrow["qid"];
         } elseif ($qrow["qid"] == $qid) {
             break;
         }
     }
     // Now, using the same array which is now properly sorted by group then question
     // Create an array of all the questions that appear AFTER the current one
     $position = "before";
     foreach ($qrows as $qrow) {
         if ($qrow["qid"] == $qid) {
             $position = "after";
             //break;
         } elseif ($qrow["qid"] != $qid && $position == "after") {
             $postquestionlist[] = $qrow['qid'];
         }
     }
     $theserows = array();
     $postrows = array();
     if (isset($questionlist) && is_array($questionlist)) {
         foreach ($questionlist as $ql) {
             $result = Questions::model()->with(array('groups' => array('condition' => 'groups.language = :lang', 'params' => array(':lang' => Survey::model()->findByPk($iSurveyID)->language))))->findAllByAttributes(array('qid' => $ql, 'parent_qid' => 0, 'sid' => $iSurveyID, 'language' => Survey::model()->findByPk($iSurveyID)->language));
             $thiscount = count($result);
             // And store again these questions in this array...
             foreach ($result as $myrows) {
                 //key => value
                 $theserows[] = array("qid" => $myrows['qid'], "sid" => $myrows['sid'], "gid" => $myrows['gid'], "question" => $myrows['question'], "type" => $myrows['type'], "mandatory" => $myrows['mandatory'], "other" => $myrows['other'], "title" => $myrows['title']);
             }
         }
     }
     if (isset($postquestionlist) && is_array($postquestionlist)) {
         foreach ($postquestionlist as $pq) {
             $result = Questions::model()->with(array('groups' => array('condition' => 'groups.language = :lang', 'params' => array(':lang' => Survey::model()->findByPk($iSurveyID)->language))))->findAllByAttributes(array('qid' => $pq, 'parent_qid' => 0, 'sid' => $iSurveyID, 'language' => Survey::model()->findByPk($iSurveyID)->language));
             $postcount = count($result);
             foreach ($result as $myrows) {
                 $postrows[] = array("qid" => $myrows['qid'], "sid" => $myrows['sid'], "gid" => $myrows['gid'], "question" => $myrows['question'], "type" => $myrows['type'], "mandatory" => $myrows['mandatory'], "other" => $myrows['other'], "title" => $myrows['title']);
             }
             // while
         }
         $postquestionscount = count($postrows);
     }
     $questionscount = count($theserows);
     if (isset($postquestionscount) && $postquestionscount > 0) {
         //Build the array used for the questionNav and copyTo select boxes
         foreach ($postrows as $pr) {
             $pquestions[] = array("text" => $pr['title'] . ": " . substr(strip_tags($pr['question']), 0, 80), "fieldname" => $pr['sid'] . "X" . $pr['gid'] . "X" . $pr['qid']);
         }
     }
     // Previous question parsing ==> building cquestions[] and canswers[]
     if ($questionscount > 0) {
         $X = "X";
         foreach ($theserows as $rows) {
             $shortquestion = $rows['title'] . ": " . strip_tags($rows['question']);
             if ($rows['type'] == "A" || $rows['type'] == "B" || $rows['type'] == "C" || $rows['type'] == "E" || $rows['type'] == "F" || $rows['type'] == "H") {
                 $aresult = Questions::model()->findAllByAttributes(array('parent_qid' => $rows['qid'], 'language' => Survey::model()->findByPk($iSurveyID)->language), array('order' => 'question_order ASC'));
                 foreach ($aresult as $arows) {
                     $shortanswer = "{$arows['title']}: [" . flattenText($arows['question']) . "]";
                     $shortquestion = $rows['title'] . ":{$shortanswer} " . flattenText($rows['question']);
                     $cquestions[] = array($shortquestion, $rows['qid'], $rows['type'], $rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title']);
                     switch ($rows['type']) {
                         case "A":
                             //Array 5 buttons
                             for ($i = 1; $i <= 5; $i++) {
                                 $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], $i, $i);
                             }
                             break;
                         case "B":
                             //Array 10 buttons
                             for ($i = 1; $i <= 10; $i++) {
                                 $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], $i, $i);
                             }
                             break;
                         case "C":
                             //Array Y/N/NA
                             $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], "Y", $clang->gT("Yes"));
                             $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], "U", $clang->gT("Uncertain"));
                             $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], "N", $clang->gT("No"));
                             break;
                         case "E":
                             //Array >/=/<
                             $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], "I", $clang->gT("Increase"));
                             $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], "S", $clang->gT("Same"));
                             $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], "D", $clang->gT("Decrease"));
                             break;
                         case "F":
                             //Array Flexible Row
                         //Array Flexible Row
                         case "H":
                             //Array Flexible Column
                             $fresult = Answers::model()->findAllByAttributes(array('qid' => $rows['qid'], "language" => Survey::model()->findByPk($iSurveyID)->language, 'scale_id' => 0), array('order' => 'sortorder, code'));
                             foreach ($fresult as $frow) {
                                 $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], $frow['code'], $frow['answer']);
                             }
                             break;
                     }
                     // Only Show No-Answer if question is not mandatory
                     if ($rows['mandatory'] != 'Y') {
                         $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], "", $clang->gT("No answer"));
                     }
                 }
                 //while
             } elseif ($rows['type'] == ":" || $rows['type'] == ";") {
                 // Multiflexi
                 //Get question attribute for $canswers
                 $qidattributes = getQuestionAttributeValues($rows['qid'], $rows['type']);
                 if (isset($qidattributes['multiflexible_max']) && trim($qidattributes['multiflexible_max']) != '') {
                     $maxvalue = floatval($qidattributes['multiflexible_max']);
                 } else {
                     $maxvalue = 10;
                 }
                 if (isset($qidattributes['multiflexible_min']) && trim($qidattributes['multiflexible_min']) != '') {
                     $minvalue = floatval($qidattributes['multiflexible_min']);
                 } else {
                     $minvalue = 1;
                 }
                 if (isset($qidattributes['multiflexible_step']) && trim($qidattributes['multiflexible_step']) != '') {
                     $stepvalue = floatval($qidattributes['multiflexible_step']);
                     if ($stepvalue == 0) {
                         $stepvalue = 1;
                     }
                 } else {
                     $stepvalue = 1;
                 }
                 if (isset($qidattributes['multiflexible_checkbox']) && $qidattributes['multiflexible_checkbox'] != 0) {
                     $minvalue = 0;
                     $maxvalue = 1;
                     $stepvalue = 1;
                 }
                 // Get the Y-Axis
                 $fquery = "SELECT sq.*, q.other" . " FROM {{questions sq}}, {{questions q}}" . " WHERE sq.sid={$iSurveyID} AND sq.parent_qid=q.qid " . "AND q.language=:lang" . " AND sq.language=:lang" . " AND q.qid=:qid\n                    AND sq.scale_id=0\n                    ORDER BY sq.question_order";
                 $sLanguage = Survey::model()->findByPk($iSurveyID)->language;
                 $y_axis_db = Yii::app()->db->createCommand($fquery)->bindParam(":lang", $sLanguage, PDO::PARAM_STR)->bindParam(":qid", $rows['qid'], PDO::PARAM_INT)->query();
                 // Get the X-Axis
                 $aquery = "SELECT sq.*\n                    FROM {{questions q}}, {{questions sq}}\n                    WHERE q.sid={$iSurveyID}\n                    AND sq.parent_qid=q.qid\n                    AND q.language=:lang\n                    AND sq.language=:lang\n                    AND q.qid=:qid\n                    AND sq.scale_id=1\n                    ORDER BY sq.question_order";
                 $x_axis_db = Yii::app()->db->createCommand($aquery)->bindParam(":lang", $sLanguage, PDO::PARAM_STR)->bindParam(":qid", $rows['qid'], PDO::PARAM_INT)->query() or safeDie("Couldn't get answers to Array questions<br />{$aquery}<br />");
                 foreach ($x_axis_db->readAll() as $frow) {
                     $x_axis[$frow['title']] = $frow['question'];
                 }
                 foreach ($y_axis_db->readAll() as $yrow) {
                     foreach ($x_axis as $key => $val) {
                         $shortquestion = $rows['title'] . ":{$yrow['title']}:{$key}: [" . strip_tags($yrow['question']) . "][" . strip_tags($val) . "] " . flattenText($rows['question']);
                         $cquestions[] = array($shortquestion, $rows['qid'], $rows['type'], $rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $yrow['title'] . "_" . $key);
                         if ($rows['type'] == ":") {
                             for ($ii = $minvalue; $ii <= $maxvalue; $ii += $stepvalue) {
                                 $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $yrow['title'] . "_" . $key, $ii, $ii);
                             }
                         }
                     }
                 }
                 unset($x_axis);
             } elseif ($rows['type'] == "1") {
                 $aresult = Questions::model()->findAllByAttributes(array('parent_qid' => $rows['qid'], 'language' => Survey::model()->findByPk($iSurveyID)->language), array('order' => 'question_order desc'));
                 foreach ($aresult as $arows) {
                     $attr = getQuestionAttributeValues($rows['qid']);
                     $label1 = isset($attr['dualscale_headerA']) ? $attr['dualscale_headerA'] : 'Label1';
                     $label2 = isset($attr['dualscale_headerB']) ? $attr['dualscale_headerB'] : 'Label2';
                     $shortanswer = "{$arows['title']}: [" . strip_tags($arows['question']) . "][{$label1}]";
                     $shortquestion = $rows['title'] . ":{$shortanswer} " . strip_tags($rows['question']);
                     $cquestions[] = array($shortquestion, $rows['qid'], $rows['type'], $rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'] . "#0");
                     $shortanswer = "{$arows['title']}: [" . strip_tags($arows['question']) . "][{$label2}]";
                     $shortquestion = $rows['title'] . ":{$shortanswer} " . strip_tags($rows['question']);
                     $cquestions[] = array($shortquestion, $rows['qid'], $rows['type'], $rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'] . "#1");
                     // first label
                     $lresult = Answers::model()->findAllByAttributes(array('qid' => $rows['qid'], 'scale_id' => 0, 'language' => Survey::model()->findByPk($iSurveyID)->language), array('order' => 'sortorder, answer'));
                     foreach ($lresult as $lrows) {
                         $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'] . "#0", "{$lrows['code']}", "{$lrows['code']}");
                     }
                     // second label
                     $lresult = Answers::model()->findAllByAttributes(array('qid' => $rows['qid'], 'scale_id' => 1, 'language' => Survey::model()->findByPk($iSurveyID)->language), array('order' => 'sortorder, answer'));
                     foreach ($lresult as $lrows) {
                         $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'] . "#1", "{$lrows['code']}", "{$lrows['code']}");
                     }
                     // Only Show No-Answer if question is not mandatory
                     if ($rows['mandatory'] != 'Y') {
                         $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'] . "#0", "", $clang->gT("No answer"));
                         $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'] . "#1", "", $clang->gT("No answer"));
                     }
                 }
                 //while
             } elseif ($rows['type'] == "K" || $rows['type'] == "Q") {
                 $aresult = Questions::model()->findAllByAttributes(array("parent_qid" => $rows['qid'], "language" => Survey::model()->findByPk($iSurveyID)->language), array('order' => 'question_order desc'));
                 foreach ($aresult as $arows) {
                     $shortanswer = "{$arows['title']}: [" . strip_tags($arows['question']) . "]";
                     $shortquestion = $rows['title'] . ":{$shortanswer} " . strip_tags($rows['question']);
                     $cquestions[] = array($shortquestion, $rows['qid'], $rows['type'], $rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title']);
                     // Only Show No-Answer if question is not mandatory
                     if ($rows['mandatory'] != 'Y') {
                         $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], "", $clang->gT("No answer"));
                     }
                 }
                 //while
             } elseif ($rows['type'] == "R") {
                 $aresult = Answers::model()->findAllByAttributes(array("qid" => $rows['qid'], "scale_id" => 0, "language" => Survey::model()->findByPk($iSurveyID)->language), array('order' => 'sortorder, answer'));
                 $acount = count($aresult);
                 foreach ($aresult as $arow) {
                     $theanswer = addcslashes($arow['answer'], "'");
                     $quicky[] = array($arow['code'], $theanswer);
                 }
                 for ($i = 1; $i <= $acount; $i++) {
                     $cquestions[] = array("{$rows['title']}: [RANK {$i}] " . strip_tags($rows['question']), $rows['qid'], $rows['type'], $rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $i);
                     foreach ($quicky as $qck) {
                         $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $i, $qck[0], $qck[1]);
                     }
                     // Only Show No-Answer if question is not mandatory
                     if ($rows['mandatory'] != 'Y') {
                         $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $i, " ", $clang->gT("No answer"));
                     }
                 }
                 unset($quicky);
             } elseif ($rows['type'] == "M" || $rows['type'] == "P") {
                 $shortanswer = " [" . $clang->gT("Group of checkboxes") . "]";
                 $shortquestion = $rows['title'] . ":{$shortanswer} " . strip_tags($rows['question']);
                 $cquestions[] = array($shortquestion, $rows['qid'], $rows['type'], $rows['sid'] . $X . $rows['gid'] . $X . $rows['qid']);
                 $aresult = Questions::model()->findAllByAttributes(array("parent_qid" => $rows['qid'], "language" => Survey::model()->findByPk($iSurveyID)->language), array('order' => 'question_order desc'));
                 foreach ($aresult as $arows) {
                     $theanswer = addcslashes($arows['question'], "'");
                     $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], $arows['title'], $theanswer);
                     $shortanswer = "{$arows['title']}: [" . strip_tags($arows['question']) . "]";
                     $shortanswer .= "[" . $clang->gT("Single checkbox") . "]";
                     $shortquestion = $rows['title'] . ":{$shortanswer} " . strip_tags($rows['question']);
                     $cquestions[] = array($shortquestion, $rows['qid'], $rows['type'], "+" . $rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title']);
                     $canswers[] = array("+" . $rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], 'Y', $clang->gT("checked"));
                     $canswers[] = array("+" . $rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], '', $clang->gT("not checked"));
                 }
             } elseif ($rows['type'] == "X") {
                 //Just ignore this questiontype
             } else {
                 $cquestions[] = array($shortquestion, $rows['qid'], $rows['type'], $rows['sid'] . $X . $rows['gid'] . $X . $rows['qid']);
                 switch ($rows['type']) {
                     case "Y":
                         // Y/N/NA
                         $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], "Y", $clang->gT("Yes"));
                         $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], "N", $clang->gT("No"));
                         // Only Show No-Answer if question is not mandatory
                         if ($rows['mandatory'] != 'Y') {
                             $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], " ", $clang->gT("No answer"));
                         }
                         break;
                     case "G":
                         //Gender
                         $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], "F", $clang->gT("Female"));
                         $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], "M", $clang->gT("Male"));
                         // Only Show No-Answer if question is not mandatory
                         if ($rows['mandatory'] != 'Y') {
                             $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], " ", $clang->gT("No answer"));
                         }
                         break;
                     case "5":
                         // 5 choice
                         for ($i = 1; $i <= 5; $i++) {
                             $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], $i, $i);
                         }
                         // Only Show No-Answer if question is not mandatory
                         if ($rows['mandatory'] != 'Y') {
                             $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], " ", $clang->gT("No answer"));
                         }
                         break;
                     case "N":
                         // Simple Numerical questions
                         // Only Show No-Answer if question is not mandatory
                         if ($rows['mandatory'] != 'Y') {
                             $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], " ", $clang->gT("No answer"));
                         }
                         break;
                     default:
                         $aresult = Answers::model()->findAllByAttributes(array('qid' => $rows['qid'], 'scale_id' => 0, 'language' => Survey::model()->findByPk($iSurveyID)->language), array('order' => 'sortorder, answer'));
                         foreach ($aresult as $arows) {
                             $theanswer = addcslashes($arows['answer'], "'");
                             $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], $arows['code'], $theanswer);
                         }
                         if ($rows['type'] == "D") {
                             // Only Show No-Answer if question is not mandatory
                             if ($rows['mandatory'] != 'Y') {
                                 $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], " ", $clang->gT("No answer"));
                             }
                         } elseif ($rows['type'] != "M" && $rows['type'] != "P" && $rows['type'] != "J" && $rows['type'] != "I") {
                             // For dropdown questions
                             // optinnaly add the 'Other' answer
                             if (($rows['type'] == "L" || $rows['type'] == "!") && $rows['other'] == "Y") {
                                 $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], "-oth-", $clang->gT("Other"));
                             }
                             // Only Show No-Answer if question is not mandatory
                             if ($rows['mandatory'] != 'Y') {
                                 $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], " ", $clang->gT("No answer"));
                             }
                         }
                         break;
                 }
                 //switch row type
             }
             //else
         }
         //foreach theserows
     }
     //if questionscount > 0
     //END Gather Information for this question
     $questionNavOptions = CHtml::openTag('optgroup', array('class' => 'activesurveyselect', 'label' => $clang->gT("Before", "js")));
     foreach ($theserows as $row) {
         $question = $row['question'];
         $question = strip_tags($question);
         if (strlen($question) < 35) {
             $questionselecter = $question;
         } else {
             //$questionselecter = substr($question, 0, 35)."..";
             $questionselecter = htmlspecialchars(mb_strcut(html_entity_decode($question, ENT_QUOTES, 'UTF-8'), 0, 35, 'UTF-8')) . "...";
         }
         $questionNavOptions .= CHtml::tag('option', array('value' => $this->getController()->createUrl("/admin/conditions/sa/index/subaction/editconditionsform/surveyid/{$iSurveyID}/gid/{$row['gid']}/qid/{$row['qid']}")), $questionselecter);
     }
     $questionNavOptions .= CHtml::closeTag('optgroup');
     $questionNavOptions .= CHtml::openTag('optgroup', array('class' => 'activesurveyselect', 'label' => $clang->gT("Current", "js")));
     $question = strip_tags($questiontext);
     if (strlen($question) < 35) {
         $questiontextshort = $question;
     } else {
         //$questiontextshort = substr($question, 0, 35)."..";
         $questiontextshort = htmlspecialchars(mb_strcut(html_entity_decode($question, ENT_QUOTES, 'UTF-8'), 0, 35, 'UTF-8')) . "...";
     }
     $questionNavOptions .= CHtml::tag('option', array('value' => $this->getController()->createUrl("/admin/conditions/sa/index/subaction/editconditionsform/surveyid/{$iSurveyID}/gid/{$gid}/qid/{$qid}"), 'selected' => 'selected'), $questiontitle . ': ' . $questiontextshort);
     $questionNavOptions .= CHtml::closeTag('optgroup');
     $questionNavOptions .= CHtml::openTag('optgroup', array('class' => 'activesurveyselect', 'label' => $clang->gT("After", "js")));
     foreach ($postrows as $row) {
         $question = $row['question'];
         $question = strip_tags($question);
         if (strlen($question) < 35) {
             $questionselecter = $question;
         } else {
             //$questionselecter = substr($question, 0, 35)."..";
             $questionselecter = htmlspecialchars(mb_strcut(html_entity_decode($question, ENT_QUOTES, 'UTF-8'), 0, 35, 'UTF-8')) . "...";
         }
         $questionNavOptions .= CHtml::tag('option', array('value' => $this->getController()->createUrl("/admin/conditions/sa/index/subaction/editconditionsform/surveyid/{$iSurveyID}/gid/{$row['gid']}/qid/{$row['qid']}")), $row['title'] . ':' . $questionselecter);
     }
     $questionNavOptions .= CHtml::closeTag('optgroup');
     //Now display the information and forms
     //BEGIN: PREPARE JAVASCRIPT TO SHOW MATCHING ANSWERS TO SELECTED QUESTION
     $javascriptpre = CHtml::openTag('script', array('type' => 'text/javascript')) . "<!--\n" . "\tvar Fieldnames = new Array();\n" . "\tvar Codes = new Array();\n" . "\tvar Answers = new Array();\n" . "\tvar QFieldnames = new Array();\n" . "\tvar Qcqids = new Array();\n" . "\tvar Qtypes = new Array();\n";
     $jn = 0;
     if (isset($canswers)) {
         foreach ($canswers as $can) {
             $an = ls_json_encode(flattenText($can[2]));
             $javascriptpre .= "Fieldnames[{$jn}]='{$can['0']}';\n" . "Codes[{$jn}]='{$can['1']}';\n" . "Answers[{$jn}]={$an};\n";
             $jn++;
         }
     }
     $jn = 0;
     if (isset($cquestions)) {
         foreach ($cquestions as $cqn) {
             $javascriptpre .= "QFieldnames[{$jn}]='{$cqn['3']}';\n" . "Qcqids[{$jn}]='{$cqn['1']}';\n" . "Qtypes[{$jn}]='{$cqn['2']}';\n";
             $jn++;
         }
     }
     //  record a JS variable to let jQuery know if survey is Anonymous
     if ($thissurvey['anonymized'] == 'Y') {
         $javascriptpre .= "isAnonymousSurvey = true;";
     } else {
         $javascriptpre .= "isAnonymousSurvey = false;";
     }
     $javascriptpre .= "//-->\n" . CHtml::closeTag('script');
     //END: PREPARE JAVASCRIPT TO SHOW MATCHING ANSWERS TO SELECTED QUESTION
     $this->getController()->_css_admin_includes(Yii::app()->getConfig("publicstyleurl") . 'jquery.multiselect.css');
     $aViewUrls = array();
     $aData['clang'] = $clang;
     $aData['surveyid'] = $iSurveyID;
     $aData['qid'] = $qid;
     $aData['gid'] = $gid;
     $aData['imageurl'] = $imageurl;
     $aData['extraGetParams'] = $extraGetParams;
     $aData['quesitonNavOptions'] = $questionNavOptions;
     $aData['conditionsoutput_action_error'] = $conditionsoutput_action_error;
     $aData['javascriptpre'] = $javascriptpre;
     $aViewUrls['conditionshead_view'][] = $aData;
     //BEGIN DISPLAY CONDITIONS FOR THIS QUESTION
     if ($subaction == 'index' || $subaction == 'editconditionsform' || $subaction == 'insertcondition' || $subaction == "editthiscondition" || $subaction == "delete" || $subaction == "updatecondition" || $subaction == "deletescenario" || $subaction == "renumberscenarios" || $subaction == "deleteallconditions" || $subaction == "updatescenario" || $subaction == 'copyconditionsform' || $subaction == 'copyconditions' || $subaction == 'conditions') {
         //3: Get other conditions currently set for this question
         $conditionscount = 0;
         $s = 0;
         $criteria = new CDbCriteria();
         $criteria->select = 'scenario';
         // only select the 'scenario' column
         $criteria->condition = 'qid=:qid';
         $criteria->params = array(':qid' => $qid);
         $criteria->order = 'scenario';
         $criteria->group = 'scenario';
         $scenarioresult = Conditions::model()->findAll($criteria);
         $scenariocount = count($scenarioresult);
         $showreplace = "{$questiontitle}" . $this->_showSpeaker($questiontext);
         $onlyshow = sprintf($clang->gT("Only show question %s IF"), $showreplace);
         $aData['conditionsoutput'] = '';
         $aData['extraGetParams'] = $extraGetParams;
         $aData['quesitonNavOptions'] = $questionNavOptions;
         $aData['conditionsoutput_action_error'] = $conditionsoutput_action_error;
         $aData['javascriptpre'] = $javascriptpre;
         $aData['onlyshow'] = $onlyshow;
         $aData['subaction'] = $subaction;
         $aData['scenariocount'] = $scenariocount;
         $aViewUrls['conditionslist_view'][] = $aData;
         if ($scenariocount > 0) {
             //self::_js_admin_includes($this->config->item("generalscripts").'jquery/jquery.checkgroup.js');
             $this->getController()->_js_admin_includes(Yii::app()->getConfig("generalscripts") . 'jquery/jquery.checkgroup.js');
             foreach ($scenarioresult as $scenarionr) {
                 $scenariotext = "";
                 if ($s == 0 && $scenariocount > 1) {
                     $scenariotext = " -------- <i>Scenario {$scenarionr['scenario']}</i> --------";
                 }
                 if ($s > 0) {
                     $scenariotext = " -------- <i>" . $clang->gT("OR") . " Scenario {$scenarionr['scenario']}</i> --------";
                 }
                 if ($subaction == "copyconditionsform" || $subaction == "copyconditions") {
                     $initialCheckbox = "<td><input type='checkbox' id='scenarioCbx{$scenarionr['scenario']}' checked='checked'/>\n" . "<script type='text/javascript'>\$(document).ready(function () { \$('#scenarioCbx{$scenarionr['scenario']}').checkgroup({ groupName:'aConditionFromScenario{$scenarionr['scenario']}'}); });</script>" . "</td><td>&nbsp;</td>\n";
                 } else {
                     $initialCheckbox = "";
                 }
                 if ($scenariotext != "" && ($subaction == "editconditionsform" || $subaction == "insertcondition" || $subaction == "updatecondition" || $subaction == "editthiscondition" || $subaction == "renumberscenarios" || $subaction == "updatescenario" || $subaction == "deletescenario" || $subaction == "delete")) {
                     $img_tag = CHtml::image($imageurl . '/scenario_delete.png', $clang->gT("Delete this scenario"), array('name' => 'DeleteWholeGroup'));
                     $additional_main_content = CHtml::link($img_tag, '#', array('onclick' => "if ( confirm('" . $clang->gT("Are you sure you want to delete all conditions set in this scenario?", "js") . "')) { document.getElementById('deletescenario{$scenarionr['scenario']}').submit();}"));
                     $img_tag = CHtml::image($imageurl . '/scenario_edit.png', $clang->gT("Edit scenario"), array('name' => 'DeleteWholeGroup'));
                     $additional_main_content .= CHtml::link($img_tag, '#', array('id' => 'editscenariobtn' . $scenarionr['scenario'], 'onclick' => "\$('#editscenario{$scenarionr['scenario']}').toggle('slow');"));
                     $aData['additional_content'] = $additional_main_content;
                 }
                 $aData['initialCheckbox'] = $initialCheckbox;
                 $aData['scenariotext'] = $scenariotext;
                 $aData['scenarionr'] = $scenarionr;
                 if (!isset($aViewUrls['output'])) {
                     $aViewUrls['output'] = '';
                 }
                 $aViewUrls['output'] .= $this->getController()->render('/admin/conditions/includes/conditions_scenario', $aData, TRUE);
                 unset($currentfield);
                 $query = "SELECT count(*) as recordcount\n                    FROM {{conditions}} c, {{questions}} q, {{groups}} g\n                    WHERE c.cqid=q.qid " . "AND q.gid=g.gid " . "AND q.parent_qid=0 " . "AND q.language=:lang1 " . "AND g.language=:lang2 " . "AND c.qid=:qid " . "AND c.scenario=:scenario " . "AND c.cfieldname NOT LIKE '{%' ";
                 // avoid catching SRCtokenAttr conditions
                 $sLanguage = Survey::model()->findByPk($iSurveyID)->language;
                 $result = Yii::app()->db->createCommand($query)->bindValue(":scenario", $scenarionr['scenario'])->bindValue(":qid", $qid, PDO::PARAM_INT)->bindValue(":lang1", $sLanguage, PDO::PARAM_STR)->bindValue(":lang2", $sLanguage, PDO::PARAM_STR)->queryRow();
                 $conditionscount = (int) $result['recordcount'];
                 $query = "SELECT c.cid, c.scenario, c.cqid, c.cfieldname, c.method, c.value, q.type\n                    FROM {{conditions}} c, {{questions}} q, {{groups}} g\n                    WHERE c.cqid=q.qid " . "AND q.gid=g.gid " . "AND q.parent_qid=0 " . "AND q.language=:lang1 " . "AND g.language=:lang2 " . "AND c.qid=:qid " . "AND c.scenario=:scenario " . "AND c.cfieldname NOT LIKE '{%' " . "ORDER BY g.group_order, q.question_order, c.cfieldname";
                 $sLanguage = Survey::model()->findByPk($iSurveyID)->language;
                 $result = Yii::app()->db->createCommand($query)->bindValue(":scenario", $scenarionr['scenario'])->bindValue(":qid", $qid, PDO::PARAM_INT)->bindValue(":lang1", $sLanguage, PDO::PARAM_STR)->bindValue(":lang2", $sLanguage, PDO::PARAM_STR)->query() or safeDie("Couldn't get other conditions for question {$qid}<br />{$query}<br />");
                 $querytoken = "SELECT count(*) as recordcount " . "FROM {{conditions}} " . "WHERE " . " {{conditions}}.qid=:qid " . "AND {{conditions}}.scenario=:scenario " . "AND {{conditions}}.cfieldname LIKE '{%' ";
                 // only catching SRCtokenAttr conditions
                 $resulttoken = Yii::app()->db->createCommand($querytoken)->bindValue(":scenario", $scenarionr['scenario'], PDO::PARAM_INT)->bindValue(":qid", $qid, PDO::PARAM_INT)->queryRow() or safeDie("Couldn't get other conditions for question {$qid}<br />{$query}<br />");
                 $conditionscounttoken = (int) $resulttoken['recordcount'];
                 $querytoken = "SELECT {{conditions}}.cid, " . "{{conditions}}.scenario, " . "{{conditions}}.cqid, " . "{{conditions}}.cfieldname, " . "{{conditions}}.method, " . "{{conditions}}.value, " . "'' AS type " . "FROM {{conditions}} " . "WHERE " . " {{conditions}}.qid=:qid " . "AND {{conditions}}.scenario=:scenario " . "AND {{conditions}}.cfieldname LIKE '{%' " . "ORDER BY {{conditions}}.cfieldname";
                 $resulttoken = Yii::app()->db->createCommand($querytoken)->bindValue(":scenario", $scenarionr['scenario'], PDO::PARAM_INT)->bindValue(":qid", $qid, PDO::PARAM_INT)->query() or safeDie("Couldn't get other conditions for question {$qid}<br />{$query}<br />");
                 $conditionscount = $conditionscount + $conditionscounttoken;
                 if ($conditionscount > 0) {
                     $aConditionsMerged = array();
                     foreach ($resulttoken->readAll() as $arow) {
                         $aConditionsMerged[] = $arow;
                     }
                     foreach ($result->readAll() as $arow) {
                         $aConditionsMerged[] = $arow;
                     }
                     foreach ($aConditionsMerged as $rows) {
                         if ($rows['method'] == "") {
                             $rows['method'] = "==";
                         }
                         //Fill in the empty method from previous versions
                         $markcidstyle = "oddrow";
                         if (array_search($rows['cid'], $markcidarray) !== FALSE) {
                             // This is the style used when the condition editor is called
                             // in order to check which conditions prevent a question deletion
                             $markcidstyle = "markedrow";
                         }
                         if ($subaction == "editthiscondition" && isset($p_cid) && $rows['cid'] === $p_cid) {
                             // Style used when editing a condition
                             $markcidstyle = "editedrow";
                         }
                         if (isset($currentfield) && $currentfield != $rows['cfieldname']) {
                             $aViewUrls['output'] .= "<tr class='evenrow'>\n" . "\t<td colspan='2'>\n" . "<span><strong>" . $clang->gT("and") . "</strong></span></td></tr>";
                         } elseif (isset($currentfield)) {
                             $aViewUrls['output'] .= "<tr class='evenrow'>\n" . "\t<td colspan='2'>\n" . "<span><strong>" . $clang->gT("or") . "</strong></span></td></tr>";
                         }
                         $aViewUrls['output'] .= "\t<tr class='{$markcidstyle}'>\n" . "\t<td colspan='2'>" . CHtml::form(array("/admin/conditions/sa/index/subaction/{$subaction}/surveyid/{$iSurveyID}/gid/{$gid}/qid/{$qid}/"), 'post', array('id' => "conditionaction{$rows['cid']}", 'name' => "conditionaction{$rows['cid']}")) . "<table>\n" . "\t<tr>\n";
                         if ($subaction == "copyconditionsform" || $subaction == "copyconditions") {
                             $aViewUrls['output'] .= "<td>&nbsp;&nbsp;</td>" . "<td>\n" . "\t<input type='checkbox' name='aConditionFromScenario{$scenarionr['scenario']}' id='cbox{$rows['cid']}' value='{$rows['cid']}' checked='checked'/>\n" . "</td>\n";
                         }
                         $aViewUrls['output'] .= "" . "<td>\n" . "\t<span>\n";
                         $leftOperandType = 'unknown';
                         // prevquestion, tokenattr
                         if ($thissurvey['anonymized'] != 'Y' && preg_match('/^{TOKEN:([^}]*)}$/', $rows['cfieldname'], $extractedTokenAttr) > 0) {
                             $leftOperandType = 'tokenattr';
                             $aTokenAttrNames = getTokenFieldsAndNames($iSurveyID);
                             if (count($aTokenAttrNames) != 0) {
                                 $thisAttrName = HTMLEscape($aTokenAttrNames[strtolower($extractedTokenAttr[1])]['description']) . " [" . $clang->gT("From token table") . "]";
                             } else {
                                 $thisAttrName = HTMLEscape($extractedTokenAttr[1]) . " [" . $clang->gT("Inexistant token table") . "]";
                             }
                             $aViewUrls['output'] .= "\t{$thisAttrName}\n";
                             // TIBO not sure this is used anymore !!
                             $conditionsList[] = array("cid" => $rows['cid'], "text" => $thisAttrName);
                         } else {
                             $leftOperandType = 'prevquestion';
                             foreach ($cquestions as $cqn) {
                                 if ($cqn[3] == $rows['cfieldname']) {
                                     $aViewUrls['output'] .= "\t{$cqn['0']} (qid{$rows['cqid']})\n";
                                     $conditionsList[] = array("cid" => $rows['cid'], "text" => $cqn[0] . " ({$rows['value']})");
                                 } else {
                                     //$aViewUrls['output'] .= "\t<font color='red'>ERROR: Delete this condition. It is out of order.</font>\n";
                                 }
                             }
                         }
                         $aViewUrls['output'] .= "\t</span></td>\n" . "\t<td>\n" . "<span>\n" . $method[trim($rows['method'])] . "</span>\n" . "\t</td>\n" . "\n" . "\t<td>\n" . "<span>\n";
                         // let's read the condition's right operand
                         // determine its type and display it
                         $rightOperandType = 'unknown';
                         // predefinedAnsw,constantVal, prevQsgqa, tokenAttr, regexp
                         if ($rows['method'] == 'RX') {
                             $rightOperandType = 'regexp';
                             $aViewUrls['output'] .= "" . HTMLEscape($rows['value']) . "\n";
                         } elseif (preg_match('/^@([0-9]+X[0-9]+X[^@]*)@$/', $rows['value'], $matchedSGQA) > 0) {
                             // SGQA
                             $rightOperandType = 'prevQsgqa';
                             $textfound = false;
                             foreach ($cquestions as $cqn) {
                                 if ($cqn[3] == $matchedSGQA[1]) {
                                     $matchedSGQAText = $cqn[0];
                                     $textfound = true;
                                     break;
                                 }
                             }
                             if ($textfound === false) {
                                 $matchedSGQAText = $rows['value'] . ' (' . $clang->gT("Not found") . ')';
                             }
                             $aViewUrls['output'] .= "" . HTMLEscape($matchedSGQAText) . "\n";
                         } elseif ($thissurvey['anonymized'] != 'Y' && preg_match('/^{TOKEN:([^}]*)}$/', $rows['value'], $extractedTokenAttr) > 0) {
                             $rightOperandType = 'tokenAttr';
                             $aTokenAttrNames = getTokenFieldsAndNames($iSurveyID);
                             if (count($aTokenAttrNames) != 0) {
                                 $thisAttrName = HTMLEscape($aTokenAttrNames[strtolower($extractedTokenAttr[1])]['description']) . " [" . $clang->gT("From token table") . "]";
                             } else {
                                 $thisAttrName = HTMLEscape($extractedTokenAttr[1]) . " [" . $clang->gT("Inexistant token table") . "]";
                             }
                             $aViewUrls['output'] .= "\t{$thisAttrName}\n";
                         } elseif (isset($canswers)) {
                             foreach ($canswers as $can) {
                                 if ($can[0] == $rows['cfieldname'] && $can[1] == $rows['value']) {
                                     $aViewUrls['output'] .= "{$can['2']} ({$can['1']})\n";
                                     $rightOperandType = 'predefinedAnsw';
                                 }
                             }
                         }
                         // if $rightOperandType is still unkown then it is a simple constant
                         if ($rightOperandType == 'unknown') {
                             $rightOperandType = 'constantVal';
                             if ($rows['value'] == ' ' || $rows['value'] == '') {
                                 $aViewUrls['output'] .= "" . $clang->gT("No answer") . "\n";
                             } else {
                                 $aViewUrls['output'] .= "" . HTMLEscape($rows['value']) . "\n";
                             }
                         }
                         $aViewUrls['output'] .= "\t</span></td>\n" . "\t<td>\n";
                         if ($subaction == "editconditionsform" || $subaction == "insertcondition" || $subaction == "updatecondition" || $subaction == "editthiscondition" || $subaction == "renumberscenarios" || $subaction == "deleteallconditions" || $subaction == "updatescenario" || $subaction == "deletescenario" || $subaction == "delete") {
                             // show single condition action buttons in edit mode
                             $aData['rows'] = $rows;
                             $aData['sImageURL'] = Yii::app()->getConfig('adminimageurl');
                             //$aViewUrls['includes/conditions_edit'][] = $aData;
                             $aViewUrls['output'] .= $this->getController()->render('/admin/conditions/includes/conditions_edit', $aData, TRUE);
                             // now sets e corresponding hidden input field
                             // depending on the leftOperandType
                             if ($leftOperandType == 'tokenattr') {
                                 $aViewUrls['output'] .= CHtml::hiddenField('csrctoken', HTMLEscape($rows['cfieldname']), array('id' => 'csrctoken' . $rows['cid']));
                             } else {
                                 $aViewUrls['output'] .= CHtml::hiddenField('cquestions', HTMLEscape($rows['cfieldname']), array('id' => 'cquestions' . $rows['cid']));
                             }
                             // now set the corresponding hidden input field
                             // depending on the rightOperandType
                             // This is used when Editting a condition
                             if ($rightOperandType == 'predefinedAnsw') {
                                 $aViewUrls['output'] .= CHtml::hiddenField('EDITcanswers[]', HTMLEscape($rows['value']), array('id' => 'editModeTargetVal' . $rows['cid']));
                             } elseif ($rightOperandType == 'prevQsgqa') {
                                 $aViewUrls['output'] .= CHtml::hiddenField('EDITprevQuestionSGQA', HTMLEscape($rows['value']), array('id' => 'editModeTargetVal' . $rows['cid']));
                             } elseif ($rightOperandType == 'tokenAttr') {
                                 $aViewUrls['output'] .= CHtml::hiddenField('EDITtokenAttr', HTMLEscape($rows['value']), array('id' => 'editModeTargetVal' . $rows['cid']));
                             } elseif ($rightOperandType == 'regexp') {
                                 $aViewUrls['output'] .= CHtml::hiddenField('EDITConditionRegexp', HTMLEscape($rows['value']), array('id' => 'editModeTargetVal' . $rows['cid']));
                             } else {
                                 $aViewUrls['output'] .= CHtml::hiddenField('EDITConditionConst', HTMLEscape($rows['value']), array('id' => 'editModeTargetVal' . $rows['cid']));
                             }
                         }
                         $aViewUrls['output'] .= CHtml::closeTag('td') . CHtml::closeTag('tr') . CHtml::closeTag('table') . CHtml::closeTag('form') . CHtml::closeTag('td') . CHtml::closeTag('tr');
                         $currentfield = $rows['cfieldname'];
                     }
                 }
                 $s++;
             }
         } else {
             // no condition ==> disable delete all conditions button, and display a simple comment
             $aViewUrls['output'] = CHtml::openTag('tr') . CHtml::tag('td', array(), $clang->gT("This question is always shown.")) . CHtml::tag('td', array(), '&nbsp;') . CHtml::closeTag('tr');
         }
         $aViewUrls['output'] .= CHtml::closeTag('table');
     }
     //END DISPLAY CONDITIONS FOR THIS QUESTION
     // BEGIN: DISPLAY THE COPY CONDITIONS FORM
     if ($subaction == "copyconditionsform" || $subaction == "copyconditions") {
         $aViewUrls['output'] .= "<tr class=''><td colspan='3'>\n" . CHtml::form(array("/admin/conditions/sa/index/subaction/copyconditions/surveyid/{$iSurveyID}/gid/{$gid}/qid/{$qid}/"), 'post', array('id' => "copyconditions", 'name' => "copyconditions")) . "<div class='header ui-widget-header'>" . $clang->gT("Copy conditions") . "</div>\n";
         //CopyConditionsMessage
         if (isset($CopyConditionsMessage)) {
             $aViewUrls['output'] .= "<div class='messagebox ui-corner-all'>\n" . "{$CopyConditionsMessage}\n" . "</div>\n";
         }
         if (isset($conditionsList) && is_array($conditionsList)) {
             //TIBO
             $this->getController()->_js_admin_includes(Yii::app()->getConfig("generalscripts") . 'jquery/jquery.multiselect.min.js');
             // TODO
             $aViewUrls['output'] .= "<script type='text/javascript'>\$(document).ready(function () { \$('#copytomultiselect').multiselect( { autoOpen: true, noneSelectedText: '" . $clang->gT("No questions selected") . "', checkAllText: '" . $clang->gT("Check all") . "', uncheckAllText: '" . $clang->gT("Uncheck all") . "', selectedText: '# " . $clang->gT("selected") . "', beforeclose: function(){ return false;},height: 200 } ); });</script>";
             $aViewUrls['output'] .= "\t<div class='conditioncopy-tbl-row'>\n" . "\t<div class='condition-tbl-left'>" . $clang->gT("Copy the selected conditions to") . ":</div>\n" . "\t<div class='condition-tbl-right'>\n" . "\t\t<select name='copyconditionsto[]' id='copytomultiselect'  multiple='multiple' >\n";
             if (isset($pquestions) && count($pquestions) != 0) {
                 foreach ($pquestions as $pq) {
                     $aViewUrls['output'] .= "\t\t<option value='{$pq['fieldname']}'>" . $pq['text'] . "</option>\n";
                 }
             }
             $aViewUrls['output'] .= "\t\t</select>\n" . "\t</div>\n" . "\t</div>\n";
             if (!isset($pquestions) || count($pquestions) == 0) {
                 $disableCopyCondition = " disabled='disabled'";
             } else {
                 $disableCopyCondition = " ";
             }
             $aViewUrls['output'] .= "\t<div class='condition-tbl-full'>\n" . "\t\t<input type='submit' value='" . $clang->gT("Copy conditions") . "' onclick=\"prepareCopyconditions(); return true;\" {$disableCopyCondition}/>\n" . "<input type='hidden' name='subaction' value='copyconditions' />\n" . "<input type='hidden' name='sid' value='{$iSurveyID}' />\n" . "<input type='hidden' name='gid' value='{$gid}' />\n" . "<input type='hidden' name='qid' value='{$qid}' />\n" . "</div>\n";
             $aViewUrls['output'] .= "<script type=\"text/javascript\">\n" . "function prepareCopyconditions()\n" . "{\n" . "\t\$(\"input:checked[name^='aConditionFromScenario']\").each(function(i,val)\n" . "\t{\n" . "var thecid = val.value;\n" . "var theform = document.getElementById('copyconditions');\n" . "addHiddenElement(theform,'copyconditionsfrom[]',thecid);\n" . "return true;\n" . "\t});\n" . "}\n" . "</script>\n";
         } else {
             $aViewUrls['output'] .= "<div class='messagebox ui-corner-all'>\n" . "<div class='partialheader'>" . $clang->gT("There are no existing conditions in this survey.") . "</div><br />\n" . "</div>\n";
         }
         $aViewUrls['output'] .= "</form></td></tr>\n";
     }
     // END: DISPLAY THE COPY CONDITIONS FORM
     if (isset($cquestions)) {
         if (count($cquestions) > 0 && count($cquestions) <= 10) {
             $qcount = count($cquestions);
         } else {
             $qcount = 9;
         }
     } else {
         $qcount = 0;
     }
     //BEGIN: DISPLAY THE ADD or EDIT CONDITION FORM
     if ($subaction == "editconditionsform" || $subaction == "insertcondition" || $subaction == "updatecondition" || $subaction == "deletescenario" || $subaction == "renumberscenarios" || $subaction == "deleteallconditions" || $subaction == "updatescenario" || $subaction == "editthiscondition" || $subaction == "delete") {
         $aViewUrls['output'] .= CHtml::form(array("/admin/conditions/sa/index/subaction/{$subaction}/surveyid/{$iSurveyID}/gid/{$gid}/qid/{$qid}/"), 'post', array('id' => "editconditions", 'name' => "editconditions"));
         if ($subaction == "editthiscondition" && isset($p_cid)) {
             $mytitle = $clang->gT("Edit condition");
         } else {
             $mytitle = $clang->gT("Add condition");
         }
         $aViewUrls['output'] .= "<div class='header ui-widget-header'>" . $mytitle . "</div>\n";
         ///////////////////////////////////////////////////////////////////////////////////////////
         // Begin "Scenario" row
         if ($subaction != "editthiscondition" && isset($scenariocount) && ($scenariocount == 1 || $scenariocount == 0) || $subaction == "editthiscondition" && isset($scenario) && $scenario == 1) {
             $scenarioAddBtn = "\t<a id='scenarioaddbtn' href='#' onclick=\"\$('#scenarioaddbtn').hide();\$('#defaultscenariotxt').hide('slow');\$('#scenario').show('slow');\">" . "<img src='{$imageurl}/plus.png' alt='" . $clang->gT('Add scenario') . "' /></a>\n";
             $scenarioTxt = "<span id='defaultscenariotxt'>" . $clang->gT("Default scenario") . "</span>";
             $scenarioInputStyle = "style = 'display: none;'";
         } else {
             $scenarioAddBtn = "";
             $scenarioTxt = "";
             $scenarioInputStyle = "style = ''";
         }
         $aViewUrls['output'] .= "<div class='condition-tbl-row'>\n" . "<div class='condition-tbl-left'>{$scenarioAddBtn}&nbsp;" . $clang->gT("Scenario") . "</div>\n" . "<div class='condition-tbl-right'><input type='text' name='scenario' id='scenario' value='1' size='2' {$scenarioInputStyle}/>" . "{$scenarioTxt}\n" . "</div>\n" . "</div>\n";
         // Begin "Question" row
         $aViewUrls['output'] .= "<div class='condition-tbl-row'>\n" . "<div class='condition-tbl-left'>" . $clang->gT("Question") . "</div>\n" . "<div class='condition-tbl-right'>\n" . "\t<div id=\"conditionsource\" class=\"tabs-nav\">\n" . "\t<ul>\n" . "\t<li><a href=\"#SRCPREVQUEST\"><span>" . $clang->gT("Previous questions") . "</span></a></li>\n" . "\t<li><a href=\"#SRCTOKENATTRS\"><span>" . $clang->gT("Token fields") . "</span></a></li>\n" . "\t</ul>\n";
         // Previous question tab
         $aViewUrls['output'] .= "<div id='SRCPREVQUEST'><select name='cquestions' id='cquestions' size='" . ($qcount + 1) . "' >\n";
         if (isset($cquestions)) {
             $js_getAnswers_onload = "";
             foreach ($cquestions as $cqn) {
                 $aViewUrls['output'] .= "<option value='{$cqn['3']}' title=\"" . htmlspecialchars($cqn[0]) . "\"";
                 if (isset($p_cquestions) && $cqn[3] == $p_cquestions) {
                     $aViewUrls['output'] .= " selected";
                     if (isset($p_canswers)) {
                         $canswersToSelect = "";
                         foreach ($p_canswers as $checkval) {
                             $canswersToSelect .= ";{$checkval}";
                         }
                         $canswersToSelect = substr($canswersToSelect, 1);
                         $js_getAnswers_onload .= "\$('#canswersToSelect').val('{$canswersToSelect}');\n";
                     }
                 }
                 $aViewUrls['output'] .= ">{$cqn['0']}</option>\n";
             }
         }
         $aViewUrls['output'] .= "</select>\n" . "</div>\n";
         // Source token Tab
         $aViewUrls['output'] .= "<div id='SRCTOKENATTRS'><select name='csrctoken' id='csrctoken' size='" . ($qcount + 1) . "' >\n";
         foreach (getTokenFieldsAndNames($iSurveyID) as $tokenattr => $tokenattrName) {
             // Check to select
             if (isset($p_csrctoken) && $p_csrctoken == '{TOKEN:' . strtoupper($tokenattr) . '}') {
                 $selectThisSrcTokenAttr = "selected=\"selected\"";
             } else {
                 $selectThisSrcTokenAttr = "";
             }
             $aViewUrls['output'] .= "<option value='{TOKEN:" . strtoupper($tokenattr) . "}' {$selectThisSrcTokenAttr}>" . HTMLEscape($tokenattrName['description']) . "</option>\n";
         }
         $aViewUrls['output'] .= "</select>\n" . "</div>\n\n";
         $aViewUrls['output'] .= "\t</div>\n";
         // end conditionsource div
         $aViewUrls['output'] .= "</div>\n" . "</div>\n";
         // Begin "Comparison operator" row
         $aViewUrls['output'] .= "<div class='condition-tbl-row'>\n" . "<div class='condition-tbl-left'>" . $clang->gT("Comparison operator") . "</div>\n" . "<div class='condition-tbl-right'>\n" . "<select name='method' id='method'>\n";
         foreach ($method as $methodCode => $methodTxt) {
             $selected = $methodCode == "==" ? " selected='selected'" : "";
             $aViewUrls['output'] .= "\t<option value='" . $methodCode . "'{$selected}>" . $methodTxt . "</option>\n";
         }
         $aViewUrls['output'] .= "</select>\n" . "</div>\n" . "</div>\n";
         // Begin "Answer" row
         $aViewUrls['output'] .= "<div class='condition-tbl-row'>\n" . "<div class='condition-tbl-left'>" . $clang->gT("Answer") . "</div>\n";
         if ($subaction == "editthiscondition") {
             $multipletext = "";
             if (isset($_POST['EDITConditionConst']) && $_POST['EDITConditionConst'] != '') {
                 $EDITConditionConst = HTMLEscape($_POST['EDITConditionConst']);
             } else {
                 $EDITConditionConst = "";
             }
             if (isset($_POST['EDITConditionRegexp']) && $_POST['EDITConditionRegexp'] != '') {
                 $EDITConditionRegexp = HTMLEscape($_POST['EDITConditionRegexp']);
             } else {
                 $EDITConditionRegexp = "";
             }
         } else {
             $multipletext = "multiple";
             if (isset($_POST['ConditionConst']) && $_POST['ConditionConst'] != '') {
                 $EDITConditionConst = HTMLEscape($_POST['ConditionConst']);
             } else {
                 $EDITConditionConst = "";
             }
             if (isset($_POST['ConditionRegexp']) && $_POST['ConditionRegexp'] != '') {
                 $EDITConditionRegexp = HTMLEscape($_POST['ConditionRegexp']);
             } else {
                 $EDITConditionRegexp = "";
             }
         }
         $aViewUrls['output'] .= "" . "<div class='condition-tbl-right'>\n" . "<div id=\"conditiontarget\" class=\"tabs-nav\">\n" . "\t<ul>\n" . "\t\t<li><a href=\"#CANSWERSTAB\"><span>" . $clang->gT("Predefined") . "</span></a></li>\n" . "\t\t<li><a href=\"#CONST\"><span>" . $clang->gT("Constant") . "</span></a></li>\n" . "\t\t<li><a href=\"#PREVQUESTIONS\"><span>" . $clang->gT("Questions") . "</span></a></li>\n" . "\t\t<li><a href=\"#TOKENATTRS\"><span>" . $clang->gT("Token fields") . "</span></a></li>\n" . "\t\t<li><a href=\"#REGEXP\"><span>" . $clang->gT("RegExp") . "</span></a></li>\n" . "\t</ul>\n";
         // Predefined answers tab
         $aViewUrls['output'] .= "\t<div id='CANSWERSTAB'>\n" . "\t\t<select  name='canswers[]' {$multipletext} id='canswers' size='7'>\n" . "\t\t</select>\n" . "\t\t<br /><span id='canswersLabel'>" . $clang->gT("Predefined answer options for this question") . "</span>\n" . "\t</div>\n";
         // Constant tab
         $aViewUrls['output'] .= "\t<div id='CONST' style='display:block;' >\n" . "\t\t<textarea name='ConditionConst' id='ConditionConst' rows='5' cols='113'>{$EDITConditionConst}</textarea>\n" . "\t\t<br /><div id='ConditionConstLabel'>" . $clang->gT("Constant value") . "</div>\n" . "\t</div>\n";
         // Previous answers tab @SGQA@ placeholders
         $aViewUrls['output'] .= "\t<div id='PREVQUESTIONS'>\n" . "\t\t<select name='prevQuestionSGQA' id='prevQuestionSGQA' size='7'>\n";
         foreach ($cquestions as $cqn) {
             // building the @SGQA@ placeholders options
             if ($cqn[2] != 'M' && $cqn[2] != 'P') {
                 // Type M or P aren't real fieldnames and thus can't be used in @SGQA@ placehodlers
                 $aViewUrls['output'] .= "\t\t<option value='@{$cqn['3']}@' title=\"" . htmlspecialchars($cqn[0]) . "\"";
                 if (isset($p_prevquestionsgqa) && $p_prevquestionsgqa == "@" . $cqn[3] . "@") {
                     $aViewUrls['output'] .= " selected='selected'";
                 }
                 $aViewUrls['output'] .= ">{$cqn['0']}</option>\n";
             }
         }
         $aViewUrls['output'] .= "\t\t</select>\n" . "\t\t<br /><span id='prevQuestionSGQALabel'>" . $clang->gT("Answers from previous questions") . "</span>\n" . "\t</div>\n";
         // Token tab
         $aViewUrls['output'] .= "\t<div id='TOKENATTRS'>\n" . "\t\t<select name='tokenAttr' id='tokenAttr' size='7'>\n";
         foreach (getTokenFieldsAndNames($iSurveyID) as $tokenattr => $tokenattrName) {
             $aViewUrls['output'] .= "\t\t<option value='{TOKEN:" . strtoupper($tokenattr) . "}'>" . HTMLEscape($tokenattrName['description']) . "</option>\n";
         }
         $aViewUrls['output'] .= "\t\t</select>\n" . "\t\t<br /><span id='tokenAttrLabel'>" . $clang->gT("Attributes values from the participant's token") . "</span>\n" . "\t</div>\n";
         // Regexp Tab
         $aViewUrls['output'] .= "\t<div id='REGEXP' style='display:block;'>\n" . "\t\t<textarea name='ConditionRegexp' id='ConditionRegexp' rows='5' cols='113'>{$EDITConditionRegexp}</textarea>\n" . "\t\t<br /><div id='ConditionRegexpLabel'><a href=\"http://docs.limesurvey.org/tiki-index.php?page=Using+Regular+Expressions\" target=\"_blank\">" . $clang->gT("Regular expression") . "</a></div>\n" . "\t</div>\n";
         $aViewUrls['output'] .= "</div>\n";
         // end conditiontarget div
         $this->getController()->_js_admin_includes(Yii::app()->getConfig("adminscripts") . 'conditions.js');
         $this->getController()->_js_admin_includes(Yii::app()->getConfig("generalscripts") . 'jquery/lime-conditions-tabs.js');
         if ($subaction == "editthiscondition" && isset($p_cid)) {
             $submitLabel = $clang->gT("Update condition");
             $submitSubaction = "updatecondition";
             $submitcid = sanitize_int($p_cid);
         } else {
             $submitLabel = $clang->gT("Add condition");
             $submitSubaction = "insertcondition";
             $submitcid = "";
         }
         $aViewUrls['output'] .= "</div>\n" . "</div>\n";
         // Begin buttons row
         $aViewUrls['output'] .= "<div class='condition-tbl-full'>\n" . "\t<input type='reset' id='resetForm' value='" . $clang->gT("Clear") . "' />\n" . "\t<input type='submit' value='" . $submitLabel . "' />\n" . "<input type='hidden' name='sid' value='{$iSurveyID}' />\n" . "<input type='hidden' name='gid' value='{$gid}' />\n" . "<input type='hidden' name='qid' value='{$qid}' />\n" . "<input type='hidden' name='subaction' value='{$submitSubaction}' />\n" . "<input type='hidden' name='cqid' id='cqid' value='' />\n" . "<input type='hidden' name='cid' id='cid' value='" . $submitcid . "' />\n" . "<input type='hidden' name='editTargetTab' id='editTargetTab' value='' />\n" . "<input type='hidden' name='editSourceTab' id='editSourceTab' value='' />\n" . "<input type='hidden' name='canswersToSelect' id='canswersToSelect' value='' />\n" . "</div>\n" . "</form>\n";
         if (!isset($js_getAnswers_onload)) {
             $js_getAnswers_onload = '';
         }
         $aViewUrls['output'] .= "<script type='text/javascript'>\n" . "<!--\n" . "\t" . $js_getAnswers_onload . "\n";
         if (isset($p_method)) {
             $aViewUrls['output'] .= "\tdocument.getElementById('method').value='" . $p_method . "';\n";
         }
         if ($subaction == "editthiscondition") {
             // in edit mode we read previous values in order to dusplay them in the corresponding inputs
             if (isset($_POST['EDITConditionConst']) && $_POST['EDITConditionConst'] != '') {
                 // In order to avoid issues with backslash escaping, I don't use javascript to set the value
                 // Thus the value is directly set when creating the Textarea element
                 //$aViewUrls['output'] .= "\tdocument.getElementById('ConditionConst').value='".HTMLEscape($_POST['EDITConditionConst'])."';\n";
                 $aViewUrls['output'] .= "\tdocument.getElementById('editTargetTab').value='#CONST';\n";
             } elseif (isset($_POST['EDITprevQuestionSGQA']) && $_POST['EDITprevQuestionSGQA'] != '') {
                 $aViewUrls['output'] .= "\tdocument.getElementById('prevQuestionSGQA').value='" . HTMLEscape($_POST['EDITprevQuestionSGQA']) . "';\n";
                 $aViewUrls['output'] .= "\tdocument.getElementById('editTargetTab').value='#PREVQUESTIONS';\n";
             } elseif (isset($_POST['EDITtokenAttr']) && $_POST['EDITtokenAttr'] != '') {
                 $aViewUrls['output'] .= "\tdocument.getElementById('tokenAttr').value='" . HTMLEscape($_POST['EDITtokenAttr']) . "';\n";
                 $aViewUrls['output'] .= "\tdocument.getElementById('editTargetTab').value='#TOKENATTRS';\n";
             } elseif (isset($_POST['EDITConditionRegexp']) && $_POST['EDITConditionRegexp'] != '') {
                 // In order to avoid issues with backslash escaping, I don't use javascript to set the value
                 // Thus the value is directly set when creating the Textarea element
                 //$aViewUrls['output'] .= "\tdocument.getElementById('ConditionRegexp').value='".HTMLEscape($_POST['EDITConditionRegexp'])."';\n";
                 $aViewUrls['output'] .= "\tdocument.getElementById('editTargetTab').value='#REGEXP';\n";
             } elseif (isset($_POST['EDITcanswers']) && is_array($_POST['EDITcanswers'])) {
                 // was a predefined answers post
                 $aViewUrls['output'] .= "\tdocument.getElementById('editTargetTab').value='#CANSWERSTAB';\n";
                 $aViewUrls['output'] .= "\t\$('#canswersToSelect').val('" . $_POST['EDITcanswers'][0] . "');\n";
             }
             if (isset($_POST['csrctoken']) && $_POST['csrctoken'] != '') {
                 $aViewUrls['output'] .= "\tdocument.getElementById('csrctoken').value='" . HTMLEscape($_POST['csrctoken']) . "';\n";
                 $aViewUrls['output'] .= "\tdocument.getElementById('editSourceTab').value='#SRCTOKENATTRS';\n";
             } else {
                 if (isset($_POST['cquestions']) && $_POST['cquestions'] != '') {
                     $aViewUrls['output'] .= "\tdocument.getElementById('cquestions').value='" . HTMLEscape($_POST['cquestions']) . "';\n";
                     $aViewUrls['output'] .= "\tdocument.getElementById('editSourceTab').value='#SRCPREVQUEST';\n";
                 }
             }
         } else {
             // in other modes, for the moment we do the same as for edit mode
             if (isset($_POST['ConditionConst']) && $_POST['ConditionConst'] != '') {
                 // In order to avoid issues with backslash escaping, I don't use javascript to set the value
                 // Thus the value is directly set when creating the Textarea element
                 //$aViewUrls['output'] .= "\tdocument.getElementById('ConditionConst').value='".HTMLEscape($_POST['ConditionConst'])."';\n";
                 $aViewUrls['output'] .= "\tdocument.getElementById('editTargetTab').value='#CONST';\n";
             } elseif (isset($_POST['prevQuestionSGQA']) && $_POST['prevQuestionSGQA'] != '') {
                 $aViewUrls['output'] .= "\tdocument.getElementById('prevQuestionSGQA').value='" . HTMLEscape($_POST['prevQuestionSGQA']) . "';\n";
                 $aViewUrls['output'] .= "\tdocument.getElementById('editTargetTab').value='#PREVQUESTIONS';\n";
             } elseif (isset($_POST['tokenAttr']) && $_POST['tokenAttr'] != '') {
                 $aViewUrls['output'] .= "\tdocument.getElementById('tokenAttr').value='" . HTMLEscape($_POST['tokenAttr']) . "';\n";
                 $aViewUrls['output'] .= "\tdocument.getElementById('editTargetTab').value='#TOKENATTRS';\n";
             } elseif (isset($_POST['ConditionRegexp']) && $_POST['ConditionRegexp'] != '') {
                 // In order to avoid issues with backslash escaping, I don't use javascript to set the value
                 // Thus the value is directly set when creating the Textarea element
                 //$aViewUrls['output'] .= "\tdocument.getElementById('ConditionRegexp').value='".HTMLEscape($_POST['ConditionRegexp'])."';\n";
                 $aViewUrls['output'] .= "\tdocument.getElementById('editTargetTab').value='#REGEXP';\n";
             } else {
                 // was a predefined answers post
                 if (isset($_POST['cquestions'])) {
                     $aViewUrls['output'] .= "\tdocument.getElementById('cquestions').value='" . HTMLEscape($_POST['cquestions']) . "';\n";
                 }
                 $aViewUrls['output'] .= "\tdocument.getElementById('editTargetTab').value='#CANSWERSTAB';\n";
             }
             if (isset($_POST['csrctoken']) && $_POST['csrctoken'] != '') {
                 $aViewUrls['output'] .= "\tdocument.getElementById('csrctoken').value='" . HTMLEscape($_POST['csrctoken']) . "';\n";
                 $aViewUrls['output'] .= "\tdocument.getElementById('editSourceTab').value='#SRCTOKENATTRS';\n";
             } else {
                 if (isset($_POST['cquestions'])) {
                     $aViewUrls['output'] .= "\tdocument.getElementById('cquestions').value='" . javascriptEscape($_POST['cquestions']) . "';\n";
                 }
                 $aViewUrls['output'] .= "\tdocument.getElementById('editSourceTab').value='#SRCPREVQUEST';\n";
             }
         }
         if (isset($p_scenario)) {
             $aViewUrls['output'] .= "\tdocument.getElementById('scenario').value='" . $p_scenario . "';\n";
         }
         $aViewUrls['output'] .= "-->\n" . "</script>\n";
     }
     //END: DISPLAY THE ADD or EDIT CONDITION FORM
     $conditionsoutput = $aViewUrls['output'];
     $aData['conditionsoutput'] = $conditionsoutput;
     $this->_renderWrappedTemplate('conditions', $aViewUrls, $aData);
     // TMSW Conditions->Relevance:  Must call LEM->ConvertConditionsToRelevance() whenever Condition is added or updated - what is best location for that action?
 }
 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 . ")";
 }
Exemplo n.º 18
0
/**
* Import survey from an TSV file template that does not require or allow assigning of GID or QID values.
* NOTE:  This currently only supports import of one language
* @global type $connect
* @global type $dbprefix
* @global type $clang
* @global type $timeadjust
* @param type $sFullFilePath
* @return type
*
* @author TMSWhite
*/
function TSVImportSurvey($sFullFilePath)
{
    $clang = Yii::app()->lang;
    $insertdata = array();
    $results = array();
    $results['error'] = false;
    $baselang = 'en';
    // TODO set proper default
    $encoding = '';
    $handle = fopen($sFullFilePath, 'r');
    $bom = fread($handle, 2);
    rewind($handle);
    $aAttributeList = questionAttributes();
    // Excel tends to save CSV as UTF-16, which PHP does not properly detect
    if ($bom === chr(0xff) . chr(0xfe) || $bom === chr(0xfe) . chr(0xff)) {
        // UTF16 Byte Order Mark present
        $encoding = 'UTF-16';
    } else {
        $file_sample = fread($handle, 1000) + 'e';
        //read first 1000 bytes
        // + e is a workaround for mb_string bug
        rewind($handle);
        $encoding = mb_detect_encoding($file_sample, 'UTF-8, UTF-7, ASCII, EUC-JP,SJIS, eucJP-win, SJIS-win, JIS, ISO-2022-JP');
    }
    if ($encoding && $encoding != 'UTF-8') {
        stream_filter_append($handle, 'convert.iconv.' . $encoding . '/UTF-8');
    }
    $file = stream_get_contents($handle);
    fclose($handle);
    // fix Excel non-breaking space
    $file = str_replace("0xC20xA0", ' ', $file);
    $filelines = explode("\n", $file);
    $row = array_shift($filelines);
    $headers = explode("\t", $row);
    $rowheaders = array();
    foreach ($headers as $header) {
        $rowheaders[] = trim($header);
    }
    // remove BOM from the first header cell, if needed
    $rowheaders[0] = preg_replace("/^\\W+/", "", $rowheaders[0]);
    if (preg_match('/class$/', $rowheaders[0])) {
        $rowheaders[0] = 'class';
        // second attempt to remove BOM
    }
    $adata = array();
    foreach ($filelines as $rowline) {
        $rowarray = array();
        $row = explode("\t", $rowline);
        for ($i = 0; $i < count($rowheaders); ++$i) {
            $val = isset($row[$i]) ? $row[$i] : '';
            // if Excel was used, it surrounds strings with quotes and doubles internal double quotes.  Fix that.
            if (preg_match('/^".*"$/', $val)) {
                $val = str_replace('""', '"', substr($val, 1, -1));
            }
            $rowarray[$rowheaders[$i]] = $val;
        }
        $adata[] = $rowarray;
    }
    $results['defaultvalues'] = 0;
    $results['answers'] = 0;
    $results['surveys'] = 0;
    $results['languages'] = 0;
    $results['questions'] = 0;
    $results['subquestions'] = 0;
    $results['question_attributes'] = 0;
    $results['groups'] = 0;
    $results['importwarnings'] = array();
    // these aren't used here, but are needed to avoid errors in post-import display
    $results['assessments'] = 0;
    $results['quota'] = 0;
    $results['quotamembers'] = 0;
    $results['quotals'] = 0;
    // collect information about survey and its language settings
    $surveyinfo = array();
    $surveyls = array();
    foreach ($adata as $row) {
        switch ($row['class']) {
            case 'S':
                if (isset($row['text']) && $row['name'] != 'datecreated') {
                    $surveyinfo[$row['name']] = $row['text'];
                }
                break;
            case 'SL':
                if (!isset($surveyls[$row['language']])) {
                    $surveyls[$row['language']] = array();
                }
                if (isset($row['text'])) {
                    $surveyls[$row['language']][$row['name']] = $row['text'];
                }
                break;
        }
    }
    $iOldSID = 1;
    if (isset($surveyinfo['sid'])) {
        $iOldSID = (int) $surveyinfo['sid'];
    }
    // Create the survey entry
    $surveyinfo['startdate'] = NULL;
    $surveyinfo['active'] = 'N';
    // unset($surveyinfo['datecreated']);
    $iNewSID = Survey::model()->insertNewSurvey($surveyinfo);
    //or safeDie($clang->gT("Error").": Failed to insert survey<br />");
    if (!$iNewSID) {
        $results['error'] = Survey::model()->getErrors();
        $results['bFailed'] = true;
        return $results;
    }
    $surveyinfo['sid'] = $iNewSID;
    $results['surveys']++;
    $results['newsid'] = $iNewSID;
    $gid = 0;
    $gseq = 0;
    // group_order
    $qid = 0;
    $qseq = 0;
    // question_order
    $qtype = 'T';
    $aseq = 0;
    // answer sortorder
    // set the language for the survey
    $_title = 'Missing Title';
    foreach ($surveyls as $_lang => $insertdata) {
        $insertdata['surveyls_survey_id'] = $iNewSID;
        $insertdata['surveyls_language'] = $_lang;
        if (isset($insertdata['surveyls_title'])) {
            $_title = $insertdata['surveyls_title'];
        } else {
            $insertdata['surveyls_title'] = $_title;
        }
        $result = SurveyLanguageSetting::model()->insertNewSurvey($insertdata);
        //
        if (!$result) {
            $results['error'][] = $clang->gT("Error") . " : " . $clang->gT("Failed to insert survey language");
            break;
        }
        $results['languages']++;
    }
    $ginfo = array();
    $qinfo = array();
    $sqinfo = array();
    if (isset($surveyinfo['language'])) {
        $baselang = $surveyinfo['language'];
        // the base language
    }
    $rownumber = 1;
    $lastglang = '';
    foreach ($adata as $row) {
        $rownumber += 1;
        switch ($row['class']) {
            case 'G':
                // insert group
                $insertdata = array();
                $insertdata['sid'] = $iNewSID;
                $gname = !empty($row['name']) ? $row['name'] : 'G' . $gseq;
                $glang = !empty($row['language']) ? $row['language'] : $baselang;
                // when a multi-lang tsv-file without information on the group id/number (old style) is imported,
                // we make up this information by giving a number 0..[numberofgroups-1] per language.
                // the number and order of groups per language should be the same, so we can also import these files
                if ($lastglang != $glang) {
                    $iGroupcounter = 0;
                }
                $lastglang = $glang;
                //use group id/number from file. if missing, use an increasing number (s.a.)
                $sGroupseq = !empty($row['type/scale']) ? $row['type/scale'] : 'G' . $iGroupcounter++;
                $insertdata['group_name'] = $gname;
                $insertdata['grelevance'] = isset($row['relevance']) ? $row['relevance'] : '';
                $insertdata['description'] = isset($row['text']) ? $row['text'] : '';
                $insertdata['language'] = $glang;
                // For multi language survey: same gid/sort order across all languages
                if (isset($ginfo[$sGroupseq])) {
                    $gid = $ginfo[$sGroupseq]['gid'];
                    $insertdata['gid'] = $gid;
                    $insertdata['group_order'] = $ginfo[$sGroupseq]['group_order'];
                } else {
                    $insertdata['group_order'] = $gseq;
                }
                $newgid = QuestionGroup::model()->insertRecords($insertdata);
                if (!$newgid) {
                    $results['error'][] = $clang->gT("Error") . " : " . $clang->gT("Failed to insert group") . ". " . $clang->gT("Text file row number ") . $rownumber . " (" . $gname . ")";
                    break;
                }
                if (!isset($ginfo[$sGroupseq])) {
                    $results['groups']++;
                    $gid = $newgid;
                    $ginfo[$sGroupseq]['gid'] = $gid;
                    $ginfo[$sGroupseq]['group_order'] = $gseq++;
                }
                $qseq = 0;
                // reset the question_order
                break;
            case 'Q':
                // insert question
                $insertdata = array();
                $insertdata['sid'] = $iNewSID;
                $qtype = isset($row['type/scale']) ? $row['type/scale'] : 'T';
                $qname = isset($row['name']) ? $row['name'] : 'Q' . $qseq;
                $insertdata['gid'] = $gid;
                $insertdata['type'] = $qtype;
                $insertdata['title'] = $qname;
                $insertdata['question'] = isset($row['text']) ? $row['text'] : '';
                $insertdata['relevance'] = isset($row['relevance']) ? $row['relevance'] : '';
                $insertdata['preg'] = isset($row['validation']) ? $row['validation'] : '';
                $insertdata['help'] = isset($row['help']) ? $row['help'] : '';
                $insertdata['language'] = isset($row['language']) ? $row['language'] : $baselang;
                $insertdata['mandatory'] = isset($row['mandatory']) ? $row['mandatory'] : '';
                $lastother = $insertdata['other'] = isset($row['other']) ? $row['other'] : 'N';
                // Keep trace of other settings for sub question
                $insertdata['same_default'] = isset($row['same_default']) ? $row['same_default'] : 0;
                $insertdata['parent_qid'] = 0;
                // For multi numeric survey : same name, add the gid to have same name on different gid. Bad for EM.
                $fullqname = "G{$gid}_" . $qname;
                if (isset($qinfo[$fullqname])) {
                    $qseq = $qinfo[$fullqname]['question_order'];
                    $qid = $qinfo[$fullqname]['qid'];
                    $insertdata['qid'] = $qid;
                    $insertdata['question_order'] = $qseq;
                } else {
                    $insertdata['question_order'] = $qseq;
                }
                // Insert question and keep the qid for multi language survey
                $result = Question::model()->insertRecords($insertdata);
                if (!$result) {
                    $results['error'][] = $clang->gT("Error") . " : " . $clang->gT("Could not insert question") . ". " . $clang->gT("Text file row number ") . $rownumber . " (" . $qname . ")";
                    break;
                }
                $newqid = $result;
                if (!isset($qinfo[$fullqname])) {
                    $results['questions']++;
                    $qid = $newqid;
                    // save this for later
                    $qinfo[$fullqname]['qid'] = $qid;
                    $qinfo[$fullqname]['question_order'] = $qseq++;
                }
                $aseq = 0;
                //reset the answer sortorder
                $sqseq = 0;
                //reset the sub question sortorder
                // insert question attributes
                foreach ($row as $key => $val) {
                    switch ($key) {
                        case 'class':
                        case 'type/scale':
                        case 'name':
                        case 'text':
                        case 'validation':
                        case 'relevance':
                        case 'help':
                        case 'language':
                        case 'mandatory':
                        case 'other':
                        case 'same_default':
                        case 'default':
                            break;
                        default:
                            if ($key != '' && $val != '') {
                                $insertdata = array();
                                $insertdata['qid'] = $qid;
                                // check if attribute is a i18n attribute. If yes, set language, else set language to null in attribute table
                                if (isset($aAttributeList[$qtype][$key]['i18n']) && $aAttributeList[$qtype][$key]['i18n'] == 1) {
                                    $insertdata['language'] = isset($row['language']) ? $row['language'] : $baselang;
                                } else {
                                    $insertdata['language'] = NULL;
                                }
                                $insertdata['attribute'] = $key;
                                $insertdata['value'] = $val;
                                $result = QuestionAttribute::model()->insertRecords($insertdata);
                                //
                                if (!$result) {
                                    $results['importwarnings'][] = $clang->gT("Warning") . " : " . $clang->gT("Failed to insert question attribute") . ". " . $clang->gT("Text file row number ") . $rownumber . " ({$key})";
                                    break;
                                }
                                $results['question_attributes']++;
                            }
                            break;
                    }
                }
                // insert default value
                if (isset($row['default'])) {
                    $insertdata = array();
                    $insertdata['qid'] = $qid;
                    $insertdata['language'] = isset($row['language']) ? $row['language'] : $baselang;
                    $insertdata['defaultvalue'] = $row['default'];
                    $result = DefaultValue::model()->insertRecords($insertdata);
                    if (!$result) {
                        $results['importwarnings'][] = $clang->gT("Warning") . " : " . $clang->gT("Failed to insert default value") . ". " . $clang->gT("Text file row number ") . $rownumber;
                        break;
                    }
                    $results['defaultvalues']++;
                }
                break;
            case 'SQ':
                $sqname = isset($row['name']) ? $row['name'] : 'SQ' . $sqseq;
                if ($qtype == 'O' || $qtype == '|') {
                    // these are fake rows to show naming of comment and filecount fields
                } elseif ($sqname == 'other' && $lastother == "Y") {
                    if ($qtype == "!" || $qtype == "L") {
                        // only used to set default value for 'other' in these cases
                        if (isset($row['default'])) {
                            $insertdata = array();
                            $insertdata['qid'] = $qid;
                            $insertdata['specialtype'] = 'other';
                            $insertdata['language'] = isset($row['language']) ? $row['language'] : $baselang;
                            $insertdata['defaultvalue'] = $row['default'];
                            $result = DefaultValue::model()->insertRecords($insertdata);
                            if (!$result) {
                                $results['importwarnings'][] = $clang->gT("Warning") . " : " . $clang->gT("Failed to insert default value") . ". " . $clang->gT("Text file row number ") . $rownumber;
                                break;
                            }
                            $results['defaultvalues']++;
                        }
                    }
                } else {
                    $insertdata = array();
                    $scale_id = isset($row['type/scale']) ? $row['type/scale'] : 0;
                    $insertdata['sid'] = $iNewSID;
                    $insertdata['gid'] = $gid;
                    $insertdata['parent_qid'] = $qid;
                    $insertdata['type'] = $qtype;
                    $insertdata['title'] = $sqname;
                    $insertdata['question'] = isset($row['text']) ? $row['text'] : '';
                    $insertdata['relevance'] = isset($row['relevance']) ? $row['relevance'] : '';
                    $insertdata['preg'] = isset($row['validation']) ? $row['validation'] : '';
                    $insertdata['help'] = isset($row['help']) ? $row['help'] : '';
                    $insertdata['language'] = isset($row['language']) ? $row['language'] : $baselang;
                    $insertdata['mandatory'] = isset($row['mandatory']) ? $row['mandatory'] : '';
                    $insertdata['scale_id'] = $scale_id;
                    // For multi nueric language, qid is needed, why not gid. name is not unique.
                    $fullsqname = "G{$gid}Q{$qid}_{$scale_id}_{$sqname}";
                    if (isset($sqinfo[$fullsqname])) {
                        $qseq = $sqinfo[$fullsqname]['question_order'];
                        $sqid = $sqinfo[$fullsqname]['sqid'];
                        $insertdata['question_order'] = $qseq;
                        $insertdata['qid'] = $sqid;
                    } else {
                        $insertdata['question_order'] = $qseq;
                    }
                    // Insert sub question and keep the sqid for multi language survey
                    $newsqid = Question::model()->insertRecords($insertdata);
                    if (!$newsqid) {
                        $results['error'][] = $clang->gT("Error") . " : " . $clang->gT("Could not insert subquestion") . ". " . $clang->gT("Text file row number ") . $rownumber . " (" . $qname . ")";
                        break;
                    }
                    if (!isset($sqinfo[$fullsqname])) {
                        $sqinfo[$fullsqname]['question_order'] = $qseq++;
                        $sqid = $newsqid;
                        // save this for later
                        $sqinfo[$fullsqname]['sqid'] = $sqid;
                        $results['subquestions']++;
                    }
                    // insert default value
                    if (isset($row['default'])) {
                        $insertdata = array();
                        $insertdata['qid'] = $qid;
                        $insertdata['sqid'] = $sqid;
                        $insertdata['scale_id'] = $scale_id;
                        $insertdata['language'] = isset($row['language']) ? $row['language'] : $baselang;
                        $insertdata['defaultvalue'] = $row['default'];
                        $result = DefaultValue::model()->insertRecords($insertdata);
                        if (!$result) {
                            $results['importwarnings'][] = $clang->gT("Warning") . " : " . $clang->gT("Failed to insert default value") . ". " . $clang->gT("Text file row number ") . $rownumber;
                            break;
                        }
                        $results['defaultvalues']++;
                    }
                }
                break;
            case 'A':
                $insertdata = array();
                $insertdata['qid'] = $qid;
                $insertdata['code'] = isset($row['name']) ? $row['name'] : 'A' . $aseq;
                $insertdata['answer'] = isset($row['text']) ? $row['text'] : '';
                $insertdata['scale_id'] = isset($row['type/scale']) ? $row['type/scale'] : 0;
                $insertdata['language'] = isset($row['language']) ? $row['language'] : $baselang;
                $insertdata['assessment_value'] = (int) (isset($row['relevance']) ? $row['relevance'] : '');
                $insertdata['sortorder'] = ++$aseq;
                $result = Answer::model()->insertRecords($insertdata);
                // or safeDie("Error: Failed to insert answer<br />");
                if (!$result) {
                    $results['error'][] = $clang->gT("Error") . " : " . $clang->gT("Could not insert answer") . ". " . $clang->gT("Text file row number ") . $rownumber;
                }
                $results['answers']++;
                break;
        }
    }
    // Delete the survey if error found
    if (is_array($results['error'])) {
        $result = Survey::model()->deleteSurvey($iNewSID);
    } else {
        LimeExpressionManager::SetSurveyId($iNewSID);
        LimeExpressionManager::RevertUpgradeConditionsToRelevance($iNewSID);
        LimeExpressionManager::UpgradeConditionsToRelevance($iNewSID);
    }
    return $results;
}
Exemplo n.º 19
0
 /**
  * Updates the group ID for all conditions
  * 
  * @param integer $iSurveyID
  * @param integer $iQuestionID
  * @param integer $iOldGroupID
  * @param integer $iNewGroupID
  */
 public function updateCFieldName($iSurveyID, $iQuestionID, $iOldGroupID, $iNewGroupID)
 {
     $oResults = $this->findAllByAttributes(array('cqid' => $iQuestionID));
     foreach ($oResults as $oRow) {
         $cfnregs = '';
         if (preg_match('/(\\S*?)' . $iSurveyID . "X" . $iOldGroupID . "X" . $iQuestionID . "(.*)/", $oRow->cfieldname, $cfnregs) > 0) {
             $sNewCfn = $cfnregs[1] . $iSurveyID . "X" . $iNewGroupID . "X" . $iQuestionID . $cfnregs[2];
             Yii::app()->db->createCommand()->update($this->tableName(), array('cfieldname' => $sNewCfn), 'cid=:cid', array(':cid' => $oRow->cid));
             LimeExpressionManager::UpgradeConditionsToRelevance($iSurveyID, $oRow->qid);
         }
     }
 }
Exemplo n.º 20
0
                } else {
                    $conditionDuplicated = true;
                }
            }
        }
        if (isset($conditionCopied) && $conditionCopied === true) {
            if (isset($conditionDuplicated) && $conditionDuplicated == true) {
                $CopyConditionsMessage = "<div class='partialheader'>(" . $clang->gT("Conditions successfully copied (some were skipped because they were duplicates)") . ")</div>";
            } else {
                $CopyConditionsMessage = "<div class='successheader'>(" . $clang->gT("Conditions successfully copied") . ")</div>";
            }
        } else {
            $CopyConditionsMessage = "<div class='warningheader'>(" . $clang->gT("No conditions could be copied (due to duplicates)") . ")</div>";
        }
    }
    LimeExpressionManager::UpgradeConditionsToRelevance($surveyid);
    // do for whole survey, since don't know which questions affected.
}
//END PROCESS ACTIONS
$cquestions = array();
$canswers = array();
//BEGIN: GATHER INFORMATION
// 1: Get information for this question
if (!isset($qid)) {
    $qid = returnglobal('qid');
}
if (!isset($surveyid)) {
    $surveyid = returnglobal('sid');
}
$thissurvey = getSurveyInfo($surveyid);
$query = "SELECT * " . "FROM {$dbprefix}questions, " . "{$dbprefix}groups " . "WHERE {$dbprefix}questions.gid={$dbprefix}groups.gid " . "AND qid={$qid} " . "AND parent_qid=0 " . "AND {$dbprefix}questions.language='" . GetBaseLanguageFromSurveyID($surveyid) . "'";
Exemplo n.º 21
0
function db_upgrade($oldversion)
{
    /// This function does anything necessary to upgrade
    /// older versions to match current functionality
    global $modifyoutput, $dbprefix, $clang;
    if ($oldversion < 111) {
        // Language upgrades from version 110 to 111 since the language names did change
        $oldnewlanguages = array('german_informal' => 'german-informal', 'cns' => 'cn-Hans', 'cnt' => 'cn-Hant', 'pt_br' => 'pt-BR', 'gr' => 'el', 'jp' => 'ja', 'si' => 'sl', 'se' => 'sv', 'vn' => 'vi');
        foreach ($oldnewlanguages as $oldlang => $newlang) {
            modify_database("", "update [prefix_answers] set [language]='{$newlang}' where language='{$oldlang}'");
            echo $modifyoutput;
            flush();
            ob_flush();
            modify_database("", "update [prefix_questions] set [language]='{$newlang}' where language='{$oldlang}'");
            echo $modifyoutput;
            flush();
            ob_flush();
            modify_database("", "update [prefix_groups] set [language]='{$newlang}' where language='{$oldlang}'");
            echo $modifyoutput;
            flush();
            ob_flush();
            modify_database("", "update [prefix_labels] set [language]='{$newlang}' where language='{$oldlang}'");
            echo $modifyoutput;
            flush();
            ob_flush();
            modify_database("", "update [prefix_surveys] set [language]='{$newlang}' where language='{$oldlang}'");
            echo $modifyoutput;
            flush();
            ob_flush();
            modify_database("", "update [prefix_surveys_languagesettings] set [surveyls_language]='{$newlang}' where surveyls_language='{$oldlang}'");
            echo $modifyoutput;
            flush();
            ob_flush();
            modify_database("", "update [prefix_users] set [lang]='{$newlang} where lang='{$oldlang}'");
            echo $modifyoutput;
            flush();
            ob_flush();
        }
        $resultdata = db_execute_assoc("select * from " . db_table_name("labelsets"));
        while ($datarow = $resultdata->FetchRow()) {
            $toreplace = $datarow['languages'];
            $toreplace = str_replace('german_informal', 'german-informal', $toreplace);
            $toreplace = str_replace('cns', 'cn-Hans', $toreplace);
            $toreplace = str_replace('cnt', 'cn-Hant', $toreplace);
            $toreplace = str_replace('pt_br', 'pt-BR', $toreplace);
            $toreplace = str_replace('gr', 'el', $toreplace);
            $toreplace = str_replace('jp', 'ja', $toreplace);
            $toreplace = str_replace('si', 'sl', $toreplace);
            $toreplace = str_replace('se', 'sv', $toreplace);
            $toreplace = str_replace('vn', 'vi', $toreplace);
            modify_database("", "update [prefix_labelsets] set [languages`='{$toreplace}' where lid=" . $datarow['lid']);
            echo $modifyoutput;
            flush();
            ob_flush();
        }
        $resultdata = db_execute_assoc("select * from " . db_table_name("surveys"));
        while ($datarow = $resultdata->FetchRow()) {
            $toreplace = $datarow['additional_languages'];
            $toreplace = str_replace('german_informal', 'german-informal', $toreplace);
            $toreplace = str_replace('cns', 'cn-Hans', $toreplace);
            $toreplace = str_replace('cnt', 'cn-Hant', $toreplace);
            $toreplace = str_replace('pt_br', 'pt-BR', $toreplace);
            $toreplace = str_replace('gr', 'el', $toreplace);
            $toreplace = str_replace('jp', 'ja', $toreplace);
            $toreplace = str_replace('si', 'sl', $toreplace);
            $toreplace = str_replace('se', 'sv', $toreplace);
            $toreplace = str_replace('vn', 'vi', $toreplace);
            modify_database("", "update [prefix_surveys] set [additional_languages`='{$toreplace}' where sid=" . $datarow['sid']);
            echo $modifyoutput;
            flush();
            ob_flush();
        }
        modify_database("", "update [prefix_settings_global] set [stg_value]='111' where stg_name='DBVersion'");
        echo $modifyoutput;
    }
    if ($oldversion < 112) {
        //The size of the users_name field is now 64 char (20 char before version 112)
        modify_database("", "ALTER TABLE [prefix_users] ALTER COLUMN [users_name] VARCHAR( 64 ) NOT NULL");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "update [prefix_settings_global] set [stg_value]='112' where stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        ob_flush();
    }
    if ($oldversion < 113) {
        //No action needed
        modify_database("", "update [prefix_settings_global] set [stg_value]='113' where stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        ob_flush();
    }
    if ($oldversion < 114) {
        modify_database("", "ALTER TABLE [prefix_saved_control] ALTER COLUMN [email] VARCHAR(320) NOT NULL");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "ALTER TABLE [prefix_surveys] ALTER COLUMN [adminemail] VARCHAR(320) NOT NULL");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "ALTER TABLE [prefix_users] ALTER COLUMN [email] VARCHAR(320) NOT NULL");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", 'INSERT INTO [prefix_settings_global] VALUES (\'SessionName\', \'$sessionname\');');
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "update [prefix_settings_global] set [stg_value]='114' where stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        ob_flush();
    }
    if ($oldversion < 126) {
        modify_database("", "ALTER TABLE [prefix_surveys] ADD  [printanswers] CHAR(1) DEFAULT 'N'");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "ALTER TABLE [prefix_surveys] ADD  [listpublic] CHAR(1) DEFAULT 'N'");
        echo $modifyoutput;
        flush();
        ob_flush();
        upgrade_survey_tables117();
        upgrade_survey_tables118();
        //119
        modify_database("", "CREATE TABLE [prefix_quota] (\r\n\t\t\t\t\t\t  [id] int NOT NULL IDENTITY (1,1),\r\n\t\t\t\t\t\t  [sid] int,\r\n\t\t\t\t\t\t  [name] varchar(255) ,\r\n\t\t\t\t\t\t  [qlimit] int ,\r\n\t\t\t\t\t\t  [action] int ,\r\n\t\t\t\t\t\t  [active] int NOT NULL default '1',\r\n\t\t\t\t\t\t  PRIMARY KEY  ([id])\r\n\t\t\t\t\t\t);");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "CREATE TABLE [prefix_quota_members] (\r\n\t\t\t\t\t\t  [id] int NOT NULL IDENTITY (1,1),\r\n\t\t\t\t\t\t  [sid] int ,\r\n\t\t\t\t\t\t  [qid] int ,\r\n\t\t\t\t\t\t  [quota_id] int ,\r\n\t\t\t\t\t\t  [code] varchar(5) ,\r\n\t\t\t\t\t\t  PRIMARY KEY  ([id])\r\n\t\t\t\t\t\t);");
        echo $modifyoutput;
        flush();
        ob_flush();
        // Rename Norwegian language code from NO to NB
        $oldnewlanguages = array('no' => 'nb');
        foreach ($oldnewlanguages as $oldlang => $newlang) {
            modify_database("", "update [prefix_answers] set [language]='{$newlang}' where [language]='{$oldlang}'");
            echo $modifyoutput;
            flush();
            ob_flush();
            modify_database("", "update [prefix_questions] set [language]='{$newlang}' where [language]='{$oldlang}'");
            echo $modifyoutput;
            flush();
            ob_flush();
            modify_database("", "update [prefix_groups] set [language]='{$newlang}' where [language]='{$oldlang}'");
            echo $modifyoutput;
            flush();
            ob_flush();
            modify_database("", "update [prefix_labels] set [language]='{$newlang}' where [language]='{$oldlang}'");
            echo $modifyoutput;
            flush();
            ob_flush();
            modify_database("", "update [prefix_surveys] set [language]='{$newlang}' where [language]='{$oldlang}'");
            echo $modifyoutput;
            flush();
            ob_flush();
            modify_database("", "update [prefix_surveys_languagesettings] set [surveyls_language]='{$newlang}' where surveyls_language='{$oldlang}'");
            echo $modifyoutput;
            flush();
            ob_flush();
            modify_database("", "update [prefix_users] set [lang]='{$newlang}' where lang='{$oldlang}'");
            echo $modifyoutput;
            flush();
            ob_flush();
        }
        $resultdata = db_execute_assoc("select * from " . db_table_name("labelsets"));
        while ($datarow = $resultdata->FetchRow()) {
            $toreplace = $datarow['languages'];
            $toreplace2 = str_replace('no', 'nb', $toreplace);
            if ($toreplace2 != $toreplace) {
                modify_database("", "update  [prefix_labelsets] set [languages]='{$toreplace}' where lid=" . $datarow['lid']);
                echo $modifyoutput;
                flush();
                ob_flush();
            }
        }
        $resultdata = db_execute_assoc("select * from " . db_table_name("surveys"));
        while ($datarow = $resultdata->FetchRow()) {
            $toreplace = $datarow['additional_languages'];
            $toreplace2 = str_replace('no', 'nb', $toreplace);
            if ($toreplace2 != $toreplace) {
                modify_database("", "update [prefix_surveys] set [additional_languages]='{$toreplace}' where sid=" . $datarow['sid']);
                echo $modifyoutput;
                flush();
                ob_flush();
            }
        }
        modify_database("", "ALTER TABLE [prefix_surveys] ADD [htmlemail] CHAR(1) DEFAULT 'N'");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "ALTER TABLE [prefix_surveys] ADD [usecaptcha] CHAR(1) DEFAULT 'N'");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "ALTER TABLE [prefix_surveys] ADD [tokenanswerspersistence] CHAR(1) DEFAULT 'N'");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "ALTER TABLE [prefix_users] ADD [htmleditormode] CHAR(7) DEFAULT 'default'");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "CREATE TABLE [prefix_templates_rights] (\r\n\t\t\t\t\t\t  [uid] int NOT NULL,\r\n\t\t\t\t\t\t  [folder] varchar(255) NOT NULL,\r\n\t\t\t\t\t\t  [use] int NOT NULL,\r\n\t\t\t\t\t\t  PRIMARY KEY  ([uid],[folder])\r\n\t\t\t\t\t\t  );");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "CREATE TABLE [prefix_templates] (\r\n\t\t\t\t\t\t  [folder] varchar(255) NOT NULL,\r\n\t\t\t\t\t\t  [creator] int NOT NULL,\r\n\t\t\t\t\t\t  PRIMARY KEY  ([folder])\r\n\t\t\t\t\t\t  );");
        echo $modifyoutput;
        flush();
        ob_flush();
        //123
        modify_database("", "ALTER TABLE [prefix_conditions] ALTER COLUMN [value] VARCHAR(255)");
        echo $modifyoutput;
        flush();
        ob_flush();
        mssql_drop_constraint('title', 'labels');
        modify_database("", "ALTER TABLE [prefix_labels] ALTER COLUMN [title] varchar(4000)");
        echo $modifyoutput;
        flush();
        ob_flush();
        //124
        modify_database("", "ALTER TABLE [prefix_surveys] ADD [bounce_email] text");
        echo $modifyoutput;
        flush();
        ob_flush();
        //125
        upgrade_token_tables125();
        modify_database("", "EXEC sp_rename 'prefix_users.move_user','superadmin'");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "UPDATE [prefix_users] SET [superadmin]=1 where ([create_survey]=1 AND [create_user]=1 AND [delete_user]=1 AND [configurator]=1)");
        echo $modifyoutput;
        flush();
        ob_flush();
        //126
        modify_database("", "ALTER TABLE [prefix_questions] ADD [lid1] int NOT NULL DEFAULT '0'");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "UPDATE [prefix_conditions] SET [method]='==' where ( [method] is null) or [method]='' or [method]='0'");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "update [prefix_settings_global] set [stg_value]='126' where stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        ob_flush();
    }
    if ($oldversion < 127) {
        modify_database("", "create index [answers_idx2] on [prefix_answers] ([sortorder])");
        echo $modifyoutput;
        modify_database("", "create index [assessments_idx2] on [prefix_assessments] ([sid])");
        echo $modifyoutput;
        modify_database("", "create index [assessments_idx3] on [prefix_assessments] ([gid])");
        echo $modifyoutput;
        modify_database("", "create index [conditions_idx2] on [prefix_conditions] ([qid])");
        echo $modifyoutput;
        modify_database("", "create index [conditions_idx3] on [prefix_conditions] ([cqid])");
        echo $modifyoutput;
        modify_database("", "create index [groups_idx2] on [prefix_groups] ([sid])");
        echo $modifyoutput;
        modify_database("", "create index [question_attributes_idx2] on [prefix_question_attributes] ([qid])");
        echo $modifyoutput;
        modify_database("", "create index [questions_idx2] on [prefix_questions] ([sid])");
        echo $modifyoutput;
        modify_database("", "create index [questions_idx3] on [prefix_questions] ([gid])");
        echo $modifyoutput;
        modify_database("", "create index [questions_idx4] on [prefix_questions] ([type])");
        echo $modifyoutput;
        modify_database("", "create index [quota_idx2] on [prefix_quota] ([sid])");
        echo $modifyoutput;
        modify_database("", "create index [saved_control_idx2] on [prefix_saved_control] ([sid])");
        echo $modifyoutput;
        modify_database("", "create index [user_in_groups_idx1] on [prefix_user_in_groups] ([ugid], [uid])");
        echo $modifyoutput;
        modify_database("", "update [prefix_settings_global] set [stg_value]='127' where stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        ob_flush();
    }
    if ($oldversion < 128) {
        upgrade_token_tables128();
        modify_database("", "update [prefix_settings_global] set [stg_value]='128' where stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        ob_flush();
    }
    if ($oldversion < 129) {
        //128
        modify_database("", "ALTER TABLE [prefix_surveys] ADD [startdate] DATETIME");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "ALTER TABLE [prefix_surveys] ADD [usestartdate] char(1) NOT NULL default 'N'");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "update [prefix_settings_global] set [stg_value]='129' where stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        ob_flush();
    }
    if ($oldversion < 130) {
        modify_database("", "ALTER TABLE [prefix_conditions] ADD [scenario] int NOT NULL DEFAULT '1'");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "UPDATE [prefix_conditions] SET [scenario]=1 where ( [scenario] is null) or [scenario]='' or [scenario]=0");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "update [prefix_settings_global] set [stg_value]='130' where stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        ob_flush();
    }
    if ($oldversion < 131) {
        modify_database("", "ALTER TABLE [prefix_surveys] ADD [publicstatistics] char(1) NOT NULL default 'N'");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "update [prefix_settings_global] set [stg_value]='131' where stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        ob_flush();
    }
    if ($oldversion < 132) {
        modify_database("", "ALTER TABLE [prefix_surveys] ADD [publicgraphs] char(1) NOT NULL default 'N'");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "update [prefix_settings_global] set [stg_value]='132' where stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        ob_flush();
    }
    if ($oldversion < 133) {
        modify_database("", "ALTER TABLE [prefix_users] ADD [one_time_pw] text");
        echo $modifyoutput;
        flush();
        ob_flush();
        // Add new assessment setting
        modify_database("", "ALTER TABLE [prefix_surveys] ADD [assessments] char(1) NOT NULL default 'N'");
        echo $modifyoutput;
        flush();
        ob_flush();
        // add new assessment value fields to answers & labels
        modify_database("", "ALTER TABLE [prefix_answers] ADD [assessment_value] int NOT NULL default '0'");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "ALTER TABLE [prefix_labels] ADD [assessment_value] int NOT NULL default '0'");
        echo $modifyoutput;
        flush();
        ob_flush();
        // copy any valid codes from code field to assessment field
        modify_database("", "update [prefix_answers] set [assessment_value]=CAST([code] as int)");
        // no output here is intended
        modify_database("", "update [prefix_labels] set [assessment_value]=CAST([code] as int)");
        // no output here is intended
        // activate assessment where assesment rules exist
        modify_database("", "update [prefix_surveys] set [assessments]='Y' where [sid] in (SELECT [sid] FROM [prefix_assessments] group by [sid])");
        echo $modifyoutput;
        flush();
        ob_flush();
        // add language field to assessment table
        modify_database("", "ALTER TABLE [prefix_assessments] ADD [language] varchar(20) NOT NULL default 'en'");
        echo $modifyoutput;
        flush();
        ob_flush();
        // update language field with default language of that particular survey
        modify_database("", "update [prefix_assessments] set [language]=(select [language] from [prefix_surveys] where [sid]=[prefix_assessments].[sid])");
        echo $modifyoutput;
        flush();
        ob_flush();
        // copy assessment link to message since from now on we will have HTML assignment messages
        modify_database("", "update [prefix_assessments] set [message]=cast([message] as varchar) +'<br /><a href=\"'+[link]+'\">'+[link]+'</a>'");
        echo $modifyoutput;
        flush();
        ob_flush();
        // drop the old link field
        modify_database("", "ALTER TABLE [prefix_assessments] DROP COLUMN [link]");
        echo $modifyoutput;
        flush();
        ob_flush();
        // change the primary index to include language
        mssql_drop_primary_index('assessments');
        // add the new primary key
        modify_database("", "ALTER TABLE [prefix_assessments] ADD CONSTRAINT pk_assessments_id_lang PRIMARY KEY ([id],[language])");
        echo $modifyoutput;
        flush();
        ob_flush();
        // Add new fields to survey language settings
        modify_database("", "ALTER TABLE [prefix_surveys_languagesettings] ADD [surveyls_url] varchar(255)");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "ALTER TABLE [prefix_surveys_languagesettings] ADD [surveyls_endtext] text");
        echo $modifyoutput;
        flush();
        ob_flush();
        // copy old URL fields ot language specific entries
        modify_database("", "update [prefix_surveys_languagesettings] set [surveyls_url]=(select [url] from [prefix_surveys] where [sid]=[prefix_surveys_languagesettings].[surveyls_survey_id])");
        echo $modifyoutput;
        flush();
        ob_flush();
        // drop old URL field
        mssql_drop_constraint('url', 'surveys');
        modify_database("", "ALTER TABLE [prefix_surveys] DROP COLUMN [url]");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "update [prefix_settings_global] set [stg_value]='133' where stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        ob_flush();
    }
    if ($oldversion < 134) {
        // Add new assessment setting
        modify_database("", "ALTER TABLE [prefix_surveys] ADD [usetokens] char(1) NOT NULL default 'N'");
        echo $modifyoutput;
        flush();
        ob_flush();
        mssql_drop_constraint('attribute1', 'surveys');
        mssql_drop_constraint('attribute2', 'surveys');
        modify_database("", "ALTER TABLE [prefix_surveys] ADD [attributedescriptions] TEXT;");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "ALTER TABLE [prefix_surveys] DROP COLUMN [attribute1]");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "ALTER TABLE [prefix_surveys] DROP COLUMN [attribute2]");
        echo $modifyoutput;
        flush();
        ob_flush();
        upgrade_token_tables134();
        modify_database("", "update [prefix_settings_global] set [stg_value]='134' where stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        ob_flush();
    }
    if ($oldversion < 135) {
        mssql_drop_constraint('value', 'question_attributes');
        modify_database("", "ALTER TABLE [prefix_question_attributes] ALTER COLUMN [value] text");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "ALTER TABLE [prefix_answers] ALTER COLUMN [answer] varchar(8000)");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "update [prefix_settings_global] set [stg_value]='135' where stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        ob_flush();
    }
    if ($oldversion < 136) {
        modify_database("", "ALTER TABLE[prefix_quota] ADD [autoload_url] int NOT NULL default '0'");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "CREATE TABLE [prefix_quota_languagesettings] (\r\n  \t\t\t\t\t\t\t[quotals_id] int NOT NULL IDENTITY (1,1),\r\n\t\t\t\t\t\t\t[quotals_quota_id] int,\r\n  \t\t\t\t\t\t\t[quotals_language] varchar(45) NOT NULL default 'en',\r\n  \t\t\t\t\t\t\t[quotals_name] varchar(255),\r\n  \t\t\t\t\t\t\t[quotals_message] text,\r\n  \t\t\t\t\t\t\t[quotals_url] varchar(255),\r\n  \t\t\t\t\t\t\t[quotals_urldescrip] varchar(255),\r\n  \t\t\t\t\t\t\tPRIMARY KEY ([quotals_id])\r\n\t\t\t\t\t\t\t);");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "update [prefix_settings_global] set [stg_value]='136' where stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        ob_flush();
    }
    if ($oldversion < 137) {
        modify_database("", "ALTER TABLE [prefix_surveys_languagesettings] ADD [surveyls_dateformat] int NOT NULL default '1'");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "ALTER TABLE [prefix_users] ADD [dateformat] int NOT NULL default '1'");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "update [prefix_surveys] set startdate=null where usestartdate='N'");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "update [prefix_surveys] set expires=null where useexpiry='N'");
        echo $modifyoutput;
        flush();
        ob_flush();
        mssql_drop_constraint('usestartdate', 'surveys');
        mssql_drop_constraint('useexpiry', 'surveys');
        modify_database("", "ALTER TABLE [prefix_surveys] DROP COLUMN usestartdate");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "ALTER TABLE [prefix_surveys] DROP COLUMN useexpiry");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "update [prefix_settings_global] set [stg_value]='137' where stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        ob_flush();
    }
    if ($oldversion < 138) {
        modify_database("", "ALTER TABLE [prefix_quota_members] ALTER COLUMN [code] VARCHAR(11) NULL");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "UPDATE [prefix_settings_global] SET [stg_value]='138' WHERE stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        ob_flush();
    }
    if ($oldversion < 139) {
        upgrade_survey_tables139();
        modify_database("", "UPDATE [prefix_settings_global] SET [stg_value]='139' WHERE stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        ob_flush();
    }
    if ($oldversion < 140) {
        modify_database("", "ALTER TABLE [prefix_surveys] ADD [emailresponseto] text");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "UPDATE [prefix_settings_global] SET [stg_value]='140' WHERE stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        ob_flush();
    }
    if ($oldversion < 141) {
        modify_database("", "ALTER TABLE [prefix_surveys] ADD [tokenlength] tinyint NOT NULL default '15'");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "UPDATE [prefix_settings_global] SET [stg_value]='141' WHERE stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        ob_flush();
    }
    if ($oldversion < 142) {
        upgrade_question_attributes142();
        modify_database("", "ALTER TABLE [prefix_surveys] ALTER COLUMN [startdate] datetime NULL");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "ALTER TABLE [prefix_surveys] ALTER COLUMN [expires] datetime NULL");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "UPDATE [prefix_question_attributes] SET [value]='0' WHERE cast([value] as varchar)='false'");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "UPDATE [prefix_question_attributes] SET [value]='1' WHERE cast([value] as varchar)='true'");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "UPDATE [prefix_settings_global] SET [stg_value]='142' WHERE stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        ob_flush();
    }
    if ($oldversion < 143) {
        modify_database("", "ALTER TABLE [prefix_questions] ADD parent_qid integer NOT NULL default '0'");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "ALTER TABLE [prefix_answers] ADD scale_id tinyint NOT NULL default '0'");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "ALTER TABLE [prefix_questions] ADD scale_id tinyint NOT NULL default '0'");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "ALTER TABLE [prefix_questions] ADD same_default tinyint NOT NULL default '0'");
        echo $modifyoutput;
        flush();
        ob_flush();
        mssql_drop_primary_index('answers');
        modify_database("", "ALTER TABLE [prefix_answers] ADD CONSTRAINT pk_answers_qcls PRIMARY KEY ([qid],[code],[language],[scale_id])");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "CREATE TABLE [prefix_defaultvalues] (\r\n                              [qid] integer NOT NULL default '0',\r\n                              [scale_id] tinyint NOT NULL default '0',\r\n                              [sqid] integer NOT NULL default '0',\r\n                              [language] varchar(20) NOT NULL,\r\n                              [specialtype] varchar(20) NOT NULL default '',\r\n                              [defaultvalue] text,\r\n                              CONSTRAINT pk_defaultvalues_qlss PRIMARY KEY ([qid] , [scale_id], [language], [specialtype], [sqid]))");
        echo $modifyoutput;
        flush();
        ob_flush();
        // -Move all 'answers' that are subquestions to the questions table
        // -Move all 'labels' that are answers to the answers table
        // -Transscribe the default values where applicable
        // -Move default values from answers to questions
        upgrade_tables143();
        mssql_drop_constraint('default_value', 'answers');
        modify_database("", "ALTER TABLE [prefix_answers] DROP COLUMN [default_value]");
        echo $modifyoutput;
        flush();
        ob_flush();
        mssql_drop_constraint('lid', 'questions');
        modify_database("", "ALTER TABLE [prefix_questions] DROP COLUMN lid");
        echo $modifyoutput;
        flush();
        ob_flush();
        mssql_drop_constraint('lid1', 'questions');
        modify_database("", "ALTER TABLE [prefix_questions] DROP COLUMN lid1");
        echo $modifyoutput;
        flush();
        ob_flush();
        // add field for timings and table for extended conditions
        modify_database("", "ALTER TABLE [prefix_surveys] ADD savetimings char(1) default 'N'");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "CREATE TABLE prefix_sessions(\r\n                              sesskey VARCHAR( 64 ) NOT NULL DEFAULT '',\r\n                              expiry DATETIME NOT NULL ,\r\n                              expireref VARCHAR( 250 ) DEFAULT '',\r\n                              created DATETIME NOT NULL ,\r\n                              modified DATETIME NOT NULL ,\r\n                              sessdata text,\r\n                              CONSTRAINT pk_sessions_sesskey PRIMARY KEY ( [sesskey] ))");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "create index [idx_expiry] on [prefix_sessions] ([expiry])");
        echo $modifyoutput;
        modify_database("", "create index [idx_expireref] on [prefix_sessions] ([expireref])");
        echo $modifyoutput;
        modify_database("", "UPDATE [prefix_settings_global] SET stg_value='143' WHERE stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        ob_flush();
    }
    if ($oldversion < 145) {
        modify_database("", "ALTER TABLE [prefix_surveys] ADD showxquestions CHAR(1) NULL default 'Y'");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "ALTER TABLE [prefix_surveys] ADD showgroupinfo CHAR(1) NULL default 'B'");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "ALTER TABLE [prefix_surveys] ADD shownoanswer CHAR(1) NULL default 'Y'");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "ALTER TABLE [prefix_surveys] ADD showqnumcode CHAR(1) NULL default 'X'");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "ALTER TABLE [prefix_surveys] ADD bouncetime BIGINT NULL");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "ALTER TABLE [prefix_surveys] ADD bounceprocessing VARCHAR(1) NULL default 'N'");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "ALTER TABLE [prefix_surveys] ADD bounceaccounttype VARCHAR(4) NULL");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "ALTER TABLE [prefix_surveys] ADD bounceaccounthost VARCHAR(200) NULL ");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "ALTER TABLE [prefix_surveys] ADD bounceaccountpass VARCHAR(100) NULL");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "ALTER TABLE [prefix_surveys] ADD bounceaccountencryption VARCHAR(3) NULL");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "ALTER TABLE [prefix_surveys] ADD bounceaccountuser VARCHAR(200) NULL");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "ALTER TABLE [prefix_surveys] ADD showwelcome CHAR(1) NULL default 'Y'");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "ALTER TABLE [prefix_surveys] ADD showprogress CHAR(1) NULL default 'Y'");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "ALTER TABLE [prefix_surveys] ADD allowjumps CHAR(1) NULL default 'N'");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "ALTER TABLE [prefix_surveys] ADD navigationdelay tinyint NOT NULL default '0'");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "ALTER TABLE [prefix_surveys] ADD nokeyboard CHAR(1) NULL default 'N'");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "ALTER TABLE [prefix_surveys] ADD alloweditaftercompletion CHAR(1) NULL default 'N'");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "CREATE TABLE [prefix_survey_permissions] (\r\n                            [sid] INT NOT NULL,\r\n                            [uid] INT NOT NULL,\r\n                            [permission] VARCHAR(20) NOT NULL,\r\n                            [create_p] TINYINT NOT NULL default '0',\r\n                            [read_p] TINYINT NOT NULL default '0',\r\n                            [update_p] TINYINT NOT NULL default '0',\r\n                            [delete_p] TINYINT NOT NULL default '0',\r\n                            [import_p] TINYINT NOT NULL default '0',\r\n                            [export_p] TINYINT NOT NULL default '0',\r\n                            PRIMARY KEY ([sid], [uid],[permission])\r\n                        );");
        echo $modifyoutput;
        flush();
        ob_flush();
        upgrade_surveypermissions_table145();
        modify_database("", "DROP TABLE [prefix_surveys_rights]");
        echo $modifyoutput;
        flush();
        ob_flush();
        // Add new fields for email templates
        modify_database("", "ALTER TABLE prefix_surveys_languagesettings ADD\r\n                              email_admin_notification_subj  VARCHAR(255) NULL,\r\n                              email_admin_notification TEXT NULL,\r\n                              email_admin_responses_subj VARCHAR(255) NULL,\r\n                              email_admin_responses TEXT NULL");
        //Add index to questions table to speed up subquestions
        modify_database("", "create index [parent_qid_idx] on [prefix_questions] ([parent_qid])");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "ALTER TABLE prefix_surveys ADD emailnotificationto text DEFAULT NULL");
        echo $modifyoutput;
        flush();
        ob_flush();
        upgrade_survey_table145();
        mssql_drop_constraint('notification', 'surveys');
        modify_database("", "ALTER TABLE [prefix_surveys] DROP COLUMN [notification]");
        echo $modifyoutput;
        flush();
        ob_flush();
        // modify length of method in conditions
        modify_database("", "ALTER TABLE [prefix_conditions] ALTER COLUMN [method] CHAR( 5 ) NOT NULL");
        echo $modifyoutput;
        flush();
        ob_flush();
        //Add index to questions table to speed up subquestions
        modify_database("", "create index [parent_qid] on [prefix_questions] ([parent_qid])");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "UPDATE prefix_surveys set [private]='N' where [private] is NULL;");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "EXEC sp_rename 'prefix_surveys.private','anonymized'");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "ALTER TABLE [prefix_surveys] ALTER COLUMN [anonymized] char(1) NOT NULL;");
        echo $modifyoutput;
        flush();
        ob_flush();
        mssql_drop_constraint('anonymized', 'surveys');
        modify_database("", "ALTER TABLE [prefix_surveys] ADD CONSTRAINT DF_surveys_anonymized DEFAULT 'N' FOR [anonymized];");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "CREATE TABLE [prefix_failed_login_attempts] (\r\n                              [id] INT NOT NULL IDENTITY (1,1) PRIMARY KEY,\r\n                              [ip] varchar(37) NOT NULL,\r\n                              [last_attempt] varchar(20) NOT NULL,\r\n                              [number_attempts] int NOT NULL );");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "ALTER TABLE  [prefix_surveys_languagesettings] ADD  [surveyls_numberformat] INT default 0 NOT NULL");
        echo $modifyoutput;
        flush();
        ob_flush();
        upgrade_token_tables145();
        modify_database("", "UPDATE [prefix_settings_global] SET stg_value='145' WHERE stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        ob_flush();
    }
    if ($oldversion < 146) {
        upgrade_timing_tables146();
        modify_database("", "INSERT into [prefix_survey_permissions] (sid,uid,permission,read_p,update_p) SELECT sid,owner_id,'translations','1','1' from [prefix_surveys]");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "UPDATE [prefix_settings_global] SET stg_value='146' WHERE stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        ob_flush();
    }
    if ($oldversion < 147) {
        modify_database("", "ALTER TABLE [prefix_users] ADD templateeditormode VARCHAR(7) NOT NULL default 'default'");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "ALTER TABLE [prefix_users] ADD questionselectormode VARCHAR(7) NOT NULL default 'default'");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "UPDATE [prefix_settings_global] SET stg_value='147' WHERE stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        ob_flush();
    }
    if ($oldversion < 148) {
        modify_database("", "CREATE TABLE [prefix_participants] (\r\n            [participant_id] varchar(50) NOT NULL,\r\n            [firstname] varchar(40) NOT NULL,\r\n            [lastname] varchar(40) NOT NULL,\r\n            [email] varchar(80) NOT NULL,\r\n            [language] varchar(2) NOT NULL,\r\n            [blacklisted] varchar(1) NOT NULL,\r\n            [owner_uid] int(20) NOT NULL,\r\n            PRIMARY KEY  ([participant_id])\r\n            );");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "CREATE TABLE [prefix_participant_attribute] (\r\n            [participant_id] varchar(50) NOT NULL,\r\n            [attribute_id] int(11) NOT NULL,\r\n            [value] varchar(50) NOT NULL,\r\n            PRIMARY KEY  ([participant_id],[attribute_id])\r\n            );");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "CREATE TABLE [prefix_participant_attribute_names] (\r\n            [attribute_id] int(11) NOT NULL AUTO_INCREMENT,\r\n            [attribute_type] varchar(4) NOT NULL,\r\n            [visible] char(5) NOT NULL,\r\n            PRIMARY KEY  ([attribute_id],[attribute_type])\r\n            );");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "CREATE TABLE [prefix_participant_attribute_names_lang] (\r\n            [attribute_id] int(11) NOT NULL,\r\n            [attribute_name] varchar(30) NOT NULL,\r\n            [lang] varchar(20) NOT NULL,\r\n            PRIMARY KEY  ([attribute_id],[lang])\r\n            );");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "CREATE TABLE [prefix_participant_attribute_values] (\r\n            [attribute_id] int(11) NOT NULL,\r\n            [value_id] int(11) NOT NULL AUTO_INCREMENT,\r\n            [value] varchar(20) NOT NULL,\r\n            PRIMARY KEY  ([value_id])\r\n            );");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "CREATE TABLE [prefix_participant_shares] (\r\n            [participant_id] varchar(50) NOT NULL,\r\n            [share_uid] int(11) NOT NULL,\r\n            [date_added] datetime,\r\n            [can_edit] text NOT NULL,\r\n            PRIMARY KEY  ([participant_id],[share_uid])\r\n            );");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "CREATE TABLE [prefix_survey_links] (\r\n            [participant_id] varchar(50) NOT NULL,\r\n            [token_id] int(11) NOT NULL,\r\n            [survey_id] int(11) NOT NULL,\r\n            [date_created] datetime,\r\n            PRIMARY KEY  ([participant_id],[token_id],[survey_id])\r\n            );");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "ALTER TABLE [prefix_users] ADD [participant_panel] int NOT NULL default '0'");
        echo $modifyoutput;
        flush();
        ob_flush();
        // Add language field to question_attributes table
        modify_database("", "ALTER TABLE [prefix_question_attributes] ADD [language] varchar(20)");
        echo $modifyoutput;
        flush();
        ob_flush();
        upgrade_question_attributes148();
        fixSubquestions();
        modify_database("", "UPDATE [prefix_settings_global] SET stg_value='148' WHERE stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        ob_flush();
    }
    if ($oldversion < 149) {
        modify_database("", "CREATE TABLE [prefix_survey_url_parameters] (\r\n        [id] int(9) NOT NULL AUTO_INCREMENT,\r\n        [sid] int(10) NOT NULL,\r\n        [parameter] varchar(50) NOT NULL,\r\n        [targetqid] int(10) NULL,\r\n        [targetsqid] int(10) NULL,\r\n        PRIMARY KEY ([id])\r\n        );");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "UPDATE [prefix_settings_global] SET stg_value='149' WHERE stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        ob_flush();
    }
    if ($oldversion < 150) {
        modify_database("", "ALTER TABLE [prefix_questions] ADD [relevance] TEXT;");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "UPDATE [prefix_settings_global] SET stg_value='150' WHERE stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        ob_flush();
    }
    if ($oldversion < 151) {
        modify_database("", "ALTER TABLE [prefix_groups] ADD [randomization_group] VARCHAR(20) NOT NULL DEFAULT '';");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "UPDATE [prefix_settings_global] SET stg_value='151' WHERE stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        ob_flush();
    }
    if ($oldversion < 152) {
        modify_database("", "CREATE INDEX [question_attributes_idx3] ON [prefix_question_attributes] ([attribute]);");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "UPDATE [prefix_settings_global] SET stg_value='152' WHERE stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        ob_flush();
    }
    if ($oldversion < 153) {
        modify_database("", "CREATE TABLE [prefix_expression_errors] (\r\n        [id] integer NOT NULL AUTO_INCREMENT,\r\n        [errortime] varchar(50) DEFAULT NULL,\r\n        [sid] integer DEFAULT NULL,\r\n        [gid] integer DEFAULT NULL,\r\n        [qid] integer DEFAULT NULL,\r\n        [gseq] integer DEFAULT NULL,\r\n        [qseq] integer DEFAULT NULL,\r\n        [type] varchar(50) ,\r\n        [eqn] text,\r\n        [prettyprint] text,\r\n        PRIMARY KEY ([id])\r\n        );");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "UPDATE [prefix_settings_global] SET stg_value='153' WHERE stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        ob_flush();
    }
    if ($oldversion < 154) {
        modify_database("", "ALTER TABLE [prefix_groups] ADD [grelevance] text DEFAULT NULL;");
        echo $modifyoutput;
        flush();
        @ob_flush();
        LimeExpressionManager::UpgradeConditionsToRelevance();
        modify_database("", "UPDATE [prefix_settings_global] SET stg_value='154' WHERE stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        ob_flush();
    }
    if ($oldversion < 155) {
        modify_database("", "ALTER TABLE [prefix_surveys] ADD [googleanalyticsstyle] char(1) DEFAULT NULL;");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE [prefix_surveys] ADD [googleanalyticsapikey] varchar(25) DEFAULT NULL;");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "EXEC sp_rename 'prefix_surveys.showXquestions','showxquestions'");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "UPDATE [prefix_settings_global] SET stg_value='155' WHERE stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        ob_flush();
    }
    echo '<br /><br />' . sprintf($clang->gT('Database update finished (%s)'), date('Y-m-d H:i:s')) . '<br />';
    return true;
}
Exemplo n.º 22
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");
 }
Exemplo n.º 23
0
function db_upgrade($oldversion)
{
    global $modifyoutput, $databasename, $databasetabletype, $clang;
    if ($oldversion < 127) {
        modify_database("", "create index answers_idx2 on prefix_answers (sortorder)");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "create index assessments_idx2 on prefix_assessments (sid)");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "create index assessments_idx on prefix_assessments (gid)");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "create index conditions_idx2 on prefix_conditions (qid)");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "create index conditions_idx3 on prefix_conditions (cqid)");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "create index groups_idx2 on prefix_groups (sid)");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "create index question_attributes_idx2 on prefix_question_attributes (qid)");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "create index questions_idx2 on prefix_questions (sid)");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "create index questions_idx3 on prefix_questions (gid)");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "create index questions_idx4 on prefix_questions (type)");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "create index quota_idx2 on prefix_quota (sid)");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "create index saved_control_idx2 on prefix_saved_control (sid)");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "create index user_in_groups_idx1 on prefix_user_in_groups (ugid, uid)");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "update prefix_settings_global set stg_value='127' where stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        ob_flush();
    }
    if ($oldversion < 128) {
        //128
        upgrade_token_tables128();
        modify_database("", "update prefix_settings_global set stg_value='128' where stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        ob_flush();
    }
    if ($oldversion < 129) {
        //129
        modify_database("", "ALTER TABLE prefix_surveys ADD startdate date");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "ALTER TABLE prefix_surveys ADD usestartdate char(1) NOT NULL default 'N'");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "update prefix_settings_global set stg_value='129' where stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        ob_flush();
    }
    if ($oldversion < 130) {
        modify_database("", "ALTER TABLE prefix_conditions ADD scenario integer NOT NULL default '1'");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "UPDATE prefix_conditions SET scenario=1 where (scenario is null) or scenario=0");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "update prefix_settings_global set stg_value='130' where stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        ob_flush();
    }
    if ($oldversion < 131) {
        modify_database("", "ALTER TABLE prefix_surveys ADD publicstatistics char(1) NOT NULL default 'N'");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "update prefix_settings_global set stg_value='131' where stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        ob_flush();
    }
    if ($oldversion < 132) {
        modify_database("", "ALTER TABLE prefix_surveys ADD publicgraphs char(1) NOT NULL default 'N'");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "update prefix_settings_global set stg_value='132' where stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        ob_flush();
    }
    if ($oldversion < 133) {
        modify_database("", "ALTER TABLE prefix_users ADD one_time_pw bytea");
        echo $modifyoutput;
        flush();
        ob_flush();
        // Add new assessment setting
        modify_database("", "ALTER TABLE prefix_surveys ADD assessments char(1) NOT NULL default 'N'");
        echo $modifyoutput;
        flush();
        ob_flush();
        // add new assessment value fields to answers & labels
        modify_database("", "ALTER TABLE prefix_answers ADD assessment_value integer NOT NULL default '0'");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "ALTER TABLE prefix_labels ADD assessment_value integer NOT NULL default '0'");
        echo $modifyoutput;
        flush();
        ob_flush();
        // copy any valid codes from code field to assessment field
        modify_database("", "update [prefix_answers set assessment_value=CAST(code as integer)");
        // no output here is intended
        modify_database("", "update prefix_labels set assessment_value=CAST(code as integer)");
        // no output here is intended
        // activate assessment where assesment rules exist
        modify_database("", "update prefix_surveys set assessments='Y' where sid in (SELECT sid FROM prefix_assessments group by sid)");
        echo $modifyoutput;
        flush();
        ob_flush();
        // add language field to assessment table
        modify_database("", "ALTER TABLE prefix_assessments ADD language character varying(20) NOT NULL default 'en'");
        echo $modifyoutput;
        flush();
        ob_flush();
        // update language field with default language of that particular survey
        modify_database("", "update prefix_assessments set language=(select language from prefix_surveys where sid=prefix_assessments.sid)");
        echo $modifyoutput;
        flush();
        ob_flush();
        // copy assessment link to message since from now on we will have HTML assignment messages
        modify_database("", "update prefix_assessments set message=cast(message as character) ||'<br /><a href=\"'||link||'\">'||link||'</a>'");
        echo $modifyoutput;
        flush();
        ob_flush();
        // drop the old link field
        modify_database("", "ALTER TABLE prefix_assessments DROP COLUMN link");
        echo $modifyoutput;
        flush();
        ob_flush();
        // change the primary index to include language
        modify_database("", "ALTER TABLE prefix_assessments DROP CONSTRAINT prefix_assessments_pkey");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "ALTER TABLE prefix_assessments ADD CONSTRAINT prefix_assessments_pkey PRIMARY KEY (id,language)");
        echo $modifyoutput;
        flush();
        ob_flush();
        // Add new fields to survey language settings
        modify_database("", "ALTER TABLE prefix_surveys_languagesettings ADD surveyls_url character varying(255)");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "ALTER TABLE prefix_surveys_languagesettings ADD surveyls_endtext text");
        echo $modifyoutput;
        flush();
        ob_flush();
        // copy old URL fields ot language specific entries
        modify_database("", "update prefix_surveys_languagesettings set surveyls_url=(select url from prefix_surveys where sid=prefix_surveys_languagesettings.surveyls_survey_id)");
        echo $modifyoutput;
        flush();
        ob_flush();
        // drop old URL field
        modify_database("", "ALTER TABLE prefix_surveys DROP COLUMN url");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "update prefix_settings_global set stg_value='133' where stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        ob_flush();
    }
    if ($oldversion < 134) {
        modify_database("", "ALTER TABLE prefix_surveys ADD usetokens char(1) NOT NULL default 'N'");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "ALTER TABLE prefix_surveys ADD attributedescriptions TEXT;");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "ALTER TABLE prefix_surveys DROP COLUMN attribute1");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "ALTER TABLE prefix_surveys DROP COLUMN attribute2");
        echo $modifyoutput;
        flush();
        ob_flush();
        upgrade_token_tables134();
        modify_database("", "update prefix_settings_global set stg_value='134' where stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        ob_flush();
    }
    if ($oldversion < 135) {
        modify_database("", "ALTER TABLE prefix_question_attributes ALTER COLUMN value TYPE text");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "update prefix_settings_global set stg_value='135' where stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        ob_flush();
    }
    if ($oldversion < 136) {
        modify_database("", "ALTER TABLE prefix_quota ADD autoload_url integer NOT NULL DEFAULT 0");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "CREATE TABLE prefix_quota_languagesettings (\r\n                            quotals_id serial NOT NULL,\r\n                            quotals_quota_id integer NOT NULL DEFAULT 0,\r\n                            quotals_language character varying(45) NOT NULL DEFAULT 'en'::character varying,\r\n                            quotals_name character varying(200),\r\n                            quotals_message text NOT NULL,\r\n                            quotals_url character varying(255),\r\n                            quotals_urldescrip character varying(255));");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "ALTER TABLE ONLY prefix_quota_languagesettings\r\n  \t   \t\t\t\t\t   ADD CONSTRAINT prefix_quota_languagesettings_pkey PRIMARY KEY (quotals_id);");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "ALTER TABLE ONLY prefix_users ADD CONSTRAINT prefix_users_pkey PRIMARY KEY (uid)");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "ALTER TABLE ONLY prefix_users ADD CONSTRAINT prefix_user_name_key UNIQUE (users_name)");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "update prefix_settings_global set stg_value='136' where stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        ob_flush();
    }
    if ($oldversion < 137) {
        modify_database("", "ALTER TABLE prefix_surveys_languagesettings ADD surveyls_dateformat integer NOT NULL default 1");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "ALTER TABLE prefix_users ADD \"dateformat\" integer NOT NULL default 1");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "update prefix_surveys set startdate=null where usestartdate='N'");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "update prefix_surveys set expires=null where useexpiry='N'");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "ALTER TABLE prefix_surveys DROP COLUMN usestartdate");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "ALTER TABLE prefix_surveys DROP COLUMN useexpiry");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "update prefix_settings_global set stg_value='137' where stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        ob_flush();
    }
    if ($oldversion < 138) {
        modify_database("", "ALTER TABLE prefix_quota_members ALTER COLUMN code TYPE character varying(11)");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "UPDATE prefix_settings_global SET stg_value='138' WHERE stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        ob_flush();
    }
    if ($oldversion < 139) {
        upgrade_survey_tables139();
        modify_database("", "UPDATE prefix_settings_global SET stg_value='139' WHERE stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        ob_flush();
    }
    if ($oldversion < 140) {
        modify_database("", "ALTER TABLE prefix_surveys ADD \"emailresponseto\" TEXT");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "UPDATE prefix_settings_global SET stg_value='140' WHERE stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        ob_flush();
    }
    if ($oldversion < 141) {
        modify_database("", "ALTER TABLE prefix_surveys ADD \"tokenlength\" smallint NOT NULL DEFAULT '15'");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "UPDATE prefix_settings_global SET stg_value='141' WHERE stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        ob_flush();
    }
    if ($oldversion < 142) {
        upgrade_question_attributes142();
        modify_database("", "ALTER TABLE prefix_surveys ALTER COLUMN \"startdate\" TYPE timestamp");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "ALTER TABLE prefix_surveys ALTER COLUMN \"expires\" TYPE timestamp");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "UPDATE prefix_question_attributes SET value='0' WHERE value='false'");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "UPDATE prefix_question_attributes SET value='1' WHERE value='true'");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "UPDATE prefix_settings_global SET stg_value='142' WHERE stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        ob_flush();
    }
    if ($oldversion < 143) {
        modify_database("", "ALTER TABLE prefix_questions ADD parent_qid integer NOT NULL default '0'");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "ALTER TABLE prefix_answers ADD scale_id smallint NOT NULL default '0'");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "ALTER TABLE prefix_questions ADD scale_id smallint NOT NULL default '0'");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "ALTER TABLE prefix_questions ADD same_default smallint NOT NULL default '0'");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "ALTER TABLE prefix_answers DROP CONSTRAINT prefix_answers_pkey");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "ALTER TABLE prefix_answers ADD CONSTRAINT prefix_answers_pkey PRIMARY KEY (qid,code,language,scale_id)");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "CREATE TABLE prefix_defaultvalues (\r\n                              qid integer NOT NULL default '0',\r\n                              scale_id integer NOT NULL default '0',\r\n                              sqid integer NOT NULL default '0',\r\n                              language character varying(20) NOT NULL,\r\n                              specialtype character varying(20) NOT NULL default '',\r\n                              defaultvalue text)");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "ALTER TABLE prefix_defaultvalues ADD CONSTRAINT prefix_defaultvalues_pkey PRIMARY KEY (qid , scale_id, language, specialtype, sqid)");
        echo $modifyoutput;
        flush();
        ob_flush();
        // -Move all 'answers' that are subquestions to the questions table
        // -Move all 'labels' that are answers to the answers table
        // -Transscribe the default values where applicable
        // -Move default values from answers to questions
        upgrade_tables143();
        modify_database("", "ALTER TABLE prefix_answers DROP COLUMN default_value");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "ALTER TABLE prefix_questions DROP COLUMN lid");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "ALTER TABLE prefix_questions DROP COLUMN lid1");
        echo $modifyoutput;
        flush();
        ob_flush();
        // add field for timings and table for extended conditions
        modify_database("", "ALTER TABLE prefix_surveys ADD savetimings char(1) default 'N'");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "CREATE TABLE prefix_sessions(\r\n                             sesskey VARCHAR( 64 ) NOT NULL DEFAULT '',\r\n                             expiry TIMESTAMP NOT NULL ,\r\n                             expireref VARCHAR( 250 ) DEFAULT '',\r\n                             created TIMESTAMP NOT NULL ,\r\n                             modified TIMESTAMP NOT NULL ,\r\n                             sessdata TEXT DEFAULT '',\r\n                             PRIMARY KEY ( sesskey )\r\n                             );");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "create INDEX sess2_expiry on prefix_sessions( expiry );");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "create INDEX sess2_expireref on prefix_sessions ( expireref );");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "UPDATE prefix_settings_global SET stg_value='143' WHERE stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        ob_flush();
    }
    if ($oldversion < 145) {
        modify_database("", "ALTER TABLE prefix_surveys ADD savetimings CHAR(1) NULL default 'N'");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "ALTER TABLE prefix_surveys ADD showxquestions CHAR(1) NULL default 'Y'");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "ALTER TABLE prefix_surveys ADD showgroupinfo CHAR(1) NULL default 'B'");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "ALTER TABLE prefix_surveys ADD shownoanswer CHAR(1) NULL default 'Y'");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "ALTER TABLE prefix_surveys ADD showqnumcode CHAR(1) NULL default 'X'");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "ALTER TABLE prefix_surveys ADD bouncetime bigint NULL");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "ALTER TABLE prefix_surveys ADD bounceprocessing character varying(1) NULL default 'N'");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "ALTER TABLE prefix_surveys ADD bounceaccounttype character varying(4) NULL");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "ALTER TABLE prefix_surveys ADD bounceaccounthost character varying(200) NULL");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "ALTER TABLE prefix_surveys ADD bounceaccountpass character varying(100) NULL");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "ALTER TABLE prefix_surveys ADD bounceaccountencryption character varying(3) NULL");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "ALTER TABLE prefix_surveys ADD bounceaccountuser character varying(200) NULL");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "ALTER TABLE prefix_surveys ADD showwelcome CHAR(1) NULL default 'Y'");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "ALTER TABLE prefix_surveys ADD showprogress CHAR(1) NULL default 'Y'");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "ALTER TABLE prefix_surveys ADD allowjumps CHAR(1) NULL default 'N'");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "ALTER TABLE prefix_surveys ADD navigationdelay smallint NOT NULL default '0'");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "ALTER TABLE prefix_surveys ADD nokeyboard char(1) default 'N'");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "ALTER TABLE prefix_surveys ADD alloweditaftercompletion char(1) default 'N'");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "CREATE TABLE prefix_survey_permissions (\r\n                            sid integer DEFAULT 0 NOT NULL,\r\n                            uid integer DEFAULT 0 NOT NULL,\r\n                            permission character varying(20) NOT NULL,\r\n                            create_p integer DEFAULT 0 NOT NULL,\r\n                            read_p integer DEFAULT 0 NOT NULL,\r\n                            update_p integer DEFAULT 0 NOT NULL,\r\n                            delete_p integer DEFAULT 0 NOT NULL,\r\n                            import_p integer DEFAULT 0 NOT NULL,\r\n                            export_p integer DEFAULT 0 NOT NULL\r\n                        );");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "ALTER TABLE ONLY prefix_survey_permissions ADD CONSTRAINT prefix_survey_permissions_pkey PRIMARY KEY (sid,uid,permission);");
        echo $modifyoutput;
        flush();
        ob_flush();
        upgrade_surveypermissions_table145();
        // drop the old survey rights table
        modify_database("", "DROP TABLE prefix_surveys_rights");
        echo $modifyoutput;
        flush();
        ob_flush();
        // Add new fields for email templates
        modify_database("", "ALTER TABLE prefix_surveys_languagesettings ADD email_admin_notification_subj character varying(255)");
        modify_database("", "ALTER TABLE prefix_surveys_languagesettings ADD email_admin_responses_subj character varying(255)");
        modify_database("", "ALTER TABLE prefix_surveys_languagesettings ADD email_admin_notification text");
        modify_database("", "ALTER TABLE prefix_surveys_languagesettings ADD email_admin_responses text");
        //Add index to questions table to speed up subquestions
        modify_database("", "create INDEX parent_qid_idx on prefix_questions( parent_qid );");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "ALTER TABLE prefix_surveys ADD emailnotificationto text DEFAULT NULL");
        echo $modifyoutput;
        flush();
        ob_flush();
        upgrade_survey_table145();
        modify_database("", "ALTER TABLE prefix_surveys DROP COLUMN notification");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "ALTER TABLE prefix_conditions ALTER COLUMN method TYPE CHAR(5)");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "UPDATE prefix_surveys set private='N' where private is NULL;");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "ALTER TABLE prefix_surveys RENAME COLUMN private TO anonymized;");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "ALTER TABLE prefix_surveys ALTER COLUMN anonymized TYPE char(1);");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "ALTER TABLE prefix_surveys ALTER COLUMN anonymized SET DEFAULT 'N';");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "ALTER TABLE prefix_surveys ALTER COLUMN anonymized SET NOT NULL ;");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "CREATE TABLE prefix_failed_login_attempts (\r\n                                  id serial PRIMARY KEY NOT NULL,\r\n                                  ip character varying(37) NOT NULL,\r\n                                  last_attempt character varying(20) NOT NULL,\r\n                                  number_attempts integer NOT NULL\r\n                                );");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "ALTER TABLE  prefix_surveys_languagesettings ADD surveyls_numberformat integer default 0 NOT NULL");
        echo $modifyoutput;
        flush();
        ob_flush();
        upgrade_token_tables145();
        modify_database("", "UPDATE prefix_settings_global SET stg_value='145' WHERE stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        ob_flush();
    }
    if ($oldversion < 146) {
        upgrade_timing_tables146();
        modify_database("", "INSERT into prefix_survey_permissions (sid,uid,permission,read_p,update_p) SELECT sid,owner_id,'translations','1','1' from prefix_surveys");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "UPDATE prefix_settings_global SET stg_value='146' WHERE stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        ob_flush();
    }
    if ($oldversion < 147) {
        modify_database("", "ALTER TABLE prefix_users ADD templateeditormode character varying(7) NOT NULL DEFAULT 'default'");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "ALTER TABLE prefix_users ADD questionselectormode character varying(7) NOT NULL DEFAULT 'default'");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "UPDATE prefix_settings_global SET stg_value='147' WHERE stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        ob_flush();
    }
    if ($oldversion < 148) {
        modify_database("", "CREATE TABLE prefix_participants (\r\n        participant_id VARCHAR( 50 ) NOT NULL,\r\n        firstname VARCHAR( 40 ) NOT NULL,\r\n        lastname VARCHAR( 40 ) NOT NULL,\r\n        email VARCHAR( 80 ) NOT NULL,\r\n        language VARCHAR( 2 ) NOT NULL,\r\n        blacklisted VARCHAR( 1 ) NOT NULL,\r\n        owner_uid integer NOT NULL,\r\n        PRIMARY KEY (participant_id)\r\n        );");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "CREATE TABLE prefix_participant_attribute (\r\n        participant_id VARCHAR( 50 ) NOT NULL,\r\n        attribute_id integer NOT NULL,\r\n        value integer NOT NULL,\r\n        PRIMARY KEY (participant_id,attribute_id)\r\n        );");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "CREATE TABLE prefix_participant_attribute_names (\r\n        attribute_id integer NOT NULL AUTO_INCREMENT,\r\n        attribute_type VARCHAR( 30 ) NOT NULL,\r\n        visible CHAR( 5 ) NOT NULL,\r\n        PRIMARY KEY (attribute_type,attribute_id)\r\n        );");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "CREATE TABLE prefix_participant_attribute_names_lang (\r\n        id integer NOT NULL AUTO_INCREMENT,\r\n        attribute_id integer NOT NULL,\r\n        attribute_name VARCHAR( 30 ) NOT NULL,\r\n        lang CHAR( 20 ) NOT NULL,\r\n        PRIMARY KEY (lang,attribute_id)\r\n        );");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "CREATE TABLE prefix_participant_attribute_values (\r\n        attribute_id integer NOT NULL,\r\n        value_id integer NOT NULL AUTO_INCREMENT,\r\n        value VARCHAR( 20 ) NOT NULL,\r\n        PRIMARY KEY (value_id)\r\n        );");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "CREATE TABLE prefix_participant_shares (\r\n        participant_id VARCHAR( 50 ) NOT NULL,\r\n        shared_uid integer NOT NULL,\r\n        date_added date NOT NULL,\r\n        can_edit VARCHAR( 5 ) NOT NULL,\r\n        PRIMARY KEY (lang,attribute_id)\r\n        );");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "CREATE TABLE prefix_survey_links (\r\n        participant_id VARCHAR( 50 ) NOT NULL,\r\n        token_id integer NOT NULL,\r\n        survey_id integer NOT NULL,\r\n        date_created date NOT NULL,\r\n        PRIMARY KEY (participant_id,token_id,survey_id)\r\n        );");
        echo $modifyoutput;
        flush();
        ob_flush();
        modify_database("", "ALTER TABLE prefix_user ADD participant_panel integer NOT NULL default '0'");
        echo $modifyoutput;
        flush();
        ob_flush();
        // add language field to question_attributes table
        modify_database("", "ALTER TABLE prefix_question_attributes ADD language character varying(20)");
        echo $modifyoutput;
        flush();
        ob_flush();
        upgrade_question_attributes148();
        fixSubquestions();
        modify_database("", "UPDATE prefix_settings_global SET stg_value='148' WHERE stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        ob_flush();
    }
    if ($oldversion < 149) {
        modify_database("", "CREATE TABLE prefix_survey_url_parameters (\r\n        id serial PRIMARY KEY NOT NULL,\r\n        sid integer NOT NULL,\r\n        parameter character varying(50) NOT NULL,\r\n        targetqid integer NULL,\r\n        targetsqid integer NULL\r\n        );");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "UPDATE prefix_settings_global SET stg_value='149' WHERE stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        ob_flush();
    }
    if ($oldversion < 150) {
        modify_database("", "ALTER TABLE prefix_questions ADD relevance TEXT;");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "UPDATE prefix_settings_global SET stg_value='150' WHERE stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        ob_flush();
    }
    if ($oldversion < 151) {
        modify_database("", "ALTER TABLE prefix_groups ADD randomization_group varying(20) NOT NULL DEFAULT '';");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "UPDATE prefix_settings_global SET stg_value='151' WHERE stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        ob_flush();
    }
    if ($oldversion < 152) {
        modify_database("", "CREATE INDEX question_attributes_idx3 ON prefix_question_attributes (attribute);");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "UPDATE prefix_settings_global SET stg_value='152' WHERE stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        ob_flush();
    }
    if ($oldversion < 153) {
        modify_database("", "CREATE TABLE prefix_expression_errors (\r\n        id integer NOT NULL AUTO_INCREMENT,\r\n        errortime varchar(50) DEFAULT NULL,\r\n        sid integer DEFAULT NULL,\r\n        gid integer DEFAULT NULL,\r\n        qid integer DEFAULT NULL,\r\n        gseq integer DEFAULT NULL,\r\n        qseq integer DEFAULT NULL,\r\n        \"type\" character varying(50) ,\r\n        eqn text,\r\n        prettyprint text,\r\n        CONSTRAINT prefix_expression_errors_pkey PRIMARY KEY (id)\r\n        );");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "UPDATE prefix_settings_global SET stg_value='153' WHERE stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        ob_flush();
    }
    if ($oldversion < 154) {
        modify_database("", "ALTER TABLE prefix_groups ADD grelevance text DEFAULT NULL;");
        echo $modifyoutput;
        flush();
        @ob_flush();
        LimeExpressionManager::UpgradeConditionsToRelevance();
        modify_database("", "UPDATE prefix_settings_global SET stg_value='154' WHERE stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        ob_flush();
    }
    if ($oldversion < 155) {
        modify_database("", "ALTER TABLE prefix_surveys ADD googleanalyticsstyle char(1) DEFAULT NULL;");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE prefix_surveys ADD googleanalyticsapikey character varying(25) DEFAULT NULL;");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "ALTER TABLE prefix_surveys RENAME COLUMN showXquestions TO showxquestions;");
        echo $modifyoutput;
        flush();
        @ob_flush();
        modify_database("", "UPDATE prefix_settings_global SET stg_value='155' WHERE stg_name='DBVersion'");
        echo $modifyoutput;
        flush();
        ob_flush();
    }
    fixLanguageConsistencyAllSurveys();
    echo '<br /><br />' . sprintf($clang->gT('Database update finished (%s)'), date('Y-m-d H:i:s')) . '<br />';
    return true;
}