Beispiel #1
0
 /**
  * Update survey settings with post value
  *
  * @param $iSurveyId  The survey id
  */
 function update($iSurveyId)
 {
     if (!Yii::app()->request->isPostRequest) {
         throw new CHttpException(500);
     }
     if (!Permission::model()->hasSurveyPermission($iSurveyId, 'surveysettings', 'update')) {
         throw new CHttpException(401, "401 Unauthorized");
     }
     // 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->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 = implode(' ', Yii::app()->request->getPost('additional_languages', array()));
     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 = App()->request->getPost('usecaptcha');
     $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 (Yii::app()->request->getPost('redirect')) {
         $this->getController()->redirect(Yii::app()->request->getPost('redirect'));
         App()->end();
     }
 }
Beispiel #2
0
 /**
  * Delete token attributes
  */
 function deletetokenattributes($iSurveyId)
 {
     $clang = $this->getController()->lang;
     $iSurveyId = sanitize_int($iSurveyId);
     // CHECK TO SEE IF A TOKEN TABLE EXISTS FOR THIS SURVEY
     $bTokenExists = tableExists('{{tokens_' . $iSurveyId . '}}');
     if (!$bTokenExists) {
         Yii::app()->session['flashmessage'] = $clang->gT("No token table.");
         $this->getController()->redirect($this->getController()->createUrl("/admin/survey/sa/view/surveyid/{$iSurveyId}"));
     }
     if (!Permission::model()->hasSurveyPermission($iSurveyId, 'tokens', 'update') && !Permission::model()->hasSurveyPermission($iSurveyID, 'surveysettings', 'update')) {
         Yii::app()->session['flashmessage'] = $clang->gT("You do not have sufficient rights to access this page.");
         $this->getController()->redirect($this->getController()->createUrl("/admin/survey/sa/view/surveyid/{$iSurveyId}"));
     }
     $aData['thissurvey'] = getSurveyInfo($iSurveyId);
     $aData['surveyid'] = $iSurveyId;
     $confirm = Yii::app()->request->getPost('confirm', '');
     $cancel = Yii::app()->request->getPost('cancel', '');
     $tokenfields = getAttributeFieldNames($iSurveyId);
     $sAttributeToDelete = Yii::app()->request->getPost('deleteattribute', '');
     tracevar($sAttributeToDelete);
     if (!in_array($sAttributeToDelete, $tokenfields)) {
         $sAttributeToDelete = false;
     }
     tracevar($sAttributeToDelete);
     if ($cancel == 'cancel') {
         Yii::app()->getController()->redirect(Yii::app()->getController()->createUrl("/admin/tokens/sa/managetokenattributes/surveyid/{$iSurveyId}"));
     } elseif ($confirm != 'confirm' && $sAttributeToDelete) {
         $this->_renderWrappedTemplate('token', array('tokenbar', 'message' => array('title' => sprintf($clang->gT("Delete token attribute %s"), $sAttributeToDelete), 'message' => "<p>" . $clang->gT("If you remove this attribute, you will lose all information.") . "</p>\n" . CHtml::form(array("admin/tokens/sa/deletetokenattributes/surveyid/{$iSurveyId}"), 'post', array('id' => 'attributenumber')) . CHtml::hiddenField('deleteattribute', $sAttributeToDelete) . CHtml::hiddenField('sid', $iSurveyId) . CHtml::htmlButton($clang->gT('Delete attribute'), array('type' => 'submit', 'value' => 'confirm', 'name' => 'confirm')) . CHtml::htmlButton($clang->gT('Cancel'), array('type' => 'submit', 'value' => 'cancel', 'name' => 'cancel')) . CHtml::endForm())), $aData);
     } elseif ($sAttributeToDelete) {
         $sTableName = "{{tokens_" . intval($iSurveyId) . "}}";
         Yii::app()->db->createCommand(Yii::app()->db->getSchema()->dropColumn($sTableName, $sAttributeToDelete))->execute();
         Yii::app()->db->schema->getTable($sTableName, true);
         // Refresh schema cache just in case the table existed in the past
         LimeExpressionManager::SetDirtyFlag();
         Yii::app()->session['flashmessage'] = sprintf($clang->gT("Attribute %s was deleted."), $sAttributeToDelete);
         Yii::app()->getController()->redirect(Yii::app()->getController()->createUrl("/admin/tokens/sa/managetokenattributes/surveyid/{$iSurveyId}"));
     } else {
         Yii::app()->session['flashmessage'] = $clang->gT("The selected attribute was invalid.");
         Yii::app()->getController()->redirect(Yii::app()->getController()->createUrl("/admin/tokens/sa/managetokenattributes/surveyid/{$iSurveyId}"));
     }
 }
 /**
  * Creates a new survey - does some basic checks of the suppplied data
  *
  * @param array $aData Array with fieldname=>fieldcontents data
  * @return integer The new survey id
  */
 public function insertNewSurvey($aData)
 {
     do {
         if (isset($aData['wishSID'])) {
             $aData['sid'] = $aData['wishSID'];
             unset($aData['wishSID']);
         } else {
             $aData['sid'] = randomChars(6, '123456789');
         }
         $isresult = self::model()->findByPk($aData['sid']);
     } while (!is_null($isresult));
     $survey = new self();
     foreach ($aData as $k => $v) {
         $survey->{$k} = $v;
     }
     $sResult = $survey->save();
     if (!$sResult) {
         tracevar($survey->getErrors());
         return false;
     } else {
         return $aData['sid'];
     }
 }
