Example #1
0
function upgrade_question_attributes148()
{
    global $modifyoutput, $dbprefix;
    $sDBPrefix = $dbprefix;
    $sSurveyQuery = "SELECT sid FROM {$sDBPrefix}surveys";
    $oSurveyResult = db_execute_assoc($sSurveyQuery);
    foreach ($oSurveyResult->FetchRow() as $aSurveyRow) {
        $surveyid = $aSurveyRow['sid'];
        $languages = array_merge(array(GetBaseLanguageFromSurveyID($surveyid)), GetAdditionalLanguagesFromSurveyID($surveyid));
        $sAttributeQuery = "select q.qid,attribute,value from {$sDBPrefix}question_attributes qa , {$sDBPrefix}questions q where q.qid=qa.qid and sid={$surveyid}";
        $oAttributeResult = db_execute_assoc($sAttributeQuery);
        $aAllAttributes = questionAttributes(true);
        foreach ($oAttributeResult->FetchRow() as $aAttributeRow) {
            if (isset($aAllAttributes[$aAttributeRow['attribute']]['i18n']) && $aAllAttributes[$aAttributeRow['attribute']]['i18n']) {
                modify_database("delete from {$sDBPrefix}question_attributes where qid={$aAttributeRow['qid']} and attribute='{$aAttributeRow['attribute']}'");
                echo $modifyoutput;
                flush();
                @ob_flush();
                foreach ($languages as $language) {
                    $sAttributeInsertQuery = "insert into {$sDBPrefix}question_attributes (qid,attribute,value,language) VALUES({$aAttributeRow['qid']},'{$aAttributeRow['attribute']}','{$aAttributeRow['value']}','{$language}' )";
                    modify_database("", $sAttributeInsertQuery);
                    echo $modifyoutput;
                    flush();
                    @ob_flush();
                }
            }
        }
    }
}
Example #2
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;
}
Example #3
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;
}
function upgradeQuestionAttributes148()
{
    $sSurveyQuery = "SELECT sid FROM {{surveys}}";
    $oSurveyResult = dbExecuteAssoc($sSurveyQuery);
    $aAllAttributes = questionAttributes(true);
    foreach ($oSurveyResult->readAll() as $aSurveyRow) {
        $iSurveyID = $aSurveyRow['sid'];
        $aLanguages = array_merge(array(Survey::model()->findByPk($iSurveyID)->language), Survey::model()->findByPk($iSurveyID)->additionalLanguages);
        $sAttributeQuery = "select q.qid,attribute,value from {{question_attributes}} qa , {{questions}} q where q.qid=qa.qid and sid={$iSurveyID}";
        $oAttributeResult = dbExecuteAssoc($sAttributeQuery);
        foreach ($oAttributeResult->readAll() as $aAttributeRow) {
            if (isset($aAllAttributes[$aAttributeRow['attribute']]['i18n']) && $aAllAttributes[$aAttributeRow['attribute']]['i18n']) {
                Yii::app()->getDb()->createCommand("delete from {{question_attributes}} where qid={$aAttributeRow['qid']} and attribute='{$aAttributeRow['attribute']}'")->execute();
                foreach ($aLanguages as $sLanguage) {
                    $sAttributeInsertQuery = "insert into {{question_attributes}} (qid,attribute,value,language) VALUES({$aAttributeRow['qid']},'{$aAttributeRow['attribute']}','{$aAttributeRow['value']}','{$sLanguage}' )";
                    modifyDatabase("", $sAttributeInsertQuery);
                }
            }
        }
    }
}
Example #5
0
 /**
  * This function returns an array of the advanced attributes for the particular question
  * including their values set in the database
  *
  * @access public
  * @param int $iQuestionID  The question ID - if 0 then all settings will use the default value
  * @param string $sQuestionType  The question type
  * @param int $iSurveyID
  * @param string $sLanguage  If you give a language then only the attributes for that language are returned
  * @return array
  */
 public function getAdvancedSettingsWithValues($iQuestionID, $sQuestionType, $iSurveyID, $sLanguage = null)
 {
     if (is_null($sLanguage)) {
         $aLanguages = array_merge(array(Survey::model()->findByPk($iSurveyID)->language), Survey::model()->findByPk($iSurveyID)->additionalLanguages);
     } else {
         $aLanguages = array($sLanguage);
     }
     if ($iQuestionID) {
         $oAttributeValues = QuestionAttribute::model()->findAll("qid=:qid", array('qid' => $iQuestionID));
         $aAttributeValues = array();
         foreach ($oAttributeValues as $oAttributeValue) {
             if ($oAttributeValue->language) {
                 $aAttributeValues[$oAttributeValue->attribute][$oAttributeValue->language] = $oAttributeValue->value;
             } else {
                 $aAttributeValues[$oAttributeValue->attribute] = $oAttributeValue->value;
             }
         }
     }
     $aAttributeNames = questionAttributes();
     $aAttributeNames = $aAttributeNames[$sQuestionType];
     uasort($aAttributeNames, 'categorySort');
     foreach ($aAttributeNames as $iKey => $aAttribute) {
         if ($aAttribute['i18n'] == false) {
             if (isset($aAttributeValues[$aAttribute['name']])) {
                 $aAttributeNames[$iKey]['value'] = $aAttributeValues[$aAttribute['name']];
             } else {
                 $aAttributeNames[$iKey]['value'] = $aAttribute['default'];
             }
         } else {
             foreach ($aLanguages as $sLanguage) {
                 if (isset($aAttributeValues[$aAttribute['name']][$sLanguage])) {
                     $aAttributeNames[$iKey][$sLanguage]['value'] = $aAttributeValues[$aAttribute['name']][$sLanguage];
                 } else {
                     $aAttributeNames[$iKey][$sLanguage]['value'] = $aAttribute['default'];
                 }
             }
         }
     }
     return $aAttributeNames;
 }