Beispiel #4
0
 function insertRecords($data)
 {
     $oRecord = new self();
     foreach ($data as $k => $v) {
         $oRecord->{$k} = $v;
     }
     if ($oRecord->validate()) {
         return $oRecord->save();
     }
     tracevar($oRecord->getErrors());
 }
 /**
  * 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");
 }
Beispiel #6
0
 /**
  * Insert an array into the questions table
  * Returns null if insertion fails, otherwise the new QID
  *
  * @param array $data
  */
 function insertRecords($data)
 {
     // This function must be deprecated : don't find a way to have getErrors after (Shnoulle on 131206)
     $oRecord = new self();
     foreach ($data as $k => $v) {
         $oRecord->{$k} = $v;
     }
     if ($oRecord->validate()) {
         $oRecord->save();
         return $oRecord->qid;
     }
     tracevar($oRecord->getErrors());
 }
Beispiel #7
0
 /**
  * import from csv
  */
 function import($iSurveyId)
 {
     $iSurveyId = (int) $iSurveyId;
     if (!Permission::model()->hasSurveyPermission($iSurveyId, 'tokens', 'import')) {
         Yii::app()->session['flashmessage'] = gT("You do not have sufficient rights to access this page.");
         $this->getController()->redirect(array("/admin/survey/sa/view/surveyid/{$iSurveyId}"));
     }
     // CHECK TO SEE IF A TOKEN TABLE EXISTS FOR THIS SURVEY
     $bTokenExists = tableExists('{{tokens_' . $iSurveyId . '}}');
     if (!$bTokenExists) {
         self::_newtokentable($iSurveyId);
     }
     App()->getClientScript()->registerScriptFile(Yii::app()->getConfig('adminscripts') . 'tokensimport.js');
     $aEncodings = aEncodingsArray();
     if (Yii::app()->request->isPostRequest) {
         $sUploadCharset = Yii::app()->request->getPost('csvcharset');
         if (!array_key_exists($sUploadCharset, $aEncodings)) {
             $sUploadCharset = 'auto';
         }
         $bFilterDuplicateToken = Yii::app()->request->getPost('filterduplicatetoken');
         $bFilterBlankEmail = Yii::app()->request->getPost('filterblankemail');
         $bAllowInvalidEmail = Yii::app()->request->getPost('allowinvalidemail');
         $aAttrFieldNames = getAttributeFieldNames($iSurveyId);
         $aDuplicateList = array();
         $aInvalidEmailList = array();
         $aInvalidFormatList = array();
         $aModelErrorList = array();
         $aFirstLine = array();
         $oFile = CUploadedFile::getInstanceByName("the_file");
         $sPath = Yii::app()->getConfig('tempdir');
         $sFileName = $sPath . '/' . randomChars(20);
         //$sFileTmpName=$oFile->getTempName();
         /* More way to validate CSV ?
            $aCsvMimetypes = array(
                'text/csv',
                'text/plain',
                'application/csv',
                'text/comma-separated-values',
                'application/excel',
                'application/vnd.ms-excel',
                'application/vnd.msexcel',
                'text/anytext',
                'application/octet-stream',
                'application/txt',
            );
            */
         if (strtolower($oFile->getExtensionName()) != 'csv') {
             Yii::app()->setFlashMessage(gT("Only CSV files are allowed."), 'error');
         } elseif (!@$oFile->saveAs($sFileName)) {
             Yii::app()->setFlashMessage(sprintf(gT("Upload file not found. Check your permissions and path (%s) for the upload directory"), $sPath), 'error');
         } else {
             $iRecordImported = 0;
             $iRecordCount = 0;
             $iRecordOk = 0;
             $iInvalidEmailCount = 0;
             // Count invalid email imported
             // This allows to read file with MAC line endings too
             @ini_set('auto_detect_line_endings', true);
             // open it and trim the ednings
             $aTokenListArray = file($sFileName);
             $sBaseLanguage = Survey::model()->findByPk($iSurveyId)->language;
             if (!Yii::app()->request->getPost('filterduplicatefields') || Yii::app()->request->getPost('filterduplicatefields') && count(Yii::app()->request->getPost('filterduplicatefields')) == 0) {
                 $aFilterDuplicateFields = array('firstname', 'lastname', 'email');
             } else {
                 $aFilterDuplicateFields = Yii::app()->request->getPost('filterduplicatefields');
             }
             $sSeparator = Yii::app()->request->getPost('separator');
             foreach ($aTokenListArray as $buffer) {
                 $buffer = @mb_convert_encoding($buffer, "UTF-8", $sUploadCharset);
                 if ($iRecordCount == 0) {
                     // Parse first line (header) from CSV
                     $buffer = removeBOM($buffer);
                     // We alow all field except tid because this one is really not needed.
                     $aAllowedFieldNames = Token::model($iSurveyId)->tableSchema->getColumnNames();
                     if (($kTid = array_search('tid', $aAllowedFieldNames)) !== false) {
                         unset($aAllowedFieldNames[$kTid]);
                     }
                     // Some header don't have same column name
                     $aReplacedFields = array('invited' => 'sent', 'reminded' => 'remindersent');
                     switch ($sSeparator) {
                         case 'comma':
                             $sSeparator = ',';
                             break;
                         case 'semicolon':
                             $sSeparator = ';';
                             break;
                         default:
                             $comma = substr_count($buffer, ',');
                             $semicolon = substr_count($buffer, ';');
                             if ($semicolon > $comma) {
                                 $sSeparator = ';';
                             } else {
                                 $sSeparator = ',';
                             }
                     }
                     $aFirstLine = str_getcsv($buffer, $sSeparator, '"');
                     $aFirstLine = array_map('trim', $aFirstLine);
                     $aIgnoredColumns = array();
                     // Now check the first line for invalid fields
                     foreach ($aFirstLine as $index => $sFieldname) {
                         $aFirstLine[$index] = preg_replace("/(.*) <[^,]*>\$/", "\$1", $sFieldname);
                         $sFieldname = $aFirstLine[$index];
                         if (!in_array($sFieldname, $aAllowedFieldNames)) {
                             $aIgnoredColumns[] = $sFieldname;
                         }
                         if (array_key_exists($sFieldname, $aReplacedFields)) {
                             $aFirstLine[$index] = $aReplacedFields[$sFieldname];
                         }
                     }
                 } else {
                     $line = str_getcsv($buffer, $sSeparator, '"');
                     if (count($aFirstLine) != count($line)) {
                         $aInvalidFormatList[] = sprintf(gt("Line %s"), $iRecordCount);
                         $iRecordCount++;
                         continue;
                     }
                     $aWriteArray = array_combine($aFirstLine, $line);
                     //kick out ignored columns
                     foreach ($aIgnoredColumns as $column) {
                         unset($aWriteArray[$column]);
                     }
                     $bDuplicateFound = false;
                     $bInvalidEmail = false;
                     $aWriteArray['email'] = isset($aWriteArray['email']) ? trim($aWriteArray['email']) : "";
                     $aWriteArray['firstname'] = isset($aWriteArray['firstname']) ? $aWriteArray['firstname'] : "";
                     $aWriteArray['lastname'] = isset($aWriteArray['lastname']) ? $aWriteArray['lastname'] : "";
                     $aWriteArray['language'] = isset($aWriteArray['language']) ? $aWriteArray['language'] : $sBaseLanguage;
                     if ($bFilterDuplicateToken) {
                         $aParams = array();
                         $oCriteria = new CDbCriteria();
                         $oCriteria->condition = "";
                         foreach ($aFilterDuplicateFields as $field) {
                             if (isset($aWriteArray[$field])) {
                                 $oCriteria->addCondition("{$field} = :{$field}");
                                 $aParams[":{$field}"] = $aWriteArray[$field];
                             }
                         }
                         if (!empty($aParams)) {
                             $oCriteria->params = $aParams;
                         }
                         $dupresult = TokenDynamic::model($iSurveyId)->count($oCriteria);
                         if ($dupresult > 0) {
                             $bDuplicateFound = true;
                             $aDuplicateList[] = sprintf(gt("Line %s : %s %s (%s)"), $iRecordCount, $aWriteArray['firstname'], $aWriteArray['lastname'], $aWriteArray['email']);
                         }
                     }
                     //treat blank emails
                     if (!$bDuplicateFound && $bFilterBlankEmail && $aWriteArray['email'] == '') {
                         $bInvalidEmail = true;
                         $aInvalidEmailList[] = sprintf(gt("Line %s : %s %s"), $iRecordCount, CHtml::encode($aWriteArray['firstname']), CHtml::encode($aWriteArray['lastname']));
                     }
                     if (!$bDuplicateFound && $aWriteArray['email'] != '') {
                         $aEmailAddresses = explode(';', $aWriteArray['email']);
                         foreach ($aEmailAddresses as $sEmailaddress) {
                             if (!validateEmailAddress($sEmailaddress)) {
                                 if ($bAllowInvalidEmail) {
                                     $iInvalidEmailCount++;
                                     if (empty($aWriteArray['emailstatus']) || strtoupper($aWriteArray['emailstatus'] == "OK")) {
                                         $aWriteArray['emailstatus'] = "invalid";
                                     }
                                 } else {
                                     $bInvalidEmail = true;
                                     $aInvalidEmailList[] = sprintf(gt("Line %s : %s %s (%s)"), $iRecordCount, CHtml::encode($aWriteArray['firstname']), CHtml::encode($aWriteArray['lastname']), CHtml::encode($aWriteArray['email']));
                                 }
                             }
                         }
                     }
                     if (!$bDuplicateFound && !$bInvalidEmail && isset($aWriteArray['token'])) {
                         $aWriteArray['token'] = sanitize_token($aWriteArray['token']);
                         // We allways search for duplicate token (it's in model. Allow to reset or update token ?
                         if (Token::model($iSurveyId)->count("token=:token", array(":token" => $aWriteArray['token']))) {
                             $bDuplicateFound = true;
                             $aDuplicateList[] = sprintf(gt("Line %s : %s %s (%s) - token : %s"), $iRecordCount, CHtml::encode($aWriteArray['firstname']), CHtml::encode($aWriteArray['lastname']), CHtml::encode($aWriteArray['email']), CHtml::encode($aWriteArray['token']));
                         }
                     }
                     if (!$bDuplicateFound && !$bInvalidEmail) {
                         // unset all empty value
                         foreach ($aWriteArray as $key => $value) {
                             if ($aWriteArray[$key] == "") {
                                 unset($aWriteArray[$key]);
                             }
                             if (substr($value, 0, 1) == '"' && substr($value, -1) == '"') {
                                 // Fix CSV quote
                                 $value = substr($value, 1, -1);
                             }
                         }
                         // Some default value : to be moved to Token model rules in future release ?
                         // But think we have to accept invalid email etc ... then use specific scenario
                         $oToken = Token::create($iSurveyId);
                         if ($bAllowInvalidEmail) {
                             $oToken->scenario = 'allowinvalidemail';
                         }
                         foreach ($aWriteArray as $key => $value) {
                             $oToken->{$key} = $value;
                         }
                         if (!$oToken->save()) {
                             tracevar($oToken->getErrors());
                             $aModelErrorList[] = sprintf(gt("Line %s : %s"), $iRecordCount, Chtml::errorSummary($oToken));
                         } else {
                             $iRecordImported++;
                         }
                     }
                     $iRecordOk++;
                 }
                 $iRecordCount++;
             }
             $iRecordCount = $iRecordCount - 1;
             unlink($sFileName);
             $aData['aTokenListArray'] = $aTokenListArray;
             // Big array in memory, just for success ?
             $aData['iRecordImported'] = $iRecordImported;
             $aData['iRecordOk'] = $iRecordOk;
             $aData['iRecordCount'] = $iRecordCount;
             $aData['aFirstLine'] = $aFirstLine;
             // Seem not needed
             $aData['aDuplicateList'] = $aDuplicateList;
             $aData['aInvalidFormatList'] = $aInvalidFormatList;
             $aData['aInvalidEmailList'] = $aInvalidEmailList;
             $aData['aModelErrorList'] = $aModelErrorList;
             $aData['iInvalidEmailCount'] = $iInvalidEmailCount;
             $aData['thissurvey'] = getSurveyInfo($iSurveyId);
             $aData['iSurveyId'] = $aData['surveyid'] = $iSurveyId;
             $this->_renderWrappedTemplate('token', array('tokenbar', 'csvpost'), $aData);
             Yii::app()->end();
         }
     }
     // If there are error with file : show the form
     $aData['aEncodings'] = $aEncodings;
     $aData['iSurveyId'] = $iSurveyId;
     $aData['thissurvey'] = getSurveyInfo($iSurveyId);
     $aData['surveyid'] = $iSurveyId;
     $aTokenTableFields = getTokenFieldsAndNames($iSurveyId);
     unset($aTokenTableFields['sent']);
     unset($aTokenTableFields['remindersent']);
     unset($aTokenTableFields['remindercount']);
     unset($aTokenTableFields['usesleft']);
     foreach ($aTokenTableFields as $sKey => $sValue) {
         if ($sValue['description'] != $sKey) {
             $sValue['description'] .= ' - ' . $sKey;
         }
         $aNewTokenTableFields[$sKey] = $sValue['description'];
     }
     $aData['aTokenTableFields'] = $aNewTokenTableFields;
     $this->_renderWrappedTemplate('token', array('tokenbar', 'csvupload'), $aData);
 }
Beispiel #8
0
 /**
  * import from csv
  */
 function import($iSurveyId)
 {
     $clang = $this->getController()->lang;
     $iSurveyId = (int) $iSurveyId;
     if (!Permission::model()->hasSurveyPermission($iSurveyId, 'tokens', 'import')) {
         Yii::app()->session['flashmessage'] = $clang->gT("You do not have sufficient rights to access this page.");
         $this->getController()->redirect(array("/admin/survey/sa/view/surveyid/{$iSurveyId}"));
     }
     // CHECK TO SEE IF A TOKEN TABLE EXISTS FOR THIS SURVEY
     $bTokenExists = tableExists('{{tokens_' . $iSurveyId . '}}');
     if (!$bTokenExists) {
         self::_newtokentable($iSurveyId);
     }
     App()->getClientScript()->registerScriptFile(Yii::app()->getConfig('adminscripts') . 'tokensimport.js');
     $aEncodings = aEncodingsArray();
     if (Yii::app()->request->getPost('submit')) {
         if (Yii::app()->request->getPost('csvcharset') && Yii::app()->request->getPost('csvcharset')) {
             $uploadcharset = Yii::app()->request->getPost('csvcharset');
             if (!array_key_exists($uploadcharset, $aEncodings)) {
                 $uploadcharset = 'auto';
             }
             $filterduplicatetoken = Yii::app()->request->getPost('filterduplicatetoken') && Yii::app()->request->getPost('filterduplicatetoken') == 'on';
             $filterblankemail = Yii::app()->request->getPost('filterblankemail') && Yii::app()->request->getPost('filterblankemail') == 'on';
         }
         $attrfieldnames = getAttributeFieldNames($iSurveyId);
         $duplicatelist = array();
         $invalidemaillist = array();
         $invalidformatlist = array();
         $errorlist = array();
         $firstline = array();
         $sPath = Yii::app()->getConfig('tempdir');
         $sFileTmpName = $_FILES['the_file']['tmp_name'];
         $sFilePath = $sPath . '/' . randomChars(20);
         if (!@move_uploaded_file($sFileTmpName, $sFilePath)) {
             $aData['sError'] = $clang->gT("Upload file not found. Check your permissions and path ({$sFilePath}) for the upload directory");
             $aData['aEncodings'] = $aEncodings;
             $aData['iSurveyId'] = $aData['surveyid'] = $iSurveyId;
             $aData['thissurvey'] = getSurveyInfo($iSurveyId);
             $this->_renderWrappedTemplate('token', array('tokenbar', 'csvupload'), $aData);
         } else {
             $xz = 0;
             $recordcount = 0;
             $xv = 0;
             // This allows to read file with MAC line endings too
             @ini_set('auto_detect_line_endings', true);
             // open it and trim the ednings
             $tokenlistarray = file($sFilePath);
             $sBaseLanguage = Survey::model()->findByPk($iSurveyId)->language;
             if (!Yii::app()->request->getPost('filterduplicatefields') || Yii::app()->request->getPost('filterduplicatefields') && count(Yii::app()->request->getPost('filterduplicatefields')) == 0) {
                 $filterduplicatefields = array('firstname', 'lastname', 'email');
             } else {
                 $filterduplicatefields = Yii::app()->request->getPost('filterduplicatefields');
             }
             $separator = returnGlobal('separator');
             foreach ($tokenlistarray as $buffer) {
                 $buffer = @mb_convert_encoding($buffer, "UTF-8", $uploadcharset);
                 if ($recordcount == 0) {
                     // Parse first line (header) from CSV
                     $buffer = removeBOM($buffer);
                     // We alow all field except tid because this one is really not needed.
                     $allowedfieldnames = array('participant_id', 'firstname', 'lastname', 'email', 'emailstatus', 'token', 'language', 'blacklisted', 'sent', 'remindersent', 'remindercount', 'validfrom', 'validuntil', 'completed', 'usesleft');
                     $allowedfieldnames = array_merge($attrfieldnames, $allowedfieldnames);
                     // Some header don't have same column name
                     $aReplacedFields = array('invited' => 'sent');
                     switch ($separator) {
                         case 'comma':
                             $separator = ',';
                             break;
                         case 'semicolon':
                             $separator = ';';
                             break;
                         default:
                             $comma = substr_count($buffer, ',');
                             $semicolon = substr_count($buffer, ';');
                             if ($semicolon > $comma) {
                                 $separator = ';';
                             } else {
                                 $separator = ',';
                             }
                     }
                     $firstline = str_getcsv($buffer, $separator, '"');
                     $firstline = array_map('trim', $firstline);
                     $ignoredcolumns = array();
                     // Now check the first line for invalid fields
                     foreach ($firstline as $index => $fieldname) {
                         $firstline[$index] = preg_replace("/(.*) <[^,]*>\$/", "\$1", $fieldname);
                         $fieldname = $firstline[$index];
                         if (!in_array($fieldname, $allowedfieldnames)) {
                             $ignoredcolumns[] = $fieldname;
                         }
                         if (array_key_exists($fieldname, $aReplacedFields)) {
                             $firstline[$index] = $aReplacedFields[$fieldname];
                         }
                     }
                     if (!in_array('firstname', $firstline) || !in_array('lastname', $firstline) || !in_array('email', $firstline)) {
                         $recordcount = count($tokenlistarray);
                         break;
                     }
                 } else {
                     $line = str_getcsv($buffer, $separator, '"');
                     if (count($firstline) != count($line)) {
                         $invalidformatlist[] = sprintf(gt("Line %s"), $recordcount);
                         $recordcount++;
                         continue;
                     }
                     $writearray = array_combine($firstline, $line);
                     //kick out ignored columns
                     foreach ($ignoredcolumns as $column) {
                         unset($writearray[$column]);
                     }
                     $dupfound = false;
                     $invalidemail = false;
                     if ($filterduplicatetoken != false) {
                         $aParams = array();
                         $oCriteria = new CDbCriteria();
                         $oCriteria->condition = "";
                         foreach ($filterduplicatefields as $field) {
                             if (isset($writearray[$field])) {
                                 $oCriteria->addCondition("{$field} = :{$field}");
                                 $aParams[":{$field}"] = $writearray[$field];
                             }
                         }
                         if (!empty($aParams)) {
                             $oCriteria->params = $aParams;
                         }
                         $dupresult = TokenDynamic::model($iSurveyId)->count($oCriteria);
                         if ($dupresult > 0) {
                             $dupfound = true;
                             $duplicatelist[] = sprintf(gt("Line %s : %s %s (%s)"), $recordcount, $writearray['firstname'], $writearray['lastname'], $writearray['email']);
                         }
                     }
                     $writearray['email'] = trim($writearray['email']);
                     //treat blank emails
                     if (!$dupfound && $filterblankemail && $writearray['email'] == '') {
                         $invalidemail = true;
                         $invalidemaillist[] = $line[0] . " " . $line[1] . " ( )";
                     }
                     if (!$dupfound && $writearray['email'] != '') {
                         $aEmailAddresses = explode(';', $writearray['email']);
                         foreach ($aEmailAddresses as $sEmailaddress) {
                             if (!validateEmailAddress($sEmailaddress)) {
                                 $invalidemail = true;
                                 $invalidemaillist[] = $line[0] . " " . $line[1] . " (" . $line[2] . ")";
                             }
                         }
                     }
                     if (isset($writearray['token'])) {
                         $writearray['token'] = sanitize_token($writearray['token']);
                         if (!$dupfound && $writearray['token']) {
                             $dupresult = TokenDynamic::model($iSurveyId)->count("token=:token", array('token' => $writearray['token']));
                             if ($dupresult > 0) {
                                 $duplicatelist[] = sprintf(gt("Line %s : token %s already used."), $recordcount, $writearray['token']);
                                 $dupfound = true;
                             }
                         }
                     }
                     if (!$dupfound && !$invalidemail) {
                         // unset all empty value
                         foreach ($writearray as $key => $value) {
                             if ($writearray[$key] == "" && !in_array($key, array('firstname', 'lastname', 'email'))) {
                                 unset($writearray[$key]);
                             }
                             if (substr($value, 0, 1) == '"' && substr($value, -1) == '"') {
                                 // Fix CSV quote
                                 $value = substr($value, 1, -1);
                             }
                         }
                         // Some default value : to be moved to Token model rules in future release ?
                         // But think we have to accept invalid email etc ... then use specific scenario
                         //$writearray['emailstatus']=isset($writearray['emailstatus'])?$writearray['emailstatus']:"OK";
                         $writearray['language'] = isset($writearray['language']) ? $writearray['language'] : $sBaseLanguage;
                         //$oToken = Token::create($iSurveyId);//
                         TokenDynamic::sid($iSurveyId);
                         $oToken = new TokenDynamic();
                         foreach ($writearray as $key => $value) {
                             //if(in_array($key,$oToken->attributes)) Not needed because we filter attributes before
                             $oToken->{$key} = $value;
                         }
                         if (!$oToken->save()) {
                             $errorlist[] = sprintf(gt("Line %s : %s %s (%s)"), $recordcount, $writearray['firstname'], $writearray['lastname'], $writearray['email']);
                             tracevar($oToken->getErrors());
                         } else {
                             $xz++;
                         }
                     }
                     $xv++;
                 }
                 $recordcount++;
             }
             $recordcount = $recordcount - 1;
             unlink($sFilePath);
             $aData['tokenlistarray'] = $tokenlistarray;
             $aData['xz'] = $xz;
             $aData['xv'] = $xv;
             $aData['recordcount'] = $recordcount;
             $aData['firstline'] = $firstline;
             $aData['duplicatelist'] = $duplicatelist;
             $aData['invalidformatlist'] = $invalidformatlist;
             $aData['invalidemaillist'] = $invalidemaillist;
             $aData['errorlist'] = $errorlist;
             $aData['thissurvey'] = getSurveyInfo($iSurveyId);
             $aData['iSurveyId'] = $aData['surveyid'] = $iSurveyId;
             $this->_renderWrappedTemplate('token', array('tokenbar', 'csvpost'), $aData);
         }
     } else {
         $aData['aEncodings'] = $aEncodings;
         $aData['iSurveyId'] = $iSurveyId;
         $aData['thissurvey'] = getSurveyInfo($iSurveyId);
         $aData['surveyid'] = $iSurveyId;
         $aTokenTableFields = getTokenFieldsAndNames($iSurveyId);
         unset($aTokenTableFields['sent']);
         unset($aTokenTableFields['remindersent']);
         unset($aTokenTableFields['remindercount']);
         unset($aTokenTableFields['usesleft']);
         foreach ($aTokenTableFields as $sKey => $sValue) {
             if ($sValue['description'] != $sKey) {
                 $sValue['description'] .= ' - ' . $sKey;
             }
             $aNewTokenTableFields[$sKey] = $sValue['description'];
         }
         $aData['aTokenTableFields'] = $aNewTokenTableFields;
         $this->_renderWrappedTemplate('token', array('tokenbar', 'csvupload'), $aData);
     }
 }
 private function addResult($sString, $sType = 'warning', $oTrace = NULL)
 {
     if (in_array($sType, array('success', 'warning', 'error')) && is_string($sString) && $sString) {
         $this->aResult[$sType][] = $sString;
     } elseif (is_numeric($sType)) {
         $this->aResult['question'][] = $sType;
     } elseif ($sType) {
         tracevar(array($sType, $sString));
     }
     if ($oTrace) {
         tracevar($oTrace);
     }
 }