Example #6
0
 /**
  * Load edit/new question screen depending on $action.
  *
  * @access public
  * @param string $action
  * @param int $surveyid
  * @param int $gid
  * @param int $qid
  * @return void
  */
 public function index($sa, $surveyid, $gid, $qid = null)
 {
     $action = $sa;
     $surveyid = sanitize_int($surveyid);
     $gid = sanitize_int($gid);
     if (isset($qid)) {
         $qid = sanitize_int($qid);
     }
     $aViewUrls = array();
     $aData['surveyid'] = $surveyid;
     $aData['gid'] = $gid;
     $aData['qid'] = $qid;
     $aData['display']['menu_bars']['surveysummary'] = 'viewgroup';
     $aData['display']['menu_bars']['gid_action'] = 'addquestion';
     Yii::app()->session['FileManagerContext'] = "create:question:{$surveyid}";
     if (hasSurveyPermission($surveyid, 'surveycontent', 'read')) {
         $clang = $this->getController()->lang;
         $surveyinfo = getSurveyInfo($surveyid);
         Yii::app()->loadHelper('admin/htmleditor');
         Yii::app()->loadHelper('surveytranslator');
         if (isset($_POST['sortorder'])) {
             $postsortorder = sanitize_int($_POST['sortorder']);
         }
         $aData['adding'] = $adding = $action == 'addquestion';
         $aData['copying'] = $copying = $action == 'copyquestion';
         $questlangs = Survey::model()->findByPk($surveyid)->additionalLanguages;
         $baselang = Survey::model()->findByPk($surveyid)->language;
         $questlangs[] = $baselang;
         $questlangs = array_flip($questlangs);
         // Prepare selector Mode TODO: with and without image
         if (!$adding) {
             Yii::app()->session['FileManagerContext'] = "edit:question:{$surveyid}";
             $aData['display']['menu_bars']['qid_action'] = 'editquestion';
             $egresult = Questions::model()->findAllByAttributes(array('sid' => $surveyid, 'gid' => $gid, 'qid' => $qid));
             foreach ($egresult as $esrow) {
                 if (!array_key_exists($esrow->language, $questlangs)) {
                     // Language Exists, BUT ITS NOT ON THE SURVEY ANYMORE.
                     $esrow->delete();
                 } else {
                     $questlangs[$esrow->language] = 99;
                 }
                 if ($esrow->language == $baselang) {
                     $esrow = $esrow->attributes;
                     $basesettings = array('question_order' => $esrow['question_order'], 'other' => $esrow['other'], 'mandatory' => $esrow['mandatory'], 'type' => $esrow['type'], 'title' => $esrow['title'], 'preg' => $esrow['preg'], 'question' => $esrow['question'], 'help' => $esrow['help']);
                 }
             }
             if (!$egresult) {
                 $this->getController()->error('Invalid question id');
             }
             while (list($key, $value) = each($questlangs)) {
                 if ($value != 99) {
                     Questions::model()->insert(array('qid' => $qid, 'sid' => $surveyid, 'gid' => $gid, 'type' => $basesettings['type'], 'title' => $basesettings['title'], 'question' => $basesettings['question'], 'preg' => $basesettings['preg'], 'help' => $basesettings['help'], 'other' => $basesettings['other'], 'mandatory' => $basesettings['mandatory'], 'question_order' => $basesettings['question_order'], 'language' => $key));
                 }
             }
             $eqresult = Questions::model()->with('groups')->together()->findByAttributes(array('sid' => $surveyid, 'gid' => $gid, 'qid' => $qid, 'language' => $baselang));
         } else {
             // This is needed to properly color-code content if it contains replacements
             LimeExpressionManager::StartProcessingPage(false, Yii::app()->baseUrl, true);
             // so can click on syntax highlighting to edit questions
         }
         $qtypelist = getQuestionTypeList('', 'array');
         $qDescToCode = 'qDescToCode = {';
         $qCodeToInfo = 'qCodeToInfo = {';
         foreach ($qtypelist as $qtype => $qdesc) {
             $qDescToCode .= " '{$qdesc['description']}' : '{$qtype}', \n";
             $qCodeToInfo .= " '{$qtype}' : '" . ls_json_encode($qdesc) . "', \n";
         }
         $aData['qTypeOutput'] = "{$qDescToCode} 'null':'null' }; \n {$qCodeToInfo} 'null':'null' };";
         if (!$adding) {
             $eqrow = array_merge($eqresult->attributes, $eqresult->groups->attributes);
             // Todo: handler in case that record is not found
             if ($copying) {
                 $eqrow['title'] = '';
             }
         } else {
             $eqrow['language'] = $baselang;
             $eqrow['title'] = '';
             $eqrow['question'] = '';
             $eqrow['help'] = '';
             $eqrow['type'] = 'T';
             $eqrow['lid'] = 0;
             $eqrow['lid1'] = 0;
             $eqrow['gid'] = $gid;
             $eqrow['other'] = 'N';
             $eqrow['mandatory'] = 'N';
             $eqrow['preg'] = '';
             $eqrow['relevance'] = 1;
             $eqrow['group_name'] = '';
         }
         $aData['eqrow'] = $eqrow;
         $aData['surveyid'] = $surveyid;
         $aData['gid'] = $gid;
         if (!$adding) {
             $criteria = new CDbCriteria();
             $criteria->addColumnCondition(array('sid' => $surveyid, 'gid' => $gid, 'qid' => $qid));
             $criteria->params[':lang'] = $baselang;
             $criteria->addCondition('language != :lang');
             $aqresult = Questions::model()->findAll($criteria);
             $aData['aqresult'] = $aqresult;
         }
         $aData['clang'] = $clang;
         $aData['action'] = $action;
         $sumresult1 = Survey::model()->findByPk($surveyid);
         if (is_null($sumresult1)) {
             $this->getController()->error('Invalid Survey ID');
         }
         $surveyinfo = $sumresult1->attributes;
         $surveyinfo = array_map('flattenText', $surveyinfo);
         $aData['activated'] = $activated = $surveyinfo['active'];
         if ($activated != "Y") {
             // Prepare selector Class for javascript function : TODO with or without picture
             $selectormodeclass = 'full';
             if (Yii::app()->session['questionselectormode'] == 'none') {
                 $selectormodeclass = 'none';
             }
             $aData['selectormodeclass'] = $selectormodeclass;
         }
         if (!$adding) {
             $qattributes = questionAttributes();
         } else {
             $qattributes = array();
         }
         if ($adding) {
             // Get the questions for this group
             $baselang = Survey::model()->findByPk($surveyid)->language;
             $oqresult = Questions::model()->findAllByAttributes(array('sid' => $surveyid, 'gid' => $gid, 'language' => $baselang, 'parent_qid' => 0), array('order' => 'question_order'));
             $aData['oqresult'] = $oqresult;
         }
         $this->getController()->_js_admin_includes(Yii::app()->getConfig('adminscripts') . 'questions.js');
         $aViewUrls['editQuestion_view'][] = $aData;
         $aViewUrls['questionJavascript_view'][] = array('type' => $eqrow['type']);
     } else {
         include 'accessDenied.php';
     }
     $this->_renderWrappedTemplate('survey/Question', $aViewUrls, $aData);
 }
Example #7
0
     $_SESSION['flashmessage'] = $clang->gT("Default value settings were successfully saved.");
     LimeExpressionManager::SetDirtyFlag();
 } elseif ($action == "updatequestion" && bHasSurveyPermission($surveyid, 'surveycontent', 'update')) {
     LimeExpressionManager::RevertUpgradeConditionsToRelevance($surveyid);
     $cqquery = "SELECT type, gid FROM " . db_table_name('questions') . " WHERE qid={$postqid}";
     $cqresult = db_execute_assoc($cqquery) or safe_die("Couldn't get question type to check for change<br />" . $cqquery . "<br />" . $connect->ErrorMsg());
     // Checked
     $cqr = $cqresult->FetchRow();
     $oldtype = $cqr['type'];
     $oldgid = $cqr['gid'];
     if ($filterxsshtml) {
         require_once "../classes/inputfilter/class.inputfilter_clean.php";
         $myFilter = new InputFilter('', '', 1, 1, 1);
     }
     // Remove invalid question attributes on saving
     $qattributes = questionAttributes();
     $attsql = "delete from " . db_table_name('question_attributes') . " where qid='{$postqid}' and ";
     if (isset($qattributes[$_POST['type']])) {
         $validAttributes = $qattributes[$_POST['type']];
         foreach ($validAttributes as $validAttribute) {
             $attsql .= 'attribute<>' . db_quoteall($validAttribute['name']) . " and ";
         }
     }
     $attsql .= '1=1';
     db_execute_assoc($attsql) or safe_die("Couldn't delete obsolete question attributes<br />" . $attsql . "<br />" . $connect->ErrorMsg());
     // Checked
     //now save all valid attributes
     $validAttributes = $qattributes[$_POST['type']];
     foreach ($validAttributes as $validAttribute) {
         if (isset($_POST[$validAttribute['name']])) {
             if ($filterxsshtml) {
 /**
  * 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");
 }
Example #9
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");
 }
Example #10
0
 /**
  * Load edit/new question screen depending on $action.
  *
  * @access public
  * @param string $sa subaction
  * @param int $surveyid
  * @param int $gid
  * @param int $qid
  * @return void
  */
 public function index($sa, $surveyid, $gid, $qid = null)
 {
     App()->getClientScript()->registerPackage('qTip2');
     $action = $sa;
     $surveyid = $iSurveyID = sanitize_int($surveyid);
     $gid = sanitize_int($gid);
     if (isset($qid)) {
         $qid = sanitize_int($qid);
     }
     $aViewUrls = array();
     $aData['surveyid'] = $surveyid;
     $aData['gid'] = $gid;
     $aData['qid'] = $qid;
     $aData['display']['menu_bars']['surveysummary'] = 'viewgroup';
     $aData['display']['menu_bars']['gid_action'] = 'addquestion';
     $surveyinfo = Survey::model()->findByPk($iSurveyID)->surveyinfo;
     $aData['title_bar']['title'] = $surveyinfo['surveyls_title'] . "(" . gT("ID") . ":" . $iSurveyID . ")";
     $aData['questiongroupbar']['savebutton']['form'] = 'frmeditgroup';
     $aData['questiongroupbar']['saveandclosebutton']['form'] = 'frmeditgroup';
     $aData['questiongroupbar']['closebutton']['url'] = 'admin/questions/sa/view/surveyid/' . $surveyid . '/gid/' . $gid . '/qid/' . $qid;
     Yii::app()->session['FileManagerContext'] = "create:question:{$surveyid}";
     if (Permission::model()->hasSurveyPermission($surveyid, 'surveycontent', 'read')) {
         $surveyinfo = getSurveyInfo($surveyid);
         Yii::app()->loadHelper('admin/htmleditor');
         Yii::app()->loadHelper('surveytranslator');
         if (isset($_POST['sortorder'])) {
             $postsortorder = sanitize_int($_POST['sortorder']);
         }
         $aData['adding'] = $adding = $action == 'addquestion';
         $aData['copying'] = $copying = $action == 'copyquestion';
         $questlangs = Survey::model()->findByPk($surveyid)->additionalLanguages;
         $baselang = Survey::model()->findByPk($surveyid)->language;
         $questlangs[] = $baselang;
         $questlangs = array_flip($questlangs);
         // Prepare selector Mode TODO: with and without image
         if (!$adding) {
             Yii::app()->session['FileManagerContext'] = "edit:question:{$surveyid}";
             $aData['display']['menu_bars']['qid_action'] = 'editquestion';
             $egresult = Question::model()->findAllByAttributes(array('sid' => $surveyid, 'gid' => $gid, 'qid' => $qid));
             foreach ($egresult as $esrow) {
                 if (!array_key_exists($esrow->language, $questlangs)) {
                     // Language Exists, BUT ITS NOT ON THE SURVEY ANYMORE.
                     $esrow->delete();
                 } else {
                     $questlangs[$esrow->language] = 99;
                 }
                 if ($esrow->language == $baselang) {
                     $esrow = $esrow->attributes;
                     $basesettings = array('question_order' => $esrow['question_order'], 'other' => $esrow['other'], 'mandatory' => $esrow['mandatory'], 'type' => $esrow['type'], 'title' => $esrow['title'], 'preg' => $esrow['preg'], 'question' => $esrow['question'], 'help' => $esrow['help']);
                 }
             }
             if (!$egresult) {
                 $this->getController()->error('Invalid question id');
             }
             while (list($key, $value) = each($questlangs)) {
                 if ($value != 99) {
                     $arQuestion = new Question();
                     $arQuestion->qid = $qid;
                     $arQuestion->sid = $surveyid;
                     $arQuestion->gid = $gid;
                     $arQuestion->type = $basesettings['type'];
                     $arQuestion->title = $basesettings['title'];
                     $arQuestion->question = $basesettings['question'];
                     $arQuestion->preg = $basesettings['preg'];
                     $arQuestion->help = $basesettings['help'];
                     $arQuestion->other = $basesettings['other'];
                     $arQuestion->mandatory = $basesettings['mandatory'];
                     $arQuestion->question_order = $basesettings['question_order'];
                     $arQuestion->language = $key;
                     $arQuestion->insert();
                 }
             }
             $eqresult = Question::model()->with('groups')->together()->findByAttributes(array('sid' => $surveyid, 'gid' => $gid, 'qid' => $qid, 'language' => $baselang));
         } else {
             // This is needed to properly color-code content if it contains replacements
             LimeExpressionManager::StartProcessingPage(false, Yii::app()->baseUrl, true);
             // so can click on syntax highlighting to edit questions
         }
         $qtypelist = getQuestionTypeList('', 'array');
         $qDescToCode = 'qDescToCode = {';
         $qCodeToInfo = 'qCodeToInfo = {';
         foreach ($qtypelist as $qtype => $qdesc) {
             $qDescToCode .= " '{$qdesc['description']}' : '{$qtype}', \n";
             $qCodeToInfo .= " '{$qtype}' : '" . ls_json_encode($qdesc) . "', \n";
         }
         $aData['qTypeOutput'] = "{$qDescToCode} 'null':'null' }; \n {$qCodeToInfo} 'null':'null' };";
         if (!$adding) {
             if (is_object($eqresult->groups)) {
                 $eqrow = array_merge($eqresult->attributes, $eqresult->groups->attributes);
             } else {
                 $eqrow = $eqresult->attributes;
             }
             // Todo: handler in case that record is not found
             if ($copying) {
                 $eqrow['title'] = '';
             }
         } else {
             $eqrow['language'] = $baselang;
             $eqrow['title'] = '';
             $eqrow['question'] = '';
             $eqrow['help'] = '';
             $eqrow['type'] = 'T';
             $eqrow['lid'] = 0;
             $eqrow['lid1'] = 0;
             $eqrow['gid'] = $gid;
             $eqrow['other'] = 'N';
             $eqrow['mandatory'] = 'N';
             $eqrow['preg'] = '';
             $eqrow['relevance'] = 1;
             $eqrow['group_name'] = '';
         }
         $eqrow['conditions_number'] = Condition::Model()->count("qid=:qid", array('qid' => $qid));
         if ($eqrow['modulename'] != null) {
             $oQuestionModule = Question::getQuestionModule($esrow['modulename']);
             $questionTitle = (array) $oQuestionModule->title;
             $questionModuleName = (array) $oQuestionModule->modulename;
             $eqrow['modulename'] = $questionModuleName[0];
             $eqrow['moduletitle'] = $questionTitle[0];
         }
         $aData['eqrow'] = $eqrow;
         $aData['surveyid'] = $surveyid;
         $aData['gid'] = $gid;
         if (!$adding) {
             $criteria = new CDbCriteria();
             $criteria->addColumnCondition(array('sid' => $surveyid, 'gid' => $gid, 'qid' => $qid));
             $criteria->params[':lang'] = $baselang;
             $criteria->addCondition('language != :lang');
             $aqresult = Question::model()->findAll($criteria);
             $aData['aqresult'] = $aqresult;
         }
         $aData['action'] = $action;
         $sumresult1 = Survey::model()->findByPk($surveyid);
         if (is_null($sumresult1)) {
             $this->getController()->error('Invalid Survey ID');
         }
         $surveyinfo = $sumresult1->attributes;
         $surveyinfo = array_map('flattenText', $surveyinfo);
         $aData['activated'] = $activated = $surveyinfo['active'];
         if ($activated != "Y") {
             // Prepare selector Class for javascript function
             if (Yii::app()->session['questionselectormode'] !== 'default') {
                 $selectormodeclass = Yii::app()->session['questionselectormode'];
             } else {
                 $selectormodeclass = getGlobalSetting('defaultquestionselectormode', 'default');
             }
             $aData['selectormodeclass'] = $selectormodeclass;
         }
         if (!$adding) {
             $qattributes = questionAttributes();
         } else {
             $qattributes = array();
         }
         if ($adding) {
             // Get the questions for this group
             $baselang = Survey::model()->findByPk($surveyid)->language;
             $oqresult = Question::model()->findAllByAttributes(array('sid' => $surveyid, 'gid' => $gid, 'language' => $baselang, 'parent_qid' => 0), array('order' => 'question_order'));
             $aData['oqresult'] = $oqresult;
         }
         App()->getClientScript()->registerScriptFile(App()->getAssetManager()->publish(ADMIN_SCRIPT_PATH . 'questions.js'));
         $aData['sValidateUrl'] = $adding || $copying ? $this->getController()->createUrl('admin/questions', array('sa' => 'ajaxValidate', 'surveyid' => $surveyid)) : $this->getController()->createUrl('admin/questions', array('sa' => 'ajaxValidate', 'surveyid' => $surveyid, 'qid' => $qid));
         $aData['addlanguages'] = Survey::model()->findByPk($surveyid)->additionalLanguages;
         $aViewUrls['editQuestion_view'][] = $aData;
         $aViewUrls['questionJavascript_view'][] = array('type' => $eqrow['type']);
     } else {
         include 'accessDenied.php';
     }
     $aData['ajaxDatas']['sValidateUrl'] = isset($aData['sValidateUrl']) ? $aData['sValidateUrl'] : $this->getController()->createUrl('admin/questions', array('sa' => 'ajaxValidate', 'surveyid' => $surveyid));
     $aData['ajaxDatas']['qTypeOutput'] = $aData['qTypeOutput'];
     ///////////
     // sidemenu
     $aData['sidemenu']['state'] = false;
     $aData['sidemenu']['explorer']['state'] = true;
     $aData['sidemenu']['explorer']['gid'] = isset($gid) ? $gid : false;
     $aData['sidemenu']['explorer']['qid'] = isset($qid) ? $qid : false;
     $this->_renderWrappedTemplate('survey/Question', $aViewUrls, $aData);
 }
Example #11
0
/**
* Returns a flat array with all question attributes for the question only (and the qid we gave it)!
* @param $iQID The question ID
* @return array$bOrderByNative=>value, attribute=>value} or false if the question ID does not exist (anymore)
*/
function getQuestionAttributeValues($iQID)
{
    static $cache = array();
    static $availableattributesarr = null;
    $iQID = sanitize_int($iQID);
    if (isset($cache[$iQID])) {
        return $cache[$iQID];
    }
    $row = Questions::model()->findByAttributes(array('qid' => $iQID));
    //, 'parent_qid' => 0), array('group' => 'type')
    if (empty($row)) {
        $cache[$iQID] = false;
        return false;
    } else {
        $row = $row->getAttributes();
    }
    $type = $row['type'];
    $surveyid = $row['sid'];
    $aLanguages = array_merge((array) Survey::model()->findByPk($surveyid)->language, Survey::model()->findByPk($surveyid)->additionalLanguages);
    //Now read available attributes, make sure we do this only once per request to save
    //processing cycles and memory
    if (is_null($availableattributesarr)) {
        $availableattributesarr = questionAttributes();
    }
    if (isset($availableattributesarr[$type])) {
        $aAvailableAttributes = $availableattributesarr[$type];
    } else {
        $cache[$iQID] = array();
        return array();
    }
    $aResultAttributes = array();
    foreach ($aAvailableAttributes as $attribute) {
        if ($attribute['i18n']) {
            foreach ($aLanguages as $sLanguage) {
                $aResultAttributes[$attribute['name']][$sLanguage] = $attribute['default'];
            }
        } else {
            $aResultAttributes[$attribute['name']] = $attribute['default'];
        }
    }
    $result = Question_attributes::model()->findAllByAttributes(array('qid' => $iQID));
    foreach ($result as $row) {
        $row = $row->attributes;
        if (!isset($aAvailableAttributes[$row['attribute']])) {
            continue;
            // Sort out attributes not belonging to this question
        }
        if (!$aAvailableAttributes[$row['attribute']]['i18n']) {
            $aResultAttributes[$row['attribute']] = $row['value'];
        } elseif (!empty($row['language'])) {
            $aResultAttributes[$row['attribute']][$row['language']] = $row['value'];
        }
    }
    $cache[$iQID] = $aResultAttributes;
    return $aResultAttributes;
}
    $surveyid = returnglobal('sid');
    if ($match == 1) {
        $language = GetBaseLanguageFromSurveyID($surveyid);
    } else {
        $language = null;
    }
    $resultdata = getlabelsets($language);
    echo json_encode($resultdata);
}
if ($action == "ajaxquestionattributes") {
    $thissurvey = getSurveyInfo($surveyid);
    $type = returnglobal('question_type');
    if (isset($qid)) {
        $attributesettings = getQuestionAttributes($qid);
    }
    $availableattributes = questionAttributes();
    if (isset($availableattributes[$type])) {
        uasort($availableattributes[$type], 'CategorySort');
        $ajaxoutput = '';
        $currentfieldset = '';
        foreach ($availableattributes[$type] as $qa) {
            if (isset($attributesettings[$qa['name']])) {
                $value = $attributesettings[$qa['name']];
            } else {
                $value = $qa['default'];
            }
            if ($currentfieldset != $qa['category']) {
                if ($currentfieldset != '') {
                    $ajaxoutput .= '</ul></fieldset>';
                }
                $ajaxoutput .= "<fieldset>\n";
/**
 *
 * Returns a flat array with all question attributes for the question only (and the qid we gave it)!
 * @author: c_schmitz
 * @param $qid The question ID
 * @param $type optional The question type - saves a DB query if you provide it
 * @return array{attribute=>value , attribute=>value} or false if the question ID does not exist (anymore)
 */
function getQuestionAttributes($qid, $type = '')
{
    static $cache = array();
    static $availableattributesarr = null;
    if (isset($cache[$qid])) {
        return $cache[$qid];
    }
    if ($type == '') {
        $query = "SELECT type FROM " . db_table_name('questions') . " WHERE qid={$qid} and parent_qid=0 group by type";
        $result = db_execute_assoc($query) or safe_die("Error finding question attributes");
        //Checked
        $row = $result->FetchRow();
        if ($row === false) {
            $cache[$qid] = false;
            return false;
        }
        $type = $row['type'];
    }
    //Now read available attributes, make sure we do this only once per request to save
    //processing cycles and memory
    if (is_null($availableattributesarr)) {
        $availableattributesarr = questionAttributes();
    }
    if (isset($availableattributesarr[$type])) {
        $availableattributes = $availableattributesarr[$type];
    } else {
        $cache[$qid] = array();
        return array();
    }
    foreach ($availableattributes as $attribute) {
        $defaultattributes[$attribute['name']] = $attribute['default'];
    }
    $setattributes = array();
    $qid = sanitize_int($qid);
    $query = "SELECT attribute, value FROM " . db_table_name('question_attributes') . " WHERE qid={$qid}";
    $result = db_execute_assoc($query) or safe_die("Error finding question attributes");
    //Checked
    $setattributes = array();
    while ($row = $result->FetchRow()) {
        $setattributes[$row['attribute']] = $row['value'];
    }
    //echo "<pre>";print_r($qid_attributes);echo "</pre>";
    $qid_attributes = array_merge($defaultattributes, $setattributes);
    $cache[$qid] = $qid_attributes;
    return $qid_attributes;
}
 /**
  * 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");
     }
 }
 /**
  * Returns Question attribute array name=>value
  *
  * @access public
  * @param int $iQuestionID
  * @return array
  */
 public function getQuestionAttributes($iQuestionID)
 {
     $iQuestionID = (int) $iQuestionID;
     static $aQuestionAttributesStatic = array();
     // TODO : replace by Yii::app()->cache
     // Limit the size of the attribute cache due to memory usage
     $aQuestionAttributesStatic = array_splice($aQuestionAttributesStatic, -1000, null, true);
     if (isset($aQuestionAttributesStatic[$iQuestionID])) {
         return $aQuestionAttributesStatic[$iQuestionID];
     }
     $aQuestionAttributes = array();
     $oQuestion = Question::model()->find("qid=:qid", array('qid' => $iQuestionID));
     // Maybe take parent_qid attribute before this qid attribute
     if ($oQuestion) {
         $aLanguages = array_merge(array(Survey::model()->findByPk($oQuestion->sid)->language), Survey::model()->findByPk($oQuestion->sid)->additionalLanguages);
         // Get all atribute set for this question
         $sType = $oQuestion->type;
         $aAttributeNames = questionAttributes();
         $aAttributeNames = $aAttributeNames[$sType];
         $oAttributeValues = QuestionAttribute::model()->findAll("qid=:qid", array('qid' => $iQuestionID));
         $aAttributeValues = array();
         foreach ($oAttributeValues as $oAttributeValue) {
             if ($oAttributeValue->language) {
                 $aAttributeValues[$oAttributeValue->attribute][$oAttributeValue->language] = $oAttributeValue->value;
             } else {
                 $aAttributeValues[$oAttributeValue->attribute] = $oAttributeValue->value;
             }
         }
         // Fill with aQuestionAttributes with default attribute or with aAttributeValues
         // Can not use array_replace due to i18n
         foreach ($aAttributeNames as $aAttribute) {
             if ($aAttribute['i18n'] == false) {
                 if (isset($aAttributeValues[$aAttribute['name']])) {
                     $aQuestionAttributes[$aAttribute['name']] = $aAttributeValues[$aAttribute['name']];
                 } else {
                     $aQuestionAttributes[$aAttribute['name']] = $aAttribute['default'];
                 }
             } else {
                 foreach ($aLanguages as $sLanguage) {
                     if (isset($aAttributeValues[$aAttribute['name']][$sLanguage])) {
                         $aQuestionAttributes[$aAttribute['name']][$sLanguage] = $aAttributeValues[$aAttribute['name']][$sLanguage];
                     } else {
                         $aQuestionAttributes[$aAttribute['name']][$sLanguage] = $aAttribute['default'];
                     }
                 }
             }
         }
     } else {
         return false;
         // return false but don't set $aQuestionAttributesStatic[$iQuestionID]
     }
     $aQuestionAttributesStatic[$iQuestionID] = $aQuestionAttributes;
     return $aQuestionAttributes;
 }
Example #16
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");
     }
 }