Пример #1
1
 public function deactivate($contractor_id)
 {
     $criteria = new CDbCriteria();
     $criteria->condition = "user_type='contractor' AND userid=" . $contractor_id;
     Affiliates::model()->deleteAll($criteria);
     Referral::model()->deleteAll($criteria);
     $criteria = new CDbCriteria();
     $criteria->condition = "owner_user_type='contractor' AND owner_id=" . $contractor_id;
     Answers::model()->deleteAll($criteria);
     Questions::model()->deleteAll($criteria);
     $criteria = new CDbCriteria();
     $criteria->condition = "user_type='contractor' AND deleted_by=" . $contractor_id;
     Messagedeleted::model()->deleteAll($criteria);
     $criteria = new CDbCriteria();
     $criteria->condition = "from_user_type='contractor' AND from_id=" . $contractor_id;
     Messages::model()->deleteAll($criteria);
     $criteria = new CDbCriteria();
     $criteria->condition = "to_user_type='contractor' AND to_id=" . $contractor_id;
     Messages::model()->deleteAll($criteria);
     $criteria = new CDbCriteria();
     $criteria->condition = "viewed_user_type='contractor' AND viewed_by=" . $contractor_id;
     QuestionViews::model()->deleteAll($criteria);
     $criteria = new CDbCriteria();
     $criteria->condition = "referred_by_type='contractor' AND referred_by=" . $contractor_id;
     Referral::model()->deleteAll($criteria);
     $criteria = new CDbCriteria();
     $criteria->condition = "invited_id=" . $contractor_id;
     ContractorTeam::model()->deleteAll($criteria);
     $criteria = new CDbCriteria();
     $criteria->condition = "contractor_id=" . $contractor_id;
     ContractorBond::model()->deleteAll($criteria);
     ContractorLicense::model()->deleteAll($criteria);
     ContractorPoints::model()->deleteAll($criteria);
     ContractorSocials::model()->deleteAll($criteria);
     ContractorTeam::model()->deleteAll($criteria);
     ContractorViews::model()->deleteAll($criteria);
     Contractorphotos::model()->deleteAll($criteria);
     Feedback::model()->deleteAll($criteria);
     $criteria = new CDbCriteria();
     $criteria->condition = "ContractorId=" . $contractor_id;
     self::model()->deleteAll($criteria);
     return true;
 }
Пример #2
0
 /**
  * Returns the data model based on the primary key given in the GET variable.
  * If the data model is not found, an HTTP exception will be raised.
  * @param integer $id the ID of the model to be loaded
  * @return Questions the loaded model
  * @throws CHttpException
  */
 public function loadModel($id)
 {
     $model = Questions::model()->findByPk($id);
     if ($model === null) {
         throw new CHttpException(404, 'The requested page does not exist.');
     }
     return $model;
 }
 public function checkifCanVote()
 {
     $can_vote = 0;
     $q_id = Yii::app()->Ini->v('question_id');
     $question = Questions::model()->findByPk($q_id);
     if (!Yii::app()->user->isGuest) {
         $viewed_by = Yii::app()->user->getId();
         $viewed_user_type = Yii::app()->user->role;
         $vote = QuestionVotes::model()->countByAttributes(array('question_id' => $q_id, 'voted_by' => $viewed_by, 'voted_user_type' => $viewed_user_type));
         if ($vote == 0 && ($question->owner_id != $viewed_by && $question->owner_user_type != $viewed_user_type)) {
             $can_vote = 1;
         }
     }
     $return = array('can_vote' => $can_vote);
     $this->renderJSON($can_vote);
 }
 /**
  * This function checks the LimeSurvey database for logical consistency and returns an according array
  * containing all issues in the particular tables.
  * @returns Array with all found issues.
  */
 protected function _checkintegrity()
 {
     $clang = Yii::app()->lang;
     /*** Plainly delete survey permissions if the survey or user does not exist ***/
     $users = User::model()->findAll();
     $uids = array();
     foreach ($users as $user) {
         $uids[] = $user['uid'];
     }
     $criteria = new CDbCriteria();
     $criteria->addNotInCondition('uid', $uids, 'OR');
     $surveys = Survey::model()->findAll();
     $sids = array();
     foreach ($surveys as $survey) {
         $sids[] = $survey['sid'];
     }
     $criteria->addNotInCondition('sid', $sids, 'OR');
     Survey_permissions::model()->deleteAll($criteria);
     // Deactivate surveys that have a missing response table
     foreach ($surveys as $survey) {
         if ($survey['active'] == 'Y' && !tableExists("{{survey_{$survey['sid']}}}")) {
             Survey::model()->updateByPk($survey['sid'], array('active' => 'N'));
         }
     }
     // Fix subquestions
     fixSubquestions();
     /*** Check for active survey tables with missing survey entry and rename them ***/
     $sDBPrefix = Yii::app()->db->tablePrefix;
     $sQuery = dbSelectTablesLike('{{survey}}\\_%');
     $aResult = dbQueryOrFalse($sQuery) or safeDie("Couldn't get list of conditions from database<br />{$sQuery}<br />");
     foreach ($aResult->readAll() as $aRow) {
         $sTableName = substr(reset($aRow), strlen($sDBPrefix));
         if ($sTableName == 'survey_permissions' || $sTableName == 'survey_links' || $sTableName == 'survey_url_parameters') {
             continue;
         }
         $aTableName = explode('_', $sTableName);
         if (isset($aTableName[1]) && ctype_digit($aTableName[1])) {
             $iSurveyID = $aTableName[1];
             if (!in_array($iSurveyID, $sids)) {
                 $sDate = date('YmdHis') . rand(1, 1000);
                 $sOldTable = "survey_{$iSurveyID}";
                 $sNewTable = "old_survey_{$iSurveyID}_{$sDate}";
                 try {
                     $deactivateresult = Yii::app()->db->createCommand()->renameTable("{{{$sOldTable}}}", "{{{$sNewTable}}}");
                 } catch (CDbException $e) {
                     die('Couldn\'t make backup of the survey table. Please try again. The database reported the following error:<br />' . htmlspecialchars($e) . '<br />');
                 }
             }
         }
     }
     /*** Check for active token tables with missing survey entry ***/
     $aResult = dbQueryOrFalse(dbSelectTablesLike('{{tokens}}\\_%')) or safeDie("Couldn't get list of conditions from database<br />{$sQuery}<br />");
     foreach ($aResult->readAll() as $aRow) {
         $sTableName = substr(reset($aRow), strlen($sDBPrefix));
         $iSurveyID = substr($sTableName, strpos($sTableName, '_') + 1);
         if (!in_array($iSurveyID, $sids)) {
             $sDate = date('YmdHis') . rand(1, 1000);
             $sOldTable = "tokens_{$iSurveyID}";
             $sNewTable = "old_tokens_{$iSurveyID}_{$sDate}";
             try {
                 $deactivateresult = Yii::app()->db->createCommand()->renameTable("{{{$sOldTable}}}", "{{{$sNewTable}}}");
             } catch (CDbException $e) {
                 die('Couldn\'t make backup of the survey table. Please try again. The database reported the following error:<br />' . htmlspecialchars($e) . '<br />');
             }
         }
     }
     /**********************************************************************/
     /*     Check conditions                                               */
     /**********************************************************************/
     // TMSW Conditions->Relevance:  Replace this with analysis of relevance
     $conditions = Conditions::model()->findAll();
     if (Conditions::model()->hasErrors()) {
         safeDie(Conditions::model()->getError());
     }
     $okQuestion = array();
     foreach ($conditions as $condition) {
         if ($condition['cqid'] != 0) {
             // skip case with cqid=0 for codnitions on {TOKEN:EMAIL} for instance
             if (!array_key_exists($condition['cqid'], $okQuestion)) {
                 $iRowCount = Questions::model()->countByAttributes(array('qid' => $condition['cqid']));
                 if (Questions::model()->hasErrors()) {
                     safeDie(Questions::model()->getError());
                 }
                 if (!$iRowCount) {
                     $aDelete['conditions'][] = array('cid' => $condition['cid'], 'reason' => $clang->gT('No matching CQID'));
                 } else {
                     $okQuestion[$condition['cqid']] = $condition['cqid'];
                 }
             }
         }
         if ($condition['cfieldname']) {
             if (preg_match('/^\\+{0,1}[0-9]+X[0-9]+X*$/', $condition['cfieldname'])) {
                 // only if cfieldname isn't Tag such as {TOKEN:EMAIL} or any other token
                 list($surveyid, $gid, $rest) = explode('X', $condition['cfieldname']);
                 $iRowCount = count(Groups::model()->findAllByAttributes(array('gid' => $gid)));
                 if (Groups::model()->hasErrors()) {
                     safeDie(Groups::model()->getError());
                 }
                 if (!$iRowCount) {
                     $aDelete['conditions'][] = array('cid' => $condition['cid'], 'reason' => $clang->gT('No matching CFIELDNAME group!') . " ({$gid}) ({$condition['cfieldname']})");
                 }
             }
         } elseif (!$condition['cfieldname']) {
             $aDelete['conditions'][] = array('cid' => $condition['cid'], 'reason' => $clang->gT('No CFIELDNAME field set!') . " ({$condition['cfieldname']})");
         }
     }
     /**********************************************************************/
     /*     Check question attributes                                      */
     /**********************************************************************/
     $question_attributes = Question_attributes::model()->findAllBySql('select qid from {{question_attributes}} where qid not in (select qid from {{questions}})');
     if (Question_attributes::model()->hasErrors()) {
         safeDie(Question_attributes::model()->getError());
     }
     foreach ($question_attributes as $question_attribute) {
         $aDelete['questionattributes'][] = array('qid' => $question_attribute['qid']);
     }
     // foreach
     /**********************************************************************/
     /*     Check default values                                           */
     /**********************************************************************/
     $questions = Questions::model()->findAll();
     if (Questions::model()->hasErrors()) {
         safeDie(Questions::model()->getError());
     }
     $qids = array();
     foreach ($questions as $question) {
         $qids[] = $question['qid'];
     }
     $criteria = new CDbCriteria();
     $criteria->addNotInCondition('qid', $qids);
     $aDelete['defaultvalues'] = count(Defaultvalues::model()->findAll($criteria));
     if (Defaultvalues::model()->hasErrors()) {
         safeDie(Defaultvalues::model()->getError());
     }
     /**********************************************************************/
     /*     Check quotas                                                   */
     /**********************************************************************/
     $surveys = Survey::model()->findAll();
     if (Survey::model()->hasErrors()) {
         safeDie(Survey::model()->getError());
     }
     $sids = array();
     foreach ($surveys as $survey) {
         $sids[] = $survey['sid'];
     }
     $criteria = new CDbCriteria();
     $criteria->addNotInCondition('sid', $sids);
     $aDelete['quotas'] = count(Quota::model()->findAll($criteria));
     if (Quota::model()->hasErrors()) {
         safeDie(Quota::model()->getError());
     }
     /**********************************************************************/
     /*     Check quota languagesettings                                   */
     /**********************************************************************/
     $quotas = Quota::model()->findAll();
     if (Quota::model()->hasErrors()) {
         safeDie(Quota::model()->getError());
     }
     $ids = array();
     foreach ($quotas as $quota) {
         $ids[] = $quota['id'];
     }
     $criteria = new CDbCriteria();
     $criteria->addNotInCondition('quotals_quota_id', $ids);
     $aDelete['quotals'] = count(Quota_languagesettings::model()->findAll($criteria));
     if (Quota_languagesettings::model()->hasErrors()) {
         safeDie(Quota_languagesettings::model()->getError());
     }
     /**********************************************************************/
     /*     Check quota members                                   */
     /**********************************************************************/
     $quotas = Quota::model()->findAll();
     $quota_ids = array();
     foreach ($quotas as $quota) {
         $quota_ids[] = $quota['id'];
     }
     $criteria = new CDbCriteria();
     $criteria->addNotInCondition('quota_id', $quota_ids);
     $questions = Questions::model()->findAll();
     $qids = array();
     foreach ($questions as $question) {
         $qids[] = $question['qid'];
     }
     $criteria->addNotInCondition('qid', $qids, 'OR');
     $surveys = Survey::model()->findAll();
     $sids = array();
     foreach ($surveys as $survey) {
         $sids[] = $survey['sid'];
     }
     $criteria->addNotInCondition('sid', $sids, 'OR');
     $aDelete['quotamembers'] = count(Quota_members::model()->findAll($criteria));
     if (Quota_members::model()->hasErrors()) {
         safeDie(Quota_members::model()->getError());
     }
     /**********************************************************************/
     /*     Check assessments                                              */
     /**********************************************************************/
     $criteria = new CDbCriteria();
     $criteria->compare('scope', 'T');
     $assessments = Assessment::model()->findAll($criteria);
     if (Assessment::model()->hasErrors()) {
         safeDie(Assessment::model()->getError());
     }
     foreach ($assessments as $assessment) {
         $iAssessmentCount = count(Survey::model()->findAllByPk($assessment['sid']));
         if (Survey::model()->hasErrors()) {
             safeDie(Survey::model()->getError());
         }
         if (!$iAssessmentCount) {
             $aDelete['assessments'][] = array('id' => $assessment['id'], 'assessment' => $assessment['name'], 'reason' => $clang->gT('No matching survey'));
         }
     }
     $criteria = new CDbCriteria();
     $criteria->compare('scope', 'G');
     $assessments = Assessment::model()->findAll($criteria);
     if (Assessment::model()->hasErrors()) {
         safeDie(Assessment::model()->getError());
     }
     foreach ($assessments as $assessment) {
         $iAssessmentCount = count(Groups::model()->findAllByPk(array('gid' => $assessment['gid'], 'language' => $assessment['language'])));
         if (Groups::model()->hasErrors()) {
             safeDie(Groups::model()->getError());
         }
         if (!$iAssessmentCount) {
             $aDelete['assessments'][] = array('id' => $assessment['id'], 'assessment' => $assessment['name'], 'reason' => $clang->gT('No matching group'));
         }
     }
     /**********************************************************************/
     /*     Check answers                                                  */
     /**********************************************************************/
     $answers = Answers::model()->findAll();
     if (Answers::model()->hasErrors()) {
         safeDie(Answers::model()->getError());
     }
     $okQuestion = array();
     foreach ($answers as $answer) {
         if (!array_key_exists($answer['qid'], $okQuestion)) {
             $iAnswerCount = Questions::model()->countByAttributes(array('qid' => $answer['qid']));
             if (Questions::model()->hasErrors()) {
                 safeDie(Questions::model()->getError());
             }
             if (!$iAnswerCount) {
                 $aDelete['answers'][] = array('qid' => $answer['qid'], 'code' => $answer['code'], 'reason' => $clang->gT('No matching question'));
             } else {
                 $okQuestion[$answer['qid']] = $answer['qid'];
             }
         }
     }
     /***************************************************************************/
     /*   Check survey languagesettings and restore them if they don't exist    */
     /***************************************************************************/
     $surveys = Survey::model()->findAll();
     foreach ($surveys as $survey) {
         $aLanguages = $survey->additionalLanguages;
         $aLanguages[] = $survey->language;
         foreach ($aLanguages as $langname) {
             if ($langname) {
                 $oLanguageSettings = Surveys_languagesettings::model()->find('surveyls_survey_id=:surveyid AND surveyls_language=:langname', array(':surveyid' => $survey->sid, ':langname' => $langname));
                 if (!$oLanguageSettings) {
                     $oLanguageSettings = new Surveys_languagesettings();
                     $languagedetails = getLanguageDetails($langname);
                     $insertdata = array('surveyls_survey_id' => $survey->sid, 'surveyls_language' => $langname, 'surveyls_title' => '', 'surveyls_dateformat' => $languagedetails['dateformat']);
                     foreach ($insertdata as $k => $v) {
                         $oLanguageSettings->{$k} = $v;
                     }
                     $usresult = $oLanguageSettings->save();
                 }
             }
         }
     }
     /**********************************************************************/
     /*     Check survey language settings                                 */
     /**********************************************************************/
     $surveys = Survey::model()->findAll();
     if (Survey::model()->hasErrors()) {
         safeDie(Survey::model()->getError());
     }
     $sids = array();
     foreach ($surveys as $survey) {
         $sids[] = $survey['sid'];
     }
     $criteria = new CDbCriteria();
     $criteria->addNotInCondition('surveyls_survey_id', $sids);
     $surveys_languagesettings = Surveys_languagesettings::model()->findAll($criteria);
     if (Surveys_languagesettings::model()->hasErrors()) {
         safeDie(Surveys_languagesettings::model()->getError());
     }
     foreach ($surveys_languagesettings as $surveys_languagesetting) {
         $aDelete['surveylanguagesettings'][] = array('slid' => $surveys_languagesetting['surveyls_survey_id'], 'reason' => $clang->gT('The related survey is missing.'));
     }
     /**********************************************************************/
     /*     Check questions                                                */
     /**********************************************************************/
     $questions = Questions::model()->findAll();
     if (Questions::model()->hasErrors()) {
         safeDie(Questions::model()->getError());
     }
     $groups = Groups::model()->findAll();
     if (Groups::model()->hasErrors()) {
         safeDie(Groups::model()->getError());
     }
     $gids = array();
     foreach ($groups as $group) {
         $gids[] = $group['gid'];
     }
     foreach ($questions as $question) {
         //Make sure the group exists
         if (!in_array($question['gid'], $gids)) {
             $aDelete['questions'][] = array('qid' => $question['qid'], 'reason' => $clang->gT('No matching group') . " ({$question['gid']})");
         }
         //Make sure survey exists
         if (!in_array($question['sid'], $sids)) {
             $aDelete['questions'][] = array('qid' => $question['qid'], 'reason' => $clang->gT('There is no matching survey.') . " ({$question['sid']})");
         }
     }
     /**********************************************************************/
     /*     Check groups                                                   */
     /**********************************************************************/
     $surveys = Survey::model()->findAll();
     if (Survey::model()->hasErrors()) {
         safeDie(Survey::model()->getError());
     }
     $sids = array();
     foreach ($surveys as $survey) {
         $sids[] = $survey['sid'];
     }
     $criteria = new CDbCriteria();
     $criteria->addNotInCondition('sid', $sids);
     $groups = Groups::model()->findAll($criteria);
     foreach ($groups as $group) {
         $aDelete['groups'][] = array('gid' => $group['gid'], 'reason' => $clang->gT('There is no matching survey.') . ' SID:' . $group['sid']);
     }
     /**********************************************************************/
     /*     Check old survey tables                                        */
     /**********************************************************************/
     //1: Get list of 'old_survey' tables and extract the survey id
     //2: Check if that survey id still exists
     //3: If it doesn't offer it for deletion
     $sQuery = dbSelectTablesLike('{{old_survey}}%');
     $aResult = dbQueryOrFalse($sQuery) or safeDie("Couldn't get list of conditions from database<br />{$sQuery}<br />");
     $aTables = $aResult->readAll();
     $aOldSIDs = array();
     $aSIDs = array();
     foreach ($aTables as $sTable) {
         $sTable = reset($sTable);
         list($sOldText, $SurveyText, $iSurveyID, $sDate) = explode('_', substr($sTable, strlen($sDBPrefix)));
         $aOldSIDs[] = $iSurveyID;
         $aFullOldSIDs[$iSurveyID][] = $sTable;
     }
     $aOldSIDs = array_unique($aOldSIDs);
     //$sQuery = 'SELECT sid FROM {{surveys}} ORDER BY sid';
     //$oResult = dbExecuteAssoc($sQuery) or safeDie('Couldn\'t get unique survey ids');
     $surveys = Survey::model()->findAll();
     if (Survey::model()->hasErrors()) {
         safeDie(Survey::model()->getError());
     }
     $aSIDs = array();
     foreach ($surveys as $survey) {
         $aSIDs[] = $survey['sid'];
     }
     foreach ($aOldSIDs as $iOldSID) {
         if (!in_array($iOldSID, $aSIDs)) {
             foreach ($aFullOldSIDs[$iOldSID] as $sTableName) {
                 $aDelete['orphansurveytables'][] = $sTableName;
             }
         } else {
             foreach ($aFullOldSIDs[$iOldSID] as $sTableName) {
                 $aTableParts = explode('_', substr($sTableName, strlen($sDBPrefix)));
                 if (count($aTableParts) == 4) {
                     $sOldText = $aTableParts[0];
                     $SurveyText = $aTableParts[1];
                     $iSurveyID = $aTableParts[2];
                     $sDateTime = $aTableParts[3];
                     $sType = $clang->gT('responses');
                 } elseif (count($aTableParts) == 5) {
                     //This is a timings table (
                     $sOldText = $aTableParts[0];
                     $SurveyText = $aTableParts[1];
                     $iSurveyID = $aTableParts[2];
                     $sDateTime = $aTableParts[4];
                     $sType = $clang->gT('timings');
                 }
                 $iYear = substr($sDateTime, 0, 4);
                 $iMonth = substr($sDateTime, 4, 2);
                 $iDay = substr($sDateTime, 6, 2);
                 $iHour = substr($sDateTime, 8, 2);
                 $iMinute = substr($sDateTime, 10, 2);
                 $sDate = date('d M Y  H:i', mktime($iHour, $iMinute, 0, $iMonth, $iDay, $iYear));
                 $sQuery = 'SELECT count(*) as recordcount FROM ' . $sTableName;
                 $aFirstRow = Yii::app()->db->createCommand($sQuery)->queryRow();
                 if ($aFirstRow['recordcount'] == 0) {
                     // empty table - so add it to immediate deletion
                     $aDelete['orphansurveytables'][] = $sTableName;
                 } else {
                     $aOldSurveyTableAsk[] = array('table' => $sTableName, 'details' => sprintf($clang->gT('Survey ID %d saved at %s containing %d record(s) (%s)'), $iSurveyID, $sDate, $aFirstRow['recordcount'], $sType));
                 }
             }
         }
     }
     /**********************************************************************/
     /*     CHECK OLD TOKEN  TABLES                                        */
     /**********************************************************************/
     //1: Get list of 'old_token' tables and extract the survey id
     //2: Check if that survey id still exists
     //3: If it doesn't offer it for deletion
     $aResult = dbQueryOrFalse(dbSelectTablesLike('{{old_token}}%')) or safeDie("Couldn't get list of conditions from database<br />{$sQuery}<br />");
     $aTables = $aResult->readAll();
     $aOldTokenSIDs = array();
     $aTokenSIDs = array();
     $aFullOldTokenSIDs = array();
     foreach ($aTables as $sTable) {
         $sTable = reset($sTable);
         list($sOldText, $SurveyText, $iSurveyID, $sDateTime) = explode('_', substr($sTable, strlen($sDBPrefix)));
         $aTokenSIDs[] = $iSurveyID;
         $aFullOldTokenSIDs[$iSurveyID][] = $sTable;
     }
     $aOldTokenSIDs = array_unique($aTokenSIDs);
     $surveys = Survey::model()->findAll();
     if (Survey::model()->hasErrors()) {
         safeDie(Survey::model()->getError());
     }
     $aSIDs = array();
     foreach ($surveys as $survey) {
         $aSIDs[] = $survey['sid'];
     }
     foreach ($aOldTokenSIDs as $iOldTokenSID) {
         if (!in_array($iOldTokenSID, $aOldTokenSIDs)) {
             foreach ($aFullOldTokenSIDs[$iOldTokenSID] as $sTableName) {
                 $aDelete['orphantokentables'][] = $sTableName;
             }
         } else {
             foreach ($aFullOldTokenSIDs[$iOldTokenSID] as $sTableName) {
                 list($sOldText, $sTokensText, $iSurveyID, $sDateTime) = explode('_', substr($sTableName, strlen($sDBPrefix)));
                 $iYear = substr($sDateTime, 0, 4);
                 $iMonth = substr($sDateTime, 4, 2);
                 $iDay = substr($sDateTime, 6, 2);
                 $iHour = substr($sDateTime, 8, 2);
                 $iMinute = substr($sDateTime, 10, 2);
                 $sDate = date('D, d M Y  h:i a', mktime($iHour, $iMinute, 0, $iMonth, $iDay, $iYear));
                 $sQuery = 'SELECT count(*) as recordcount FROM ' . $sTableName;
                 $aFirstRow = Yii::app()->db->createCommand($sQuery)->queryRow();
                 if ($aFirstRow['recordcount'] == 0) {
                     // empty table - so add it to immediate deletion
                     $aDelete['orphantokentables'][] = $sTableName;
                 } else {
                     $aOldTokenTableAsk[] = array('table' => $sTableName, 'details' => sprintf($clang->gT('Survey ID %d saved at %s containing %d record(s)'), $iSurveyID, $sDate, $aFirstRow['recordcount']));
                 }
             }
         }
     }
     if ($aDelete['defaultvalues'] == 0 && $aDelete['quotamembers'] == 0 && $aDelete['quotas'] == 0 && $aDelete['quotals'] == 0 && count($aDelete) == 4) {
         $aDelete['integrityok'] = true;
     } else {
         $aDelete['integrityok'] = false;
     }
     if (!isset($aOldTokenTableAsk) && !isset($aOldSurveyTableAsk)) {
         $aDelete['redundancyok'] = true;
     } else {
         $aDelete['redundancyok'] = false;
         $aDelete['redundanttokentables'] = array();
         $aDelete['redundantsurveytables'] = array();
         if (isset($aOldTokenTableAsk)) {
             $aDelete['redundanttokentables'] = $aOldTokenTableAsk;
         }
         if (isset($aOldSurveyTableAsk)) {
             $aDelete['redundantsurveytables'] = $aOldSurveyTableAsk;
         }
     }
     /**********************************************************************/
     /*     CHECK CPDB SURVEY_LINKS TABLE FOR REDUNDENT TOKEN TABLES       */
     /**********************************************************************/
     //1: Get distinct list of survey_link survey ids, check if tokens
     //   table still exists for each one, and remove if not
     /* TODO */
     /**********************************************************************/
     /*     CHECK CPDB SURVEY_LINKS TABLE FOR REDUNDENT TOKEN ENTRIES      */
     /**********************************************************************/
     //1: For each survey_link, see if the matching entry still exists in
     //   the token table and remove if it doesn't.
     /* TODO */
     return $aDelete;
 }
 public function actionFind()
 {
     $location = Yii::app()->Ini->getlocationbyip(Yii::app()->Ini->rip('ip'));
     $projects = Projecttypes::model()->findAll(array('order' => 'Name ASC'));
     $criteria = new CDbCriteria();
     $criteria->order = "question_id DESC";
     $criteria->limit = 5;
     $questions = Questions::model()->findAll($criteria);
     $states = States::model()->findAll(array('order' => 'Name ASC'));
     $city = Yii::app()->Ini->v('city');
     $project = Yii::app()->Ini->v('project');
     $zipcode = Yii::app()->Ini->v('zipcode');
     $match = Yii::app()->Ini->v('match');
     $homeowner_projects = $this->getHomeOwnerProjects();
     $pie = new SimplePie();
     $pie->set_feed_url('http://media.handyman.com/feed/');
     $pie->init();
     $pie->handle_content_type();
     if ($city) {
         $details = Cities::model()->findByAttributes(array('RewriteUrl' => $city . "/"));
         if (count($details) > 0) {
             $city_name = $details->Name;
         } else {
             $city_name = "";
         }
         $criteria = new CDbCriteria();
         $criteria->condition = "City like '%{$city_name}%'";
         $count = Contractors::model()->count($criteria);
         $pages = new CPagination($count);
         // results per page
         $pages->pageSize = 5;
         $pages->applyLimit($criteria);
         $models = Contractors::model()->findAll($criteria);
         $this->render('find_result', array('models' => $models, 'pages' => $pages, 'projects' => $projects, 'records' => $count, 'city_name' => $city_name, 'location' => $city_name . ",USA", 'questions' => $questions, 'homeowner_projects' => $homeowner_projects, 'feed' => $pie));
     } else {
         if ($project && $zipcode) {
             $details = Projecttypes::model()->findByAttributes(array('ProjectTypeId' => $project));
             if (count($details) > 0) {
                 $oid = $details->OID;
                 $city_name = $details->Name;
                 $home_advisor = Yii::app()->Ini->searchhomeadvisor($zipcode, $oid);
                 //$home_advisor = Yii::app()->Ini->searchhomeadvisor('11741','12005');
                 if ($home_advisor == false) {
                     $home_advisor_results = false;
                 } else {
                     $home_advisor_results = $home_advisor['serviceProvider'];
                 }
             }
             $criteria = new CDbCriteria();
             $criteria->condition = "ProjectTypeId='" . $project . "' AND Zip='" . $zipcode . "'";
             $count = Contractors::model()->count($criteria);
             $pages = new CPagination($count);
             // results per page
             $pages->pageSize = 5;
             $pages->applyLimit($criteria);
             $models = Contractors::model()->findAll($criteria);
             $this->render('match-result', array('pages' => $pages, 'result' => $models, 'home_advisors' => $home_advisor_results, 'projects' => $projects, 'states' => $states, 'location' => $location, 'city_name' => $city_name . ' In Zipcode ' . $zipcode, 'questions' => $questions, 'feed' => $pie));
         } else {
             if ($project) {
                 $details = Projecttypes::model()->findByAttributes(array('ProjectTypeId' => $project));
                 if (count($details) > 0) {
                     $city_name = $details->Name;
                 }
                 $criteria = new CDbCriteria();
                 $criteria->condition = "ProjectTypeId=" . $project;
                 $count = Contractors::model()->count($criteria);
                 $pages = new CPagination($count);
                 // results per page
                 $pages->pageSize = 5;
                 $pages->applyLimit($criteria);
                 $models = Contractors::model()->findAll($criteria);
                 $this->render('find_result', array('models' => $models, 'pages' => $pages, 'projects' => $projects, 'records' => $count, 'city_name' => $city_name, 'location' => $location, 'questions' => $questions, 'homeowner_projects' => $homeowner_projects, 'feed' => $pie));
             } else {
                 if ($zipcode) {
                     $criteria = new CDbCriteria();
                     $criteria->condition = "Zip='{$zipcode}'";
                     $count = Contractors::model()->count($criteria);
                     $pages = new CPagination($count);
                     // results per page
                     $pages->pageSize = 5;
                     $pages->applyLimit($criteria);
                     $models = Contractors::model()->findAll($criteria);
                     $this->render('find_result', array('models' => $models, 'pages' => $pages, 'projects' => $projects, 'records' => $count, 'city_name' => $zipcode, 'questions' => $questions, 'homeowner_projects' => $homeowner_projects, 'feed' => $pie));
                 } else {
                     if ($match) {
                         $proj = Projects::model()->findByPk($match);
                         if (count($proj) > 0) {
                             $proj_zipcode = $proj->zipcode;
                             $project_type_id = $proj->project_type_id;
                             $criteria = new CDbCriteria();
                             $criteria->condition = "ProjectTypeId='" . $project_type_id . "' AND Zip = '" . $proj_zipcode . "'";
                             $count = Contractors::model()->count($criteria);
                             $pages = new CPagination($count);
                             $result = Contractors::model()->findAll($criteria);
                             $projecttypes = ProjectTypes::model()->findByPK($project_type_id);
                             $proj_oid = $projecttypes->OID;
                             //$proj_zipcode = '11741';
                             //$proj_oid = '12070';
                             $home_advisor = Yii::app()->Ini->searchhomeadvisor($proj_zipcode, $proj_oid);
                             if ($home_advisor == false) {
                                 $home_advisor_results = false;
                             } else {
                                 $home_advisor_results = $home_advisor['serviceProvider'];
                             }
                             $this->render('match-result', array('pages' => $pages, 'result' => $result, 'home_advisors' => $home_advisor_results, 'projects' => $projects, 'states' => $states, 'location' => $location, 'city_name' => $this->getProjectTypeName($project_type_id) . ' In Zipcode ' . $proj_zipcode, 'questions' => $questions, 'feed' => $pie));
                         } else {
                             $this->render('find_form', array('projects' => $projects, 'states' => $states, 'location' => $location, 'questions' => $questions));
                         }
                     } else {
                         $this->render('find_form', array('projects' => $projects, 'states' => $states, 'location' => $location, 'questions' => $questions, 'feed' => $pie));
                     }
                 }
             }
         }
     }
 }
Пример #6
0
 private function query($type, $action, $iSurveyID, $tolang, $baselang, $id1 = "", $id2 = "", $new = "")
 {
     $amTypeOptions = array();
     switch ($action) {
         case "queryto":
             $baselang = $tolang;
         case "querybase":
             switch ($type) {
                 case 'title':
                 case 'description':
                 case 'welcome':
                 case 'end':
                 case 'emailinvite':
                 case 'emailinvitebody':
                 case 'emailreminder':
                 case 'emailreminderbody':
                 case 'emailconfirmation':
                 case 'emailconfirmationbody':
                 case 'emailregistration':
                 case 'emailregistrationbody':
                 case 'email_confirm':
                 case 'email_confirmbody':
                     return Surveys_languagesettings::model()->findAllByPk(array('surveyls_survey_id' => $iSurveyID, 'surveyls_language' => $baselang));
                 case 'group':
                 case 'group_desc':
                     return Groups::model()->findAllByAttributes(array('sid' => $iSurveyID, 'language' => $baselang), array('order' => 'gid'));
                 case 'question':
                 case 'question_help':
                     return Questions::model()->findAllByAttributes(array('sid' => $iSurveyID, 'language' => $baselang, 'parent_qid' => 0), array('order' => 'question_order, scale_id'));
                 case 'subquestion':
                     return Questions::model()->with('parents', 'groups')->findAllByAttributes(array('sid' => $iSurveyID, 'language' => $baselang), array('order' => 'groups.group_order, parents.question_order, t.scale_id, t.question_order', 'condition' => 'parents.language=:baselang1 AND groups.language=:baselang2 AND t.parent_qid>0', 'params' => array(':baselang1' => $baselang, ':baselang2' => $baselang)));
                 case 'answer':
                     return Answers::model()->with('questions', 'groups')->findAllByAttributes(array('language' => $baselang), array('order' => 'groups.group_order, questions.question_order, t.scale_id, t.sortorder', 'condition' => 'questions.sid=:sid AND questions.language=:baselang1 AND groups.language=:baselang2', 'params' => array(':baselang1' => $baselang, ':baselang2' => $baselang, ':sid' => $iSurveyID)));
             }
         case "queryupdate":
             switch ($type) {
                 case 'title':
                     return Surveys_languagesettings::model()->updateByPk(array('surveyls_survey_id' => $iSurveyID, 'surveyls_language' => $tolang), array('surveyls_title' => $new));
                 case 'description':
                     return Surveys_languagesettings::model()->updateByPk(array('surveyls_survey_id' => $iSurveyID, 'surveyls_language' => $tolang), array('surveyls_description' => $new));
                 case 'welcome':
                     return Surveys_languagesettings::model()->updateByPk(array('surveyls_survey_id' => $iSurveyID, 'surveyls_language' => $tolang), array('surveyls_welcometext' => $new));
                 case 'end':
                     return Surveys_languagesettings::model()->updateByPk(array('surveyls_survey_id' => $iSurveyID, 'surveyls_language' => $tolang), array('surveyls_endtext' => $new));
                 case 'emailinvite':
                     return Surveys_languagesettings::model()->updateByPk(array('surveyls_survey_id' => $iSurveyID, 'surveyls_language' => $tolang), array('surveyls_email_invite_subj' => $new));
                 case 'emailinvitebody':
                     return Surveys_languagesettings::model()->updateByPk(array('surveyls_survey_id' => $iSurveyID, 'surveyls_language' => $tolang), array('surveyls_email_invite' => $new));
                 case 'emailreminder':
                     return Surveys_languagesettings::model()->updateByPk(array('surveyls_survey_id' => $iSurveyID, 'surveyls_language' => $tolang), array('surveyls_email_remind_subj' => $new));
                 case 'emailreminderbody':
                     return Surveys_languagesettings::model()->updateByPk(array('surveyls_survey_id' => $iSurveyID, 'surveyls_language' => $tolang), array('surveyls_email_remind' => $new));
                 case 'emailconfirmation':
                     return Surveys_languagesettings::model()->updateByPk(array('surveyls_survey_id' => $iSurveyID, 'surveyls_language' => $tolang), array('surveyls_email_confirm_subj' => $new));
                 case 'emailconfirmationbody':
                     return Surveys_languagesettings::model()->updateByPk(array('surveyls_survey_id' => $iSurveyID, 'surveyls_language' => $tolang), array('surveyls_email_confirm' => $new));
                 case 'emailregistration':
                     return Surveys_languagesettings::model()->updateByPk(array('surveyls_survey_id' => $iSurveyID, 'surveyls_language' => $tolang), array('surveyls_email_register_subj' => $new));
                 case 'emailregistrationbody':
                     return Surveys_languagesettings::model()->updateByPk(array('surveyls_survey_id' => $iSurveyID, 'surveyls_language' => $tolang), array('surveyls_email_register' => $new));
                 case 'email_confirm':
                     return Surveys_languagesettings::model()->updateByPk(array('surveyls_survey_id' => $iSurveyID, 'surveyls_language' => $tolang), array('surveyls_email_confirm_subject' => $new));
                 case 'email_confirmbody':
                     return Surveys_languagesettings::model()->updateByPk(array('surveyls_survey_id' => $iSurveyID, 'surveyls_language' => $tolang), array('surveyls_email_confirm' => $new));
                 case 'group':
                     return Groups::model()->updateByPk(array('gid' => $id1, 'language' => $tolang), array('group_name' => $new), 'sid=:sid', array(':sid' => $iSurveyID));
                 case 'group_desc':
                     return Groups::model()->updateByPk(array('gid' => $id1, 'language' => $tolang), array('description' => $new), 'sid=:sid', array(':sid' => $iSurveyID));
                 case 'question':
                     return Questions::model()->updateByPk(array('qid' => $id1, 'language' => $tolang), array('question' => $new), 'sid=:sid AND parent_qid=0', array(':sid' => $iSurveyID));
                 case 'question_help':
                     return Questions::model()->updateByPk(array('qid' => $id1, 'language' => $tolang), array('help' => $new), 'sid=:sid AND parent_qid=0', array(':sid' => $iSurveyID));
                 case 'subquestion':
                     return Questions::model()->updateByPk(array('qid' => $id1, 'language' => $tolang), array('question' => $new), 'sid=:sid', array(':sid' => $iSurveyID));
                 case 'answer':
                     return Answers::model()->updateByPk(array('qid' => $id1, 'code' => $id2, 'language' => $tolang, 'scale_id' => 0), array('answer' => $new));
                     // @todo: FIXME for dual scale answer options
             }
     }
 }
Пример #7
0
 /**
  * Constructor
  */
 public function run($surveyid = 0, $subaction = null)
 {
     $surveyid = sanitize_int($surveyid);
     //TODO: Convert question types to views
     $clang = $this->getController()->lang;
     $imageurl = Yii::app()->getConfig("imageurl");
     $aData = array('clang' => $clang, 'imageurl' => $imageurl);
     $aData['sql'] = '';
     /*
     * We need this later:
     *  1 - Array Dual Scale
     *  5 - 5 Point Choice
     *  A - Array (5 Point Choice)
     *  B - Array (10 Point Choice)
     *  C - Array (Yes/No/Uncertain)
     *  D - Date
     *  E - Array (Increase, Same, Decrease)
     *  F - Array (Flexible Labels)
     *  G - Gender
     *  H - Array (Flexible Labels) by Column
     *  I - Language Switch
     *  K - Multiple Numerical Input
     *  L - List (Radio)
     *  M - Multiple choice
     *  N - Numerical Input
     *  O - List With Comment
     *  P - Multiple choice with comments
     *  Q - Multiple Short Text
     *  R - Ranking
     *  S - Short Free Text
     *  T - Long Free Text
     *  U - Huge Free Text
     *  X - Boilerplate Question
     *  Y - Yes/No
     *  ! - List (Dropdown)
     *  : - Array (Flexible Labels) multiple drop down
     *  ; - Array (Flexible Labels) multiple texts
     *  | - File Upload
     
     
     Debugging help:
     echo '<script language="javascript" type="text/javascript">alert("HI");</script>';
     */
     //split up results to extend statistics -> NOT WORKING YET! DO NOT ENABLE THIS!
     $showcombinedresults = 0;
     /*
      * this variable is used in the function shortencode() which cuts off a question/answer title
      * after $maxchars and shows the rest as tooltip
      */
     $maxchars = 50;
     //we collect all the output within this variable
     $statisticsoutput = '';
     //output for chosing questions to cross query
     $cr_statisticsoutput = '';
     // This gets all the 'to be shown questions' from the POST and puts these into an array
     $summary = returnGlobal('summary');
     $statlang = returnGlobal('statlang');
     //if $summary isn't an array we create one
     if (isset($summary) && !is_array($summary)) {
         $summary = explode("+", $summary);
     }
     //no survey ID? -> come and get one
     if (!isset($surveyid)) {
         $surveyid = returnGlobal('sid');
     }
     //still no survey ID -> error
     $aData['surveyid'] = $surveyid;
     // Set language for questions and answers to base language of this survey
     $language = Survey::model()->findByPk($surveyid)->language;
     $aData['language'] = $language;
     //Call the javascript file
     $this->getController()->_js_admin_includes(Yii::app()->getConfig('adminscripts') . 'statistics.js');
     $aData['display']['menu_bars']['browse'] = $clang->gT("Quick statistics");
     //Select public language file
     $row = Survey::model()->find('sid = :sid', array(':sid' => $surveyid));
     /*
      * check if there is a datestamp available for this survey
      * yes -> $datestamp="Y"
      * no -> $datestamp="N"
      */
     $datestamp = $row->datestamp;
     // 1: Get list of questions from survey
     /*
      * We want to have the following data
      * a) "questions" -> all table namens, e.g.
      * qid
      * sid
      * gid
      * type
      * title
      * question
      * preg
      * help
      * other
      * mandatory
      * lid
      * lid1
      * question_order
      * language
      *
      * b) "groups" -> group_name + group_order *
      */
     //store all the data in $rows
     $rows = Questions::model()->getQuestionList($surveyid, $language);
     //SORT IN NATURAL ORDER!
     usort($rows, 'groupOrderThenQuestionOrder');
     //put the question information into the filter array
     $filters = array();
     foreach ($rows as $row) {
         //store some column names in $filters array
         $filters[] = array($row['qid'], $row['gid'], $row['type'], $row['title'], $row['group_name'], flattenText($row['question']));
     }
     $aData['filters'] = $filters;
     //var_dump($filters);
     // SHOW ID FIELD
     $grapherror = false;
     $error = '';
     if (!function_exists("gd_info")) {
         $grapherror = true;
         $error .= '<br />' . $clang->gT('You do not have the GD Library installed. Showing charts requires the GD library to function properly.');
         $error .= '<br />' . $clang->gT('visit http://us2.php.net/manual/en/ref.image.php for more information') . '<br />';
     } elseif (!function_exists("imageftbbox")) {
         $grapherror = true;
         $error .= '<br />' . $clang->gT('You do not have the Freetype Library installed. Showing charts requires the Freetype library to function properly.');
         $error .= '<br />' . $clang->gT('visit http://us2.php.net/manual/en/ref.image.php for more information') . '<br />';
     }
     if ($grapherror) {
         unset($_POST['usegraph']);
     }
     //pre-selection of filter forms
     if (incompleteAnsFilterState() == "filter") {
         $selecthide = "selected='selected'";
         $selectshow = "";
         $selectinc = "";
     } elseif (incompleteAnsFilterState() == "inc") {
         $selecthide = "";
         $selectshow = "";
         $selectinc = "selected='selected'";
     } else {
         $selecthide = "";
         $selectshow = "selected='selected'";
         $selectinc = "";
     }
     $aData['selecthide'] = $selecthide;
     $aData['selectshow'] = $selectshow;
     $aData['selectinc'] = $selectinc;
     $aData['error'] = $error;
     $survlangs = Survey::model()->findByPk($surveyid)->additionalLanguages;
     $survlangs[] = Survey::model()->findByPk($surveyid)->language;
     $aData['survlangs'] = $survlangs;
     $aData['datestamp'] = $datestamp;
     //if the survey contains timestamps you can filter by timestamp, too
     //Output selector
     //second row below options -> filter settings headline
     $filterchoice_state = returnGlobal('filterchoice_state');
     $aData['filterchoice_state'] = $filterchoice_state;
     /*
     * let's go through the filter array which contains
     * 	['qid'],
     ['gid'],
     ['type'],
     ['title'],
     ['group_name'],
     ['question'],
     ['lid'],
     ['lid1']);
     */
     $currentgroup = '';
     $counter = 0;
     foreach ($filters as $key1 => $flt) {
         //is there a previous question type set?
         /*
         * remember: $flt is structured like this
         *  ['qid'],
         ['gid'],
         ['type'],
         ['title'],
         ['group_name'],
         ['question'],
         ['lid'],
         ['lid1']);
         */
         //SGQ identifier
         //full question title
         /*
         * Check question type: This question types will be used (all others are separated in the if clause)
         *  5 - 5 Point Choice
         G - Gender
         I - Language Switch
         L - List (Radio)
         M - Multiple choice
         N - Numerical Input
         | - File Upload
         O - List With Comment
         P - Multiple choice with comments
         Y - Yes/No
         ! - List (Dropdown) )
         */
         /////////////////////////////////////////////////////////////////////////////////////////////////
         //This section presents the filter list, in various different ways depending on the question type
         /////////////////////////////////////////////////////////////////////////////////////////////////
         //let's switch through the question type for each question
         switch ($flt[2]) {
             case "K":
                 // Multiple Numerical
                 //get answers
                 $result = Questions::model()->getQuestionsForStatistics('title as code, question as answer', "parent_qid={$flt['0']} AND language = '{$language}'", 'question_order');
                 $aData['result'][$key1]['key1'] = $result;
                 break;
             case "Q":
                 // Multiple Short Text
                 //get subqestions
                 $result = Questions::model()->getQuestionsForStatistics('title as code, question as answer', "parent_qid={$flt['0']} AND language = '{$language}'", 'question_order');
                 $aData['result'][$key1] = $result;
                 break;
                 //----------------------- ARRAYS --------------------------
             //----------------------- ARRAYS --------------------------
             case "A":
                 // ARRAY OF 5 POINT CHOICE QUESTIONS
                 //get answers
                 $result = Questions::model()->getQuestionsForStatistics('title, question', "parent_qid={$flt['0']} AND language = '{$language}'", 'question_order');
                 $aData['result'][$key1] = $result;
                 break;
                 //just like above only a different loop
             //just like above only a different loop
             case "B":
                 // ARRAY OF 10 POINT CHOICE QUESTIONS
                 $result = Questions::model()->getQuestionsForStatistics('title, question', "parent_qid={$flt['0']} AND language = '{$language}'", 'question_order');
                 $aData['result'][$key1] = $result;
                 break;
             case "C":
                 // ARRAY OF YES\No\$clang->gT("Uncertain") QUESTIONS
                 //get answers
                 $result = Questions::model()->getQuestionsForStatistics('title, question', "parent_qid={$flt['0']} AND language = '{$language}'", 'question_order');
                 $aData['result'][$key1] = $result;
                 break;
                 //similiar to the above one
             //similiar to the above one
             case "E":
                 // ARRAY OF Increase/Same/Decrease QUESTIONS
                 $result = Questions::model()->getQuestionsForStatistics('title, question', "parent_qid={$flt['0']} AND language = '{$language}'", 'question_order');
                 $aData['result'][$key1] = $result;
                 break;
             case ";":
                 //ARRAY (Multi Flex) (Text)
                 $result = Questions::model()->getQuestionsForStatistics('title, question', "parent_qid={$flt['0']} AND language = '{$language}' AND scale_id = 0", 'question_order');
                 $aData['result'][$key1] = $result;
                 foreach ($result as $key => $row) {
                     $fresult = Questions::model()->getQuestionsForStatistics('title, question', "parent_qid={$flt['0']} AND language = '{$language}' AND scale_id = 1", 'question_order');
                     $aData['fresults'][$key1][$key] = $fresult;
                 }
                 break;
             case ":":
                 //ARRAY (Multi Flex) (Numbers)
                 $result = Questions::model()->getQuestionsForStatistics('title, question', "parent_qid={$flt['0']} AND language = '{$language}' AND scale_id = 0", 'question_order');
                 $aData['result'][$key1] = $result;
                 foreach ($result as $row) {
                     $fresult = Questions::model()->getQuestionsForStatistics('*', "parent_qid={$flt['0']} AND language = '{$language}' AND scale_id = 1", 'question_order, title');
                     $aData['fresults'][$key1] = $fresult;
                 }
                 break;
                 /*
                  * For question type "F" and "H" you can use labels.
                  * The only difference is that the labels are applied to column heading
                  * or rows respectively
                  */
             /*
              * For question type "F" and "H" you can use labels.
              * The only difference is that the labels are applied to column heading
              * or rows respectively
              */
             case "F":
                 // FlEXIBLE ARRAY
             // FlEXIBLE ARRAY
             case "H":
                 // ARRAY (By Column)
                 //Get answers. We always use the answer code because the label might be too long elsewise
                 $result = Questions::model()->getQuestionsForStatistics('title, question', "parent_qid={$flt['0']} AND language = '{$language}'", 'question_order');
                 $aData['result'][$key1] = $result;
                 //check all the answers
                 foreach ($result as $row) {
                     $fresult = Answers::model()->getQuestionsForStatistics('*', "qid={$flt['0']} AND language = '{$language}'", 'sortorder, code');
                     $aData['fresults'][$key1] = $fresult;
                 }
                 //$statisticsoutput .= "\t\t\t\t<td>\n";
                 $counter = 0;
                 break;
             case "R":
                 //RANKING
                 //get some answers
                 $result = Answers::model()->getQuestionsForStatistics('code, answer', "qid={$flt['0']} AND language = '{$language}'", 'sortorder, answer');
                 $aData['result'][$key1] = $result;
                 break;
             case "1":
                 // MULTI SCALE
                 //get answers
                 $result = Questions::model()->getQuestionsForStatistics('title, question', "parent_qid={$flt['0']} AND language = '{$language}'", 'question_order');
                 $aData['result'][$key1] = $result;
                 //loop through answers
                 foreach ($result as $key => $row) {
                     //check if there is a dualscale_headerA/B
                     $dshresult = Question_attributes::model()->getQuestionsForStatistics('value', "qid={$flt['0']} AND attribute = 'dualscale_headerA'", '');
                     $aData['dshresults'][$key1][$key] = $dshresult;
                     $fresult = Answers::model()->getQuestionsForStatistics('*', "qid={$flt['0']} AND language = '{$language}' AND scale_id = 0", 'sortorder, code');
                     $aData['fresults'][$key1][$key] = $fresult;
                     $dshresult2 = Question_attributes::model()->getQuestionsForStatistics('value', "qid={$flt['0']} AND attribute = 'dualscale_headerB'", '');
                     $aData['dshresults2'][$key1][$key] = $dshresult2;
                 }
                 break;
             case "P":
                 //P - Multiple choice with comments
             //P - Multiple choice with comments
             case "M":
                 //M - Multiple choice
                 //get answers
                 $result = Questions::model()->getQuestionsForStatistics('title, question', "parent_qid = {$flt['0']} AND language = '{$language}'", 'question_order');
                 $aData['result'][$key1] = $result;
                 break;
                 /*
                 * This question types use the default settings:
                 * 	L - List (Radio)
                 O - List With Comment
                 P - Multiple choice with comments
                 ! - List (Dropdown)
                 */
             /*
             * This question types use the default settings:
             * 	L - List (Radio)
             O - List With Comment
             P - Multiple choice with comments
             ! - List (Dropdown)
             */
             default:
                 //get answers
                 $result = Answers::model()->getQuestionsForStatistics('code, answer', "qid={$flt['0']} AND language = '{$language}'", 'sortorder, answer');
                 $aData['result'][$key1] = $result;
                 break;
         }
         //end switch -> check question types and create filter forms
         $currentgroup = $flt[1];
         $counter++;
         //temporary save the type of the previous question
         //used to adjust linebreaks
         $previousquestiontype = $flt[2];
     }
     // ----------------------------------- END FILTER FORM ---------------------------------------
     Yii::app()->loadHelper('admin/statistics');
     $showtextinline = isset($_POST['showtextinline']) ? 1 : 0;
     $aData['showtextinline'] = $showtextinline;
     //Show Summary results
     if (isset($summary) && $summary) {
         $usegraph = isset($_POST['usegraph']) ? 1 : 0;
         $aData['usegraph'] = $usegraph;
         $outputType = $_POST['outputtype'];
         switch ($outputType) {
             case 'html':
                 $statisticsoutput .= generate_statistics($surveyid, $summary, $summary, $usegraph, $outputType, 'DD', $statlang);
                 break;
             case 'pdf':
                 generate_statistics($surveyid, $summary, $summary, $usegraph, $outputType, 'I', $statlang);
                 exit;
                 break;
             case 'xls':
                 generate_statistics($surveyid, $summary, $summary, $usegraph, $outputType, 'DD', $statlang);
                 exit;
                 break;
             default:
                 break;
         }
     }
     //end if -> show summary results
     $aData['sStatisticsLanguage'] = $statlang;
     $aData['output'] = $statisticsoutput;
     $aData['summary'] = $summary;
     $this->_renderWrappedTemplate('export', 'statistics_view', $aData);
 }
function upgradeTables143()
{
    global $modifyoutput;
    $aQIDReplacements = array();
    $answerquery = "select a.*, q.sid, q.gid from {{answers}} a,{{questions}} q where a.qid=q.qid and q.type in ('L','O','!') and a.default_value='Y'";
    $answerresult = Yii::app()->db->createCommand($answerquery)->queryAll();
    foreach ($answerresult as $row) {
        modifyDatabase("", "INSERT INTO {{defaultvalues}} (qid, scale_id,language,specialtype,defaultvalue) VALUES ({$row['qid']},0," . dbQuoteAll($row['language']) . ",''," . dbQuoteAll($row['code']) . ")");
        echo $modifyoutput;
        flush();
        @ob_flush();
    }
    // Convert answers to subquestions
    $answerquery = "select a.*, q.sid, q.gid, q.type from {{answers}} a,{{questions}} q where a.qid=q.qid and a.language=q.language and q.type in ('1','A','B','C','E','F','H','K',';',':','M','P','Q')";
    $answerresult = Yii::app()->db->createCommand($answerquery)->queryAll();
    foreach ($answerresult as $row) {
        $aInsert = array();
        if (isset($aQIDReplacements[$row['qid'] . '_' . $row['code']])) {
            $aInsert['qid'] = $aQIDReplacements[$row['qid'] . '_' . $row['code']];
        }
        $aInsert['sid'] = $row['sid'];
        $aInsert['gid'] = $row['gid'];
        $aInsert['parent_qid'] = $row['qid'];
        $aInsert['type'] = $row['type'];
        $aInsert['title'] = $row['code'];
        $aInsert['question'] = $row['answer'];
        $aInsert['question_order'] = $row['sortorder'];
        $aInsert['language'] = $row['language'];
        $iLastInsertID = Questions::model()->insertRecords($aInsert);
        if (!isset($aInsert['qid'])) {
            $aQIDReplacements[$row['qid'] . '_' . $row['code']] = $iLastInsertID;
            $iSaveSQID = $aQIDReplacements[$row['qid'] . '_' . $row['code']];
        } else {
            $iSaveSQID = $aInsert['qid'];
        }
        if (($row['type'] == 'M' || $row['type'] == 'P') && $row['default_value'] == 'Y') {
            modifyDatabase("", "INSERT INTO {{defaultvalues}} (qid, sqid, scale_id,language,specialtype,defaultvalue) VALUES ({$row['qid']},{$iSaveSQID},0," . dbQuoteAll($row['language']) . ",'','Y')");
            echo $modifyoutput;
            flush();
            @ob_flush();
        }
    }
    // Sanitize data
    $sDBDriverName = Yii::app()->db->getDriverName();
    if ($sDBDriverName == 'pgsql') {
        modifyDatabase("", "delete from {{answers}} USING {{questions}} WHERE {{answers}}.qid={{questions}}.qid AND {{questions}}.type in ('1','F','H','M','P','W','Z')");
        echo $modifyoutput;
        flush();
        @ob_flush();
    } else {
        modifyDatabase("", "delete {{answers}} from {{answers}} LEFT join {{questions}} ON {{answers}}.qid={{questions}}.qid where {{questions}}.type in ('1','F','H','M','P','W','Z')");
        echo $modifyoutput;
        flush();
        @ob_flush();
    }
    // Convert labels to answers
    $answerquery = "select qid ,type ,lid ,lid1, language from {{questions}} where parent_qid=0 and type in ('1','F','H','M','P','W','Z')";
    $answerresult = Yii::app()->db->createCommand($answerquery)->queryAll();
    foreach ($answerresult as $row) {
        $labelquery = "Select * from {{labels}} where lid={$row['lid']} and language=" . dbQuoteAll($row['language']);
        $labelresult = Yii::app()->db->createCommand($labelquery)->queryAll();
        foreach ($labelresult as $lrow) {
            modifyDatabase("", "INSERT INTO {{answers}} (qid, code, answer, sortorder, language, assessment_value) VALUES ({$row['qid']}," . dbQuoteAll($lrow['code']) . "," . dbQuoteAll($lrow['title']) . ",{$lrow['sortorder']}," . dbQuoteAll($lrow['language']) . ",{$lrow['assessment_value']})");
            echo $modifyoutput;
            flush();
            @ob_flush();
            //$labelids[]
        }
        if ($row['type'] == '1') {
            $labelquery = "Select * from {{labels}} where lid={$row['lid1']} and language=" . dbQuoteAll($row['language']);
            $labelresult = Yii::app()->db->createCommand($labelquery)->queryAll();
            foreach ($labelresult as $lrow) {
                modifyDatabase("", "INSERT INTO {{answers}} (qid, code, answer, sortorder, language, scale_id, assessment_value) VALUES ({$row['qid']}," . dbQuoteAll($lrow['code']) . "," . dbQuoteAll($lrow['title']) . ",{$lrow['sortorder']}," . dbQuoteAll($lrow['language']) . ",1,{$lrow['assessment_value']})");
                echo $modifyoutput;
                flush();
                @ob_flush();
            }
        }
    }
    // Convert labels to subquestions
    $answerquery = "select * from {{questions}} where parent_qid=0 and type in (';',':')";
    $answerresult = Yii::app()->db->createCommand($answerquery)->queryAll();
    foreach ($answerresult as $row) {
        $labelquery = "Select * from {{labels}} where lid={$row['lid']} and language=" . dbQuoteAll($row['language']);
        $labelresult = Yii::app()->db->createCommand($labelquery)->queryAll();
        foreach ($labelresult as $lrow) {
            $aInsert = array();
            if (isset($aQIDReplacements[$row['qid'] . '_' . $lrow['code'] . '_1'])) {
                $aInsert['qid'] = $aQIDReplacements[$row['qid'] . '_' . $lrow['code'] . '_1'];
            }
            $aInsert['sid'] = $row['sid'];
            $aInsert['gid'] = $row['gid'];
            $aInsert['parent_qid'] = $row['qid'];
            $aInsert['type'] = $row['type'];
            $aInsert['title'] = $lrow['code'];
            $aInsert['question'] = $lrow['title'];
            $aInsert['question_order'] = $lrow['sortorder'];
            $aInsert['language'] = $lrow['language'];
            $aInsert['scale_id'] = 1;
            $iLastInsertID = Questions::model()->insertRecords($aInsert);
            if (isset($aInsert['qid'])) {
                $aQIDReplacements[$row['qid'] . '_' . $lrow['code'] . '_1'] = $iLastInsertID;
            }
        }
    }
    $updatequery = "update {{questions}} set type='!' where type='W'";
    modifyDatabase("", $updatequery);
    echo $modifyoutput;
    flush();
    @ob_flush();
    $updatequery = "update {{questions}} set type='L' where type='Z'";
    modifyDatabase("", $updatequery);
    echo $modifyoutput;
    flush();
    @ob_flush();
    // Now move all non-standard templates to the /upload dir
    global $usertemplaterootdir, $standardtemplates, $standardtemplaterootdir;
    if (!$usertemplaterootdir) {
        die("getTemplateList() no template directory");
    }
    if ($handle = opendir($standardtemplaterootdir)) {
        while (false !== ($file = readdir($handle))) {
            if (!is_file("{$standardtemplaterootdir}/{$file}") && $file != "." && $file != ".." && $file != ".svn" && !isStandardTemplate($file)) {
                if (!rename($standardtemplaterootdir . DIRECTORY_SEPARATOR . $file, $usertemplaterootdir . DIRECTORY_SEPARATOR . $file)) {
                    echo "There was a problem moving directory '" . $standardtemplaterootdir . DIRECTORY_SEPARATOR . $file . "' to '" . $usertemplaterootdir . DIRECTORY_SEPARATOR . $file . "' due to missing permissions. Please do this manually.<br />";
                }
            }
        }
        closedir($handle);
    }
}
Пример #9
0
 public function actionFind()
 {
     if (!Yii::app()->user->isGuest) {
         $location = Yii::app()->Ini->getlocationbyip(Yii::app()->Ini->rip('ip'));
         $projects = Projecttypes::model()->findAll(array('order' => 'Name ASC'));
         $states = States::model()->findAll(array('order' => 'Name ASC'));
         $criteria = new CDbCriteria();
         $criteria->order = "question_id DESC";
         $criteria->limit = 5;
         $questions = Questions::model()->findAll($criteria);
         $city = Yii::app()->Ini->v('city');
         $project = Yii::app()->Ini->v('project');
         $zipcode = Yii::app()->Ini->v('zipcode');
         $pie = new SimplePie();
         $pie->set_feed_url('http://media.handyman.com/feed/');
         $pie->init();
         $pie->handle_content_type();
         if ($city) {
             $details = Cities::model()->findByAttributes(array('RewriteUrl' => $city . "/"));
             if (count($details) > 0) {
                 $city_name = $details->Name;
             }
             $criteria = new CDbCriteria();
             $criteria->condition = "City like '%{$city_name}%'";
             $count = Contractors::model()->count($criteria);
             $pages = new CPagination($count);
             // results per page
             $pages->pageSize = 5;
             $pages->applyLimit($criteria);
             $models = Contractors::model()->findAll($criteria);
             $this->render('find_result', array('models' => $models, 'pages' => $pages, 'projects' => $projects, 'records' => $count, 'city_name' => $city_name, 'location' => $city_name . ",USA", 'questions' => $questions, 'feed' => $pie));
         } else {
             if ($project) {
                 $zipcodevalue = Yii::app()->Ini->v('zipcode');
                 $details = Projecttypes::model()->findByAttributes(array('ProjectTypeId' => $project));
                 if (count($details) > 0) {
                     $search_name = $details->Name;
                 }
                 $add_cond = "";
                 if ($zipcodevalue != "") {
                     $add_cond = "and zipcode=" . $zipcodevalue;
                     $search_name = $search_name . " in zipcode " . $zipcodevalue;
                 }
                 $criteria = new CDbCriteria();
                 $criteria->condition = "project_type_id=" . $project . " " . $add_cond;
                 $count = Projects::model()->count($criteria);
                 $pages = new CPagination($count);
                 // results per page
                 $pages->pageSize = 5;
                 $pages->applyLimit($criteria);
                 $models = Projects::model()->findAll($criteria);
                 $this->render('find_result', array('models' => $models, 'pages' => $pages, 'projects' => $projects, 'records' => $count, 'search_name' => $search_name, 'location' => "Albuquerque, New Mexico,USA", 'questions' => $questions, 'feed' => $pie));
             } else {
                 if ($zipcode) {
                     $zipcodevalue = Yii::app()->Ini->v('zipcode');
                     $project_id = Yii::app()->Ini->v('project_id');
                     $criteria = new CDbCriteria();
                     $criteria->condition = "zipcode='{$zipcodevalue}' AND project_type_id = '{$project_id}'";
                     $count = Projects::model()->count($criteria);
                     $pages = new CPagination($count);
                     // results per page
                     $pages->pageSize = 5;
                     $pages->applyLimit($criteria);
                     $models = Projects::model()->findAll($criteria);
                     $this->render('find_result', array('models' => $models, 'pages' => $pages, 'projects' => $projects, 'records' => $count, 'search_name' => "Zipcode " . $zipcode, 'location' => "Albuquerque, New Mexico,USA", 'questions' => $questions, 'feed' => $pie));
                 } else {
                     $this->render('find_form', array('projects' => $projects, 'states' => $states, 'location' => $location, 'questions' => $questions, 'feed' => $pie));
                 }
             }
         }
     } else {
         $this->redirect(Yii::app()->homeUrl . 'login');
     }
     /*$this->pageTitle = 'Welcome to Handyman.com';
      	$this->render('index', $param);
          */
 }
Пример #10
0
 /**
  * Returns the static model of the specified AR class.
  * Please note that you should have this exact method in all your CActiveRecord descendants!
  * @param string $className active record class name.
  * @return WQuestions the static model class
  */
 public static function model($className = __CLASS__)
 {
     return parent::model($className);
 }
Пример #11
0
 public static function deleteAllById($questionsIds)
 {
     if (!is_array($questionsIds)) {
         $questionsIds = array($questionsIds);
     }
     Yii::app()->db->createCommand()->delete(Conditions::model()->tableName(), array('in', 'qid', $questionsIds));
     Yii::app()->db->createCommand()->delete(Question_attributes::model()->tableName(), array('in', 'qid', $questionsIds));
     Yii::app()->db->createCommand()->delete(Answers::model()->tableName(), array('in', 'qid', $questionsIds));
     Yii::app()->db->createCommand()->delete(Questions::model()->tableName(), array('in', 'parent_qid', $questionsIds));
     Yii::app()->db->createCommand()->delete(Questions::model()->tableName(), array('in', 'qid', $questionsIds));
     Yii::app()->db->createCommand()->delete(Defaultvalues::model()->tableName(), array('in', 'qid', $questionsIds));
     Yii::app()->db->createCommand()->delete(Quota_members::model()->tableName(), array('in', 'qid', $questionsIds));
 }
Пример #12
0
 public function deactivate($homeowner_id)
 {
     $criteria = new CDbCriteria();
     $criteria->condition = "user_type='homeowner' AND userid=" . $homeowner_id;
     Affiliates::model()->deleteAll($criteria);
     Referral::model()->deleteAll($criteria);
     $criteria = new CDbCriteria();
     $criteria->condition = "owner_user_type='homeowner' AND owner_id=" . $homeowner_id;
     Answers::model()->deleteAll($criteria);
     Questions::model()->deleteAll($criteria);
     $criteria = new CDbCriteria();
     $criteria->condition = "user_type='homeowner' AND deleted_by=" . $homeowner_id;
     Messagedeleted::model()->deleteAll($criteria);
     $criteria = new CDbCriteria();
     $criteria->condition = "from_user_type='homeowner' AND from_id=" . $homeowner_id;
     Messages::model()->deleteAll($criteria);
     $criteria = new CDbCriteria();
     $criteria->condition = "to_user_type='homeowner' AND to_id=" . $homeowner_id;
     Messages::model()->deleteAll($criteria);
     $criteria = new CDbCriteria();
     $criteria->condition = "project_id NOT IN (Select project_id from projects where homeowner_id = {$homeowner_id} )";
     Projectphotos::model()->deleteAll($criteria);
     $criteria = new CDbCriteria();
     $criteria->condition = "viewed_user_type='homeowner' AND viewed_by=" . $homeowner_id;
     QuestionViews::model()->deleteAll($criteria);
     $criteria = new CDbCriteria();
     $criteria->condition = "referred_by_type='homeowner' AND referred_by=" . $homeowner_id;
     Referral::model()->deleteAll($criteria);
     $criteria = new CDbCriteria();
     $criteria->condition = "homeowner_id=" . $homeowner_id;
     HomeownerPoints::model()->deleteAll($criteria);
     Feedback::model()->deleteAll($criteria);
     HomeownerViews::model()->deleteAll($criteria);
     Projects::model()->deleteAll($criteria);
     self::model()->deleteAll($criteria);
     return true;
 }
 public function deletequestion($post)
 {
     $id = $post['id'];
     $question = Questions::model()->findByPk($id);
     $question->delete();
     $criteria = new CDbCriteria();
     $criteria->condition = 'question_id = ' . $id;
     Answers::model()->deleteAll($criteria);
     QuestionViews::model()->deleteAll($criteria);
     QuestionVotes::model()->deleteAll($criteria);
     $return['status'] = true;
     $this->renderJSON($return, true);
 }
Пример #14
0
function checkQuestion($sid)
{
    $criteria = new CDbCriteria();
    $criteria->condition = "section={$sid}";
    return Questions::model()->count($criteria);
}
Пример #15
0
function questionExport($action, $iSurveyID, $gid, $qid)
{
    $fn = "limesurvey_question_{$qid}.lsq";
    $xml = getXMLWriter();
    header("Content-Type: text/html/force-download");
    header("Content-Disposition: attachment; filename={$fn}");
    header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
    // Date in the past
    header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Pragma: cache");
    // HTTP/1.0
    $xml->openURI('php://output');
    $xml->setIndent(true);
    $xml->startDocument('1.0', 'UTF-8');
    $xml->startElement('document');
    $xml->writeElement('LimeSurveyDocType', 'Question');
    $xml->writeElement('DBVersion', getGlobalSetting('DBVersion'));
    $xml->startElement('languages');
    $questions = Questions::model()->find('qid=:qid or parent_qid=:pqid', array(':qid' => $qid, ':pqid' => $qid));
    $xml->writeElement('language', $questions->language);
    $xml->endElement();
    questionGetXMLStructure($xml, $gid, $qid);
    $xml->endElement();
    // close columns
    $xml->endDocument();
    exit;
}
Пример #16
0
/**
* Builds an array containing information about this particular question/answer combination
*
* @param string $rt The code passed from the statistics form listing the field/answer (SGQA) combination to be displayed
* @param mixed $language The language to present output in
* @param mixed $surveyid The survey id
* @param string $outputType
*
* @output array $output An array containing "alist"=>A list of answers to the question in the form of an array ($alist array
*                       contains an array for every field to be displayed - with the Actual Question Code/Title, The text (flattened)
*                       of the question, and the fieldname where the data is stored.
*                       "qtitle"=>The title of the question,
*                       "qquestion"=>The description of the question,
*                       "qtype"=>The question type code
*/
function buildOutputList($rt, $language, $surveyid, $outputType, $sql, $oLanguage)
{
    //Set up required variables
    $alist = array();
    $qtitle = "";
    $qquestion = "";
    $qtype = "";
    $statlang = $oLanguage;
    $firstletter = substr($rt, 0, 1);
    $fieldmap = createFieldMap($surveyid, "full", false, false, $language);
    $sDatabaseType = Yii::app()->db->getDriverName();
    $statisticsoutput = "";
    /* Some variable depend on output type, actually : only line feed */
    switch ($outputType) {
        case 'xls':
        case 'pdf':
            $linefeed = "\n";
            break;
        case 'html':
            $linefeed = "<br />\n";
            break;
        default:
            break;
    }
    //M - Multiple choice, therefore multiple fields - one for each answer
    if ($firstletter == "M" || $firstletter == "P") {
        //get SGQ data
        list($qsid, $qgid, $qqid) = explode("X", substr($rt, 1, strlen($rt)), 3);
        //select details for this question
        $nresult = Questions::model()->find('language=:language AND parent_qid=0 AND qid=:qid', array(':language' => $language, ':qid' => $qqid));
        $qtitle = $nresult->title;
        $qtype = $nresult->type;
        $qquestion = flattenText($nresult->question);
        $qlid = $nresult->parent_qid;
        $qother = $nresult->other;
        //1. Get list of answers
        $result = Questions::model()->findAll(array('order' => 'question_order', 'condition' => 'language=:language AND parent_qid=:qid AND scale_id=0', 'params' => array(':language' => $language, ':qid' => $qqid)));
        foreach ($result as $row) {
            $mfield = substr($rt, 1, strlen($rt)) . $row['title'];
            $alist[] = array($row['title'], flattenText($row['question']), $mfield);
        }
        //Add the "other" answer if it exists
        if ($qother == "Y") {
            $mfield = substr($rt, 1, strlen($rt)) . "other";
            $alist[] = array($statlang->gT("Other"), $statlang->gT("Other"), $mfield);
        }
    } elseif ($firstletter == "T" || $firstletter == "S") {
        //search for key
        $fld = substr($rt, 1, strlen($rt));
        $fielddata = $fieldmap[$fld];
        list($qanswer, $qlid) = !empty($fielddata['aid']) ? explode("_", $fielddata['aid']) : array("", "");
        //get question data
        $nresult = Questions::model()->find('language=:language AND parent_qid=0 AND qid=:qid', array(':language' => $language, ':qid' => $fielddata['qid']));
        $qtitle = $nresult->title;
        $qtype = $nresult->type;
        $qquestion = flattenText($nresult->question);
        $qlid = $nresult->parent_qid;
        $mfield = substr($rt, 1, strlen($rt));
        //Text questions either have an answer, or they don't. There's no other way of quantising the results.
        // So, instead of building an array of predefined answers like we do with lists & other types,
        // we instead create two "types" of possible answer - either there is a response.. or there isn't.
        // This question type then can provide a % of the question answered in the summary.
        $alist[] = array("Answers", $statlang->gT("Answer"), $mfield);
        $alist[] = array("NoAnswer", $statlang->gT("No answer"), $mfield);
    } elseif ($firstletter == "Q") {
        //Build an array of legitimate qid's for testing later
        $qidquery = Questions::model()->findAll("sid=:surveyid AND parent_qid=0", array(":surveyid" => $surveyid));
        foreach ($qidquery as $row) {
            $legitqids[] = $row['qid'];
        }
        //get SGQ data
        list($qsid, $qgid, $qqid) = explode("X", substr($rt, 1, strlen($rt)), 3);
        //separating another ID
        $tmpqid = substr($qqid, 0, strlen($qqid) - 1);
        //check if we have a QID that actually exists. if not create them by substringing. Note that
        //all of this is due to the fact that when we create a field for an subquestion, we don't seperate
        //the question id from the subquestion id - and this is a weird, backwards way of doing that.
        while (!in_array($tmpqid, $legitqids)) {
            $tmpqid = substr($tmpqid, 0, strlen($tmpqid) - 1);
        }
        //length of QID
        $iQuestionIDlength = strlen($tmpqid);
        //we somehow get the answer code (see SQL later) from the $qqid
        $qaid = substr($qqid, $iQuestionIDlength, strlen($qqid) - $iQuestionIDlength);
        //get question data
        $nresult = Questions::model()->find('language=:language AND parent_qid=0 AND qid=:qid', array(':language' => $language, ':qid' => substr($qqid, 0, $iQuestionIDlength)));
        $qtitle = $nresult->title;
        $qtype = $nresult->type;
        $qquestion = flattenText($nresult->question);
        //more substrings
        $count = substr($qqid, strlen($qqid) - 1);
        //get answers
        $nresult = Questions::model()->find(array('order' => 'question_order', 'condition' => 'language=:language AND parent_qid=:parent_qid AND title=:title', 'params' => array(':language' => $language, ':parent_qid' => substr($qqid, 0, $iQuestionIDlength), ':title' => $qaid)));
        $atext = flattenText($nresult->question);
        //add this to the question title
        $qtitle .= " [{$atext}]";
        //even more substrings...
        $mfield = substr($rt, 1, strlen($rt));
        //Text questions either have an answer, or they don't. There's no other way of quantising the results.
        // So, instead of building an array of predefined answers like we do with lists & other types,
        // we instead create two "types" of possible answer - either there is a response.. or there isn't.
        // This question type then can provide a % of the question answered in the summary.
        $alist[] = array("Answers", $statlang->gT("Answer"), $mfield);
        $alist[] = array("NoAnswer", $statlang->gT("No answer"), $mfield);
    } elseif ($firstletter == "R") {
        //getting the needed IDs somehow
        $lengthofnumeral = substr($rt, strpos($rt, "-") + 1, 1);
        list($qsid, $qgid, $qqid) = explode("X", substr($rt, 1, strpos($rt, "-") - ($lengthofnumeral + 1)), 3);
        //get question data
        $nquery = "SELECT title, type, question FROM {{questions}} WHERE parent_qid=0 AND qid='{$qqid}' AND language='{$language}'";
        $nresult = Yii::app()->db->createCommand($nquery)->query();
        //loop through question data
        foreach ($nresult->readAll() as $nrow) {
            $nrow = array_values($nrow);
            $qtitle = flattenText($nrow[0]) . " [" . substr($rt, strpos($rt, "-") - $lengthofnumeral, $lengthofnumeral) . "]";
            $qtype = $nrow[1];
            $qquestion = flattenText($nrow[2]) . "[" . $statlang->gT("Ranking") . " " . substr($rt, strpos($rt, "-") - $lengthofnumeral, $lengthofnumeral) . "]";
        }
        //get answers
        $query = "SELECT code, answer FROM {{answers}} WHERE qid='{$qqid}' AND scale_id=0 AND language='{$language}' ORDER BY sortorder, answer";
        $result = Yii::app()->db->createCommand($query)->query();
        //loop through answers
        foreach ($result->readAll() as $row) {
            $row = array_values($row);
            //create an array containing answer code, answer and fieldname(??)
            $mfield = substr($rt, 1, strpos($rt, "-") - 1);
            $alist[] = array("{$row['0']}", flattenText($row[1]), $mfield);
        }
    } else {
        if ($firstletter == "|") {
            //get SGQ data
            list($qsid, $qgid, $qqid) = explode("X", substr($rt, 1, strlen($rt)), 3);
            //select details for this question
            $nresult = Questions::model()->find('language=:language AND parent_qid=0 AND qid=:qid', array(':language' => $language, ':qid' => substr($qqid, 0, $iQuestionIDlength)));
            $qtitle = $nresult->title;
            $qtype = $nresult->type;
            $qquestion = flattenText($nresult->question);
            $qlid = $nresult->parent_qid;
            $qother = $nresult->other;
            /*
            4)      Average size of file per respondent
            5)      Average no. of files
            5)      Summary/count of file types (ie: 37 jpg, 65 gif, 12 png)
            6)      Total size of all files (useful if you re about to download them all)
            7)      You could also add things like  smallest file size, largest file size, median file size
            8)      no. of files corresponding to each extension
            9)      max file size
            10)     min file size
            */
            // 1) Total number of files uploaded
            // 2)      Number of respondents who uploaded at least one file (with the inverse being the number of respondents who didn t upload any)
            $fieldname = substr($rt, 1, strlen($rt));
            $query = "SELECT SUM(" . Yii::app()->db->quoteColumnName($fieldname . '_filecount') . ") as sum, AVG(" . Yii::app()->db->quoteColumnName($fieldname . '_filecount') . ") as avg FROM {{survey_{$surveyid}}}";
            $result = Yii::app()->db->createCommand($query)->query();
            $showem = array();
            foreach ($result->readAll() as $row) {
                $showem[] = array($statlang->gT("Total number of files"), $row['sum']);
                $showem[] = array($statlang->gT("Average no. of files per respondent"), $row['avg']);
            }
            $query = "SELECT " . $fieldname . " as json FROM {{survey_{$surveyid}}}";
            $result = Yii::app()->db->createCommand($query)->query();
            $responsecount = 0;
            $filecount = 0;
            $size = 0;
            foreach ($result->readAll() as $row) {
                $json = $row['json'];
                $phparray = json_decode($json);
                foreach ($phparray as $metadata) {
                    $size += (int) $metadata->size;
                    $filecount++;
                }
                $responsecount++;
            }
            $showem[] = array($statlang->gT("Total size of files"), $size . " KB");
            $showem[] = array($statlang->gT("Average file size"), $size / $filecount . " KB");
            $showem[] = array($statlang->gT("Average size per respondent"), $size / $responsecount . " KB");
            /*              $query="SELECT title, question FROM {{questions}} WHERE parent_qid='$qqid' AND language='{$language}' ORDER BY question_order";
                    $result=db_execute_num($query) or safeDie("Couldn't get list of subquestions for multitype<br />$query<br />");
            
                    //loop through multiple answers
                    while ($row=$result->FetchRow())
                    {
                    $mfield=substr($rt, 1, strlen($rt))."$row[0]";
            
                    //create an array containing answer code, answer and fieldname(??)
                    $alist[]=array("$row[0]", flattenText($row[1]), $mfield);
                    }
            
                    */
            //outputting
            switch ($outputType) {
                case 'xls':
                    $headXLS = array();
                    $tableXLS = array();
                    $footXLS = array();
                    $xlsTitle = sprintf($statlang->gT("Field summary for %s"), html_entity_decode($qtitle, ENT_QUOTES, 'UTF-8'));
                    $xlsDesc = html_entity_decode($qquestion, ENT_QUOTES, 'UTF-8');
                    ++$xlsRow;
                    ++$xlsRow;
                    ++$xlsRow;
                    $sheet->write($xlsRow, 0, $xlsTitle);
                    ++$xlsRow;
                    $sheet->write($xlsRow, 0, $xlsDesc);
                    $headXLS[] = array($statlang->gT("Calculation"), $statlang->gT("Result"));
                    ++$xlsRow;
                    $sheet->write($xlsRow, 0, $statlang->gT("Calculation"));
                    $sheet->write($xlsRow, 1, $statlang->gT("Result"));
                    break;
                case 'pdf':
                    $headPDF = array();
                    $tablePDF = array();
                    $footPDF = array();
                    $pdfTitle = sprintf($statlang->gT("Field summary for %s"), html_entity_decode($qtitle, ENT_QUOTES, 'UTF-8'));
                    $titleDesc = html_entity_decode($qquestion, ENT_QUOTES, 'UTF-8');
                    $headPDF[] = array($statlang->gT("Calculation"), $statlang->gT("Result"));
                    break;
                case 'html':
                    $statisticsoutput .= "\n<table class='statisticstable' >\n" . "\t<thead><tr><th colspan='2' align='center'><strong>" . sprintf($statlang->gT("Field summary for %s"), $qtitle) . ":</strong>" . "</th></tr>\n" . "\t<tr><th colspan='2' align='center'><strong>{$qquestion}</strong></th></tr>\n" . "\t<tr>\n\t\t<th width='50%' align='center' ><strong>" . $statlang->gT("Calculation") . "</strong></th>\n" . "\t\t<th width='50%' align='center' ><strong>" . $statlang->gT("Result") . "</strong></th>\n" . "\t</tr></thead>\n";
                    foreach ($showem as $res) {
                        $statisticsoutput .= "<tr><td>" . $res[0] . "</td><td>" . $res[1] . "</td></tr>";
                    }
                    break;
                default:
                    break;
            }
        } elseif ($firstletter == "N" || $firstletter == "K") {
            //Zero handling
            if (!isset($excludezeros)) {
                $excludezeros = 1;
            }
            //check last character, greater/less/equals don't need special treatment
            if (substr($rt, -1) == "G" || substr($rt, -1) == "L" || substr($rt, -1) == "=") {
                //DO NOTHING
            } else {
                $showem = array();
                //create SGQ identifier
                list($qsid, $qgid, $qqid) = explode("X", $rt, 3);
                //multiple numerical input
                if ($firstletter == "K") {
                    //Build an array of legitimate qid's for testing later
                    $qidquery = Questions::model()->findAll("sid=:surveyid AND parent_qid=0", array(":surveyid" => $surveyid));
                    foreach ($qidquery as $row) {
                        $legitqids[] = $row['qid'];
                    }
                    // This is a multiple numerical question so we need to strip of the answer id to find the question title
                    $tmpqid = substr($qqid, 0, strlen($qqid) - 1);
                    //did we get a valid ID?
                    while (!in_array($tmpqid, $legitqids, true)) {
                        $tmpqid = (int) substr($tmpqid, 0, strlen($tmpqid) - 1);
                    }
                    //check lenght of ID
                    $iQuestionIDlength = strlen($tmpqid);
                    //get answer ID from qid
                    $qaid = substr($qqid, $iQuestionIDlength, strlen($qqid) - $iQuestionIDlength);
                    //get question details from DB
                    $nresult = Questions::model()->findAll('parent_qid=0 AND qid=:qid AND language=:language', array(':qid' => substr($qqid, 0, $iQuestionIDlength), ':language' => $language));
                    /* $nquery = "SELECT title, type, question, qid, parent_qid
                       FROM {{questions}}
                       WHERE parent_qid=0 AND qid='".substr($qqid, 0, $iQuestionIDlength)."'
                       AND language='{$language}'";
                       $nresult = Yii::app()->db->createCommand($nquery)->query(); */
                } else {
                    $nresult = Questions::model()->findAll('parent_qid=0 AND qid=:qid AND language=:language', array(':qid' => $qqid, ':language' => $language));
                    //we can use the qqid without any editing
                    /* $nquery = "SELECT title, type, question, qid, parent_qid FROM {{questions}} WHERE parent_qid=0 AND qid='$qqid' AND language='{$language}'";
                       $nresult = Yii::app()->db->createCommand($nquery)->query(); */
                }
                //loop through results
                foreach ($nresult as $nrow) {
                    $qtitle = flattenText($nrow->title);
                    //clean up title
                    $qtype = $nrow->type;
                    $qquestion = flattenText($nrow->question);
                    $qiqid = $nrow->qid;
                    $qlid = $nrow->parent_qid;
                }
                //Get answer texts for multiple numerical
                if (substr($rt, 0, 1) == "K") {
                    //get answer data
                    $atext = Yii::app()->db->createCommand("SELECT question FROM {{questions}} WHERE parent_qid='{$qiqid}' AND scale_id=0 AND title='{$qaid}' AND language='{$language}'")->queryScalar();
                    //put single items in brackets at output
                    $qtitle .= " [{$atext}]";
                }
                //outputting
                switch ($outputType) {
                    case 'xls':
                        $headXLS = array();
                        $tableXLS = array();
                        $footXLS = array();
                        $xlsTitle = sprintf($statlang->gT("Field summary for %s"), html_entity_decode($qtitle, ENT_QUOTES, 'UTF-8'));
                        $xlsDesc = html_entity_decode($qquestion, ENT_QUOTES, 'UTF-8');
                        ++$xlsRow;
                        ++$xlsRow;
                        ++$xlsRow;
                        $sheet->setCellValueByColumnAndRow(0, $xlsRow, $xlsTitle);
                        ++$xlsRow;
                        $sheet->setCellValueByColumnAndRow(0, $xlsRow, $xlsDesc);
                        $headXLS[] = array($statlang->gT("Calculation"), $statlang->gT("Result"));
                        ++$xlsRow;
                        $sheet->setCellValueByColumnAndRow(0, $xlsRow, $statlang->gT("Calculation"));
                        $sheet->setCellValueByColumnAndRow(1, $xlsRow, $statlang->gT("Result"));
                        break;
                    case 'pdf':
                        $headPDF = array();
                        $tablePDF = array();
                        $footPDF = array();
                        $pdfTitle = sprintf($statlang->gT("Field summary for %s"), html_entity_decode($qtitle, ENT_QUOTES, 'UTF-8'));
                        $titleDesc = html_entity_decode($qquestion, ENT_QUOTES, 'UTF-8');
                        $headPDF[] = array($statlang->gT("Calculation"), $statlang->gT("Result"));
                        break;
                    case 'html':
                        $statisticsoutput .= "\n<table class='statisticstable' >\n" . "\t<thead><tr><th colspan='2' align='center'><strong>" . sprintf($statlang->gT("Field summary for %s"), $qtitle) . ":</strong>" . "</th></tr>\n" . "\t<tr><th colspan='2' align='center'><strong>{$qquestion}</strong></th></tr>\n" . "\t<tr>\n\t\t<th width='50%' align='center' ><strong>" . $statlang->gT("Calculation") . "</strong></th>\n" . "\t\t<th width='50%' align='center' ><strong>" . $statlang->gT("Result") . "</strong></th>\n" . "\t</tr></thead>\n";
                        break;
                    default:
                        break;
                }
                //this field is queried using mathematical functions
                $fieldname = substr($rt, 1, strlen($rt));
                //special treatment for MS SQL databases
                if ($sDatabaseType == 'mssql' || $sDatabaseType == 'sqlsrv') {
                    //standard deviation
                    $query = "SELECT STDEVP(" . Yii::app()->db->quoteColumnName($fieldname) . "*1) as stdev";
                } else {
                    //standard deviation
                    $query = "SELECT STDDEV(" . Yii::app()->db->quoteColumnName($fieldname) . ") as stdev";
                }
                //sum
                $query .= ", SUM(" . Yii::app()->db->quoteColumnName($fieldname) . "*1) as sum";
                //average
                $query .= ", AVG(" . Yii::app()->db->quoteColumnName($fieldname) . "*1) as average";
                //min
                $query .= ", MIN(" . Yii::app()->db->quoteColumnName($fieldname) . "*1) as minimum";
                //max
                $query .= ", MAX(" . Yii::app()->db->quoteColumnName($fieldname) . "*1) as maximum";
                //Only select responses where there is an actual number response, ignore nulls and empties (if these are included, they are treated as zeroes, and distort the deviation/mean calculations)
                //special treatment for MS SQL databases
                if ($sDatabaseType == 'mssql' || $sDatabaseType == 'sqlsrv') {
                    //no NULL/empty values please
                    $query .= " FROM {{survey_{$surveyid}}} WHERE " . Yii::app()->db->quoteColumnName($fieldname) . " IS NOT NULL";
                    if (!$excludezeros) {
                        //NO ZERO VALUES
                        $query .= " AND (" . Yii::app()->db->quoteColumnName($fieldname) . " <> 0)";
                    }
                } else {
                    //no NULL/empty values please
                    $query .= " FROM {{survey_{$surveyid}}} WHERE " . Yii::app()->db->quoteColumnName($fieldname) . " IS NOT NULL";
                    if (!$excludezeros) {
                        //NO ZERO VALUES
                        $query .= " AND (" . Yii::app()->db->quoteColumnName($fieldname) . " != 0)";
                    }
                }
                //filter incomplete answers if set
                if (incompleteAnsFilterState() == "inc") {
                    $query .= " AND submitdate is null";
                } elseif (incompleteAnsFilterState() == "filter") {
                    $query .= " AND submitdate is not null";
                }
                //$sql was set somewhere before
                if ($sql != "NULL") {
                    $query .= " AND {$sql}";
                }
                //execute query
                $result = Yii::app()->db->createCommand($query)->queryAll();
                //get calculated data
                foreach ($result as $row) {
                    //put translation of mean and calculated data into $showem array
                    $showem[] = array($statlang->gT("Sum"), $row['sum']);
                    $showem[] = array($statlang->gT("Standard deviation"), round($row['stdev'], 2));
                    $showem[] = array($statlang->gT("Average"), round($row['average'], 2));
                    $showem[] = array($statlang->gT("Minimum"), $row['minimum']);
                    //Display the maximum and minimum figures after the quartiles for neatness
                    $maximum = $row['maximum'];
                    $minimum = $row['minimum'];
                }
                //CALCULATE QUARTILES
                //get data
                $query = "SELECT COUNT(" . Yii::app()->db->quoteColumnName($fieldname) . ") FROM {{survey_{$surveyid}}} WHERE " . Yii::app()->db->quoteColumnName($fieldname) . " IS NOT null";
                //NO ZEROES
                if (!$excludezeros) {
                    $query .= " AND " . Yii::app()->db->quoteColumnName($fieldname) . " != 0";
                }
                //filtering enabled?
                if (incompleteAnsFilterState() == "inc") {
                    $query .= " AND submitdate is null";
                } elseif (incompleteAnsFilterState() == "filter") {
                    $query .= " AND submitdate is not null";
                }
                //if $sql values have been passed to the statistics script from another script, incorporate them
                if ($sql != "NULL") {
                    $query .= " AND {$sql}";
                }
                //we just put the total number of records at the beginning of this array
                $medcount = Yii::app()->db->createCommand($query)->queryScalar();
                array_unshift($showem, array($statlang->gT("Count"), $medcount));
                $querystarter = "SELECT " . Yii::app()->db->quoteColumnName($fieldname) . " FROM {{survey_{$surveyid}}} WHERE " . Yii::app()->db->quoteColumnName($fieldname) . " IS NOT null";
                //No Zeroes
                if (!$excludezeros) {
                    $querystart .= " AND " . Yii::app()->db->quoteColumnName($fieldname) . " != 0";
                }
                //filtering enabled?
                if (incompleteAnsFilterState() == "inc") {
                    $querystarter .= " AND submitdate is null";
                } elseif (incompleteAnsFilterState() == "filter") {
                    $querystarter .= " AND submitdate is not null";
                }
                //if $sql values have been passed to the statistics script from another script, incorporate them
                if ($sql != "NULL") {
                    $querystarter .= " AND {$sql}";
                }
                //no more comment from Mazi regarding the calculation
                /* IMPORTANT IMPORTANT IMPORTANT IMPORTANT IMPORTANT IMPORTANT */
                /* IF YOU DON'T UNDERSTAND WHAT QUARTILES ARE DO NOT MODIFY THIS CODE */
                /* Quartiles and Median values are NOT related to average, and the sum is irrelevent */
                // Calculating only makes sense with more than one result
                if ($medcount > 1) {
                    //1ST QUARTILE (Q1)
                    /*  L=(1/4)(n+1), U=(3/4)(n+1) */
                    /*  Minitab linear interpolation between the two
                        closest data points. Minitab would let L = 2.5 and find the value half way between the
                        2nd and 3rd data points. In our example, that would be (4+9)/2 =
                        6.5. Similarly, the upper quartile value would be half way between
                        the 7th and 8th data points, which would be (49+64)/2 = 56.5. If L
                        were 2.25, Minitab would find the value one fourth of the way
                        between the 2nd and 3rd data points and if L were 2.75, Minitab
                        would find the value three fourths of the way between the 2nd and
                        3rd data points. */
                    $q1 = 1 / 4 * ($medcount + 1);
                    $q1b = (int) (1 / 4 * ($medcount + 1));
                    $q1c = $q1b - 1;
                    $q1diff = $q1 - $q1b;
                    $total = 0;
                    // fix if there are too few values to evaluate.
                    if ($q1c < 0) {
                        $q1c = 0;
                    }
                    if ($q1 != $q1b) {
                        $query = $querystarter . " ORDER BY " . Yii::app()->db->quoteColumnName($fieldname) . "*1 ";
                        $result = Yii::app()->db->createCommand($query)->query();
                        $i = 0;
                        foreach ($result as $row) {
                            if ($row[$fieldname]) {
                                $i++;
                            }
                            if ($i == $q1c) {
                                $secondlastnumber = $row[$fieldname];
                            }
                            if ($i == $q1b) {
                                $lastnumber = $row[$fieldname];
                            }
                        }
                        $q1total = $lastnumber - (1 - $q1diff) * $secondlastnumber;
                        //if ($q3total < $maximum) {$q1total=$maximum;} //What the? If the 3rd quartiel is higher than the highest, then make the 1st quartile the highest? This makes no sense!
                        $showem[] = array($statlang->gT("1st quartile (Q1)"), $q1total);
                    } else {
                        $query = $querystarter . " ORDER BY " . Yii::app()->db->quoteColumnName($fieldname) . "*1";
                        $result = Yii::app()->db->createCommand($query)->query();
                        foreach ($result as $row) {
                            if ($row[$fieldname]) {
                                $i++;
                            }
                            if ($i == $q1b) {
                                $showem[] = array($statlang->gT("1st quartile (Q1)"), $row[$fieldname]);
                            }
                        }
                    }
                    $total = 0;
                    //MEDIAN (Q2)
                    $median = 1 / 2 * ($medcount + 1);
                    $medianb = (int) (1 / 2 * ($medcount + 1));
                    $medianc = $medianb - 1;
                    $mediandiff = $median - $medianb;
                    if ($median != $medianb) {
                        //remainder
                        $query = $querystarter . " ORDER BY " . Yii::app()->db->quoteColumnName($fieldname) . "*1 ";
                        $result = Yii::app()->db->createCommand($query)->query();
                        $i = 0;
                        foreach ($result as $row) {
                            if ($row[$fieldname]) {
                                $i++;
                            }
                            if ($i == $medianc) {
                                $secondlastnumber = $row[$fieldname];
                            }
                            if ($i == $medianb) {
                                $lastnumber = $row[$fieldname];
                            }
                        }
                        $mediantotal = $lastnumber - (1 - $mediandiff) * $secondlastnumber;
                        //if ($q3total < $maximum) {$q1total=$maximum;} //What the? If the 3rd quartiel is higher than the highest, then make the 1st quartile the highest? This makes no sense!
                        $showem[] = array($statlang->gT("2nd quartile (Median)"), $mediantotal);
                    } else {
                        $query = $querystarter . " ORDER BY " . Yii::app()->db->quoteColumnName($fieldname) . "*1";
                        $result = Yii::app()->db->createCommand($query)->query();
                        foreach ($result as $row) {
                            if ($row[$fieldname]) {
                                $i++;
                            }
                            if ($i == $medianb) {
                                $showem[] = array($statlang->gT("2nd quartile (Median)"), $row[$fieldname]);
                            }
                        }
                    }
                    $total = 0;
                    //3RD QUARTILE (Q3)
                    /*  L=(1/4)(n+1), U=(3/4)(n+1) */
                    /*  Minitab linear interpolation between the two
                        closest data points. Minitab would let L = 2.5 and find the value half way between the
                        2nd and 3rd data points. In our example, that would be (4+9)/2 =
                        6.5. Similarly, the upper quartile value would be half way between
                        the 7th and 8th data points, which would be (49+64)/2 = 56.5. If L
                        were 2.25, Minitab would find the value one fourth of the way
                        between the 2nd and 3rd data points and if L were 2.75, Minitab
                        would find the value three fourths of the way between the 2nd and
                        3rd data points. */
                    $q3 = 3 / 4 * ($medcount + 1);
                    //Find the 75th percentile according to count of items
                    $q3b = (int) (3 / 4 * ($medcount + 1));
                    //The int version of $q3
                    $q3c = $q3b - 1;
                    //The number before the int version of $q3
                    $q3diff = $q3 - $q3b;
                    if ($q3 != $q3b) {
                        $query = $querystarter . " ORDER BY " . Yii::app()->db->quoteColumnName($fieldname) . "*1 ";
                        $result = Yii::app()->db->createCommand($query)->query();
                        $i = 0;
                        foreach ($result as $row) {
                            if ($row[$fieldname]) {
                                $i++;
                            }
                            if ($i == $q3c) {
                                $secondlastnumber = $row[$fieldname];
                            }
                            if ($i == $q3b) {
                                $lastnumber = $row[$fieldname];
                            }
                        }
                        $q3total = $lastnumber - (1 - $q3diff) * $secondlastnumber;
                        //if ($q3total < $maximum) {$q1total=$maximum;} //What the? If the 3rd quartiel is higher than the highest, then make the 1st quartile the highest? This makes no sense!
                        $showem[] = array($statlang->gT("3rd quartile (Q3)"), $q3total);
                    } else {
                        $query = $querystarter . " ORDER BY " . Yii::app()->db->quoteColumnName($fieldname) . "*1";
                        $result = Yii::app()->db->createCommand($query)->query();
                        foreach ($result as $row) {
                            if ($row[$fieldname]) {
                                $i++;
                            }
                            if ($i == $q3b) {
                                $showem[] = array($statlang->gT("3rd quartile (Q3)"), $row[$fieldname]);
                            }
                        }
                    }
                    $total = 0;
                    $showem[] = array($statlang->gT("Maximum"), $maximum);
                    //output results
                    foreach ($showem as $shw) {
                        switch ($outputType) {
                            case 'xls':
                                ++$xlsRow;
                                $sheet->write($xlsRow, 0, html_entity_decode($shw[0], ENT_QUOTES, 'UTF-8'));
                                $sheet->write($xlsRow, 1, html_entity_decode($shw[1], ENT_QUOTES, 'UTF-8'));
                                $tableXLS[] = array($shw[0], $shw[1]);
                                break;
                            case 'pdf':
                                $tablePDF[] = array(html_entity_decode($shw[0], ENT_QUOTES, 'UTF-8'), html_entity_decode($shw[1], ENT_QUOTES, 'UTF-8'));
                                break;
                            case 'html':
                                $statisticsoutput .= "\t<tr>\n" . "\t\t<td align='center' >{$shw['0']}</td>\n" . "\t\t<td align='center' >{$shw['1']}</td>\n" . "\t</tr>\n";
                                break;
                            default:
                                break;
                        }
                    }
                    switch ($outputType) {
                        case 'xls':
                            ++$xlsRow;
                            $sheet->write($xlsRow, 0, $statlang->gT("Null values are ignored in calculations"));
                            ++$xlsRow;
                            $sheet->write($xlsRow, 0, sprintf($statlang->gT("Q1 and Q3 calculated using %s"), $statlang->gT("minitab method")));
                            $footXLS[] = array($statlang->gT("Null values are ignored in calculations"));
                            $footXLS[] = array(sprintf($statlang->gT("Q1 and Q3 calculated using %s"), $statlang->gT("minitab method")));
                            break;
                        case 'pdf':
                            $footPDF[] = array($statlang->gT("Null values are ignored in calculations"));
                            $footPDF[] = array(sprintf($statlang->gT("Q1 and Q3 calculated using %s"), "<a href='http://mathforum.org/library/drmath/view/60969.html' target='_blank'>" . $statlang->gT("minitab method") . "</a>"));
                            $pdf->addPage('P', 'A4');
                            $pdf->Bookmark($pdf->delete_html($qquestion), 1, 0);
                            $pdf->titleintopdf($pdfTitle, $titleDesc);
                            $pdf->headTable($headPDF, $tablePDF);
                            $pdf->tablehead($footPDF);
                            break;
                        case 'html':
                            //footer of question type "N"
                            $statisticsoutput .= "\t<tr>\n" . "\t\t<td colspan='4' align='center' bgcolor='#EEEEEE'>\n" . "\t\t\t<font size='1'>" . $statlang->gT("Null values are ignored in calculations") . "<br />\n" . "\t\t\t" . sprintf($statlang->gT("Q1 and Q3 calculated using %s"), "<a href='http://mathforum.org/library/drmath/view/60969.html' target='_blank'>" . $statlang->gT("minitab method") . "</a>") . "</font>\n" . "\t\t</td>\n" . "\t</tr>\n";
                            $statisticsoutput .= "\t<tr>\n" . "\t\t<td align='center'  colspan='4'>\n                        <input type='button' class='statisticsbrowsebutton numericalbrowse' value='" . $statlang->gT("Browse") . "' id='{$fieldname}' /></td>\n</tr>";
                            $statisticsoutput .= "<tr><td class='statisticsbrowsecolumn' colspan='3' style='display: none'>\n                            <div class='statisticsbrowsecolumn' id='columnlist_{$fieldname}'></div></td></tr>";
                            $statisticsoutput .= "</table>\n";
                            break;
                        default:
                            break;
                    }
                    //clean up
                    unset($showem);
                } else {
                    switch ($outputType) {
                        case 'xls':
                            $tableXLS = array();
                            $tableXLS[] = array($statlang->gT("Not enough values for calculation"));
                            ++$xlsRow;
                            $sheet->write($xlsRow, 0, $statlang->gT("Not enough values for calculation"));
                            break;
                        case 'pdf':
                            $tablePDF = array();
                            $tablePDF[] = array($statlang->gT("Not enough values for calculation"));
                            $pdf->addPage('P', 'A4');
                            $pdf->Bookmark($pdf->delete_html($qquestion), 1, 0);
                            $pdf->titleintopdf($pdfTitle, $titleDesc);
                            $pdf->equalTable($tablePDF);
                            break;
                        case 'html':
                            //output
                            $statisticsoutput .= "\t<tr>\n" . "\t\t<td align='center'  colspan='4'>" . $statlang->gT("Not enough values for calculation") . "</td>\n" . "\t</tr>\n</table><br />\n";
                            break;
                        default:
                            break;
                    }
                    unset($showem);
                }
            }
            //end else -> check last character, greater/less/equals don't need special treatment
        } elseif (substr($rt, 0, 2) == "id" || substr($rt, 0, 9) == "datestamp" || $firstletter == "D") {
            /*
             * DON'T show anything for date questions
             * because there aren't any statistics implemented yet!
             *
             * See bug report #2539 and
             * feature request #2620
             */
        } else {
            //search for key
            $fielddata = $fieldmap[$rt];
            //get SGQA IDs
            $qsid = $fielddata['sid'];
            $qgid = $fielddata['gid'];
            $qqid = $fielddata['qid'];
            $qanswer = $fielddata['aid'];
            $qtype = $fielddata['type'];
            //question string
            $qastring = $fielddata['question'];
            //question ID
            $rqid = $qqid;
            //get question data
            $nquery = "SELECT title, type, question, qid, parent_qid, other FROM {{questions}} WHERE qid='{$rqid}' AND parent_qid=0 and language='{$language}'";
            $nresult = Yii::app()->db->createCommand($nquery)->query();
            //loop though question data
            foreach ($nresult->readAll() as $nrow) {
                $nrow = array_values($nrow);
                $qtitle = flattenText($nrow[0]);
                $qtype = $nrow[1];
                $qquestion = flattenText($nrow[2]);
                $qiqid = $nrow[3];
                $qparentqid = $nrow[4];
                $qother = $nrow[5];
            }
            //check question types
            switch ($qtype) {
                //Array of 5 point choices (several items to rank!)
                case "A":
                    //get data
                    $qquery = "SELECT title, question FROM {{questions}} WHERE parent_qid='{$qiqid}' AND title='{$qanswer}' AND language='{$language}' ORDER BY question_order";
                    $qresult = Yii::app()->db->createCommand($qquery)->query();
                    //loop through results
                    foreach ($qresult->readAll() as $qrow) {
                        $qrow = array_values($qrow);
                        //5-point array
                        for ($i = 1; $i <= 5; $i++) {
                            //add data
                            $alist[] = array("{$i}", "{$i}");
                        }
                        //add counter
                        $atext = flattenText($qrow[1]);
                    }
                    //list IDs and answer codes in brackets
                    $qquestion .= $linefeed . "[" . $atext . "]";
                    $qtitle .= "({$qanswer})";
                    break;
                    //Array of 10 point choices
                    //same as above just with 10 items
                //Array of 10 point choices
                //same as above just with 10 items
                case "B":
                    $qquery = "SELECT title, question FROM {{questions}} WHERE parent_qid='{$qiqid}' AND title='{$qanswer}' AND language='{$language}' ORDER BY question_order";
                    $qresult = Yii::app()->db->createCommand($qquery)->query();
                    foreach ($qresult->readAll() as $qrow) {
                        $qrow = array_values($qrow);
                        for ($i = 1; $i <= 10; $i++) {
                            $alist[] = array("{$i}", "{$i}");
                        }
                        $atext = flattenText($qrow[1]);
                    }
                    $qquestion .= $linefeed . "[" . $atext . "]";
                    $qtitle .= "({$qanswer})";
                    break;
                    //Array of Yes/No/$statlang->gT("Uncertain")
                //Array of Yes/No/$statlang->gT("Uncertain")
                case "C":
                    $qquery = "SELECT title, question FROM {{questions}} WHERE parent_qid='{$qiqid}' AND title='{$qanswer}' AND language='{$language}' ORDER BY question_order";
                    $qresult = Yii::app()->db->createCommand($qquery)->query();
                    //loop thorugh results
                    foreach ($qresult->readAll() as $qrow) {
                        $qrow = array_values($qrow);
                        //add results
                        $alist[] = array("Y", $statlang->gT("Yes"));
                        $alist[] = array("N", $statlang->gT("No"));
                        $alist[] = array("U", $statlang->gT("Uncertain"));
                        $atext = flattenText($qrow[1]);
                    }
                    //output
                    $qquestion .= $linefeed . "[" . $atext . "]";
                    $qtitle .= "({$qanswer})";
                    break;
                    //Array of Yes/No/$statlang->gT("Uncertain")
                    //same as above
                //Array of Yes/No/$statlang->gT("Uncertain")
                //same as above
                case "E":
                    $qquery = "SELECT title, question FROM {{questions}} WHERE parent_qid='{$qiqid}' AND title='{$qanswer}' AND language='{$language}' ORDER BY question_order";
                    $qresult = Yii::app()->db->createCommand($qquery)->query();
                    foreach ($qresult->readAll() as $qrow) {
                        $qrow = array_values($qrow);
                        $alist[] = array("I", $statlang->gT("Increase"));
                        $alist[] = array("S", $statlang->gT("Same"));
                        $alist[] = array("D", $statlang->gT("Decrease"));
                        $atext = flattenText($qrow[1]);
                    }
                    $qquestion .= $linefeed . "[" . $atext . "]";
                    $qtitle .= "({$qanswer})";
                    break;
                case ";":
                    //Array (Multi Flexi) (Text)
                    list($qacode, $licode) = explode("_", $qanswer);
                    $qquery = "SELECT title, question FROM {{questions}} WHERE parent_qid='{$qiqid}' AND title='{$qacode}' AND language='{$language}' ORDER BY question_order";
                    $qresult = Yii::app()->db->createCommand($qquery)->query();
                    foreach ($qresult->readAll() as $qrow) {
                        $qrow = array_values($qrow);
                        $fquery = "SELECT * FROM {{answers}} WHERE qid='{$qiqid}' AND scale_id=0 AND code = '{$licode}' AND language='{$language}'ORDER BY sortorder, code";
                        $fresult = Yii::app()->db->createCommand($fquery)->query();
                        foreach ($fresult->readAll() as $frow) {
                            $alist[] = array($frow['code'], $frow['answer']);
                            $ltext = $frow['answer'];
                        }
                        $atext = flattenText($qrow[1]);
                    }
                    $qquestion .= $linefeed . "[" . $atext . "] [" . $ltext . "]";
                    $qtitle .= "({$qanswer})";
                    break;
                case ":":
                    //Array (Multiple Flexi) (Numbers)
                    $aQuestionAttributes = getQuestionAttributeValues($qiqid);
                    if (trim($aQuestionAttributes['multiflexible_max']) != '') {
                        $maxvalue = $aQuestionAttributes['multiflexible_max'];
                    } else {
                        $maxvalue = 10;
                    }
                    if (trim($aQuestionAttributes['multiflexible_min']) != '') {
                        $minvalue = $aQuestionAttributes['multiflexible_min'];
                    } else {
                        $minvalue = 1;
                    }
                    if (trim($aQuestionAttributes['multiflexible_step']) != '') {
                        $stepvalue = $aQuestionAttributes['multiflexible_step'];
                    } else {
                        $stepvalue = 1;
                    }
                    if ($aQuestionAttributes['multiflexible_checkbox'] != 0) {
                        $minvalue = 0;
                        $maxvalue = 1;
                        $stepvalue = 1;
                    }
                    for ($i = $minvalue; $i <= $maxvalue; $i += $stepvalue) {
                        $alist[] = array($i, $i);
                    }
                    $qquestion .= $linefeed . "[" . $fielddata['subquestion1'] . "] [" . $fielddata['subquestion2'] . "]";
                    list($myans, $mylabel) = explode("_", $qanswer);
                    $qtitle .= "[{$myans}][{$mylabel}]";
                    break;
                case "F":
                    //Array of Flexible
                //Array of Flexible
                case "H":
                    //Array of Flexible by Column
                    $qquery = "SELECT title, question FROM {{questions}} WHERE parent_qid='{$qiqid}' AND title='{$qanswer}' AND language='{$language}' ORDER BY question_order";
                    $qresult = Yii::app()->db->createCommand($qquery)->query();
                    //loop through answers
                    foreach ($qresult->readAll() as $qrow) {
                        $qrow = array_values($qrow);
                        //this question type uses its own labels
                        $fquery = "SELECT * FROM {{answers}} WHERE qid='{$qiqid}' AND scale_id=0 AND language='{$language}'ORDER BY sortorder, code";
                        $fresult = Yii::app()->db->createCommand($fquery)->query();
                        //add code and title to results for outputting them later
                        foreach ($fresult->readAll() as $frow) {
                            $alist[] = array($frow['code'], flattenText($frow['answer']));
                        }
                        //counter
                        $atext = flattenText($qrow[1]);
                    }
                    //output
                    $qquestion .= $linefeed . "[" . $atext . "]";
                    $qtitle .= "({$qanswer})";
                    break;
                case "G":
                    //Gender
                    $alist[] = array("F", $statlang->gT("Female"));
                    $alist[] = array("M", $statlang->gT("Male"));
                    break;
                case "Y":
                    //Yes\No
                    $alist[] = array("Y", $statlang->gT("Yes"));
                    $alist[] = array("N", $statlang->gT("No"));
                    break;
                case "I":
                    //Language
                    // Using previously defined $surveylanguagecodes array of language codes
                    foreach ($surveylanguagecodes as $availlang) {
                        $alist[] = array($availlang, getLanguageNameFromCode($availlang, false));
                    }
                    break;
                case "5":
                    //5 Point (just 1 item to rank!)
                    for ($i = 1; $i <= 5; $i++) {
                        $alist[] = array("{$i}", "{$i}");
                    }
                    break;
                case "1":
                    //array (dual scale)
                    $clang = Yii::app()->lang;
                    $sSubquestionQuery = "SELECT  question FROM {{questions}} WHERE parent_qid='{$qiqid}' AND title='{$qanswer}' AND language='{$language}' ORDER BY question_order";
                    $questionDesc = Yii::app()->db->createCommand($sSubquestionQuery)->query()->read();
                    $sSubquestion = flattenText($questionDesc['question']);
                    //get question attributes
                    $aQuestionAttributes = getQuestionAttributeValues($qqid);
                    //check last character -> label 1
                    if (substr($rt, -1, 1) == 0) {
                        //get label 1
                        $fquery = "SELECT * FROM {{answers}} WHERE qid='{$qqid}' AND scale_id=0 AND language='{$language}' ORDER BY sortorder, code";
                        //header available?
                        if (trim($aQuestionAttributes['dualscale_headerA'][$language]) != '') {
                            //output
                            $labelheader = "[" . $aQuestionAttributes['dualscale_headerA'][$language] . "]";
                        } else {
                            $labelheader = '';
                        }
                        //output
                        $labelno = sprintf($clang->gT('Label %s'), '1');
                    } else {
                        //get label 2
                        $fquery = "SELECT * FROM {{answers}} WHERE qid='{$qqid}' AND scale_id=1 AND language='{$language}' ORDER BY sortorder, code";
                        //header available?
                        if (trim($aQuestionAttributes['dualscale_headerB'][$language]) != '') {
                            //output
                            $labelheader = "[" . $aQuestionAttributes['dualscale_headerB'][$language] . "]";
                        } else {
                            $labelheader = '';
                        }
                        //output
                        $labelno = sprintf($clang->gT('Label %s'), '2');
                    }
                    //get data
                    $fresult = Yii::app()->db->createCommand($fquery)->query();
                    //put label code and label title into array
                    foreach ($fresult->readAll() as $frow) {
                        $alist[] = array($frow['code'], flattenText($frow['answer']));
                    }
                    //adapt title and question
                    $qtitle = $qtitle . " [" . $sSubquestion . "][" . $labelno . "]";
                    $qquestion = $qastring . $labelheader;
                    break;
                default:
                    //default handling
                    //get answer code and title
                    $qquery = "SELECT code, answer FROM {{answers}} WHERE qid='{$qqid}' AND scale_id=0 AND language='{$language}' ORDER BY sortorder, answer";
                    $qresult = Yii::app()->db->createCommand($qquery)->query();
                    //put answer code and title into array
                    foreach ($qresult->readAll() as $qrow) {
                        $qrow = array_values($qrow);
                        $alist[] = array("{$qrow['0']}", flattenText($qrow[1]));
                    }
                    //handling for "other" field for list radio or list drowpdown
                    if (($qtype == "L" || $qtype == "!") && $qother == "Y") {
                        //add "other"
                        $alist[] = array($statlang->gT("Other"), $statlang->gT("Other"), $fielddata['fieldname'] . 'other');
                    }
                    if ($qtype == "O") {
                        //add "comment"
                        $alist[] = array($statlang->gT("Comments"), $statlang->gT("Comments"), $fielddata['fieldname'] . 'comment');
                    }
            }
            //end switch question type
            //moved because it's better to have "no answer" at the end of the list instead of the beginning
            //put data into array
            $alist[] = array("", $statlang->gT("No answer"));
        }
    }
    return array("alist" => $alist, "qtitle" => $qtitle, "qquestion" => $qquestion, "qtype" => $qtype, "statisticsoutput" => $statisticsoutput);
}
Пример #17
0
 /**
  * Database::index()
  *
  * @param mixed $action
  * @return
  */
 function index($sa = null)
 {
     $action = Yii::app()->request->getPost('action');
     $clang = $this->getController()->lang;
     $postsid = returnGlobal('sid');
     $postgid = returnGlobal('gid');
     $postqid = returnGlobal('qid');
     $postqaid = returnGlobal('qaid');
     $databaseoutput = '';
     $surveyid = returnGlobal('sid');
     $gid = returnGlobal('gid');
     $qid = returnGlobal('qid');
     // if $action is not passed, check post data.
     if (Yii::app()->getConfig('filterxsshtml') && Yii::app()->session['USER_RIGHT_SUPERADMIN'] != 1) {
         $filter = new CHtmlPurifier();
         $filter->options = array('URI.AllowedSchemes' => array('http' => true, 'https' => true));
         $xssfilter = true;
     } else {
         $xssfilter = false;
     }
     if ($action == "updatedefaultvalues" && hasSurveyPermission($surveyid, 'surveycontent', 'update')) {
         $questlangs = Survey::model()->findByPk($surveyid)->additionalLanguages;
         $baselang = Survey::model()->findByPk($surveyid)->language;
         array_unshift($questlangs, $baselang);
         Questions::model()->updateAll(array('same_default' => Yii::app()->request->getPost('samedefault') ? 1 : 0), 'sid=:sid ANd qid=:qid', array(':sid' => $surveyid, ':qid' => $qid));
         $resrow = Questions::model()->findByAttributes(array('qid' => $qid));
         $questiontype = $resrow['type'];
         $qtproperties = getQuestionTypeList('', 'array');
         if ($qtproperties[$questiontype]['answerscales'] > 0 && $qtproperties[$questiontype]['subquestions'] == 0) {
             for ($scale_id = 0; $scale_id < $qtproperties[$questiontype]['answerscales']; $scale_id++) {
                 foreach ($questlangs as $language) {
                     if (!is_null(Yii::app()->request->getPost('defaultanswerscale_' . $scale_id . '_' . $language))) {
                         $this->_updateDefaultValues($qid, 0, $scale_id, '', $language, Yii::app()->request->getPost('defaultanswerscale_' . $scale_id . '_' . $language), true);
                     }
                     if (!is_null(Yii::app()->request->getPost('other_' . $scale_id . '_' . $language))) {
                         $this->_updateDefaultValues($qid, 0, $scale_id, 'other', $language, Yii::app()->request->getPost('other_' . $scale_id . '_' . $language), true);
                     }
                 }
             }
         }
         if ($qtproperties[$questiontype]['subquestions'] > 0) {
             foreach ($questlangs as $language) {
                 $sqresult = Questions::model()->findAllByAttributes(array('sid' => $surveyid, 'gid' => $gid, 'parent_qid' => $qid, 'language' => $language, 'scale_id' => 0));
                 for ($scale_id = 0; $scale_id < $qtproperties[$questiontype]['subquestions']; $scale_id++) {
                     foreach ($sqresult as $aSubquestionrow) {
                         if (!is_null(Yii::app()->request->getPost('defaultanswerscale_' . $scale_id . '_' . $language . '_' . $aSubquestionrow['qid']))) {
                             $this->_updateDefaultValues($qid, $aSubquestionrow['qid'], $scale_id, '', $language, Yii::app()->request->getPost('defaultanswerscale_' . $scale_id . '_' . $language . '_' . $aSubquestionrow['qid']), true);
                         }
                     }
                 }
             }
         }
         if ($qtproperties[$questiontype]['answerscales'] == 0 && $qtproperties[$questiontype]['subquestions'] == 0) {
             foreach ($questlangs as $language) {
                 if (!is_null(Yii::app()->request->getPost('defaultanswerscale_0_' . $language . '_0'))) {
                     $this->_updateDefaultValues($postqid, 0, 0, '', $language, Yii::app()->request->getPost('defaultanswerscale_0_' . $language . '_0'), true);
                 }
             }
         }
         Yii::app()->session['flashmessage'] = $clang->gT("Default value settings were successfully saved.");
         LimeExpressionManager::SetDirtyFlag();
         if ($databaseoutput != '') {
             echo $databaseoutput;
         } else {
             $this->getController()->redirect($this->getController()->createUrl('admin/survey/sa/view/surveyid/' . $surveyid . '/gid/' . $gid . '/qid/' . $qid));
         }
     }
     if ($action == "updateansweroptions" && hasSurveyPermission($surveyid, 'surveycontent', 'update')) {
         Yii::app()->loadHelper('database');
         $anslangs = Survey::model()->findByPk($surveyid)->additionalLanguages;
         $baselang = Survey::model()->findByPk($surveyid)->language;
         $alllanguages = $anslangs;
         array_unshift($alllanguages, $baselang);
         $resrow = Questions::model()->findByAttributes(array('qid' => $qid));
         $questiontype = $resrow['type'];
         // Checked)
         $qtypes = getQuestionTypeList('', 'array');
         $scalecount = $qtypes[$questiontype]['answerscales'];
         $count = 0;
         $invalidCode = 0;
         $duplicateCode = 0;
         //require_once("../classes/inputfilter/class.inputfilter_clean.php");
         //$myFilter = new InputFilter('','',1,1,1);
         //First delete all answers
         Answers::model()->deleteAllByAttributes(array('qid' => $qid));
         LimeExpressionManager::RevertUpgradeConditionsToRelevance($surveyid);
         for ($scale_id = 0; $scale_id < $scalecount; $scale_id++) {
             $maxcount = (int) Yii::app()->request->getPost('answercount_' . $scale_id);
             for ($sortorderid = 1; $sortorderid < $maxcount; $sortorderid++) {
                 $code = sanitize_paranoid_string(Yii::app()->request->getPost('code_' . $sortorderid . '_' . $scale_id));
                 if (Yii::app()->request->getPost('oldcode_' . $sortorderid . '_' . $scale_id)) {
                     $oldcode = sanitize_paranoid_string(Yii::app()->request->getPost('oldcode_' . $sortorderid . '_' . $scale_id));
                     if ($code !== $oldcode) {
                         Conditions::model()->updateAll(array('value' => $code), 'cqid=:cqid AND value=:value', array(':cqid' => $qid, ':value' => $oldcode));
                     }
                 }
                 $assessmentvalue = (int) Yii::app()->request->getPost('assessment_' . $sortorderid . '_' . $scale_id);
                 foreach ($alllanguages as $language) {
                     $answer = Yii::app()->request->getPost('answer_' . $language . '_' . $sortorderid . '_' . $scale_id);
                     if ($xssfilter) {
                         $answer = $filter->purify($answer);
                     } else {
                         $answer = html_entity_decode($answer, ENT_QUOTES, "UTF-8");
                     }
                     // Fix bug with FCKEditor saving strange BR types
                     $answer = fixCKeditorText($answer);
                     // Now we insert the answers
                     $result = Answers::model()->insertRecords(array('code' => $code, 'answer' => $answer, 'qid' => $qid, 'sortorder' => $sortorderid, 'language' => $language, 'assessment_value' => $assessmentvalue, 'scale_id' => $scale_id));
                     if (!$result) {
                         $databaseoutput .= "<script type=\"text/javascript\">\n<!--\n alert(\"" . $clang->gT("Failed to update answers", "js") . "\")\n //-->\n</script>\n";
                     }
                 }
                 // foreach ($alllanguages as $language)
                 if (isset($oldcode) && $code !== $oldcode) {
                     Conditions::model()->updateAll(array('value' => $code), 'cqid=:cqid AND value=:value', array(':cqid' => $qid, ':value' => $oldcode));
                 }
             }
             // for ($sortorderid=0;$sortorderid<$maxcount;$sortorderid++)
         }
         //  for ($scale_id=0;
         LimeExpressionManager::UpgradeConditionsToRelevance($surveyid);
         if ($invalidCode == 1) {
             $databaseoutput .= "<script type=\"text/javascript\">\n<!--\n alert(\"" . $clang->gT("Answers with a code of 0 (zero) or blank code are not allowed, and will not be saved", "js") . "\")\n //-->\n</script>\n";
         }
         if ($duplicateCode == 1) {
             $databaseoutput .= "<script type=\"text/javascript\">\n<!--\n alert(\"" . $clang->gT("Duplicate codes found, these entries won't be updated", "js") . "\")\n //-->\n</script>\n";
         }
         Yii::app()->session['flashmessage'] = $clang->gT("Answer options were successfully saved.");
         LimeExpressionManager::SetDirtyFlag();
         if ($databaseoutput != '') {
             echo $databaseoutput;
         } else {
             $this->getController()->redirect($this->getController()->createUrl('/admin/question/sa/answeroptions/surveyid/' . $surveyid . '/gid/' . $gid . '/qid/' . $qid));
         }
         //$action='editansweroptions';
     }
     if ($action == "updatesubquestions" && hasSurveyPermission($surveyid, 'surveycontent', 'update')) {
         Yii::app()->loadHelper('database');
         $anslangs = Survey::model()->findByPk($surveyid)->additionalLanguages;
         $baselang = Survey::model()->findByPk($surveyid)->language;
         array_unshift($anslangs, $baselang);
         $row = Questions::model()->findByAttributes(array('qid' => $qid));
         $questiontype = $row['type'];
         // Checked
         $qtypes = getQuestionTypeList('', 'array');
         $scalecount = $qtypes[$questiontype]['subquestions'];
         $clang = $this->getController()->lang;
         // First delete any deleted ids
         $deletedqids = explode(' ', trim(Yii::app()->request->getPost('deletedqids')));
         LimeExpressionManager::RevertUpgradeConditionsToRelevance($surveyid);
         foreach ($deletedqids as $deletedqid) {
             $deletedqid = (int) $deletedqid;
             if ($deletedqid > 0) {
                 // don't remove undefined
                 $result = Questions::model()->deleteAllByAttributes(array('qid' => $deletedqid));
                 if (!$result) {
                     $databaseoutput .= "<script type=\"text/javascript\">\n<!--\n alert(\"" . $clang->gT("Failed to delete answer", "js") . " \")\n //-->\n</script>\n";
                 }
             }
         }
         //Determine ids by evaluating the hidden field
         $rows = array();
         $codes = array();
         $oldcodes = array();
         foreach ($_POST as $postkey => $postvalue) {
             $postkey = explode('_', $postkey);
             if ($postkey[0] == 'answer') {
                 $rows[$postkey[3]][$postkey[1]][$postkey[2]] = $postvalue;
             }
             if ($postkey[0] == 'code') {
                 $codes[$postkey[2]][] = $postvalue;
             }
             if ($postkey[0] == 'oldcode') {
                 $oldcodes[$postkey[2]][] = $postvalue;
             }
         }
         $count = 0;
         $invalidCode = 0;
         $duplicateCode = 0;
         $dupanswers = array();
         /*
         for ($scale_id=0;$scale_id<$scalecount;$scale_id++)
         {
         
         // Find duplicate codes and add these to dupanswers array
         $foundCat=array_count_values($codes);
         foreach($foundCat as $key=>$value){
         if($value>=2){
         $dupanswers[]=$key;
         }
         }
         }
         */
         //require_once("../classes/inputfilter/class.inputfilter_clean.php");
         //$myFilter = new InputFilter('','',1,1,1);
         //$insertqids=array(); //?
         $insertqid = array();
         for ($scale_id = 0; $scale_id < $scalecount; $scale_id++) {
             foreach ($anslangs as $language) {
                 $position = 0;
                 foreach ($rows[$scale_id][$language] as $subquestionkey => $subquestionvalue) {
                     if (substr($subquestionkey, 0, 3) != 'new') {
                         Questions::model()->updateByPk(array('qid' => $subquestionkey, 'language' => $language), array('question_order' => $position + 1, 'title' => $codes[$scale_id][$position], 'question' => $subquestionvalue, 'scale_id' => $scale_id));
                         if (isset($oldcodes[$scale_id][$position]) && $codes[$scale_id][$position] !== $oldcodes[$scale_id][$position]) {
                             Conditions::model()->updateAll(array('cfieldname' => '+' . $surveyid . 'X' . $gid . 'X' . $qid . $codes[$scale_id][$position], 'value' => $codes[$scale_id][$position]), 'cqid=:cqid AND cfieldname=:cfieldname AND value=:value', array(':cqid' => $qid, ':cfieldname' => $surveyid . 'X' . $gid . 'X' . $qid, ':value' => $oldcodes[$scale_id][$position]));
                         }
                     } else {
                         if (!isset($insertqid[$scale_id][$position])) {
                             $insertqid[$scale_id][$position] = Questions::model()->insertRecords(array('sid' => $surveyid, 'gid' => $gid, 'question_order' => $position + 1, 'title' => $codes[$scale_id][$position], 'question' => $subquestionvalue, 'parent_qid' => $qid, 'language' => $language, 'scale_id' => $scale_id));
                         } else {
                             switchMSSQLIdentityInsert('questions', true);
                             Questions::model()->insertRecords(array('qid' => $insertqid[$scale_id][$position], 'sid' => $surveyid, 'gid' => $gid, 'question_order' => $position + 1, 'title' => $codes[$scale_id][$position], 'question' => $subquestionvalue, 'parent_qid' => $qid, 'language' => $language, 'scale_id' => $scale_id));
                             switchMSSQLIdentityInsert('questions', true);
                         }
                     }
                     $position++;
                 }
             }
         }
         LimeExpressionManager::UpgradeConditionsToRelevance($surveyid);
         //include("surveytable_functions.php");
         //surveyFixColumns($surveyid);
         Yii::app()->session['flashmessage'] = $clang->gT("Subquestions were successfully saved.");
         //$action='editsubquestions';
         LimeExpressionManager::SetDirtyFlag();
         if ($databaseoutput != '') {
             echo $databaseoutput;
         } else {
             $this->getController()->redirect($this->getController()->createUrl('/admin/question/sa/subquestions/surveyid/' . $surveyid . '/gid/' . $gid . '/qid/' . $qid));
         }
     }
     if (in_array($action, array('insertquestion', 'copyquestion')) && hasSurveyPermission($surveyid, 'surveycontent', 'create')) {
         $baselang = Survey::model()->findByPk($surveyid)->language;
         if (strlen(Yii::app()->request->getPost('title')) < 1) {
             $databaseoutput .= "<script type=\"text/javascript\">\n<!--\n " . "alert(\"" . $clang->gT("The question could not be added. You must enter at least a question code.", "js") . "\")\n " . "//-->\n</script>\n";
         } else {
             if (Yii::app()->request->getPost('questionposition', "") != "") {
                 $question_order = intval(Yii::app()->request->getPost('questionposition'));
                 //Need to renumber all questions on or after this
                 $cdquery = "UPDATE {{questions}} SET question_order=question_order+1 WHERE gid=:gid AND question_order >= :order";
                 $cdresult = Yii::app()->db->createCommand($cdquery)->bindValues(array(':gid' => $gid, ':order' => $question_order))->query();
             } else {
                 $question_order = getMaxQuestionOrder($gid, $surveyid);
                 $question_order++;
             }
             $_POST['title'] = html_entity_decode(Yii::app()->request->getPost('title'), ENT_QUOTES, "UTF-8");
             $_POST['question_' . $baselang] = html_entity_decode(Yii::app()->request->getPost('question_' . $baselang), ENT_QUOTES, "UTF-8");
             $_POST['help_' . $baselang] = html_entity_decode(Yii::app()->request->getPost('help_' . $baselang), ENT_QUOTES, "UTF-8");
             // Fix bug with FCKEditor saving strange BR types
             if ($xssfilter) {
                 $_POST['title'] = $filter->purify($_POST['title']);
                 $_POST['question_' . $baselang] = $filter->purify($_POST['question_' . $baselang]);
                 $_POST['help_' . $baselang] = $filter->purify($_POST['help_' . $baselang]);
             } else {
                 $_POST['title'] = fixCKeditorText(Yii::app()->request->getPost('title'));
                 $_POST['question_' . $baselang] = fixCKeditorText(Yii::app()->request->getPost('question_' . $baselang));
                 $_POST['help_' . $baselang] = fixCKeditorText(Yii::app()->request->getPost('help_' . $baselang));
             }
             $data = array('sid' => $surveyid, 'gid' => $gid, 'type' => Yii::app()->request->getPost('type'), 'title' => Yii::app()->request->getPost('title'), 'question' => Yii::app()->request->getPost('question_' . $baselang), 'preg' => Yii::app()->request->getPost('preg'), 'help' => Yii::app()->request->getPost('help_' . $baselang), 'other' => Yii::app()->request->getPost('other'), 'mandatory' => Yii::app()->request->getPost('mandatory'), 'relevance' => Yii::app()->request->getPost('relevance'), 'question_order' => $question_order, 'language' => $baselang);
             $qid = Questions::model()->insertRecords($data);
             // Add other languages
             if ($qid) {
                 $addlangs = Survey::model()->findByPk($surveyid)->additionalLanguages;
                 foreach ($addlangs as $alang) {
                     if ($alang != "") {
                         $data = array('qid' => $qid, 'sid' => $surveyid, 'gid' => $gid, 'type' => Yii::app()->request->getPost('type'), 'title' => Yii::app()->request->getPost('title'), 'question' => Yii::app()->request->getPost('question_' . $alang), 'preg' => Yii::app()->request->getPost('preg'), 'help' => Yii::app()->request->getPost('help_' . $alang), 'other' => Yii::app()->request->getPost('other'), 'mandatory' => Yii::app()->request->getPost('mandatory'), 'question_order' => $question_order, 'language' => $alang);
                         $langqid = Questions::model()->insertRecords($data);
                         // Checked */
                         if (!$langqid) {
                             $databaseoutput .= "<script type=\"text/javascript\">\n<!--\n alert(\"" . sprintf($clang->gT("Question in language %s could not be created.", "js"), $alang) . "\\n\")\n //-->\n</script>\n";
                         }
                     }
                 }
             }
             if (!$qid) {
                 $databaseoutput .= "<script type=\"text/javascript\">\n<!--\n alert(\"" . $clang->gT("Question could not be created.", "js") . "\\n\")\n //-->\n</script>\n";
             } else {
                 if ($action == 'copyquestion') {
                     if (returnGlobal('copysubquestions') == "Y") {
                         $aSQIDMappings = array();
                         $r1 = Questions::model()->getSubQuestions(returnGlobal('oldqid'));
                         while ($qr1 = $r1->read()) {
                             $qr1['parent_qid'] = $qid;
                             if (isset($aSQIDMappings[$qr1['qid']])) {
                                 $qr1['qid'] = $aSQIDMappings[$qr1['qid']];
                             } else {
                                 $oldqid = $qr1['qid'];
                                 unset($qr1['qid']);
                             }
                             $qr1['gid'] = $postgid;
                             $iInsertID = Questions::model()->insertRecords($qr1);
                             if (!isset($qr1['qid'])) {
                                 $aSQIDMappings[$oldqid] = $iInsertID;
                             }
                         }
                     }
                     if (returnGlobal('copyanswers') == "Y") {
                         $r1 = Answers::model()->getAnswers(returnGlobal('oldqid'));
                         while ($qr1 = $r1->read()) {
                             Answers::model()->insertRecords(array('qid' => $qid, 'code' => $qr1['code'], 'answer' => $qr1['answer'], 'sortorder' => $qr1['sortorder'], 'language' => $qr1['language'], 'scale_id' => $qr1['scale_id']));
                         }
                     }
                     if (returnGlobal('copyattributes') == "Y") {
                         $r1 = Question_attributes::model()->getQuestionAttributes(returnGlobal('oldqid'));
                         while ($qr1 = $r1->read()) {
                             $qr1['qid'] = $qid;
                             unset($qr1['qaid']);
                             Question_attributes::model()->insertRecords($qr1);
                         }
                     }
                 } else {
                     $qattributes = questionAttributes();
                     $validAttributes = $qattributes[Yii::app()->request->getPost('type')];
                     $aLanguages = array_merge(array(Survey::model()->findByPk($surveyid)->language), Survey::model()->findByPk($surveyid)->additionalLanguages);
                     foreach ($validAttributes as $validAttribute) {
                         if ($validAttribute['i18n']) {
                             foreach ($aLanguages as $sLanguage) {
                                 // TODO sanitise XSS
                                 $value = Yii::app()->request->getPost($validAttribute['name'] . '_' . $sLanguage);
                                 $result = Question_attributes::model()->findAllByAttributes(array('attribute' => $validAttribute['name'], 'qid' => $qid, 'language' => $sLanguage));
                                 if (count($result) > 0) {
                                     if ($value != '') {
                                         Question_attributes::model()->updateAll(array('value' => $value), 'attribute=:attribute AND qid=:qid AND language=:language', array(':attribute' => $validAttribute['name'], ':qid' => $qid, ':language' => $sLanguage));
                                     } else {
                                         Question_attributes::model()->deleteAll('attribute=:attribute AND qid=:qid AND language=:language', array(':attribute' => $validAttribute['name'], ':qid' => $qid, ':language' => $sLanguage));
                                     }
                                 } elseif ($value != '') {
                                     $attribute = new Question_attributes();
                                     $attribute->qid = $qid;
                                     $attribute->value = $value;
                                     $attribute->attribute = $validAttribute['name'];
                                     $attribute->language = $sLanguage;
                                     $attribute->save();
                                 }
                             }
                         } else {
                             $value = Yii::app()->request->getPost($validAttribute['name']);
                             if ($validAttribute['name'] == 'multiflexible_step' && trim($value) != '') {
                                 $value = floatval($value);
                                 if ($value == 0) {
                                     $value = 1;
                                 }
                             }
                             $result = Question_attributes::model()->findAllByAttributes(array('attribute' => $validAttribute['name'], 'qid' => $qid));
                             if (count($result) > 0) {
                                 if ($value != $validAttribute['default'] && trim($value) != "") {
                                     Question_attributes::model()->updateAll(array('value' => $value), 'attribute=:attribute AND qid=:qid', array(':attribute' => $validAttribute['name'], ':qid' => $qid));
                                 } else {
                                     Question_attributes::model()->deleteAll('attribute=:attribute AND qid=:qid', array(':attribute' => $validAttribute['name'], ':qid' => $qid));
                                 }
                             } elseif ($value != $validAttribute['default'] && trim($value) != "") {
                                 $attribute = new Question_attributes();
                                 $attribute->qid = $qid;
                                 $attribute->value = $value;
                                 $attribute->attribute = $validAttribute['name'];
                                 $attribute->save();
                             }
                         }
                     }
                 }
                 Questions::model()->updateQuestionOrder($gid, $surveyid);
                 Yii::app()->session['flashmessage'] = $clang->gT("Question was successfully added.");
             }
         }
         LimeExpressionManager::SetDirtyFlag();
         // so refreshes syntax highlighting
         if ($databaseoutput != '') {
             echo $databaseoutput;
         } else {
             $this->getController()->redirect($this->getController()->createUrl('admin/survey/sa/view/surveyid/' . $surveyid . '/gid/' . $gid . '/qid/' . $qid));
         }
     }
     if ($action == "updatequestion" && hasSurveyPermission($surveyid, 'surveycontent', 'update')) {
         LimeExpressionManager::RevertUpgradeConditionsToRelevance($surveyid);
         $cqr = Questions::model()->findByAttributes(array('qid' => $qid));
         $oldtype = $cqr['type'];
         $oldgid = $cqr['gid'];
         // Remove invalid question attributes on saving
         $qattributes = questionAttributes();
         $criteria = new CDbCriteria();
         $criteria->compare('qid', $qid);
         if (isset($qattributes[Yii::app()->request->getPost('type')])) {
             $validAttributes = $qattributes[Yii::app()->request->getPost('type')];
             foreach ($validAttributes as $validAttribute) {
                 $criteria->compare('attribute', '<>' . $validAttribute['name']);
             }
         }
         Question_attributes::model()->deleteAll($criteria);
         $aLanguages = array_merge(array(Survey::model()->findByPk($surveyid)->language), Survey::model()->findByPk($surveyid)->additionalLanguages);
         //now save all valid attributes
         $validAttributes = $qattributes[Yii::app()->request->getPost('type')];
         foreach ($validAttributes as $validAttribute) {
             if ($validAttribute['i18n']) {
                 foreach ($aLanguages as $sLanguage) {
                     // TODO sanitise XSS
                     $value = Yii::app()->request->getPost($validAttribute['name'] . '_' . $sLanguage);
                     $result = Question_attributes::model()->findAllByAttributes(array('attribute' => $validAttribute['name'], 'qid' => $qid, 'language' => $sLanguage));
                     if (count($result) > 0) {
                         if ($value != '') {
                             Question_attributes::model()->updateAll(array('value' => $value), 'attribute=:attribute AND qid=:qid AND language=:language', array(':attribute' => $validAttribute['name'], ':qid' => $qid, ':language' => $sLanguage));
                         } else {
                             Question_attributes::model()->deleteAll('attribute=:attribute AND qid=:qid AND language=:language', array(':attribute' => $validAttribute['name'], ':qid' => $qid, ':language' => $sLanguage));
                         }
                     } elseif ($value != '') {
                         $attribute = new Question_attributes();
                         $attribute->qid = $qid;
                         $attribute->value = $value;
                         $attribute->attribute = $validAttribute['name'];
                         $attribute->language = $sLanguage;
                         $attribute->save();
                     }
                 }
             } else {
                 $value = Yii::app()->request->getPost($validAttribute['name']);
                 if ($validAttribute['name'] == 'multiflexible_step' && trim($value) != '') {
                     $value = floatval($value);
                     if ($value == 0) {
                         $value = 1;
                     }
                 }
                 $result = Question_attributes::model()->findAllByAttributes(array('attribute' => $validAttribute['name'], 'qid' => $qid));
                 if (count($result) > 0) {
                     if ($value != $validAttribute['default'] && trim($value) != "") {
                         Question_attributes::model()->updateAll(array('value' => $value), 'attribute=:attribute AND qid=:qid', array(':attribute' => $validAttribute['name'], ':qid' => $qid));
                     } else {
                         Question_attributes::model()->deleteAll('attribute=:attribute AND qid=:qid', array(':attribute' => $validAttribute['name'], ':qid' => $qid));
                     }
                 } elseif ($value != $validAttribute['default'] && trim($value) != "") {
                     $attribute = new Question_attributes();
                     $attribute->qid = $qid;
                     $attribute->value = $value;
                     $attribute->attribute = $validAttribute['name'];
                     $attribute->save();
                 }
             }
         }
         $qtypes = getQuestionTypeList('', 'array');
         // These are the questions types that have no answers and therefore we delete the answer in that case
         $iAnswerScales = $qtypes[Yii::app()->request->getPost('type')]['answerscales'];
         $iSubquestionScales = $qtypes[Yii::app()->request->getPost('type')]['subquestions'];
         // These are the questions types that have the other option therefore we set everything else to 'No Other'
         if (Yii::app()->request->getPost('type') != "L" && Yii::app()->request->getPost('type') != "!" && Yii::app()->request->getPost('type') != "P" && Yii::app()->request->getPost('type') != "M") {
             $_POST['other'] = 'N';
         }
         // These are the questions types that have no validation - so zap it accordingly
         if (Yii::app()->request->getPost('type') == "!" || Yii::app()->request->getPost('type') == "L" || Yii::app()->request->getPost('type') == "M" || Yii::app()->request->getPost('type') == "P" || Yii::app()->request->getPost('type') == "F" || Yii::app()->request->getPost('type') == "H" || Yii::app()->request->getPost('type') == "X" || Yii::app()->request->getPost('type') == "") {
             $_POST['preg'] = '';
         }
         // These are the questions types that have no mandatory property - so zap it accordingly
         if (Yii::app()->request->getPost('type') == "X" || Yii::app()->request->getPost('type') == "|") {
             $_POST['mandatory'] = 'N';
         }
         if ($oldtype != Yii::app()->request->getPost('type')) {
             // TMSW Conditions->Relevance:  Do similar check via EM, but do allow such a change since will be easier to modify relevance
             //Make sure there are no conditions based on this question, since we are changing the type
             $ccresult = Conditions::model()->findAllByAttributes(array('cqid' => $qid));
             $cccount = count($ccresult);
             foreach ($ccresult as $ccr) {
                 $qidarray[] = $ccr['qid'];
             }
             if (isset($qidarray) && $qidarray) {
                 $qidlist = implode(", ", $qidarray);
             }
         }
         if (isset($cccount) && $cccount) {
             $databaseoutput .= "<script type=\"text/javascript\">\n<!--\n alert(\"" . $clang->gT("Question could not be updated. There are conditions for other questions that rely on the answers to this question and changing the type will cause problems. You must delete these conditions before you can change the type of this question.", "js") . " ({$qidlist})\")\n //-->\n</script>\n";
         } else {
             if (isset($gid) && $gid != "") {
                 //                    $array_result=checkMoveQuestionConstraintsForConditions(sanitize_int($surveyid),sanitize_int($qid), sanitize_int($gid));
                 //                    // If there is no blocking conditions that could prevent this move
                 //
                 //                    if (is_null($array_result['notAbove']) && is_null($array_result['notBelow']))
                 //                    {
                 $questlangs = Survey::model()->findByPk($surveyid)->additionalLanguages;
                 $baselang = Survey::model()->findByPk($surveyid)->language;
                 array_push($questlangs, $baselang);
                 if ($xssfilter) {
                     $_POST['title'] = $filter->purify($_POST['title']);
                 } else {
                     $_POST['title'] = html_entity_decode(Yii::app()->request->getPost('title'), ENT_QUOTES, "UTF-8");
                 }
                 // Fix bug with FCKEditor saving strange BR types
                 $_POST['title'] = fixCKeditorText(Yii::app()->request->getPost('title'));
                 foreach ($questlangs as $qlang) {
                     if ($xssfilter) {
                         $_POST['question_' . $qlang] = $filter->purify($_POST['question_' . $qlang]);
                         $_POST['help_' . $qlang] = $filter->purify($_POST['help_' . $qlang]);
                     } else {
                         $_POST['question_' . $qlang] = html_entity_decode(Yii::app()->request->getPost('question_' . $qlang), ENT_QUOTES, "UTF-8");
                         $_POST['help_' . $qlang] = html_entity_decode(Yii::app()->request->getPost('help_' . $qlang), ENT_QUOTES, "UTF-8");
                     }
                     // Fix bug with FCKEditor saving strange BR types
                     $_POST['question_' . $qlang] = fixCKeditorText(Yii::app()->request->getPost('question_' . $qlang));
                     $_POST['help_' . $qlang] = fixCKeditorText(Yii::app()->request->getPost('help_' . $qlang));
                     if (isset($qlang) && $qlang != "") {
                         // ToDo: Sanitize the POST variables !
                         $udata = array('type' => Yii::app()->request->getPost('type'), 'title' => Yii::app()->request->getPost('title'), 'question' => Yii::app()->request->getPost('question_' . $qlang), 'preg' => Yii::app()->request->getPost('preg'), 'help' => Yii::app()->request->getPost('help_' . $qlang), 'gid' => $gid, 'other' => Yii::app()->request->getPost('other'), 'mandatory' => Yii::app()->request->getPost('mandatory'), 'relevance' => Yii::app()->request->getPost('relevance'));
                         if ($oldgid != $gid) {
                             if (getGroupOrder($surveyid, $oldgid) > getGroupOrder($surveyid, $gid)) {
                                 // TMSW Conditions->Relevance:  What is needed here?
                                 // Moving question to a 'upper' group
                                 // insert question at the end of the destination group
                                 // this prevent breaking conditions if the target qid is in the dest group
                                 $insertorder = getMaxQuestionOrder($gid, $surveyid) + 1;
                                 $udata = array_merge($udata, array('question_order' => $insertorder));
                             } else {
                                 // Moving question to a 'lower' group
                                 // insert question at the beginning of the destination group
                                 shiftOrderQuestions($surveyid, $gid, 1);
                                 // makes 1 spare room for new question at top of dest group
                                 $udata = array_merge($udata, array('question_order' => 0));
                             }
                         }
                         $condn = array('sid' => $surveyid, 'qid' => $qid, 'language' => $qlang);
                         $question = Questions::model()->findByAttributes($condn);
                         foreach ($udata as $k => $v) {
                             $question->{$k} = $v;
                         }
                         $uqresult = $question->save();
                         //($uqquery); // or safeDie ("Error Update Question: ".$uqquery."<br />");  // Checked)
                         if (!$uqresult) {
                             $databaseoutput .= "<script type=\"text/javascript\">\n<!--\n alert(\"" . $clang->gT("Question could not be updated", "js") . "\n\")\n //-->\n</script>\n";
                         }
                     }
                 }
                 // Update the group ID on subquestions, too
                 if ($oldgid != $gid) {
                     Questions::model()->updateAll(array('gid' => $gid), 'qid=:qid and parent_qid>0', array(':qid' => $qid));
                     // if the group has changed then fix the sortorder of old and new group
                     Questions::model()->updateQuestionOrder($oldgid, $surveyid);
                     Questions::model()->updateQuestionOrder($gid, $surveyid);
                     // If some questions have conditions set on this question's answers
                     // then change the cfieldname accordingly
                     fixMovedQuestionConditions($qid, $oldgid, $gid);
                 }
                 if ($oldtype != Yii::app()->request->getPost('type')) {
                     Questions::model()->updateAll(array('type' => Yii::app()->request->getPost('type')), 'parent_qid=:qid', array(':qid' => $qid));
                 }
                 Answers::model()->deleteAllByAttributes(array('qid' => $qid), 'scale_id >= :scale_id', array(':scale_id' => $iAnswerScales));
                 // Remove old subquestion scales
                 Questions::model()->deleteAllByAttributes(array('parent_qid' => $qid), 'scale_id >= :scale_id', array(':scale_id' => $iSubquestionScales));
                 Yii::app()->session['flashmessage'] = $clang->gT("Question was successfully saved.");
                 //                    }
                 //                    else
                 //                    {
                 //
                 //                        // There are conditions constraints: alert the user
                 //                        $errormsg="";
                 //                        if (!is_null($array_result['notAbove']))
                 //                        {
                 //                            $errormsg.=$clang->gT("This question relies on other question's answers and can't be moved above groupId:","js")
                 //                            . " " . $array_result['notAbove'][0][0] . " " . $clang->gT("in position","js")." ".$array_result['notAbove'][0][1]."\\n"
                 //                            . $clang->gT("See conditions:")."\\n";
                 //
                 //                            foreach ($array_result['notAbove'] as $notAboveCond)
                 //                            {
                 //                                $errormsg.="- cid:". $notAboveCond[3]."\\n";
                 //                            }
                 //
                 //                        }
                 //                        if (!is_null($array_result['notBelow']))
                 //                        {
                 //                            $errormsg.=$clang->gT("Some questions rely on this question's answers. You can't move this question below groupId:","js")
                 //                            . " " . $array_result['notBelow'][0][0] . " " . $clang->gT("in position","js")." ".$array_result['notBelow'][0][1]."\\n"
                 //                            . $clang->gT("See conditions:")."\\n";
                 //
                 //                            foreach ($array_result['notBelow'] as $notBelowCond)
                 //                            {
                 //                                $errormsg.="- cid:". $notBelowCond[3]."\\n";
                 //                            }
                 //                        }
                 //
                 //                        $databaseoutput .= "<script type=\"text/javascript\">\n<!--\n alert(\"$errormsg\")\n //-->\n</script>\n";
                 //                        $gid= $oldgid; // group move impossible ==> keep display on oldgid
                 //                    }
             } else {
                 $databaseoutput .= "<script type=\"text/javascript\">\n<!--\n alert(\"" . $clang->gT("Question could not be updated", "js") . "\")\n //-->\n</script>\n";
             }
         }
         LimeExpressionManager::UpgradeConditionsToRelevance($surveyid);
         if ($databaseoutput != '') {
             echo $databaseoutput;
         } else {
             if (Yii::app()->request->getPost('newpage') == "return") {
                 $this->getController()->redirect($this->getController()->createUrl('admin/question/sa/editquestion/surveyid/' . $surveyid . '/gid/' . $gid . '/qid/' . $qid));
             } else {
                 $this->getController()->redirect($this->getController()->createUrl('admin/survey/sa/view/surveyid/' . $surveyid . '/gid/' . $gid . '/qid/' . $qid));
             }
         }
     }
     if ($action == "updatesurveylocalesettings" && hasSurveyPermission($surveyid, 'surveylocale', 'update')) {
         $languagelist = Survey::model()->findByPk($surveyid)->additionalLanguages;
         $languagelist[] = Survey::model()->findByPk($surveyid)->language;
         Yii::app()->loadHelper('database');
         foreach ($languagelist as $langname) {
             if ($langname) {
                 $url = Yii::app()->request->getPost('url_' . $langname);
                 if ($url == 'http://') {
                     $url = "";
                 }
                 // Clean XSS attacks
                 if ($xssfilter) {
                     $purifier = new CHtmlPurifier();
                     $purifier->options = array('HTML.Allowed' => 'p,a[href],b,i');
                     $short_title = $purifier->purify(Yii::app()->request->getPost('short_title_' . $langname));
                     $description = $purifier->purify(Yii::app()->request->getPost('description_' . $langname));
                     $welcome = $purifier->purify(Yii::app()->request->getPost('welcome_' . $langname));
                     $endtext = $purifier->purify(Yii::app()->request->getPost('endtext_' . $langname));
                     $sURLDescription = $purifier->purify(Yii::app()->request->getPost('urldescrip_' . $langname));
                     $sURL = $purifier->purify(Yii::app()->request->getPost('url_' . $langname));
                 } else {
                     $short_title = html_entity_decode(Yii::app()->request->getPost('short_title_' . $langname), ENT_QUOTES, "UTF-8");
                     $description = html_entity_decode(Yii::app()->request->getPost('description_' . $langname), ENT_QUOTES, "UTF-8");
                     $welcome = html_entity_decode(Yii::app()->request->getPost('welcome_' . $langname), ENT_QUOTES, "UTF-8");
                     $endtext = html_entity_decode(Yii::app()->request->getPost('endtext_' . $langname), ENT_QUOTES, "UTF-8");
                     $sURLDescription = html_entity_decode(Yii::app()->request->getPost('urldescrip_' . $langname), ENT_QUOTES, "UTF-8");
                     $sURL = html_entity_decode(Yii::app()->request->getPost('url_' . $langname), ENT_QUOTES, "UTF-8");
                 }
                 // Fix bug with FCKEditor saving strange BR types
                 $short_title = Yii::app()->request->getPost('short_title_' . $langname);
                 $description = Yii::app()->request->getPost('description_' . $langname);
                 $welcome = Yii::app()->request->getPost('welcome_' . $langname);
                 $endtext = Yii::app()->request->getPost('endtext_' . $langname);
                 $short_title = fixCKeditorText($short_title);
                 $description = fixCKeditorText($description);
                 $welcome = fixCKeditorText($welcome);
                 $endtext = fixCKeditorText($endtext);
                 $data = array('surveyls_title' => $short_title, 'surveyls_description' => $description, 'surveyls_welcometext' => $welcome, 'surveyls_endtext' => $endtext, 'surveyls_url' => $sURL, 'surveyls_urldescription' => $sURLDescription, 'surveyls_dateformat' => Yii::app()->request->getPost('dateformat_' . $langname), 'surveyls_numberformat' => Yii::app()->request->getPost('numberformat_' . $langname));
                 $Surveys_languagesettings = Surveys_languagesettings::model()->findByPk(array('surveyls_survey_id' => $postsid, 'surveyls_language' => $langname));
                 $Surveys_languagesettings->attributes = $data;
                 $Surveys_languagesettings->save();
                 // save the change to database
             }
         }
         Yii::app()->session['flashmessage'] = $clang->gT("Survey text elements successfully saved.");
         if ($databaseoutput != '') {
             echo $databaseoutput;
         } else {
             $this->getController()->redirect($this->getController()->createUrl('admin/survey/sa/view/surveyid/' . $surveyid));
         }
     }
     if (($action == "updatesurveysettingsandeditlocalesettings" || $action == "updatesurveysettings") && hasSurveyPermission($surveyid, 'surveysettings', 'update')) {
         Yii::app()->loadHelper('surveytranslator');
         Yii::app()->loadHelper('database');
         $formatdata = getDateFormatData(Yii::app()->session['dateformat']);
         $expires = $_POST['expires'];
         if (trim($expires) == "") {
             $expires = null;
         } else {
             Yii::app()->loadLibrary('Date_Time_Converter');
             $datetimeobj = new date_time_converter($expires, $formatdata['phpdate'] . ' H:i');
             //new Date_Time_Converter($expires, $formatdata['phpdate'].' H:i');
             $expires = $datetimeobj->convert("Y-m-d H:i:s");
         }
         $startdate = $_POST['startdate'];
         if (trim($startdate) == "") {
             $startdate = null;
         } else {
             Yii::app()->loadLibrary('Date_Time_Converter');
             $datetimeobj = new date_time_converter($startdate, $formatdata['phpdate'] . ' H:i');
             //new Date_Time_Converter($startdate,$formatdata['phpdate'].' H:i');
             $startdate = $datetimeobj->convert("Y-m-d H:i:s");
         }
         //make sure only numbers are passed within the $_POST variable
         $tokenlength = (int) $_POST['tokenlength'];
         //token length has to be at least 5, otherwise set it to default (15)
         if ($tokenlength < 5) {
             $tokenlength = 15;
         }
         cleanLanguagesFromSurvey($surveyid, Yii::app()->request->getPost('languageids'));
         fixLanguageConsistency($surveyid, Yii::app()->request->getPost('languageids'));
         $template = Yii::app()->request->getPost('template');
         if (Yii::app()->session['USER_RIGHT_SUPERADMIN'] != 1 && Yii::app()->session['USER_RIGHT_MANAGE_TEMPLATE'] != 1 && !hasTemplateManageRights(Yii::app()->session['loginID'], $template)) {
             $template = "default";
         }
         $aURLParams = json_decode(Yii::app()->request->getPost('allurlparams'), true);
         Survey_url_parameters::model()->deleteAllByAttributes(array('sid' => $surveyid));
         foreach ($aURLParams as $aURLParam) {
             $aURLParam['parameter'] = trim($aURLParam['parameter']);
             if ($aURLParam['parameter'] == '' || !preg_match('/^[a-zA-Z_][a-zA-Z0-9_]*$/', $aURLParam['parameter']) || $aURLParam['parameter'] == 'sid' || $aURLParam['parameter'] == 'newtest' || $aURLParam['parameter'] == 'token' || $aURLParam['parameter'] == 'lang') {
                 continue;
                 // this parameter name seems to be invalid - just ignore it
             }
             unset($aURLParam['act']);
             unset($aURLParam['title']);
             unset($aURLParam['id']);
             if ($aURLParam['targetqid'] == '') {
                 $aURLParam['targetqid'] = NULL;
             }
             if ($aURLParam['targetsqid'] == '') {
                 $aURLParam['targetsqid'] = NULL;
             }
             $aURLParam['sid'] = $surveyid;
             $param = new Survey_url_parameters();
             foreach ($aURLParam as $k => $v) {
                 $param->{$k} = $v;
             }
             $param->save();
         }
         $updatearray = array('admin' => Yii::app()->request->getPost('admin'), 'expires' => $expires, 'adminemail' => Yii::app()->request->getPost('adminemail'), 'startdate' => $startdate, 'bounce_email' => Yii::app()->request->getPost('bounce_email'), 'anonymized' => Yii::app()->request->getPost('anonymized'), 'faxto' => Yii::app()->request->getPost('faxto'), 'format' => Yii::app()->request->getPost('format'), 'savetimings' => Yii::app()->request->getPost('savetimings'), 'template' => $template, 'assessments' => Yii::app()->request->getPost('assessments'), 'language' => Yii::app()->request->getPost('language'), 'additional_languages' => Yii::app()->request->getPost('languageids'), 'datestamp' => Yii::app()->request->getPost('datestamp'), 'ipaddr' => Yii::app()->request->getPost('ipaddr'), 'refurl' => Yii::app()->request->getPost('refurl'), 'publicgraphs' => Yii::app()->request->getPost('publicgraphs'), 'usecookie' => Yii::app()->request->getPost('usecookie'), 'allowregister' => Yii::app()->request->getPost('allowregister'), 'allowsave' => Yii::app()->request->getPost('allowsave'), 'navigationdelay' => Yii::app()->request->getPost('navigationdelay'), 'printanswers' => Yii::app()->request->getPost('printanswers'), 'publicstatistics' => Yii::app()->request->getPost('publicstatistics'), 'autoredirect' => Yii::app()->request->getPost('autoredirect'), 'showxquestions' => Yii::app()->request->getPost('showxquestions'), 'showgroupinfo' => Yii::app()->request->getPost('showgroupinfo'), 'showqnumcode' => Yii::app()->request->getPost('showqnumcode'), 'shownoanswer' => Yii::app()->request->getPost('shownoanswer'), 'showwelcome' => Yii::app()->request->getPost('showwelcome'), 'allowprev' => Yii::app()->request->getPost('allowprev'), 'allowjumps' => Yii::app()->request->getPost('allowjumps'), 'nokeyboard' => Yii::app()->request->getPost('nokeyboard'), 'showprogress' => Yii::app()->request->getPost('showprogress'), 'listpublic' => Yii::app()->request->getPost('public'), 'htmlemail' => Yii::app()->request->getPost('htmlemail'), 'sendconfirmation' => Yii::app()->request->getPost('sendconfirmation'), 'tokenanswerspersistence' => Yii::app()->request->getPost('tokenanswerspersistence'), 'alloweditaftercompletion' => Yii::app()->request->getPost('alloweditaftercompletion'), 'usecaptcha' => Yii::app()->request->getPost('usecaptcha'), 'emailresponseto' => trim(Yii::app()->request->getPost('emailresponseto')), 'emailnotificationto' => trim(Yii::app()->request->getPost('emailnotificationto')), 'googleanalyticsapikey' => trim(Yii::app()->request->getPost('googleanalyticsapikey')), 'googleanalyticsstyle' => trim(Yii::app()->request->getPost('googleanalyticsstyle')), 'tokenlength' => $tokenlength);
         // use model
         $Survey = Survey::model()->findByPk($surveyid);
         foreach ($updatearray as $k => $v) {
             $Survey->{$k} = $v;
         }
         $Survey->save();
         #            Survey::model()->updateByPk($surveyid, $updatearray);
         $sqlstring = "surveyls_survey_id=:sid AND surveyls_language <> :base ";
         $params = array(':sid' => $surveyid, ':base' => Survey::model()->findByPk($surveyid)->language);
         $i = 100000;
         foreach (Survey::model()->findByPk($surveyid)->additionalLanguages as $langname) {
             if ($langname) {
                 $sqlstring .= "AND surveyls_language <> :{$i} ";
                 $params[':' . $i] = $langname;
             }
             $i++;
         }
         Surveys_languagesettings::model()->deleteAll($sqlstring, $params);
         $usresult = true;
         foreach (Survey::model()->findByPk($surveyid)->additionalLanguages as $langname) {
             if ($langname) {
                 $oLanguageSettings = Surveys_languagesettings::model()->find('surveyls_survey_id=:surveyid AND surveyls_language=:langname', array(':surveyid' => $surveyid, ':langname' => $langname));
                 if (!$oLanguageSettings) {
                     $oLanguageSettings = new Surveys_languagesettings();
                     $languagedetails = getLanguageDetails($langname);
                     $insertdata = array('surveyls_survey_id' => $surveyid, 'surveyls_language' => $langname, 'surveyls_title' => '', 'surveyls_dateformat' => $languagedetails['dateformat']);
                     foreach ($insertdata as $k => $v) {
                         $oLanguageSettings->{$k} = $v;
                     }
                     $usresult = $oLanguageSettings->save();
                 }
             }
         }
         if ($usresult) {
             Yii::app()->session['flashmessage'] = $clang->gT("Survey settings were successfully saved.");
         } else {
             Yii::app()->session['flashmessage'] = $clang->gT("Error:") . '<br>' . $clang->gT("Survey could not be updated.");
         }
         if (Yii::app()->request->getPost('action') == "updatesurveysettingsandeditlocalesettings") {
             $this->getController()->redirect($this->getController()->createUrl('admin/survey/sa/editlocalsettings/surveyid/' . $surveyid));
         } else {
             $this->getController()->redirect($this->getController()->createUrl('admin/survey/sa/view/surveyid/' . $surveyid));
         }
     }
     if (!$action) {
         $this->getController()->redirect("/admin", "refresh");
     }
 }
Пример #18
0
 private function _array_filter_help($qidattributes, $surveyprintlang, $surveyid)
 {
     $clang = $this->getController()->lang;
     $output = "";
     if (!empty($qidattributes['array_filter'])) {
         $newquestiontext = Questions::model()->findByAttributes(array('title' => $qidattributes['array_filter'], 'language' => $surveyprintlang, 'sid' => $surveyid))->getAttribute('question');
         $output .= "\n<p class='extrahelp'>\n            " . sprintf($clang->gT("Only answer this question for the items you selected in question %s ('%s')"), $qidattributes['array_filter'], flattenText(breakToNewline($newquestiontext['question']))) . "\n            </p>\n";
     }
     if (!empty($qidattributes['array_filter_exclude'])) {
         $newquestiontext = Questions::model()->findByAttributes(array('title' => $qidattributes['array_filter_exclude'], 'language' => $surveyprintlang, 'sid' => $surveyid))->getAttribute('question');
         $output .= "\n    <p class='extrahelp'>\n            " . sprintf($clang->gT("Only answer this question for the items you did not select in question %s ('%s')"), $qidattributes['array_filter_exclude'], breakToNewline($newquestiontext['question'])) . "\n            </p>\n";
     }
     return $output;
 }
Пример #19
0
/**
* Import survey from an TSV file template that does not require or allow assigning of GID or QID values.
* NOTE:  This currently only supports import of one language
* @global type $connect
* @global type $dbprefix
* @global type $clang
* @global type $timeadjust
* @param type $sFullFilepath
* @return type
*
* @author TMSWhite
*/
function TSVImportSurvey($sFullFilepath)
{
    $clang = Yii::app()->lang;
    $insertdata = array();
    $results = array();
    $results['error'] = false;
    $baselang = 'en';
    // TODO set proper default
    $encoding = '';
    $handle = fopen($sFullFilepath, 'r');
    $bom = fread($handle, 2);
    rewind($handle);
    // Excel tends to save CSV as UTF-16, which PHP does not properly detect
    if ($bom === chr(0xff) . chr(0xfe) || $bom === chr(0xfe) . chr(0xff)) {
        // UTF16 Byte Order Mark present
        $encoding = 'UTF-16';
    } else {
        $file_sample = fread($handle, 1000) + 'e';
        //read first 1000 bytes
        // + e is a workaround for mb_string bug
        rewind($handle);
        $encoding = mb_detect_encoding($file_sample, 'UTF-8, UTF-7, ASCII, EUC-JP,SJIS, eucJP-win, SJIS-win, JIS, ISO-2022-JP');
    }
    if ($encoding && $encoding != 'UTF-8') {
        stream_filter_append($handle, 'convert.iconv.' . $encoding . '/UTF-8');
    }
    $file = stream_get_contents($handle);
    fclose($handle);
    // fix Excel non-breaking space
    $file = str_replace("0xC20xA0", ' ', $file);
    $filelines = explode("\n", $file);
    $row = array_shift($filelines);
    $headers = explode("\t", $row);
    $rowheaders = array();
    foreach ($headers as $header) {
        $rowheaders[] = trim($header);
    }
    // remove BOM from the first header cell, if needed
    $rowheaders[0] = preg_replace("/^\\W+/", "", $rowheaders[0]);
    if (preg_match('/class$/', $rowheaders[0])) {
        $rowheaders[0] = 'class';
        // second attempt to remove BOM
    }
    $adata = array();
    foreach ($filelines as $rowline) {
        $rowarray = array();
        $row = explode("\t", $rowline);
        for ($i = 0; $i < count($rowheaders); ++$i) {
            $val = isset($row[$i]) ? $row[$i] : '';
            // if Excel was used, it surrounds strings with quotes and doubles internal double quotes.  Fix that.
            if (preg_match('/^".*"$/', $val)) {
                $val = str_replace('""', '"', substr($val, 1, -1));
            }
            $rowarray[$rowheaders[$i]] = $val;
        }
        $adata[] = $rowarray;
    }
    $results['defaultvalues'] = 0;
    $results['answers'] = 0;
    $results['surveys'] = 0;
    $results['languages'] = 0;
    $results['questions'] = 0;
    $results['subquestions'] = 0;
    $results['question_attributes'] = 0;
    $results['groups'] = 0;
    $results['importwarnings'] = array();
    // these aren't used here, but are needed to avoid errors in post-import display
    $results['assessments'] = 0;
    $results['quota'] = 0;
    $results['quotamembers'] = 0;
    $results['quotals'] = 0;
    // collect information about survey and its language settings
    $surveyinfo = array();
    $surveyls = array();
    foreach ($adata as $row) {
        switch ($row['class']) {
            case 'S':
                if (isset($row['text']) && $row['name'] != 'datecreated') {
                    $surveyinfo[$row['name']] = $row['text'];
                }
                break;
            case 'SL':
                if (!isset($surveyls[$row['language']])) {
                    $surveyls[$row['language']] = array();
                }
                if (isset($row['text'])) {
                    $surveyls[$row['language']][$row['name']] = $row['text'];
                }
                break;
        }
    }
    $iOldSID = 1;
    if (isset($surveyinfo['sid'])) {
        $iOldSID = (int) $surveyinfo['sid'];
    }
    // Create the survey entry
    $surveyinfo['startdate'] = NULL;
    $surveyinfo['active'] = 'N';
    // unset($surveyinfo['datecreated']);
    switchMSSQLIdentityInsert('surveys', true);
    $iNewSID = Survey::model()->insertNewSurvey($surveyinfo);
    //or safeDie($clang->gT("Error").": Failed to insert survey<br />");
    if ($iNewSID == false) {
        $results['error'] = Survey::model()->getErrors();
        $results['bFailed'] = true;
        return $results;
    }
    $surveyinfo['sid'] = $iNewSID;
    $results['surveys']++;
    switchMSSQLIdentityInsert('surveys', false);
    $results['newsid'] = $iNewSID;
    $gid = 0;
    $gseq = 0;
    // group_order
    $qid = 0;
    $qseq = 0;
    // question_order
    $qtype = 'T';
    $aseq = 0;
    // answer sortorder
    // set the language for the survey
    $_title = 'Missing Title';
    foreach ($surveyls as $_lang => $insertdata) {
        $insertdata['surveyls_survey_id'] = $iNewSID;
        $insertdata['surveyls_language'] = $_lang;
        if (isset($insertdata['surveyls_title'])) {
            $_title = $insertdata['surveyls_title'];
        } else {
            $insertdata['surveyls_title'] = $_title;
        }
        $result = Surveys_languagesettings::model()->insertNewSurvey($insertdata);
        //
        if (!$result) {
            $results['error'][] = $clang->gT("Error") . " : " . $clang->gT("Failed to insert survey language");
            break;
        }
        $results['languages']++;
    }
    $ginfo = array();
    $qinfo = array();
    $sqinfo = array();
    if (isset($surveyinfo['language'])) {
        $baselang = $surveyinfo['language'];
        // the base language
    }
    $rownumber = 1;
    foreach ($adata as $row) {
        $rownumber += 1;
        switch ($row['class']) {
            case 'G':
                // insert group
                $insertdata = array();
                $insertdata['sid'] = $iNewSID;
                $gname = isset($row['name']) ? $row['name'] : 'G' . $gseq;
                $insertdata['group_name'] = $gname;
                $insertdata['grelevance'] = isset($row['relevance']) ? $row['relevance'] : '';
                $insertdata['description'] = isset($row['text']) ? $row['text'] : '';
                $insertdata['language'] = isset($row['language']) ? $row['language'] : $baselang;
                // For multi numeric survey : same title
                if (isset($ginfo[$gname])) {
                    $gseq = $ginfo[$gname]['group_order'];
                    $gid = $ginfo[$gname]['gid'];
                    $insertdata['gid'] = $gid;
                    $insertdata['group_order'] = $gseq;
                } else {
                    $insertdata['group_order'] = $gseq;
                }
                $newgid = Groups::model()->insertRecords($insertdata);
                if (!$newgid) {
                    $results['error'][] = $clang->gT("Error") . " : " . $clang->gT("Failed to insert group") . ". " . $clang->gT("Text file row number ") . $rownumber . " (" . $gname . ")";
                    break;
                }
                if (!isset($ginfo[$gname])) {
                    $results['groups']++;
                    $gid = $newgid;
                    // save this for later
                    $ginfo[$gname]['gid'] = $gid;
                    $ginfo[$gname]['group_order'] = $gseq++;
                }
                $qseq = 0;
                // reset the question_order
                break;
            case 'Q':
                // insert question
                $insertdata = array();
                $insertdata['sid'] = $iNewSID;
                $qtype = isset($row['type/scale']) ? $row['type/scale'] : 'T';
                $qname = isset($row['name']) ? $row['name'] : 'Q' . $qseq;
                $insertdata['gid'] = $gid;
                $insertdata['type'] = $qtype;
                $insertdata['title'] = $qname;
                $insertdata['question'] = isset($row['text']) ? $row['text'] : '';
                $insertdata['relevance'] = isset($row['relevance']) ? $row['relevance'] : '';
                $insertdata['preg'] = isset($row['validation']) ? $row['validation'] : '';
                $insertdata['help'] = isset($row['help']) ? $row['help'] : '';
                $insertdata['language'] = isset($row['language']) ? $row['language'] : $baselang;
                $insertdata['mandatory'] = isset($row['mandatory']) ? $row['mandatory'] : '';
                $insertdata['other'] = isset($row['other']) ? $row['other'] : 'N';
                $insertdata['same_default'] = isset($row['same_default']) ? $row['same_default'] : 0;
                $insertdata['parent_qid'] = 0;
                // For multi numeric survey : same name, add the gid to have same name on different gid. Bad for EM.
                $fullqname = "G{$gid}_" . $qname;
                if (isset($qinfo[$fullqname])) {
                    $qseq = $qinfo[$fullqname]['question_order'];
                    $qid = $qinfo[$fullqname]['qid'];
                    $insertdata['qid'] = $qid;
                    $insertdata['question_order'] = $qseq;
                } else {
                    $insertdata['question_order'] = $qseq;
                }
                // Insert question and keep the qid for multi language survey
                $result = Questions::model()->insertRecords($insertdata);
                if (!$result) {
                    $results['error'][] = $clang->gT("Error") . " : " . $clang->gT("Could not insert question") . ". " . $clang->gT("Text file row number ") . $rownumber . " (" . $qname . ")";
                    break;
                }
                $newqid = $result;
                if (!isset($qinfo[$fullqname])) {
                    $results['questions']++;
                    $qid = $newqid;
                    // save this for later
                    $qinfo[$fullqname]['qid'] = $qid;
                    $qinfo[$fullqname]['question_order'] = $qseq++;
                }
                $aseq = 0;
                //reset the answer sortorder
                $sqseq = 0;
                //reset the sub question sortorder
                // insert question attributes
                foreach ($row as $key => $val) {
                    switch ($key) {
                        case 'class':
                        case 'type/scale':
                        case 'name':
                        case 'text':
                        case 'validation':
                        case 'relevance':
                        case 'help':
                        case 'language':
                        case 'mandatory':
                        case 'other':
                        case 'same_default':
                        case 'default':
                            break;
                        default:
                            if ($key != '' && $val != '') {
                                $insertdata = array();
                                $insertdata['qid'] = $qid;
                                $insertdata['language'] = isset($row['language']) ? $row['language'] : $baselang;
                                $insertdata['attribute'] = $key;
                                $insertdata['value'] = $val;
                                $result = Question_attributes::model()->insertRecords($insertdata);
                                //
                                if (!$result) {
                                    $results['importwarnings'][] = $clang->gT("Warning") . " : " . $clang->gT("Failed to insert question attribute") . ". " . $clang->gT("Text file row number ") . $rownumber . " ({$key})";
                                    break;
                                }
                                $results['question_attributes']++;
                            }
                            break;
                    }
                }
                // insert default value
                if (isset($row['default'])) {
                    $insertdata = array();
                    $insertdata['qid'] = $qid;
                    $insertdata['language'] = isset($row['language']) ? $row['language'] : $baselang;
                    $insertdata['defaultvalue'] = $row['default'];
                    $result = Defaultvalues::model()->insertRecords($insertdata);
                    if (!$result) {
                        $results['importwarnings'][] = $clang->gT("Warning") . " : " . $clang->gT("Failed to insert default value") . ". " . $clang->gT("Text file row number ") . $rownumber;
                        break;
                    }
                    $results['defaultvalues']++;
                }
                break;
            case 'SQ':
                $sqname = isset($row['name']) ? $row['name'] : 'SQ' . $sqseq;
                if ($qtype == 'O' || $qtype == '|') {
                    // these are fake rows to show naming of comment and filecount fields
                } elseif ($sqname == 'other' && ($qtype == '!' || $qtype == 'L')) {
                    // only want to set default value for 'other' in these cases - not a real SQ row
                    // TODO - this isn't working
                    if (isset($row['default'])) {
                        $insertdata = array();
                        $insertdata['qid'] = $qid;
                        $insertdata['specialtype'] = 'other';
                        $insertdata['language'] = isset($row['language']) ? $row['language'] : $baselang;
                        $insertdata['defaultvalue'] = $row['default'];
                        $result = Defaultvalues::model()->insertRecords($insertdata);
                        if (!$result) {
                            $results['importwarnings'][] = $clang->gT("Warning") . " : " . $clang->gT("Failed to insert default value") . ". " . $clang->gT("Text file row number ") . $rownumber;
                            break;
                        }
                        $results['defaultvalues']++;
                    }
                } else {
                    $insertdata = array();
                    $scale_id = isset($row['type/scale']) ? $row['type/scale'] : 0;
                    $insertdata['sid'] = $iNewSID;
                    $insertdata['gid'] = $gid;
                    $insertdata['parent_qid'] = $qid;
                    $insertdata['type'] = $qtype;
                    $insertdata['title'] = $sqname;
                    $insertdata['question'] = isset($row['text']) ? $row['text'] : '';
                    $insertdata['relevance'] = isset($row['relevance']) ? $row['relevance'] : '';
                    $insertdata['preg'] = isset($row['validation']) ? $row['validation'] : '';
                    $insertdata['help'] = isset($row['help']) ? $row['help'] : '';
                    $insertdata['language'] = isset($row['language']) ? $row['language'] : $baselang;
                    $insertdata['mandatory'] = isset($row['mandatory']) ? $row['mandatory'] : '';
                    $insertdata['scale_id'] = $scale_id;
                    // For multi nueric language, qid is needed, why not gid. name is not unique.
                    $fullsqname = "G{$gid}Q{$qid}_{$sqname}";
                    if (isset($sqinfo[$fullsqname])) {
                        $qseq = $sqinfo[$fullsqname]['question_order'];
                        $sqid = $sqinfo[$fullsqname]['sqid'];
                        $insertdata['question_order'] = $qseq;
                        $insertdata['qid'] = $sqid;
                    } else {
                        $insertdata['question_order'] = $qseq;
                    }
                    // Insert sub question and keep the sqid for multi language survey
                    $newsqid = Questions::model()->insertRecords($insertdata);
                    if (!$newsqid) {
                        $results['error'][] = $clang->gT("Error") . " : " . $clang->gT("Could not insert sub question") . ". " . $clang->gT("Text file row number ") . $rownumber . " (" . $qname . ")";
                        break;
                    }
                    if (!isset($sqinfo[$fullsqname])) {
                        $sqinfo[$fullsqname]['question_order'] = $qseq++;
                        $sqid = $newsqid;
                        // save this for later
                        $sqinfo[$fullsqname]['sqid'] = $sqid;
                        $results['subquestions']++;
                    }
                    // insert default value
                    if (isset($row['default'])) {
                        $insertdata = array();
                        $insertdata['qid'] = $qid;
                        $insertdata['sqid'] = $sqid;
                        $insertdata['scale_id'] = $scale_id;
                        $insertdata['language'] = isset($row['language']) ? $row['language'] : $baselang;
                        $insertdata['defaultvalue'] = $row['default'];
                        $result = Defaultvalues::model()->insertRecords($insertdata);
                        if (!$result) {
                            $results['importwarnings'][] = $clang->gT("Warning") . " : " . $clang->gT("Failed to insert default value") . ". " . $clang->gT("Text file row number ") . $rownumber;
                            break;
                        }
                        $results['defaultvalues']++;
                    }
                }
                break;
            case 'A':
                $insertdata = array();
                $insertdata['qid'] = $qid;
                $insertdata['code'] = isset($row['name']) ? $row['name'] : 'A' . $aseq;
                $insertdata['answer'] = isset($row['text']) ? $row['text'] : '';
                $insertdata['scale_id'] = isset($row['type/scale']) ? $row['type/scale'] : 0;
                $insertdata['language'] = isset($row['language']) ? $row['language'] : $baselang;
                $insertdata['assessment_value'] = isset($row['relevance']) ? $row['relevance'] : '';
                $insertdata['sortorder'] = ++$aseq;
                $result = Answers::model()->insertRecords($insertdata);
                // or safeDie("Error: Failed to insert answer<br />");
                if (!$result) {
                    $results['error'][] = $clang->gT("Error") . " : " . $clang->gT("Could not insert answer") . ". " . $clang->gT("Text file row number ") . $rownumber;
                }
                $results['answers']++;
                break;
        }
    }
    // Delete the survey if error found
    if (is_array($results['error'])) {
        $result = Survey::model()->deleteSurvey($iNewSID);
    }
    return $results;
}
Пример #20
0
 public function actionCategory()
 {
     $cat_id = Yii::app()->Ini->v('cat');
     $category = Projecttypes::model()->findByPk($cat_id);
     $this->pageTitle = 'Handyman.com - Questions under ' . $category->Name;
     $param['sidecats'] = Projecttypes::model()->findAll(array('order' => 'Name ASC'));
     $criteria = new CDbCriteria();
     $criteria->condition = "project_type_id = {$cat_id}";
     $criteria->order = "question_id DESC";
     $questions = Questions::model()->findAll($criteria);
     $count = Questions::model()->count($criteria);
     $pages = new CPagination($count);
     $pie = new SimplePie();
     $pie->set_feed_url('http://media.handyman.com/feed/');
     $pie->init();
     $pie->handle_content_type();
     $param['feed'] = $pie;
     $param['questions'] = $questions;
     $param['type'] = $category;
     $this->render('index-by-category', $param);
 }
Пример #21
0
 /**
  * RPC Routine to return the ids and info of questions of a survey/group. 
  * Returns array of ids and info.
  *
  * @access public
  * @param string $sSessionKey Auth credentials
  * @param int $iSurveyID Id of the survey to list questions
  * @param int $iGroupID Optional id of the group to list questions
  * @param string $sLanguage Optional parameter language for multilingual questions
  * @return array The list of questions
  */
 public function list_questions($sSessionKey, $iSurveyID, $iGroupID = NULL, $sLanguage = NULL)
 {
     if ($this->_checkSessionKey($sSessionKey)) {
         Yii::app()->loadHelper("surveytranslator");
         $oSurvey = Survey::model()->findByPk($iSurveyID);
         if (!isset($oSurvey)) {
             return array('status' => 'Error: Invalid survey ID');
         }
         if (hasSurveyPermission($iSurveyID, 'survey', 'read')) {
             if (is_null($sLanguage)) {
                 $sLanguage = $oSurvey->language;
             }
             if (!array_key_exists($sLanguage, getLanguageDataRestricted())) {
                 return array('status' => 'Error: Invalid language');
             }
             if ($iGroupID != NULL) {
                 $oGroup = Groups::model()->findByAttributes(array('gid' => $iGroupID));
                 $sGroupSurveyID = $oGroup['sid'];
                 if ($sGroupSurveyID != $iSurveyID) {
                     return array('status' => 'Error: IMissmatch in surveyid and groupid');
                 } else {
                     $aQuestionList = Questions::model()->findAllByAttributes(array("sid" => $iSurveyID, "gid" => $iGroupID, "parent_qid" => "0", "language" => $sLanguage));
                 }
             } else {
                 $aQuestionList = Questions::model()->findAllByAttributes(array("sid" => $iSurveyID, "parent_qid" => "0", "language" => $sLanguage));
             }
             if (count($aQuestionList) == 0) {
                 return array('status' => 'No questions found');
             }
             foreach ($aQuestionList as $oQuestion) {
                 $aData[] = array('id' => $oQuestion->primaryKey, 'type' => $oQuestion->attributes['type'], 'question' => $oQuestion->attributes['question']);
             }
             return $aData;
         } else {
             return array('status' => 'No permission');
         }
     } else {
         return array('status' => 'Invalid session key');
     }
 }
Пример #22
0
 function index($subaction, $iSurveyID = null, $gid = null, $qid = null)
 {
     $iSurveyID = sanitize_int($iSurveyID);
     $gid = sanitize_int($gid);
     $qid = sanitize_int($qid);
     $clang = $this->getController()->lang;
     $imageurl = Yii::app()->getConfig("adminimageurl");
     Yii::app()->loadHelper("database");
     if (!empty($_POST['subaction'])) {
         $subaction = Yii::app()->request->getPost('subaction');
     }
     //BEGIN Sanitizing POSTed data
     if (!isset($iSurveyID)) {
         $iSurveyID = returnGlobal('sid');
     }
     if (!isset($qid)) {
         $qid = returnGlobal('qid');
     }
     if (!isset($gid)) {
         $gid = returnGlobal('gid');
     }
     if (!isset($p_scenario)) {
         $p_scenario = returnGlobal('scenario');
     }
     if (!isset($p_cqid)) {
         $p_cqid = returnGlobal('cqid');
         if ($p_cqid == '') {
             $p_cqid = 0;
         }
         // we are not using another question as source of condition
     }
     if (!isset($p_cid)) {
         $p_cid = returnGlobal('cid');
     }
     if (!isset($p_subaction)) {
         if (isset($_POST['subaction'])) {
             $p_subaction = $_POST['subaction'];
         } else {
             $p_subaction = $subaction;
         }
     }
     if (!isset($p_cquestions)) {
         $p_cquestions = returnGlobal('cquestions');
     }
     if (!isset($p_csrctoken)) {
         $p_csrctoken = returnGlobal('csrctoken');
     }
     if (!isset($p_prevquestionsgqa)) {
         $p_prevquestionsgqa = returnGlobal('prevQuestionSGQA');
     }
     if (!isset($p_canswers)) {
         if (isset($_POST['canswers']) && is_array($_POST['canswers'])) {
             foreach ($_POST['canswers'] as $key => $val) {
                 $p_canswers[$key] = preg_replace("/[^_.a-zA-Z0-9]@/", "", $val);
             }
         }
     }
     // this array will be used soon,
     // to explain wich conditions is used to evaluate the question
     if (Yii::app()->getConfig('stringcomparizonoperators') == 1) {
         $method = array("<" => $clang->gT("Less than"), "<=" => $clang->gT("Less than or equal to"), "==" => $clang->gT("equals"), "!=" => $clang->gT("Not equal to"), ">=" => $clang->gT("Greater than or equal to"), ">" => $clang->gT("Greater than"), "RX" => $clang->gT("Regular expression"), "a<b" => $clang->gT("Less than (Strings)"), "a<=b" => $clang->gT("Less than or equal to (Strings)"), "a>=b" => $clang->gT("Greater than or equal to (Strings)"), "a>b" => $clang->gT("Greater than (Strings)"));
     } else {
         $method = array("<" => $clang->gT("Less than"), "<=" => $clang->gT("Less than or equal to"), "==" => $clang->gT("equals"), "!=" => $clang->gT("Not equal to"), ">=" => $clang->gT("Greater than or equal to"), ">" => $clang->gT("Greater than"), "RX" => $clang->gT("Regular expression"));
     }
     if (isset($_POST['method'])) {
         if (!in_array($_POST['method'], array_keys($method))) {
             $p_method = "==";
         } else {
             $p_method = trim($_POST['method']);
         }
     }
     if (isset($_POST['newscenarionum'])) {
         $p_newscenarionum = sanitize_int($_POST['newscenarionum']);
     }
     //END Sanitizing POSTed data
     //include_once("login_check.php");
     include_once "database.php";
     // Caution (lemeur): database.php uses autoUnescape on all entries in $_POST
     // Take care to not use autoUnescape on $_POST variables after this
     $br = CHtml::openTag('br /');
     //MAKE SURE THAT THERE IS A SID
     if (!isset($iSurveyID) || !$iSurveyID) {
         $conditionsoutput = $clang->gT("You have not selected a survey") . str_repeat($br, 2);
         $conditionsoutput .= CHtml::submitButton($clang->gT("Main admin screen"), array('onclick' => "window.open('" . $this->getController()->createUrl("admin/") . "', '_top')")) . $br;
         safeDie($conditionsoutput);
         return;
     }
     if (isset($p_subaction) && $p_subaction == "resetsurveylogic") {
         $clang = $this->getController()->lang;
         $resetsurveylogicoutput = $br;
         $resetsurveylogicoutput .= CHtml::openTag('table', array('class' => 'alertbox'));
         $resetsurveylogicoutput .= CHtml::openTag('tr') . CHtml::openTag('td', array('colspan' => '2'));
         $resetsurveylogicoutput .= CHtml::tag('font', array('size' => '1'), CHtml::tag('strong', array(), $clang->gT("Reset Survey Logic")));
         $resetsurveylogicoutput .= CHtml::closeTag('td') . CHtml::closeTag('tr');
         if (!isset($_GET['ok'])) {
             $button_yes = CHtml::submitButton($clang->gT("Yes"), array('onclick' => "window.open('" . $this->getController()->createUrl("admin/conditions/sa/index/subaction/resetsurveylogic/surveyid/{$iSurveyID}") . "?ok=Y" . "', '_top')"));
             $button_cancel = CHtml::submitButton($clang->gT("Cancel"), array('onclick' => "window.open('" . $this->getController()->createUrl("admin/survey/sa/view/surveyid/{$iSurveyID}") . "', '_top')"));
             $messagebox_content = $clang->gT("You are about to delete all conditions on this survey's questions") . "({$iSurveyID})" . $br . $clang->gT("We recommend that before you proceed, you export the entire survey from the main administration screen.") . $br . $clang->gT("Continue?") . $br . $button_yes . $button_cancel;
             $this->_renderWrappedTemplate('conditions', array('message' => array('title' => $clang->gT("Warning"), 'message' => $messagebox_content)));
             exit;
         } else {
             LimeExpressionManager::RevertUpgradeConditionsToRelevance($iSurveyID);
             Conditions::model()->deleteRecords("qid in (select qid from {{questions}} where sid={$iSurveyID})");
             Yii::app()->session['flashmessage'] = $clang->gT("All conditions in this survey have been deleted.");
             $this->getController()->redirect($this->getController()->createUrl('admin/survey/sa/view/surveyid/' . $iSurveyID));
         }
     }
     // MAKE SURE THAT THERE IS A QID
     if (!isset($qid) || !$qid) {
         $conditionsoutput = $clang->gT("You have not selected a question") . str_repeat($br, 2);
         $conditionsoutput .= CHtml::submitButton($clang->gT("Main admin screen"), array('onclick' => "window.open('" . $this->getController()->createUrl("admin/") . "', '_top')")) . $br;
         safeDie($conditionsoutput);
         return;
     }
     // If we made it this far, then lets develop the menu items
     // add the conditions container table
     $extraGetParams = "";
     if (isset($qid) && isset($gid)) {
         $extraGetParams = "/gid/{$gid}/qid/{$qid}";
     }
     $conditionsoutput_action_error = "";
     // defined during the actions
     $markcidarray = array();
     if (isset($_GET['markcid'])) {
         $markcidarray = explode("-", $_GET['markcid']);
     }
     //BEGIN PROCESS ACTIONS
     // ADD NEW ENTRY IF THIS IS AN ADD
     if (isset($p_subaction) && $p_subaction == "insertcondition") {
         if (!isset($p_canswers) && !isset($_POST['ConditionConst']) && !isset($_POST['prevQuestionSGQA']) && !isset($_POST['tokenAttr']) && !isset($_POST['ConditionRegexp']) || !isset($p_cquestions) && !isset($p_csrctoken)) {
             $conditionsoutput_action_error .= CHtml::script("\n<!--\n alert(\"" . $clang->gT("Your condition could not be added! It did not include the question and/or answer upon which the condition was based. Please ensure you have selected a question and an answer.", "js") . "\")\n //-->\n");
         } else {
             if (isset($p_cquestions) && $p_cquestions != '') {
                 $conditionCfieldname = $p_cquestions;
             } elseif (isset($p_csrctoken) && $p_csrctoken != '') {
                 $conditionCfieldname = $p_csrctoken;
             }
             $condition_data = array('qid' => $qid, 'scenario' => $p_scenario, 'cqid' => $p_cqid, 'cfieldname' => $conditionCfieldname, 'method' => $p_method);
             if (isset($p_canswers)) {
                 foreach ($p_canswers as $ca) {
                     //First lets make sure there isn't already an exact replica of this condition
                     $condition_data['value'] = $ca;
                     $result = Conditions::model()->findAllByAttributes($condition_data);
                     $count_caseinsensitivedupes = count($result);
                     if ($count_caseinsensitivedupes == 0) {
                         $result = Conditions::model()->insertRecords($condition_data);
                     }
                 }
             }
             unset($posted_condition_value);
             // Please note that autoUnescape is already applied in database.php included above
             // so we only need to db_quote _POST variables
             if (isset($_POST['ConditionConst']) && isset($_POST['editTargetTab']) && $_POST['editTargetTab'] == "#CONST") {
                 $posted_condition_value = Yii::app()->request->getPost('ConditionConst');
             } elseif (isset($_POST['prevQuestionSGQA']) && isset($_POST['editTargetTab']) && $_POST['editTargetTab'] == "#PREVQUESTIONS") {
                 $posted_condition_value = Yii::app()->request->getPost('prevQuestionSGQA');
             } elseif (isset($_POST['tokenAttr']) && isset($_POST['editTargetTab']) && $_POST['editTargetTab'] == "#TOKENATTRS") {
                 $posted_condition_value = Yii::app()->request->getPost('tokenAttr');
             } elseif (isset($_POST['ConditionRegexp']) && isset($_POST['editTargetTab']) && $_POST['editTargetTab'] == "#REGEXP") {
                 $posted_condition_value = Yii::app()->request->getPost('ConditionRegexp');
             }
             if (isset($posted_condition_value)) {
                 $condition_data['value'] = $posted_condition_value;
                 $result = Conditions::model()->insertRecords($condition_data);
             }
         }
         LimeExpressionManager::UpgradeConditionsToRelevance(NULL, $qid);
     }
     // UPDATE ENTRY IF THIS IS AN EDIT
     if (isset($p_subaction) && $p_subaction == "updatecondition") {
         if (!isset($p_canswers) && !isset($_POST['ConditionConst']) && !isset($_POST['prevQuestionSGQA']) && !isset($_POST['tokenAttr']) && !isset($_POST['ConditionRegexp']) || !isset($p_cquestions) && !isset($p_csrctoken)) {
             $conditionsoutput_action_error .= CHtml::script("\n<!--\n alert(\"" . $clang->gT("Your condition could not be added! It did not include the question and/or answer upon which the condition was based. Please ensure you have selected a question and an answer.", "js") . "\")\n //-->\n");
         } else {
             if (isset($p_cquestions) && $p_cquestions != '') {
                 $conditionCfieldname = $p_cquestions;
             } elseif (isset($p_csrctoken) && $p_csrctoken != '') {
                 $conditionCfieldname = $p_csrctoken;
             }
             if (isset($p_canswers)) {
                 foreach ($p_canswers as $ca) {
                     // This is an Edit, there will only be ONE VALUE
                     $updated_data = array('qid' => $qid, 'scenario' => $p_scenario, 'cqid' => $p_cqid, 'cfieldname' => $conditionCfieldname, 'method' => $p_method, 'value' => $ca);
                     $result = Conditions::model()->insertRecords($updated_data, TRUE, array('cid' => $p_cid));
                 }
             }
             unset($posted_condition_value);
             // Please note that autoUnescape is already applied in database.php included above
             // so we only need to db_quote _POST variables
             if (isset($_POST['ConditionConst']) && isset($_POST['editTargetTab']) && $_POST['editTargetTab'] == "#CONST") {
                 $posted_condition_value = Yii::app()->request->getPost('ConditionConst');
             } elseif (isset($_POST['prevQuestionSGQA']) && isset($_POST['editTargetTab']) && $_POST['editTargetTab'] == "#PREVQUESTIONS") {
                 $posted_condition_value = Yii::app()->request->getPost('prevQuestionSGQA');
             } elseif (isset($_POST['tokenAttr']) && isset($_POST['editTargetTab']) && $_POST['editTargetTab'] == "#TOKENATTRS") {
                 $posted_condition_value = Yii::app()->request->getPost('tokenAttr');
             } elseif (isset($_POST['ConditionRegexp']) && isset($_POST['editTargetTab']) && $_POST['editTargetTab'] == "#REGEXP") {
                 $posted_condition_value = Yii::app()->request->getPost('ConditionRegexp');
             }
             if (isset($posted_condition_value)) {
                 $updated_data = array('qid' => $qid, 'scenario' => $p_scenario, 'cqid' => $p_cqid, 'cfieldname' => $conditionCfieldname, 'method' => $p_method, 'value' => $posted_condition_value);
                 $result = Conditions::model()->insertRecords($updated_data, TRUE, array('cid' => $p_cid));
             }
         }
         LimeExpressionManager::UpgradeConditionsToRelevance(NULL, $qid);
     }
     // DELETE ENTRY IF THIS IS DELETE
     if (isset($p_subaction) && $p_subaction == "delete") {
         LimeExpressionManager::RevertUpgradeConditionsToRelevance(NULL, $qid);
         // in case deleted the last condition
         $result = Conditions::model()->deleteRecords(array('cid' => $p_cid));
         LimeExpressionManager::UpgradeConditionsToRelevance(NULL, $qid);
     }
     // DELETE ALL CONDITIONS IN THIS SCENARIO
     if (isset($p_subaction) && $p_subaction == "deletescenario") {
         LimeExpressionManager::RevertUpgradeConditionsToRelevance(NULL, $qid);
         // in case deleted the last condition
         $result = Conditions::model()->deleteRecords(array('qid' => $qid, 'scenario' => $p_scenario));
         LimeExpressionManager::UpgradeConditionsToRelevance(NULL, $qid);
     }
     // UPDATE SCENARIO
     if (isset($p_subaction) && $p_subaction == "updatescenario" && isset($p_newscenarionum)) {
         $result = Conditions::model()->insertRecords(array('scenario' => $p_newscenarionum), TRUE, array('qid' => $qid, 'scenario' => $p_scenario));
         LimeExpressionManager::UpgradeConditionsToRelevance(NULL, $qid);
     }
     // DELETE ALL CONDITIONS FOR THIS QUESTION
     if (isset($p_subaction) && $p_subaction == "deleteallconditions") {
         LimeExpressionManager::RevertUpgradeConditionsToRelevance(NULL, $qid);
         // in case deleted the last condition
         $result = Conditions::model()->deleteRecords(array('qid' => $qid));
     }
     // RENUMBER SCENARIOS
     if (isset($p_subaction) && $p_subaction == "renumberscenarios") {
         $query = "SELECT DISTINCT scenario FROM {{conditions}} WHERE qid=:qid ORDER BY scenario";
         $result = Yii::app()->db->createCommand($query)->bindParam(":qid", $qid, PDO::PARAM_INT)->query() or safeDie("Couldn't select scenario<br />{$query}<br />");
         $newindex = 1;
         foreach ($result->readAll() as $srow) {
             // new var $update_result == old var $result2
             $update_result = Conditions::model()->insertRecords(array('scenario' => $newindex), TRUE, array('qid' => $qid, 'scenario' => $srow['scenario']));
             $newindex++;
         }
         LimeExpressionManager::UpgradeConditionsToRelevance(NULL, $qid);
         Yii::app()->session['flashmessage'] = $clang->gT("All conditions scenarios were renumbered.");
     }
     // COPY CONDITIONS IF THIS IS COPY
     if (isset($p_subaction) && $p_subaction == "copyconditions") {
         $qid = returnGlobal('qid');
         $copyconditionsfrom = returnGlobal('copyconditionsfrom');
         $copyconditionsto = returnGlobal('copyconditionsto');
         if (isset($copyconditionsto) && is_array($copyconditionsto) && isset($copyconditionsfrom) && is_array($copyconditionsfrom)) {
             //Get the conditions we are going to copy
             foreach ($copyconditionsfrom as &$entry) {
                 $entry = Yii::app()->db->quoteValue($entry);
             }
             $query = "SELECT * FROM {{conditions}}\n" . "WHERE cid in (";
             $query .= implode(", ", $copyconditionsfrom);
             $query .= ")";
             $result = Yii::app()->db->createCommand($query)->query() or safeDie("Couldn't get conditions for copy<br />{$query}<br />");
             foreach ($result->readAll() as $row) {
                 $proformaconditions[] = array("scenario" => $row['scenario'], "cqid" => $row['cqid'], "cfieldname" => $row['cfieldname'], "method" => $row['method'], "value" => $row['value']);
             }
             // while
             foreach ($copyconditionsto as $copyc) {
                 list($newsid, $newgid, $newqid) = explode("X", $copyc);
                 foreach ($proformaconditions as $pfc) {
                     //TIBO
                     //First lets make sure there isn't already an exact replica of this condition
                     $conditions_data = array('qid' => $newqid, 'scenario' => $pfc['scenario'], 'cqid' => $pfc['cqid'], 'cfieldname' => $pfc['cfieldname'], 'method' => $pfc['method'], 'value' => $pfc['value']);
                     $result = Conditions::model()->findAllByAttributes($conditions_data);
                     $count_caseinsensitivedupes = count($result);
                     $countduplicates = 0;
                     if ($count_caseinsensitivedupes != 0) {
                         foreach ($result as $ccrow) {
                             if ($ccrow['value'] == $pfc['value']) {
                                 $countduplicates++;
                             }
                         }
                     }
                     if ($countduplicates == 0) {
                         $result = Conditions::model()->insertRecords($conditions_data);
                         $conditionCopied = true;
                     } else {
                         $conditionDuplicated = true;
                     }
                 }
             }
             if (isset($conditionCopied) && $conditionCopied === true) {
                 if (isset($conditionDuplicated) && $conditionDuplicated == true) {
                     $CopyConditionsMessage = CHtml::tag('div', array('class' => 'partialheader'), '(' . $clang->gT("Conditions successfully copied (some were skipped because they were duplicates)") . ')');
                 } else {
                     $CopyConditionsMessage = CHtml::tag('div', array('class' => 'successheader'), '(' . $clang->gT("Conditions successfully copied") . ')');
                 }
             } else {
                 $CopyConditionsMessage = CHtml::tag('div', array('class' => 'warningheader'), '(' . $clang->gT("No conditions could be copied (due to duplicates)") . ')');
             }
         }
         LimeExpressionManager::UpgradeConditionsToRelevance($iSurveyID);
         // do for whole survey, since don't know which questions affected.
     }
     //END PROCESS ACTIONS
     $cquestions = array();
     $canswers = array();
     //BEGIN: GATHER INFORMATION
     // 1: Get information for this question
     if (!isset($qid)) {
         $qid = returnGlobal('qid');
     }
     if (!isset($iSurveyID)) {
         $iSurveyID = returnGlobal('sid');
     }
     $thissurvey = getSurveyInfo($iSurveyID);
     $qresult = Questions::model()->with('groups')->findByAttributes(array('qid' => $qid, 'parent_qid' => 0, 'language' => Survey::model()->findByPk($iSurveyID)->language));
     $questiongroupname = $qresult->groups->group_name;
     $questiontitle = $qresult['title'];
     $questiontext = $qresult['question'];
     $questiontype = $qresult['type'];
     // 2: Get all other questions that occur before this question that are pre-determined answer types
     // To avoid natural sort order issues,
     // first get all questions in natural sort order
     // , and find out which number in that order this question is
     $qresult = Questions::model()->with(array('groups' => array('condition' => 'groups.language = :lang', 'params' => array(':lang' => Survey::model()->findByPk($iSurveyID)->language))))->findAllByAttributes(array('parent_qid' => 0, 'sid' => $iSurveyID, 'language' => Survey::model()->findByPk($iSurveyID)->language));
     $qrows = array();
     foreach ($qresult as $k => $v) {
         $qrows[$k] = array_merge($v->attributes, $v->groups->attributes);
     }
     // Perform a case insensitive natural sort on group name then question title (known as "code" in the form) of a multidimensional array
     usort($qrows, 'groupOrderThenQuestionOrder');
     $position = "before";
     // Go through each question until we reach the current one
     foreach ($qrows as $qrow) {
         if ($qrow["qid"] != $qid && $position == "before") {
             // remember all previous questions
             // all question types are supported.
             $questionlist[] = $qrow["qid"];
         } elseif ($qrow["qid"] == $qid) {
             break;
         }
     }
     // Now, using the same array which is now properly sorted by group then question
     // Create an array of all the questions that appear AFTER the current one
     $position = "before";
     foreach ($qrows as $qrow) {
         if ($qrow["qid"] == $qid) {
             $position = "after";
             //break;
         } elseif ($qrow["qid"] != $qid && $position == "after") {
             $postquestionlist[] = $qrow['qid'];
         }
     }
     $theserows = array();
     $postrows = array();
     if (isset($questionlist) && is_array($questionlist)) {
         foreach ($questionlist as $ql) {
             $result = Questions::model()->with(array('groups' => array('condition' => 'groups.language = :lang', 'params' => array(':lang' => Survey::model()->findByPk($iSurveyID)->language))))->findAllByAttributes(array('qid' => $ql, 'parent_qid' => 0, 'sid' => $iSurveyID, 'language' => Survey::model()->findByPk($iSurveyID)->language));
             $thiscount = count($result);
             // And store again these questions in this array...
             foreach ($result as $myrows) {
                 //key => value
                 $theserows[] = array("qid" => $myrows['qid'], "sid" => $myrows['sid'], "gid" => $myrows['gid'], "question" => $myrows['question'], "type" => $myrows['type'], "mandatory" => $myrows['mandatory'], "other" => $myrows['other'], "title" => $myrows['title']);
             }
         }
     }
     if (isset($postquestionlist) && is_array($postquestionlist)) {
         foreach ($postquestionlist as $pq) {
             $result = Questions::model()->with(array('groups' => array('condition' => 'groups.language = :lang', 'params' => array(':lang' => Survey::model()->findByPk($iSurveyID)->language))))->findAllByAttributes(array('qid' => $pq, 'parent_qid' => 0, 'sid' => $iSurveyID, 'language' => Survey::model()->findByPk($iSurveyID)->language));
             $postcount = count($result);
             foreach ($result as $myrows) {
                 $postrows[] = array("qid" => $myrows['qid'], "sid" => $myrows['sid'], "gid" => $myrows['gid'], "question" => $myrows['question'], "type" => $myrows['type'], "mandatory" => $myrows['mandatory'], "other" => $myrows['other'], "title" => $myrows['title']);
             }
             // while
         }
         $postquestionscount = count($postrows);
     }
     $questionscount = count($theserows);
     if (isset($postquestionscount) && $postquestionscount > 0) {
         //Build the array used for the questionNav and copyTo select boxes
         foreach ($postrows as $pr) {
             $pquestions[] = array("text" => $pr['title'] . ": " . substr(strip_tags($pr['question']), 0, 80), "fieldname" => $pr['sid'] . "X" . $pr['gid'] . "X" . $pr['qid']);
         }
     }
     // Previous question parsing ==> building cquestions[] and canswers[]
     if ($questionscount > 0) {
         $X = "X";
         foreach ($theserows as $rows) {
             $shortquestion = $rows['title'] . ": " . strip_tags($rows['question']);
             if ($rows['type'] == "A" || $rows['type'] == "B" || $rows['type'] == "C" || $rows['type'] == "E" || $rows['type'] == "F" || $rows['type'] == "H") {
                 $aresult = Questions::model()->findAllByAttributes(array('parent_qid' => $rows['qid'], 'language' => Survey::model()->findByPk($iSurveyID)->language), array('order' => 'question_order ASC'));
                 foreach ($aresult as $arows) {
                     $shortanswer = "{$arows['title']}: [" . flattenText($arows['question']) . "]";
                     $shortquestion = $rows['title'] . ":{$shortanswer} " . flattenText($rows['question']);
                     $cquestions[] = array($shortquestion, $rows['qid'], $rows['type'], $rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title']);
                     switch ($rows['type']) {
                         case "A":
                             //Array 5 buttons
                             for ($i = 1; $i <= 5; $i++) {
                                 $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], $i, $i);
                             }
                             break;
                         case "B":
                             //Array 10 buttons
                             for ($i = 1; $i <= 10; $i++) {
                                 $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], $i, $i);
                             }
                             break;
                         case "C":
                             //Array Y/N/NA
                             $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], "Y", $clang->gT("Yes"));
                             $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], "U", $clang->gT("Uncertain"));
                             $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], "N", $clang->gT("No"));
                             break;
                         case "E":
                             //Array >/=/<
                             $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], "I", $clang->gT("Increase"));
                             $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], "S", $clang->gT("Same"));
                             $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], "D", $clang->gT("Decrease"));
                             break;
                         case "F":
                             //Array Flexible Row
                         //Array Flexible Row
                         case "H":
                             //Array Flexible Column
                             $fresult = Answers::model()->findAllByAttributes(array('qid' => $rows['qid'], "language" => Survey::model()->findByPk($iSurveyID)->language, 'scale_id' => 0), array('order' => 'sortorder, code'));
                             foreach ($fresult as $frow) {
                                 $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], $frow['code'], $frow['answer']);
                             }
                             break;
                     }
                     // Only Show No-Answer if question is not mandatory
                     if ($rows['mandatory'] != 'Y') {
                         $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], "", $clang->gT("No answer"));
                     }
                 }
                 //while
             } elseif ($rows['type'] == ":" || $rows['type'] == ";") {
                 // Multiflexi
                 //Get question attribute for $canswers
                 $qidattributes = getQuestionAttributeValues($rows['qid'], $rows['type']);
                 if (isset($qidattributes['multiflexible_max']) && trim($qidattributes['multiflexible_max']) != '') {
                     $maxvalue = floatval($qidattributes['multiflexible_max']);
                 } else {
                     $maxvalue = 10;
                 }
                 if (isset($qidattributes['multiflexible_min']) && trim($qidattributes['multiflexible_min']) != '') {
                     $minvalue = floatval($qidattributes['multiflexible_min']);
                 } else {
                     $minvalue = 1;
                 }
                 if (isset($qidattributes['multiflexible_step']) && trim($qidattributes['multiflexible_step']) != '') {
                     $stepvalue = floatval($qidattributes['multiflexible_step']);
                     if ($stepvalue == 0) {
                         $stepvalue = 1;
                     }
                 } else {
                     $stepvalue = 1;
                 }
                 if (isset($qidattributes['multiflexible_checkbox']) && $qidattributes['multiflexible_checkbox'] != 0) {
                     $minvalue = 0;
                     $maxvalue = 1;
                     $stepvalue = 1;
                 }
                 // Get the Y-Axis
                 $fquery = "SELECT sq.*, q.other" . " FROM {{questions sq}}, {{questions q}}" . " WHERE sq.sid={$iSurveyID} AND sq.parent_qid=q.qid " . "AND q.language=:lang" . " AND sq.language=:lang" . " AND q.qid=:qid\n                    AND sq.scale_id=0\n                    ORDER BY sq.question_order";
                 $sLanguage = Survey::model()->findByPk($iSurveyID)->language;
                 $y_axis_db = Yii::app()->db->createCommand($fquery)->bindParam(":lang", $sLanguage, PDO::PARAM_STR)->bindParam(":qid", $rows['qid'], PDO::PARAM_INT)->query();
                 // Get the X-Axis
                 $aquery = "SELECT sq.*\n                    FROM {{questions q}}, {{questions sq}}\n                    WHERE q.sid={$iSurveyID}\n                    AND sq.parent_qid=q.qid\n                    AND q.language=:lang\n                    AND sq.language=:lang\n                    AND q.qid=:qid\n                    AND sq.scale_id=1\n                    ORDER BY sq.question_order";
                 $x_axis_db = Yii::app()->db->createCommand($aquery)->bindParam(":lang", $sLanguage, PDO::PARAM_STR)->bindParam(":qid", $rows['qid'], PDO::PARAM_INT)->query() or safeDie("Couldn't get answers to Array questions<br />{$aquery}<br />");
                 foreach ($x_axis_db->readAll() as $frow) {
                     $x_axis[$frow['title']] = $frow['question'];
                 }
                 foreach ($y_axis_db->readAll() as $yrow) {
                     foreach ($x_axis as $key => $val) {
                         $shortquestion = $rows['title'] . ":{$yrow['title']}:{$key}: [" . strip_tags($yrow['question']) . "][" . strip_tags($val) . "] " . flattenText($rows['question']);
                         $cquestions[] = array($shortquestion, $rows['qid'], $rows['type'], $rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $yrow['title'] . "_" . $key);
                         if ($rows['type'] == ":") {
                             for ($ii = $minvalue; $ii <= $maxvalue; $ii += $stepvalue) {
                                 $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $yrow['title'] . "_" . $key, $ii, $ii);
                             }
                         }
                     }
                 }
                 unset($x_axis);
             } elseif ($rows['type'] == "1") {
                 $aresult = Questions::model()->findAllByAttributes(array('parent_qid' => $rows['qid'], 'language' => Survey::model()->findByPk($iSurveyID)->language), array('order' => 'question_order desc'));
                 foreach ($aresult as $arows) {
                     $attr = getQuestionAttributeValues($rows['qid']);
                     $label1 = isset($attr['dualscale_headerA']) ? $attr['dualscale_headerA'] : 'Label1';
                     $label2 = isset($attr['dualscale_headerB']) ? $attr['dualscale_headerB'] : 'Label2';
                     $shortanswer = "{$arows['title']}: [" . strip_tags($arows['question']) . "][{$label1}]";
                     $shortquestion = $rows['title'] . ":{$shortanswer} " . strip_tags($rows['question']);
                     $cquestions[] = array($shortquestion, $rows['qid'], $rows['type'], $rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'] . "#0");
                     $shortanswer = "{$arows['title']}: [" . strip_tags($arows['question']) . "][{$label2}]";
                     $shortquestion = $rows['title'] . ":{$shortanswer} " . strip_tags($rows['question']);
                     $cquestions[] = array($shortquestion, $rows['qid'], $rows['type'], $rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'] . "#1");
                     // first label
                     $lresult = Answers::model()->findAllByAttributes(array('qid' => $rows['qid'], 'scale_id' => 0, 'language' => Survey::model()->findByPk($iSurveyID)->language), array('order' => 'sortorder, answer'));
                     foreach ($lresult as $lrows) {
                         $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'] . "#0", "{$lrows['code']}", "{$lrows['code']}");
                     }
                     // second label
                     $lresult = Answers::model()->findAllByAttributes(array('qid' => $rows['qid'], 'scale_id' => 1, 'language' => Survey::model()->findByPk($iSurveyID)->language), array('order' => 'sortorder, answer'));
                     foreach ($lresult as $lrows) {
                         $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'] . "#1", "{$lrows['code']}", "{$lrows['code']}");
                     }
                     // Only Show No-Answer if question is not mandatory
                     if ($rows['mandatory'] != 'Y') {
                         $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'] . "#0", "", $clang->gT("No answer"));
                         $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'] . "#1", "", $clang->gT("No answer"));
                     }
                 }
                 //while
             } elseif ($rows['type'] == "K" || $rows['type'] == "Q") {
                 $aresult = Questions::model()->findAllByAttributes(array("parent_qid" => $rows['qid'], "language" => Survey::model()->findByPk($iSurveyID)->language), array('order' => 'question_order desc'));
                 foreach ($aresult as $arows) {
                     $shortanswer = "{$arows['title']}: [" . strip_tags($arows['question']) . "]";
                     $shortquestion = $rows['title'] . ":{$shortanswer} " . strip_tags($rows['question']);
                     $cquestions[] = array($shortquestion, $rows['qid'], $rows['type'], $rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title']);
                     // Only Show No-Answer if question is not mandatory
                     if ($rows['mandatory'] != 'Y') {
                         $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], "", $clang->gT("No answer"));
                     }
                 }
                 //while
             } elseif ($rows['type'] == "R") {
                 $aresult = Answers::model()->findAllByAttributes(array("qid" => $rows['qid'], "scale_id" => 0, "language" => Survey::model()->findByPk($iSurveyID)->language), array('order' => 'sortorder, answer'));
                 $acount = count($aresult);
                 foreach ($aresult as $arow) {
                     $theanswer = addcslashes($arow['answer'], "'");
                     $quicky[] = array($arow['code'], $theanswer);
                 }
                 for ($i = 1; $i <= $acount; $i++) {
                     $cquestions[] = array("{$rows['title']}: [RANK {$i}] " . strip_tags($rows['question']), $rows['qid'], $rows['type'], $rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $i);
                     foreach ($quicky as $qck) {
                         $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $i, $qck[0], $qck[1]);
                     }
                     // Only Show No-Answer if question is not mandatory
                     if ($rows['mandatory'] != 'Y') {
                         $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $i, " ", $clang->gT("No answer"));
                     }
                 }
                 unset($quicky);
             } elseif ($rows['type'] == "M" || $rows['type'] == "P") {
                 $shortanswer = " [" . $clang->gT("Group of checkboxes") . "]";
                 $shortquestion = $rows['title'] . ":{$shortanswer} " . strip_tags($rows['question']);
                 $cquestions[] = array($shortquestion, $rows['qid'], $rows['type'], $rows['sid'] . $X . $rows['gid'] . $X . $rows['qid']);
                 $aresult = Questions::model()->findAllByAttributes(array("parent_qid" => $rows['qid'], "language" => Survey::model()->findByPk($iSurveyID)->language), array('order' => 'question_order desc'));
                 foreach ($aresult as $arows) {
                     $theanswer = addcslashes($arows['question'], "'");
                     $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], $arows['title'], $theanswer);
                     $shortanswer = "{$arows['title']}: [" . strip_tags($arows['question']) . "]";
                     $shortanswer .= "[" . $clang->gT("Single checkbox") . "]";
                     $shortquestion = $rows['title'] . ":{$shortanswer} " . strip_tags($rows['question']);
                     $cquestions[] = array($shortquestion, $rows['qid'], $rows['type'], "+" . $rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title']);
                     $canswers[] = array("+" . $rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], 'Y', $clang->gT("checked"));
                     $canswers[] = array("+" . $rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], '', $clang->gT("not checked"));
                 }
             } elseif ($rows['type'] == "X") {
                 //Just ignore this questiontype
             } else {
                 $cquestions[] = array($shortquestion, $rows['qid'], $rows['type'], $rows['sid'] . $X . $rows['gid'] . $X . $rows['qid']);
                 switch ($rows['type']) {
                     case "Y":
                         // Y/N/NA
                         $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], "Y", $clang->gT("Yes"));
                         $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], "N", $clang->gT("No"));
                         // Only Show No-Answer if question is not mandatory
                         if ($rows['mandatory'] != 'Y') {
                             $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], " ", $clang->gT("No answer"));
                         }
                         break;
                     case "G":
                         //Gender
                         $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], "F", $clang->gT("Female"));
                         $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], "M", $clang->gT("Male"));
                         // Only Show No-Answer if question is not mandatory
                         if ($rows['mandatory'] != 'Y') {
                             $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], " ", $clang->gT("No answer"));
                         }
                         break;
                     case "5":
                         // 5 choice
                         for ($i = 1; $i <= 5; $i++) {
                             $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], $i, $i);
                         }
                         // Only Show No-Answer if question is not mandatory
                         if ($rows['mandatory'] != 'Y') {
                             $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], " ", $clang->gT("No answer"));
                         }
                         break;
                     case "N":
                         // Simple Numerical questions
                         // Only Show No-Answer if question is not mandatory
                         if ($rows['mandatory'] != 'Y') {
                             $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], " ", $clang->gT("No answer"));
                         }
                         break;
                     default:
                         $aresult = Answers::model()->findAllByAttributes(array('qid' => $rows['qid'], 'scale_id' => 0, 'language' => Survey::model()->findByPk($iSurveyID)->language), array('order' => 'sortorder, answer'));
                         foreach ($aresult as $arows) {
                             $theanswer = addcslashes($arows['answer'], "'");
                             $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], $arows['code'], $theanswer);
                         }
                         if ($rows['type'] == "D") {
                             // Only Show No-Answer if question is not mandatory
                             if ($rows['mandatory'] != 'Y') {
                                 $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], " ", $clang->gT("No answer"));
                             }
                         } elseif ($rows['type'] != "M" && $rows['type'] != "P" && $rows['type'] != "J" && $rows['type'] != "I") {
                             // For dropdown questions
                             // optinnaly add the 'Other' answer
                             if (($rows['type'] == "L" || $rows['type'] == "!") && $rows['other'] == "Y") {
                                 $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], "-oth-", $clang->gT("Other"));
                             }
                             // Only Show No-Answer if question is not mandatory
                             if ($rows['mandatory'] != 'Y') {
                                 $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], " ", $clang->gT("No answer"));
                             }
                         }
                         break;
                 }
                 //switch row type
             }
             //else
         }
         //foreach theserows
     }
     //if questionscount > 0
     //END Gather Information for this question
     $questionNavOptions = CHtml::openTag('optgroup', array('class' => 'activesurveyselect', 'label' => $clang->gT("Before", "js")));
     foreach ($theserows as $row) {
         $question = $row['question'];
         $question = strip_tags($question);
         if (strlen($question) < 35) {
             $questionselecter = $question;
         } else {
             //$questionselecter = substr($question, 0, 35)."..";
             $questionselecter = htmlspecialchars(mb_strcut(html_entity_decode($question, ENT_QUOTES, 'UTF-8'), 0, 35, 'UTF-8')) . "...";
         }
         $questionNavOptions .= CHtml::tag('option', array('value' => $this->getController()->createUrl("/admin/conditions/sa/index/subaction/editconditionsform/surveyid/{$iSurveyID}/gid/{$row['gid']}/qid/{$row['qid']}")), $questionselecter);
     }
     $questionNavOptions .= CHtml::closeTag('optgroup');
     $questionNavOptions .= CHtml::openTag('optgroup', array('class' => 'activesurveyselect', 'label' => $clang->gT("Current", "js")));
     $question = strip_tags($questiontext);
     if (strlen($question) < 35) {
         $questiontextshort = $question;
     } else {
         //$questiontextshort = substr($question, 0, 35)."..";
         $questiontextshort = htmlspecialchars(mb_strcut(html_entity_decode($question, ENT_QUOTES, 'UTF-8'), 0, 35, 'UTF-8')) . "...";
     }
     $questionNavOptions .= CHtml::tag('option', array('value' => $this->getController()->createUrl("/admin/conditions/sa/index/subaction/editconditionsform/surveyid/{$iSurveyID}/gid/{$gid}/qid/{$qid}"), 'selected' => 'selected'), $questiontitle . ': ' . $questiontextshort);
     $questionNavOptions .= CHtml::closeTag('optgroup');
     $questionNavOptions .= CHtml::openTag('optgroup', array('class' => 'activesurveyselect', 'label' => $clang->gT("After", "js")));
     foreach ($postrows as $row) {
         $question = $row['question'];
         $question = strip_tags($question);
         if (strlen($question) < 35) {
             $questionselecter = $question;
         } else {
             //$questionselecter = substr($question, 0, 35)."..";
             $questionselecter = htmlspecialchars(mb_strcut(html_entity_decode($question, ENT_QUOTES, 'UTF-8'), 0, 35, 'UTF-8')) . "...";
         }
         $questionNavOptions .= CHtml::tag('option', array('value' => $this->getController()->createUrl("/admin/conditions/sa/index/subaction/editconditionsform/surveyid/{$iSurveyID}/gid/{$row['gid']}/qid/{$row['qid']}")), $row['title'] . ':' . $questionselecter);
     }
     $questionNavOptions .= CHtml::closeTag('optgroup');
     //Now display the information and forms
     //BEGIN: PREPARE JAVASCRIPT TO SHOW MATCHING ANSWERS TO SELECTED QUESTION
     $javascriptpre = CHtml::openTag('script', array('type' => 'text/javascript')) . "<!--\n" . "\tvar Fieldnames = new Array();\n" . "\tvar Codes = new Array();\n" . "\tvar Answers = new Array();\n" . "\tvar QFieldnames = new Array();\n" . "\tvar Qcqids = new Array();\n" . "\tvar Qtypes = new Array();\n";
     $jn = 0;
     if (isset($canswers)) {
         foreach ($canswers as $can) {
             $an = ls_json_encode(flattenText($can[2]));
             $javascriptpre .= "Fieldnames[{$jn}]='{$can['0']}';\n" . "Codes[{$jn}]='{$can['1']}';\n" . "Answers[{$jn}]={$an};\n";
             $jn++;
         }
     }
     $jn = 0;
     if (isset($cquestions)) {
         foreach ($cquestions as $cqn) {
             $javascriptpre .= "QFieldnames[{$jn}]='{$cqn['3']}';\n" . "Qcqids[{$jn}]='{$cqn['1']}';\n" . "Qtypes[{$jn}]='{$cqn['2']}';\n";
             $jn++;
         }
     }
     //  record a JS variable to let jQuery know if survey is Anonymous
     if ($thissurvey['anonymized'] == 'Y') {
         $javascriptpre .= "isAnonymousSurvey = true;";
     } else {
         $javascriptpre .= "isAnonymousSurvey = false;";
     }
     $javascriptpre .= "//-->\n" . CHtml::closeTag('script');
     //END: PREPARE JAVASCRIPT TO SHOW MATCHING ANSWERS TO SELECTED QUESTION
     $this->getController()->_css_admin_includes(Yii::app()->getConfig("publicstyleurl") . 'jquery.multiselect.css');
     $aViewUrls = array();
     $aData['clang'] = $clang;
     $aData['surveyid'] = $iSurveyID;
     $aData['qid'] = $qid;
     $aData['gid'] = $gid;
     $aData['imageurl'] = $imageurl;
     $aData['extraGetParams'] = $extraGetParams;
     $aData['quesitonNavOptions'] = $questionNavOptions;
     $aData['conditionsoutput_action_error'] = $conditionsoutput_action_error;
     $aData['javascriptpre'] = $javascriptpre;
     $aViewUrls['conditionshead_view'][] = $aData;
     //BEGIN DISPLAY CONDITIONS FOR THIS QUESTION
     if ($subaction == 'index' || $subaction == 'editconditionsform' || $subaction == 'insertcondition' || $subaction == "editthiscondition" || $subaction == "delete" || $subaction == "updatecondition" || $subaction == "deletescenario" || $subaction == "renumberscenarios" || $subaction == "deleteallconditions" || $subaction == "updatescenario" || $subaction == 'copyconditionsform' || $subaction == 'copyconditions' || $subaction == 'conditions') {
         //3: Get other conditions currently set for this question
         $conditionscount = 0;
         $s = 0;
         $criteria = new CDbCriteria();
         $criteria->select = 'scenario';
         // only select the 'scenario' column
         $criteria->condition = 'qid=:qid';
         $criteria->params = array(':qid' => $qid);
         $criteria->order = 'scenario';
         $criteria->group = 'scenario';
         $scenarioresult = Conditions::model()->findAll($criteria);
         $scenariocount = count($scenarioresult);
         $showreplace = "{$questiontitle}" . $this->_showSpeaker($questiontext);
         $onlyshow = sprintf($clang->gT("Only show question %s IF"), $showreplace);
         $aData['conditionsoutput'] = '';
         $aData['extraGetParams'] = $extraGetParams;
         $aData['quesitonNavOptions'] = $questionNavOptions;
         $aData['conditionsoutput_action_error'] = $conditionsoutput_action_error;
         $aData['javascriptpre'] = $javascriptpre;
         $aData['onlyshow'] = $onlyshow;
         $aData['subaction'] = $subaction;
         $aData['scenariocount'] = $scenariocount;
         $aViewUrls['conditionslist_view'][] = $aData;
         if ($scenariocount > 0) {
             //self::_js_admin_includes($this->config->item("generalscripts").'jquery/jquery.checkgroup.js');
             $this->getController()->_js_admin_includes(Yii::app()->getConfig("generalscripts") . 'jquery/jquery.checkgroup.js');
             foreach ($scenarioresult as $scenarionr) {
                 $scenariotext = "";
                 if ($s == 0 && $scenariocount > 1) {
                     $scenariotext = " -------- <i>Scenario {$scenarionr['scenario']}</i> --------";
                 }
                 if ($s > 0) {
                     $scenariotext = " -------- <i>" . $clang->gT("OR") . " Scenario {$scenarionr['scenario']}</i> --------";
                 }
                 if ($subaction == "copyconditionsform" || $subaction == "copyconditions") {
                     $initialCheckbox = "<td><input type='checkbox' id='scenarioCbx{$scenarionr['scenario']}' checked='checked'/>\n" . "<script type='text/javascript'>\$(document).ready(function () { \$('#scenarioCbx{$scenarionr['scenario']}').checkgroup({ groupName:'aConditionFromScenario{$scenarionr['scenario']}'}); });</script>" . "</td><td>&nbsp;</td>\n";
                 } else {
                     $initialCheckbox = "";
                 }
                 if ($scenariotext != "" && ($subaction == "editconditionsform" || $subaction == "insertcondition" || $subaction == "updatecondition" || $subaction == "editthiscondition" || $subaction == "renumberscenarios" || $subaction == "updatescenario" || $subaction == "deletescenario" || $subaction == "delete")) {
                     $img_tag = CHtml::image($imageurl . '/scenario_delete.png', $clang->gT("Delete this scenario"), array('name' => 'DeleteWholeGroup'));
                     $additional_main_content = CHtml::link($img_tag, '#', array('onclick' => "if ( confirm('" . $clang->gT("Are you sure you want to delete all conditions set in this scenario?", "js") . "')) { document.getElementById('deletescenario{$scenarionr['scenario']}').submit();}"));
                     $img_tag = CHtml::image($imageurl . '/scenario_edit.png', $clang->gT("Edit scenario"), array('name' => 'DeleteWholeGroup'));
                     $additional_main_content .= CHtml::link($img_tag, '#', array('id' => 'editscenariobtn' . $scenarionr['scenario'], 'onclick' => "\$('#editscenario{$scenarionr['scenario']}').toggle('slow');"));
                     $aData['additional_content'] = $additional_main_content;
                 }
                 $aData['initialCheckbox'] = $initialCheckbox;
                 $aData['scenariotext'] = $scenariotext;
                 $aData['scenarionr'] = $scenarionr;
                 if (!isset($aViewUrls['output'])) {
                     $aViewUrls['output'] = '';
                 }
                 $aViewUrls['output'] .= $this->getController()->render('/admin/conditions/includes/conditions_scenario', $aData, TRUE);
                 unset($currentfield);
                 $query = "SELECT count(*) as recordcount\n                    FROM {{conditions}} c, {{questions}} q, {{groups}} g\n                    WHERE c.cqid=q.qid " . "AND q.gid=g.gid " . "AND q.parent_qid=0 " . "AND q.language=:lang1 " . "AND g.language=:lang2 " . "AND c.qid=:qid " . "AND c.scenario=:scenario " . "AND c.cfieldname NOT LIKE '{%' ";
                 // avoid catching SRCtokenAttr conditions
                 $sLanguage = Survey::model()->findByPk($iSurveyID)->language;
                 $result = Yii::app()->db->createCommand($query)->bindValue(":scenario", $scenarionr['scenario'])->bindValue(":qid", $qid, PDO::PARAM_INT)->bindValue(":lang1", $sLanguage, PDO::PARAM_STR)->bindValue(":lang2", $sLanguage, PDO::PARAM_STR)->queryRow();
                 $conditionscount = (int) $result['recordcount'];
                 $query = "SELECT c.cid, c.scenario, c.cqid, c.cfieldname, c.method, c.value, q.type\n                    FROM {{conditions}} c, {{questions}} q, {{groups}} g\n                    WHERE c.cqid=q.qid " . "AND q.gid=g.gid " . "AND q.parent_qid=0 " . "AND q.language=:lang1 " . "AND g.language=:lang2 " . "AND c.qid=:qid " . "AND c.scenario=:scenario " . "AND c.cfieldname NOT LIKE '{%' " . "ORDER BY g.group_order, q.question_order, c.cfieldname";
                 $sLanguage = Survey::model()->findByPk($iSurveyID)->language;
                 $result = Yii::app()->db->createCommand($query)->bindValue(":scenario", $scenarionr['scenario'])->bindValue(":qid", $qid, PDO::PARAM_INT)->bindValue(":lang1", $sLanguage, PDO::PARAM_STR)->bindValue(":lang2", $sLanguage, PDO::PARAM_STR)->query() or safeDie("Couldn't get other conditions for question {$qid}<br />{$query}<br />");
                 $querytoken = "SELECT count(*) as recordcount " . "FROM {{conditions}} " . "WHERE " . " {{conditions}}.qid=:qid " . "AND {{conditions}}.scenario=:scenario " . "AND {{conditions}}.cfieldname LIKE '{%' ";
                 // only catching SRCtokenAttr conditions
                 $resulttoken = Yii::app()->db->createCommand($querytoken)->bindValue(":scenario", $scenarionr['scenario'], PDO::PARAM_INT)->bindValue(":qid", $qid, PDO::PARAM_INT)->queryRow() or safeDie("Couldn't get other conditions for question {$qid}<br />{$query}<br />");
                 $conditionscounttoken = (int) $resulttoken['recordcount'];
                 $querytoken = "SELECT {{conditions}}.cid, " . "{{conditions}}.scenario, " . "{{conditions}}.cqid, " . "{{conditions}}.cfieldname, " . "{{conditions}}.method, " . "{{conditions}}.value, " . "'' AS type " . "FROM {{conditions}} " . "WHERE " . " {{conditions}}.qid=:qid " . "AND {{conditions}}.scenario=:scenario " . "AND {{conditions}}.cfieldname LIKE '{%' " . "ORDER BY {{conditions}}.cfieldname";
                 $resulttoken = Yii::app()->db->createCommand($querytoken)->bindValue(":scenario", $scenarionr['scenario'], PDO::PARAM_INT)->bindValue(":qid", $qid, PDO::PARAM_INT)->query() or safeDie("Couldn't get other conditions for question {$qid}<br />{$query}<br />");
                 $conditionscount = $conditionscount + $conditionscounttoken;
                 if ($conditionscount > 0) {
                     $aConditionsMerged = array();
                     foreach ($resulttoken->readAll() as $arow) {
                         $aConditionsMerged[] = $arow;
                     }
                     foreach ($result->readAll() as $arow) {
                         $aConditionsMerged[] = $arow;
                     }
                     foreach ($aConditionsMerged as $rows) {
                         if ($rows['method'] == "") {
                             $rows['method'] = "==";
                         }
                         //Fill in the empty method from previous versions
                         $markcidstyle = "oddrow";
                         if (array_search($rows['cid'], $markcidarray) !== FALSE) {
                             // This is the style used when the condition editor is called
                             // in order to check which conditions prevent a question deletion
                             $markcidstyle = "markedrow";
                         }
                         if ($subaction == "editthiscondition" && isset($p_cid) && $rows['cid'] === $p_cid) {
                             // Style used when editing a condition
                             $markcidstyle = "editedrow";
                         }
                         if (isset($currentfield) && $currentfield != $rows['cfieldname']) {
                             $aViewUrls['output'] .= "<tr class='evenrow'>\n" . "\t<td colspan='2'>\n" . "<span><strong>" . $clang->gT("and") . "</strong></span></td></tr>";
                         } elseif (isset($currentfield)) {
                             $aViewUrls['output'] .= "<tr class='evenrow'>\n" . "\t<td colspan='2'>\n" . "<span><strong>" . $clang->gT("or") . "</strong></span></td></tr>";
                         }
                         $aViewUrls['output'] .= "\t<tr class='{$markcidstyle}'>\n" . "\t<td colspan='2'>" . CHtml::form(array("/admin/conditions/sa/index/subaction/{$subaction}/surveyid/{$iSurveyID}/gid/{$gid}/qid/{$qid}/"), 'post', array('id' => "conditionaction{$rows['cid']}", 'name' => "conditionaction{$rows['cid']}")) . "<table>\n" . "\t<tr>\n";
                         if ($subaction == "copyconditionsform" || $subaction == "copyconditions") {
                             $aViewUrls['output'] .= "<td>&nbsp;&nbsp;</td>" . "<td>\n" . "\t<input type='checkbox' name='aConditionFromScenario{$scenarionr['scenario']}' id='cbox{$rows['cid']}' value='{$rows['cid']}' checked='checked'/>\n" . "</td>\n";
                         }
                         $aViewUrls['output'] .= "" . "<td>\n" . "\t<span>\n";
                         $leftOperandType = 'unknown';
                         // prevquestion, tokenattr
                         if ($thissurvey['anonymized'] != 'Y' && preg_match('/^{TOKEN:([^}]*)}$/', $rows['cfieldname'], $extractedTokenAttr) > 0) {
                             $leftOperandType = 'tokenattr';
                             $aTokenAttrNames = getTokenFieldsAndNames($iSurveyID);
                             if (count($aTokenAttrNames) != 0) {
                                 $thisAttrName = HTMLEscape($aTokenAttrNames[strtolower($extractedTokenAttr[1])]['description']) . " [" . $clang->gT("From token table") . "]";
                             } else {
                                 $thisAttrName = HTMLEscape($extractedTokenAttr[1]) . " [" . $clang->gT("Inexistant token table") . "]";
                             }
                             $aViewUrls['output'] .= "\t{$thisAttrName}\n";
                             // TIBO not sure this is used anymore !!
                             $conditionsList[] = array("cid" => $rows['cid'], "text" => $thisAttrName);
                         } else {
                             $leftOperandType = 'prevquestion';
                             foreach ($cquestions as $cqn) {
                                 if ($cqn[3] == $rows['cfieldname']) {
                                     $aViewUrls['output'] .= "\t{$cqn['0']} (qid{$rows['cqid']})\n";
                                     $conditionsList[] = array("cid" => $rows['cid'], "text" => $cqn[0] . " ({$rows['value']})");
                                 } else {
                                     //$aViewUrls['output'] .= "\t<font color='red'>ERROR: Delete this condition. It is out of order.</font>\n";
                                 }
                             }
                         }
                         $aViewUrls['output'] .= "\t</span></td>\n" . "\t<td>\n" . "<span>\n" . $method[trim($rows['method'])] . "</span>\n" . "\t</td>\n" . "\n" . "\t<td>\n" . "<span>\n";
                         // let's read the condition's right operand
                         // determine its type and display it
                         $rightOperandType = 'unknown';
                         // predefinedAnsw,constantVal, prevQsgqa, tokenAttr, regexp
                         if ($rows['method'] == 'RX') {
                             $rightOperandType = 'regexp';
                             $aViewUrls['output'] .= "" . HTMLEscape($rows['value']) . "\n";
                         } elseif (preg_match('/^@([0-9]+X[0-9]+X[^@]*)@$/', $rows['value'], $matchedSGQA) > 0) {
                             // SGQA
                             $rightOperandType = 'prevQsgqa';
                             $textfound = false;
                             foreach ($cquestions as $cqn) {
                                 if ($cqn[3] == $matchedSGQA[1]) {
                                     $matchedSGQAText = $cqn[0];
                                     $textfound = true;
                                     break;
                                 }
                             }
                             if ($textfound === false) {
                                 $matchedSGQAText = $rows['value'] . ' (' . $clang->gT("Not found") . ')';
                             }
                             $aViewUrls['output'] .= "" . HTMLEscape($matchedSGQAText) . "\n";
                         } elseif ($thissurvey['anonymized'] != 'Y' && preg_match('/^{TOKEN:([^}]*)}$/', $rows['value'], $extractedTokenAttr) > 0) {
                             $rightOperandType = 'tokenAttr';
                             $aTokenAttrNames = getTokenFieldsAndNames($iSurveyID);
                             if (count($aTokenAttrNames) != 0) {
                                 $thisAttrName = HTMLEscape($aTokenAttrNames[strtolower($extractedTokenAttr[1])]['description']) . " [" . $clang->gT("From token table") . "]";
                             } else {
                                 $thisAttrName = HTMLEscape($extractedTokenAttr[1]) . " [" . $clang->gT("Inexistant token table") . "]";
                             }
                             $aViewUrls['output'] .= "\t{$thisAttrName}\n";
                         } elseif (isset($canswers)) {
                             foreach ($canswers as $can) {
                                 if ($can[0] == $rows['cfieldname'] && $can[1] == $rows['value']) {
                                     $aViewUrls['output'] .= "{$can['2']} ({$can['1']})\n";
                                     $rightOperandType = 'predefinedAnsw';
                                 }
                             }
                         }
                         // if $rightOperandType is still unkown then it is a simple constant
                         if ($rightOperandType == 'unknown') {
                             $rightOperandType = 'constantVal';
                             if ($rows['value'] == ' ' || $rows['value'] == '') {
                                 $aViewUrls['output'] .= "" . $clang->gT("No answer") . "\n";
                             } else {
                                 $aViewUrls['output'] .= "" . HTMLEscape($rows['value']) . "\n";
                             }
                         }
                         $aViewUrls['output'] .= "\t</span></td>\n" . "\t<td>\n";
                         if ($subaction == "editconditionsform" || $subaction == "insertcondition" || $subaction == "updatecondition" || $subaction == "editthiscondition" || $subaction == "renumberscenarios" || $subaction == "deleteallconditions" || $subaction == "updatescenario" || $subaction == "deletescenario" || $subaction == "delete") {
                             // show single condition action buttons in edit mode
                             $aData['rows'] = $rows;
                             $aData['sImageURL'] = Yii::app()->getConfig('adminimageurl');
                             //$aViewUrls['includes/conditions_edit'][] = $aData;
                             $aViewUrls['output'] .= $this->getController()->render('/admin/conditions/includes/conditions_edit', $aData, TRUE);
                             // now sets e corresponding hidden input field
                             // depending on the leftOperandType
                             if ($leftOperandType == 'tokenattr') {
                                 $aViewUrls['output'] .= CHtml::hiddenField('csrctoken', HTMLEscape($rows['cfieldname']), array('id' => 'csrctoken' . $rows['cid']));
                             } else {
                                 $aViewUrls['output'] .= CHtml::hiddenField('cquestions', HTMLEscape($rows['cfieldname']), array('id' => 'cquestions' . $rows['cid']));
                             }
                             // now set the corresponding hidden input field
                             // depending on the rightOperandType
                             // This is used when Editting a condition
                             if ($rightOperandType == 'predefinedAnsw') {
                                 $aViewUrls['output'] .= CHtml::hiddenField('EDITcanswers[]', HTMLEscape($rows['value']), array('id' => 'editModeTargetVal' . $rows['cid']));
                             } elseif ($rightOperandType == 'prevQsgqa') {
                                 $aViewUrls['output'] .= CHtml::hiddenField('EDITprevQuestionSGQA', HTMLEscape($rows['value']), array('id' => 'editModeTargetVal' . $rows['cid']));
                             } elseif ($rightOperandType == 'tokenAttr') {
                                 $aViewUrls['output'] .= CHtml::hiddenField('EDITtokenAttr', HTMLEscape($rows['value']), array('id' => 'editModeTargetVal' . $rows['cid']));
                             } elseif ($rightOperandType == 'regexp') {
                                 $aViewUrls['output'] .= CHtml::hiddenField('EDITConditionRegexp', HTMLEscape($rows['value']), array('id' => 'editModeTargetVal' . $rows['cid']));
                             } else {
                                 $aViewUrls['output'] .= CHtml::hiddenField('EDITConditionConst', HTMLEscape($rows['value']), array('id' => 'editModeTargetVal' . $rows['cid']));
                             }
                         }
                         $aViewUrls['output'] .= CHtml::closeTag('td') . CHtml::closeTag('tr') . CHtml::closeTag('table') . CHtml::closeTag('form') . CHtml::closeTag('td') . CHtml::closeTag('tr');
                         $currentfield = $rows['cfieldname'];
                     }
                 }
                 $s++;
             }
         } else {
             // no condition ==> disable delete all conditions button, and display a simple comment
             $aViewUrls['output'] = CHtml::openTag('tr') . CHtml::tag('td', array(), $clang->gT("This question is always shown.")) . CHtml::tag('td', array(), '&nbsp;') . CHtml::closeTag('tr');
         }
         $aViewUrls['output'] .= CHtml::closeTag('table');
     }
     //END DISPLAY CONDITIONS FOR THIS QUESTION
     // BEGIN: DISPLAY THE COPY CONDITIONS FORM
     if ($subaction == "copyconditionsform" || $subaction == "copyconditions") {
         $aViewUrls['output'] .= "<tr class=''><td colspan='3'>\n" . CHtml::form(array("/admin/conditions/sa/index/subaction/copyconditions/surveyid/{$iSurveyID}/gid/{$gid}/qid/{$qid}/"), 'post', array('id' => "copyconditions", 'name' => "copyconditions")) . "<div class='header ui-widget-header'>" . $clang->gT("Copy conditions") . "</div>\n";
         //CopyConditionsMessage
         if (isset($CopyConditionsMessage)) {
             $aViewUrls['output'] .= "<div class='messagebox ui-corner-all'>\n" . "{$CopyConditionsMessage}\n" . "</div>\n";
         }
         if (isset($conditionsList) && is_array($conditionsList)) {
             //TIBO
             $this->getController()->_js_admin_includes(Yii::app()->getConfig("generalscripts") . 'jquery/jquery.multiselect.min.js');
             // TODO
             $aViewUrls['output'] .= "<script type='text/javascript'>\$(document).ready(function () { \$('#copytomultiselect').multiselect( { autoOpen: true, noneSelectedText: '" . $clang->gT("No questions selected") . "', checkAllText: '" . $clang->gT("Check all") . "', uncheckAllText: '" . $clang->gT("Uncheck all") . "', selectedText: '# " . $clang->gT("selected") . "', beforeclose: function(){ return false;},height: 200 } ); });</script>";
             $aViewUrls['output'] .= "\t<div class='conditioncopy-tbl-row'>\n" . "\t<div class='condition-tbl-left'>" . $clang->gT("Copy the selected conditions to") . ":</div>\n" . "\t<div class='condition-tbl-right'>\n" . "\t\t<select name='copyconditionsto[]' id='copytomultiselect'  multiple='multiple' >\n";
             if (isset($pquestions) && count($pquestions) != 0) {
                 foreach ($pquestions as $pq) {
                     $aViewUrls['output'] .= "\t\t<option value='{$pq['fieldname']}'>" . $pq['text'] . "</option>\n";
                 }
             }
             $aViewUrls['output'] .= "\t\t</select>\n" . "\t</div>\n" . "\t</div>\n";
             if (!isset($pquestions) || count($pquestions) == 0) {
                 $disableCopyCondition = " disabled='disabled'";
             } else {
                 $disableCopyCondition = " ";
             }
             $aViewUrls['output'] .= "\t<div class='condition-tbl-full'>\n" . "\t\t<input type='submit' value='" . $clang->gT("Copy conditions") . "' onclick=\"prepareCopyconditions(); return true;\" {$disableCopyCondition}/>\n" . "<input type='hidden' name='subaction' value='copyconditions' />\n" . "<input type='hidden' name='sid' value='{$iSurveyID}' />\n" . "<input type='hidden' name='gid' value='{$gid}' />\n" . "<input type='hidden' name='qid' value='{$qid}' />\n" . "</div>\n";
             $aViewUrls['output'] .= "<script type=\"text/javascript\">\n" . "function prepareCopyconditions()\n" . "{\n" . "\t\$(\"input:checked[name^='aConditionFromScenario']\").each(function(i,val)\n" . "\t{\n" . "var thecid = val.value;\n" . "var theform = document.getElementById('copyconditions');\n" . "addHiddenElement(theform,'copyconditionsfrom[]',thecid);\n" . "return true;\n" . "\t});\n" . "}\n" . "</script>\n";
         } else {
             $aViewUrls['output'] .= "<div class='messagebox ui-corner-all'>\n" . "<div class='partialheader'>" . $clang->gT("There are no existing conditions in this survey.") . "</div><br />\n" . "</div>\n";
         }
         $aViewUrls['output'] .= "</form></td></tr>\n";
     }
     // END: DISPLAY THE COPY CONDITIONS FORM
     if (isset($cquestions)) {
         if (count($cquestions) > 0 && count($cquestions) <= 10) {
             $qcount = count($cquestions);
         } else {
             $qcount = 9;
         }
     } else {
         $qcount = 0;
     }
     //BEGIN: DISPLAY THE ADD or EDIT CONDITION FORM
     if ($subaction == "editconditionsform" || $subaction == "insertcondition" || $subaction == "updatecondition" || $subaction == "deletescenario" || $subaction == "renumberscenarios" || $subaction == "deleteallconditions" || $subaction == "updatescenario" || $subaction == "editthiscondition" || $subaction == "delete") {
         $aViewUrls['output'] .= CHtml::form(array("/admin/conditions/sa/index/subaction/{$subaction}/surveyid/{$iSurveyID}/gid/{$gid}/qid/{$qid}/"), 'post', array('id' => "editconditions", 'name' => "editconditions"));
         if ($subaction == "editthiscondition" && isset($p_cid)) {
             $mytitle = $clang->gT("Edit condition");
         } else {
             $mytitle = $clang->gT("Add condition");
         }
         $aViewUrls['output'] .= "<div class='header ui-widget-header'>" . $mytitle . "</div>\n";
         ///////////////////////////////////////////////////////////////////////////////////////////
         // Begin "Scenario" row
         if ($subaction != "editthiscondition" && isset($scenariocount) && ($scenariocount == 1 || $scenariocount == 0) || $subaction == "editthiscondition" && isset($scenario) && $scenario == 1) {
             $scenarioAddBtn = "\t<a id='scenarioaddbtn' href='#' onclick=\"\$('#scenarioaddbtn').hide();\$('#defaultscenariotxt').hide('slow');\$('#scenario').show('slow');\">" . "<img src='{$imageurl}/plus.png' alt='" . $clang->gT('Add scenario') . "' /></a>\n";
             $scenarioTxt = "<span id='defaultscenariotxt'>" . $clang->gT("Default scenario") . "</span>";
             $scenarioInputStyle = "style = 'display: none;'";
         } else {
             $scenarioAddBtn = "";
             $scenarioTxt = "";
             $scenarioInputStyle = "style = ''";
         }
         $aViewUrls['output'] .= "<div class='condition-tbl-row'>\n" . "<div class='condition-tbl-left'>{$scenarioAddBtn}&nbsp;" . $clang->gT("Scenario") . "</div>\n" . "<div class='condition-tbl-right'><input type='text' name='scenario' id='scenario' value='1' size='2' {$scenarioInputStyle}/>" . "{$scenarioTxt}\n" . "</div>\n" . "</div>\n";
         // Begin "Question" row
         $aViewUrls['output'] .= "<div class='condition-tbl-row'>\n" . "<div class='condition-tbl-left'>" . $clang->gT("Question") . "</div>\n" . "<div class='condition-tbl-right'>\n" . "\t<div id=\"conditionsource\" class=\"tabs-nav\">\n" . "\t<ul>\n" . "\t<li><a href=\"#SRCPREVQUEST\"><span>" . $clang->gT("Previous questions") . "</span></a></li>\n" . "\t<li><a href=\"#SRCTOKENATTRS\"><span>" . $clang->gT("Token fields") . "</span></a></li>\n" . "\t</ul>\n";
         // Previous question tab
         $aViewUrls['output'] .= "<div id='SRCPREVQUEST'><select name='cquestions' id='cquestions' size='" . ($qcount + 1) . "' >\n";
         if (isset($cquestions)) {
             $js_getAnswers_onload = "";
             foreach ($cquestions as $cqn) {
                 $aViewUrls['output'] .= "<option value='{$cqn['3']}' title=\"" . htmlspecialchars($cqn[0]) . "\"";
                 if (isset($p_cquestions) && $cqn[3] == $p_cquestions) {
                     $aViewUrls['output'] .= " selected";
                     if (isset($p_canswers)) {
                         $canswersToSelect = "";
                         foreach ($p_canswers as $checkval) {
                             $canswersToSelect .= ";{$checkval}";
                         }
                         $canswersToSelect = substr($canswersToSelect, 1);
                         $js_getAnswers_onload .= "\$('#canswersToSelect').val('{$canswersToSelect}');\n";
                     }
                 }
                 $aViewUrls['output'] .= ">{$cqn['0']}</option>\n";
             }
         }
         $aViewUrls['output'] .= "</select>\n" . "</div>\n";
         // Source token Tab
         $aViewUrls['output'] .= "<div id='SRCTOKENATTRS'><select name='csrctoken' id='csrctoken' size='" . ($qcount + 1) . "' >\n";
         foreach (getTokenFieldsAndNames($iSurveyID) as $tokenattr => $tokenattrName) {
             // Check to select
             if (isset($p_csrctoken) && $p_csrctoken == '{TOKEN:' . strtoupper($tokenattr) . '}') {
                 $selectThisSrcTokenAttr = "selected=\"selected\"";
             } else {
                 $selectThisSrcTokenAttr = "";
             }
             $aViewUrls['output'] .= "<option value='{TOKEN:" . strtoupper($tokenattr) . "}' {$selectThisSrcTokenAttr}>" . HTMLEscape($tokenattrName['description']) . "</option>\n";
         }
         $aViewUrls['output'] .= "</select>\n" . "</div>\n\n";
         $aViewUrls['output'] .= "\t</div>\n";
         // end conditionsource div
         $aViewUrls['output'] .= "</div>\n" . "</div>\n";
         // Begin "Comparison operator" row
         $aViewUrls['output'] .= "<div class='condition-tbl-row'>\n" . "<div class='condition-tbl-left'>" . $clang->gT("Comparison operator") . "</div>\n" . "<div class='condition-tbl-right'>\n" . "<select name='method' id='method'>\n";
         foreach ($method as $methodCode => $methodTxt) {
             $selected = $methodCode == "==" ? " selected='selected'" : "";
             $aViewUrls['output'] .= "\t<option value='" . $methodCode . "'{$selected}>" . $methodTxt . "</option>\n";
         }
         $aViewUrls['output'] .= "</select>\n" . "</div>\n" . "</div>\n";
         // Begin "Answer" row
         $aViewUrls['output'] .= "<div class='condition-tbl-row'>\n" . "<div class='condition-tbl-left'>" . $clang->gT("Answer") . "</div>\n";
         if ($subaction == "editthiscondition") {
             $multipletext = "";
             if (isset($_POST['EDITConditionConst']) && $_POST['EDITConditionConst'] != '') {
                 $EDITConditionConst = HTMLEscape($_POST['EDITConditionConst']);
             } else {
                 $EDITConditionConst = "";
             }
             if (isset($_POST['EDITConditionRegexp']) && $_POST['EDITConditionRegexp'] != '') {
                 $EDITConditionRegexp = HTMLEscape($_POST['EDITConditionRegexp']);
             } else {
                 $EDITConditionRegexp = "";
             }
         } else {
             $multipletext = "multiple";
             if (isset($_POST['ConditionConst']) && $_POST['ConditionConst'] != '') {
                 $EDITConditionConst = HTMLEscape($_POST['ConditionConst']);
             } else {
                 $EDITConditionConst = "";
             }
             if (isset($_POST['ConditionRegexp']) && $_POST['ConditionRegexp'] != '') {
                 $EDITConditionRegexp = HTMLEscape($_POST['ConditionRegexp']);
             } else {
                 $EDITConditionRegexp = "";
             }
         }
         $aViewUrls['output'] .= "" . "<div class='condition-tbl-right'>\n" . "<div id=\"conditiontarget\" class=\"tabs-nav\">\n" . "\t<ul>\n" . "\t\t<li><a href=\"#CANSWERSTAB\"><span>" . $clang->gT("Predefined") . "</span></a></li>\n" . "\t\t<li><a href=\"#CONST\"><span>" . $clang->gT("Constant") . "</span></a></li>\n" . "\t\t<li><a href=\"#PREVQUESTIONS\"><span>" . $clang->gT("Questions") . "</span></a></li>\n" . "\t\t<li><a href=\"#TOKENATTRS\"><span>" . $clang->gT("Token fields") . "</span></a></li>\n" . "\t\t<li><a href=\"#REGEXP\"><span>" . $clang->gT("RegExp") . "</span></a></li>\n" . "\t</ul>\n";
         // Predefined answers tab
         $aViewUrls['output'] .= "\t<div id='CANSWERSTAB'>\n" . "\t\t<select  name='canswers[]' {$multipletext} id='canswers' size='7'>\n" . "\t\t</select>\n" . "\t\t<br /><span id='canswersLabel'>" . $clang->gT("Predefined answer options for this question") . "</span>\n" . "\t</div>\n";
         // Constant tab
         $aViewUrls['output'] .= "\t<div id='CONST' style='display:block;' >\n" . "\t\t<textarea name='ConditionConst' id='ConditionConst' rows='5' cols='113'>{$EDITConditionConst}</textarea>\n" . "\t\t<br /><div id='ConditionConstLabel'>" . $clang->gT("Constant value") . "</div>\n" . "\t</div>\n";
         // Previous answers tab @SGQA@ placeholders
         $aViewUrls['output'] .= "\t<div id='PREVQUESTIONS'>\n" . "\t\t<select name='prevQuestionSGQA' id='prevQuestionSGQA' size='7'>\n";
         foreach ($cquestions as $cqn) {
             // building the @SGQA@ placeholders options
             if ($cqn[2] != 'M' && $cqn[2] != 'P') {
                 // Type M or P aren't real fieldnames and thus can't be used in @SGQA@ placehodlers
                 $aViewUrls['output'] .= "\t\t<option value='@{$cqn['3']}@' title=\"" . htmlspecialchars($cqn[0]) . "\"";
                 if (isset($p_prevquestionsgqa) && $p_prevquestionsgqa == "@" . $cqn[3] . "@") {
                     $aViewUrls['output'] .= " selected='selected'";
                 }
                 $aViewUrls['output'] .= ">{$cqn['0']}</option>\n";
             }
         }
         $aViewUrls['output'] .= "\t\t</select>\n" . "\t\t<br /><span id='prevQuestionSGQALabel'>" . $clang->gT("Answers from previous questions") . "</span>\n" . "\t</div>\n";
         // Token tab
         $aViewUrls['output'] .= "\t<div id='TOKENATTRS'>\n" . "\t\t<select name='tokenAttr' id='tokenAttr' size='7'>\n";
         foreach (getTokenFieldsAndNames($iSurveyID) as $tokenattr => $tokenattrName) {
             $aViewUrls['output'] .= "\t\t<option value='{TOKEN:" . strtoupper($tokenattr) . "}'>" . HTMLEscape($tokenattrName['description']) . "</option>\n";
         }
         $aViewUrls['output'] .= "\t\t</select>\n" . "\t\t<br /><span id='tokenAttrLabel'>" . $clang->gT("Attributes values from the participant's token") . "</span>\n" . "\t</div>\n";
         // Regexp Tab
         $aViewUrls['output'] .= "\t<div id='REGEXP' style='display:block;'>\n" . "\t\t<textarea name='ConditionRegexp' id='ConditionRegexp' rows='5' cols='113'>{$EDITConditionRegexp}</textarea>\n" . "\t\t<br /><div id='ConditionRegexpLabel'><a href=\"http://docs.limesurvey.org/tiki-index.php?page=Using+Regular+Expressions\" target=\"_blank\">" . $clang->gT("Regular expression") . "</a></div>\n" . "\t</div>\n";
         $aViewUrls['output'] .= "</div>\n";
         // end conditiontarget div
         $this->getController()->_js_admin_includes(Yii::app()->getConfig("adminscripts") . 'conditions.js');
         $this->getController()->_js_admin_includes(Yii::app()->getConfig("generalscripts") . 'jquery/lime-conditions-tabs.js');
         if ($subaction == "editthiscondition" && isset($p_cid)) {
             $submitLabel = $clang->gT("Update condition");
             $submitSubaction = "updatecondition";
             $submitcid = sanitize_int($p_cid);
         } else {
             $submitLabel = $clang->gT("Add condition");
             $submitSubaction = "insertcondition";
             $submitcid = "";
         }
         $aViewUrls['output'] .= "</div>\n" . "</div>\n";
         // Begin buttons row
         $aViewUrls['output'] .= "<div class='condition-tbl-full'>\n" . "\t<input type='reset' id='resetForm' value='" . $clang->gT("Clear") . "' />\n" . "\t<input type='submit' value='" . $submitLabel . "' />\n" . "<input type='hidden' name='sid' value='{$iSurveyID}' />\n" . "<input type='hidden' name='gid' value='{$gid}' />\n" . "<input type='hidden' name='qid' value='{$qid}' />\n" . "<input type='hidden' name='subaction' value='{$submitSubaction}' />\n" . "<input type='hidden' name='cqid' id='cqid' value='' />\n" . "<input type='hidden' name='cid' id='cid' value='" . $submitcid . "' />\n" . "<input type='hidden' name='editTargetTab' id='editTargetTab' value='' />\n" . "<input type='hidden' name='editSourceTab' id='editSourceTab' value='' />\n" . "<input type='hidden' name='canswersToSelect' id='canswersToSelect' value='' />\n" . "</div>\n" . "</form>\n";
         if (!isset($js_getAnswers_onload)) {
             $js_getAnswers_onload = '';
         }
         $aViewUrls['output'] .= "<script type='text/javascript'>\n" . "<!--\n" . "\t" . $js_getAnswers_onload . "\n";
         if (isset($p_method)) {
             $aViewUrls['output'] .= "\tdocument.getElementById('method').value='" . $p_method . "';\n";
         }
         if ($subaction == "editthiscondition") {
             // in edit mode we read previous values in order to dusplay them in the corresponding inputs
             if (isset($_POST['EDITConditionConst']) && $_POST['EDITConditionConst'] != '') {
                 // In order to avoid issues with backslash escaping, I don't use javascript to set the value
                 // Thus the value is directly set when creating the Textarea element
                 //$aViewUrls['output'] .= "\tdocument.getElementById('ConditionConst').value='".HTMLEscape($_POST['EDITConditionConst'])."';\n";
                 $aViewUrls['output'] .= "\tdocument.getElementById('editTargetTab').value='#CONST';\n";
             } elseif (isset($_POST['EDITprevQuestionSGQA']) && $_POST['EDITprevQuestionSGQA'] != '') {
                 $aViewUrls['output'] .= "\tdocument.getElementById('prevQuestionSGQA').value='" . HTMLEscape($_POST['EDITprevQuestionSGQA']) . "';\n";
                 $aViewUrls['output'] .= "\tdocument.getElementById('editTargetTab').value='#PREVQUESTIONS';\n";
             } elseif (isset($_POST['EDITtokenAttr']) && $_POST['EDITtokenAttr'] != '') {
                 $aViewUrls['output'] .= "\tdocument.getElementById('tokenAttr').value='" . HTMLEscape($_POST['EDITtokenAttr']) . "';\n";
                 $aViewUrls['output'] .= "\tdocument.getElementById('editTargetTab').value='#TOKENATTRS';\n";
             } elseif (isset($_POST['EDITConditionRegexp']) && $_POST['EDITConditionRegexp'] != '') {
                 // In order to avoid issues with backslash escaping, I don't use javascript to set the value
                 // Thus the value is directly set when creating the Textarea element
                 //$aViewUrls['output'] .= "\tdocument.getElementById('ConditionRegexp').value='".HTMLEscape($_POST['EDITConditionRegexp'])."';\n";
                 $aViewUrls['output'] .= "\tdocument.getElementById('editTargetTab').value='#REGEXP';\n";
             } elseif (isset($_POST['EDITcanswers']) && is_array($_POST['EDITcanswers'])) {
                 // was a predefined answers post
                 $aViewUrls['output'] .= "\tdocument.getElementById('editTargetTab').value='#CANSWERSTAB';\n";
                 $aViewUrls['output'] .= "\t\$('#canswersToSelect').val('" . $_POST['EDITcanswers'][0] . "');\n";
             }
             if (isset($_POST['csrctoken']) && $_POST['csrctoken'] != '') {
                 $aViewUrls['output'] .= "\tdocument.getElementById('csrctoken').value='" . HTMLEscape($_POST['csrctoken']) . "';\n";
                 $aViewUrls['output'] .= "\tdocument.getElementById('editSourceTab').value='#SRCTOKENATTRS';\n";
             } else {
                 if (isset($_POST['cquestions']) && $_POST['cquestions'] != '') {
                     $aViewUrls['output'] .= "\tdocument.getElementById('cquestions').value='" . HTMLEscape($_POST['cquestions']) . "';\n";
                     $aViewUrls['output'] .= "\tdocument.getElementById('editSourceTab').value='#SRCPREVQUEST';\n";
                 }
             }
         } else {
             // in other modes, for the moment we do the same as for edit mode
             if (isset($_POST['ConditionConst']) && $_POST['ConditionConst'] != '') {
                 // In order to avoid issues with backslash escaping, I don't use javascript to set the value
                 // Thus the value is directly set when creating the Textarea element
                 //$aViewUrls['output'] .= "\tdocument.getElementById('ConditionConst').value='".HTMLEscape($_POST['ConditionConst'])."';\n";
                 $aViewUrls['output'] .= "\tdocument.getElementById('editTargetTab').value='#CONST';\n";
             } elseif (isset($_POST['prevQuestionSGQA']) && $_POST['prevQuestionSGQA'] != '') {
                 $aViewUrls['output'] .= "\tdocument.getElementById('prevQuestionSGQA').value='" . HTMLEscape($_POST['prevQuestionSGQA']) . "';\n";
                 $aViewUrls['output'] .= "\tdocument.getElementById('editTargetTab').value='#PREVQUESTIONS';\n";
             } elseif (isset($_POST['tokenAttr']) && $_POST['tokenAttr'] != '') {
                 $aViewUrls['output'] .= "\tdocument.getElementById('tokenAttr').value='" . HTMLEscape($_POST['tokenAttr']) . "';\n";
                 $aViewUrls['output'] .= "\tdocument.getElementById('editTargetTab').value='#TOKENATTRS';\n";
             } elseif (isset($_POST['ConditionRegexp']) && $_POST['ConditionRegexp'] != '') {
                 // In order to avoid issues with backslash escaping, I don't use javascript to set the value
                 // Thus the value is directly set when creating the Textarea element
                 //$aViewUrls['output'] .= "\tdocument.getElementById('ConditionRegexp').value='".HTMLEscape($_POST['ConditionRegexp'])."';\n";
                 $aViewUrls['output'] .= "\tdocument.getElementById('editTargetTab').value='#REGEXP';\n";
             } else {
                 // was a predefined answers post
                 if (isset($_POST['cquestions'])) {
                     $aViewUrls['output'] .= "\tdocument.getElementById('cquestions').value='" . HTMLEscape($_POST['cquestions']) . "';\n";
                 }
                 $aViewUrls['output'] .= "\tdocument.getElementById('editTargetTab').value='#CANSWERSTAB';\n";
             }
             if (isset($_POST['csrctoken']) && $_POST['csrctoken'] != '') {
                 $aViewUrls['output'] .= "\tdocument.getElementById('csrctoken').value='" . HTMLEscape($_POST['csrctoken']) . "';\n";
                 $aViewUrls['output'] .= "\tdocument.getElementById('editSourceTab').value='#SRCTOKENATTRS';\n";
             } else {
                 if (isset($_POST['cquestions'])) {
                     $aViewUrls['output'] .= "\tdocument.getElementById('cquestions').value='" . javascriptEscape($_POST['cquestions']) . "';\n";
                 }
                 $aViewUrls['output'] .= "\tdocument.getElementById('editSourceTab').value='#SRCPREVQUEST';\n";
             }
         }
         if (isset($p_scenario)) {
             $aViewUrls['output'] .= "\tdocument.getElementById('scenario').value='" . $p_scenario . "';\n";
         }
         $aViewUrls['output'] .= "-->\n" . "</script>\n";
     }
     //END: DISPLAY THE ADD or EDIT CONDITION FORM
     $conditionsoutput = $aViewUrls['output'];
     $aData['conditionsoutput'] = $conditionsoutput;
     $this->_renderWrappedTemplate('conditions', $aViewUrls, $aData);
     // TMSW Conditions->Relevance:  Must call LEM->ConvertConditionsToRelevance() whenever Condition is added or updated - what is best location for that action?
 }
Пример #23
0
 /**
  * Show survey summary
  * @param int Survey id
  * @param string Action to be performed
  */
 function _surveysummary($iSurveyID, $action = null, $gid = null)
 {
     $clang = $this->getController()->lang;
     $baselang = Survey::model()->findByPk($iSurveyID)->language;
     $condition = array('sid' => $iSurveyID, 'language' => $baselang);
     $sumresult1 = Survey::model()->with(array('languagesettings' => array('condition' => 'surveyls_language=language')))->findByPk($iSurveyID);
     //$sumquery1, 1) ; //Checked
     if (is_null($sumresult1)) {
         Yii::app()->session['flashmessage'] = $clang->gT("Invalid survey ID");
         $this->getController()->redirect($this->getController()->createUrl("admin/index"));
     }
     //  if surveyid is invalid then die to prevent errors at a later time
     $surveyinfo = $sumresult1->attributes;
     $surveyinfo = array_merge($surveyinfo, $sumresult1->languagesettings[0]->attributes);
     $surveyinfo = array_map('flattenText', $surveyinfo);
     //$surveyinfo = array_map('htmlspecialchars', $surveyinfo);
     $activated = $surveyinfo['active'];
     $condition = array('sid' => $iSurveyID, 'parent_qid' => 0, 'language' => $baselang);
     $sumresult3 = Questions::model()->findAllByAttributes($condition);
     //Checked
     $sumcount3 = count($sumresult3);
     $condition = array('sid' => $iSurveyID, 'language' => $baselang);
     //$sumquery2 = "SELECT * FROM ".db_table_name('groups')." WHERE sid={$iSurveyID} AND language='".$baselang."'"; //Getting a count of groups for this survey
     $sumresult2 = Groups::model()->findAllByAttributes($condition);
     //Checked
     $sumcount2 = count($sumresult2);
     //SURVEY SUMMARY
     $aAdditionalLanguages = Survey::model()->findByPk($iSurveyID)->additionalLanguages;
     $surveysummary2 = "";
     if ($surveyinfo['anonymized'] != "N") {
         $surveysummary2 .= $clang->gT("Responses to this survey are anonymized.") . "<br />";
     } else {
         $surveysummary2 .= $clang->gT("Responses to this survey are NOT anonymized.") . "<br />";
     }
     if ($surveyinfo['format'] == "S") {
         $surveysummary2 .= $clang->gT("It is presented question by question.") . "<br />";
     } elseif ($surveyinfo['format'] == "G") {
         $surveysummary2 .= $clang->gT("It is presented group by group.") . "<br />";
     } else {
         $surveysummary2 .= $clang->gT("It is presented on one single page.") . "<br />";
     }
     if ($surveyinfo['allowjumps'] == "Y") {
         if ($surveyinfo['format'] == 'A') {
             $surveysummary2 .= $clang->gT("No question index will be shown with this format.") . "<br />";
         } else {
             $surveysummary2 .= $clang->gT("A question index will be shown; participants will be able to jump between viewed questions.") . "<br />";
         }
     }
     if ($surveyinfo['datestamp'] == "Y") {
         $surveysummary2 .= $clang->gT("Responses will be date stamped.") . "<br />";
     }
     if ($surveyinfo['ipaddr'] == "Y") {
         $surveysummary2 .= $clang->gT("IP Addresses will be logged") . "<br />";
     }
     if ($surveyinfo['refurl'] == "Y") {
         $surveysummary2 .= $clang->gT("Referrer URL will be saved.") . "<br />";
     }
     if ($surveyinfo['usecookie'] == "Y") {
         $surveysummary2 .= $clang->gT("It uses cookies for access control.") . "<br />";
     }
     if ($surveyinfo['allowregister'] == "Y") {
         $surveysummary2 .= $clang->gT("If tokens are used, the public may register for this survey") . "<br />";
     }
     if ($surveyinfo['allowsave'] == "Y" && $surveyinfo['tokenanswerspersistence'] == 'N') {
         $surveysummary2 .= $clang->gT("Participants can save partially finished surveys") . "<br />\n";
     }
     if ($surveyinfo['emailnotificationto'] != '') {
         $surveysummary2 .= $clang->gT("Basic email notification is sent to:") . " {$surveyinfo['emailnotificationto']}<br />\n";
     }
     if ($surveyinfo['emailresponseto'] != '') {
         $surveysummary2 .= $clang->gT("Detailed email notification with response data is sent to:") . " {$surveyinfo['emailresponseto']}<br />\n";
     }
     $dateformatdetails = getDateFormatData(Yii::app()->session['dateformat']);
     if (trim($surveyinfo['startdate']) != '') {
         Yii::import('application.libraries.Date_Time_Converter');
         $datetimeobj = new Date_Time_Converter($surveyinfo['startdate'], 'Y-m-d H:i:s');
         $aData['startdate'] = $datetimeobj->convert($dateformatdetails['phpdate'] . ' H:i');
     } else {
         $aData['startdate'] = "-";
     }
     if (trim($surveyinfo['expires']) != '') {
         //$constructoritems = array($surveyinfo['expires'] , "Y-m-d H:i:s");
         Yii::import('application.libraries.Date_Time_Converter');
         $datetimeobj = new Date_Time_Converter($surveyinfo['expires'], 'Y-m-d H:i:s');
         //$datetimeobj = new Date_Time_Converter($surveyinfo['expires'] , "Y-m-d H:i:s");
         $aData['expdate'] = $datetimeobj->convert($dateformatdetails['phpdate'] . ' H:i');
     } else {
         $aData['expdate'] = "-";
     }
     if (!$surveyinfo['language']) {
         $aData['language'] = getLanguageNameFromCode($currentadminlang, false);
     } else {
         $aData['language'] = getLanguageNameFromCode($surveyinfo['language'], false);
     }
     // get the rowspan of the Additionnal languages row
     // is at least 1 even if no additionnal language is present
     $additionnalLanguagesCount = count($aAdditionalLanguages);
     $first = true;
     $aData['additionnalLanguages'] = "";
     if ($additionnalLanguagesCount == 0) {
         $aData['additionnalLanguages'] .= "<td>-</td>\n";
     } else {
         foreach ($aAdditionalLanguages as $langname) {
             if ($langname) {
                 if (!$first) {
                     $aData['additionnalLanguages'] .= "<tr><td>&nbsp;</td>";
                 }
                 $first = false;
                 $aData['additionnalLanguages'] .= "<td>" . getLanguageNameFromCode($langname, false) . "</td></tr>\n";
             }
         }
     }
     if ($first) {
         $aData['additionnalLanguages'] .= "</tr>";
     }
     if ($surveyinfo['surveyls_urldescription'] == "") {
         $surveyinfo['surveyls_urldescription'] = htmlspecialchars($surveyinfo['surveyls_url']);
     }
     if ($surveyinfo['surveyls_url'] != "") {
         $aData['endurl'] = " <a target='_blank' href=\"" . htmlspecialchars($surveyinfo['surveyls_url']) . "\" title=\"" . htmlspecialchars($surveyinfo['surveyls_url']) . "\">{$surveyinfo['surveyls_urldescription']}</a>";
     } else {
         $aData['endurl'] = "-";
     }
     $aData['sumcount3'] = $sumcount3;
     $aData['sumcount2'] = $sumcount2;
     if ($activated == "N") {
         $aData['activatedlang'] = $clang->gT("No");
     } else {
         $aData['activatedlang'] = $clang->gT("Yes");
     }
     $aData['activated'] = $activated;
     if ($activated == "Y") {
         $aData['surveydb'] = Yii::app()->db->tablePrefix . "survey_" . $iSurveyID;
     }
     $aData['warnings'] = "";
     if ($activated == "N" && $sumcount3 == 0) {
         $aData['warnings'] = $clang->gT("Survey cannot be activated yet.") . "<br />\n";
         if ($sumcount2 == 0 && hasSurveyPermission($iSurveyID, 'surveycontent', 'create')) {
             $aData['warnings'] .= "<span class='statusentryhighlight'>[" . $clang->gT("You need to add question groups") . "]</span><br />";
         }
         if ($sumcount3 == 0 && hasSurveyPermission($iSurveyID, 'surveycontent', 'create')) {
             $aData['warnings'] .= "<span class='statusentryhighlight'>[" . $clang->gT("You need to add questions") . "]</span><br />";
         }
     }
     $aData['hints'] = $surveysummary2;
     //return (array('column'=>array($columns_used,$hard_limit) , 'size' => array($length, $size_limit) ));
     //        $aData['tableusage'] = getDBTableUsage($iSurveyID);
     // ToDo: Table usage is calculated on every menu display which is too slow with bug surveys.
     // Needs to be moved to a database field and only updated if there are question/subquestions added/removed (it's currently also not functional due to the port)
     //
     $aData['tableusage'] = false;
     if ($gid || $action !== true && in_array($action, array('deactivate', 'activate', 'surveysecurity', 'editdefaultvalues', 'editemailtemplates', 'surveyrights', 'addsurveysecurity', 'addusergroupsurveysecurity', 'setsurveysecurity', 'setusergroupsurveysecurity', 'delsurveysecurity', 'editsurveysettings', 'editsurveylocalesettings', 'updatesurveysettingsandeditlocalesettings', 'addgroup', 'importgroup', 'ordergroups', 'deletesurvey', 'resetsurveylogic', 'importsurveyresources', 'translate', 'emailtemplates', 'exportstructure', 'quotas', 'copysurvey', 'viewgroup', 'viewquestion'))) {
         $showstyle = "style='display: none'";
     } else {
         $showstyle = "";
     }
     $aData['showstyle'] = $showstyle;
     $aData['aAdditionalLanguages'] = $aAdditionalLanguages;
     $aData['clang'] = $clang;
     $aData['surveyinfo'] = $surveyinfo;
     $this->getController()->render("/admin/survey/surveySummary_view", $aData);
 }
Пример #24
0
    /**
     * Load preview of a question screen.
     *
     * @access public
     * @param int $surveyid
     * @param int $qid
     * @param string $lang
     * @return void
     */
    public function preview($surveyid, $qid, $lang = null)
    {
        $surveyid = sanitize_int($surveyid);
        $qid = sanitize_int($qid);
        $LEMdebugLevel = 0;
        Yii::app()->loadHelper("qanda");
        Yii::app()->loadHelper("surveytranslator");
        if (empty($surveyid)) {
            $this->getController()->error('No Survey ID provided');
        }
        if (empty($qid)) {
            $this->getController()->error('No Question ID provided');
        }
        if (empty($lang)) {
            $language = Survey::model()->findByPk($surveyid)->language;
        } else {
            $language = $lang;
        }
        if (!isset(Yii::app()->session['step'])) {
            Yii::app()->session['step'] = 0;
        }
        if (!isset(Yii::app()->session['prevstep'])) {
            Yii::app()->session['prevstep'] = 0;
        }
        if (!isset(Yii::app()->session['maxstep'])) {
            Yii::app()->session['maxstep'] = 0;
        }
        // Use $_SESSION instead of $this->session for frontend features.
        $_SESSION['survey_' . $surveyid]['s_lang'] = $language;
        $_SESSION['survey_' . $surveyid]['fieldmap'] = createFieldMap($surveyid, 'full', true, $qid, $language);
        // Prefill question/answer from defaultvalues
        foreach ($_SESSION['survey_' . $surveyid]['fieldmap'] as $field) {
            if (isset($field['defaultvalue'])) {
                $_SESSION['survey_' . $surveyid][$field['fieldname']] = $field['defaultvalue'];
            }
        }
        $clang = new limesurvey_lang($language);
        $thissurvey = getSurveyInfo($surveyid);
        setNoAnswerMode($thissurvey);
        Yii::app()->session['dateformats'] = getDateFormatData($thissurvey['surveyls_dateformat']);
        $qrows = Questions::model()->findByAttributes(array('sid' => $surveyid, 'qid' => $qid, 'language' => $language))->getAttributes();
        $ia = array(0 => $qid, 1 => $surveyid . 'X' . $qrows['gid'] . 'X' . $qid, 2 => $qrows['title'], 3 => $qrows['question'], 4 => $qrows['type'], 5 => $qrows['gid'], 6 => $qrows['mandatory'], 7 => 'N', 8 => 'N');
        $radix = getRadixPointData($thissurvey['surveyls_numberformat']);
        $radix = $radix['seperator'];
        $surveyOptions = array('radix' => $radix, 'tempdir' => Yii::app()->getConfig('tempdir'));
        LimeExpressionManager::StartSurvey($surveyid, 'question', $surveyOptions, false, $LEMdebugLevel);
        $qseq = LimeExpressionManager::GetQuestionSeq($qid);
        $moveResult = LimeExpressionManager::JumpTo($qseq + 1, true, false, true);
        $answers = retrieveAnswers($ia, $surveyid);
        if (!$thissurvey['template']) {
            $thistpl = getTemplatePath(Yii::app()->getConfig('defaulttemplate'));
        } else {
            $thistpl = getTemplatePath(validateTemplateDir($thissurvey['template']));
        }
        doHeader();
        $showQuestion = "\$('#question{$qid}').show();";
        $dummy_js = <<<EOD
            <script type='text/javascript'>
            <!--
            LEMradix='{$radix}';
            var numRegex = new RegExp('[^-' + LEMradix + '0-9]','g');
            var intRegex = new RegExp('[^-0-9]','g');
            function fixnum_checkconditions(value, name, type, evt_type, intonly)
            {
                newval = new String(value);
                if (typeof intonly !=='undefined' && intonly==1) {
                    newval = newval.replace(intRegex,'');
                }
                else {
                    newval = newval.replace(numRegex,'');
                }
                if (LEMradix === ',') {
                    newval = newval.split(',').join('.');
                }
                if (newval != '-' && newval != '.' && newval != '-.' && newval != parseFloat(newval)) {
                    newval = '';
                }
                displayVal = newval;
                if (LEMradix === ',') {
                    displayVal = displayVal.split('.').join(',');
                }
                if (name.match(/other\$/)) {
                    \$('#answer'+name+'text').val(displayVal);
                }
                \$('#answer'+name).val(displayVal);

                if (typeof evt_type === 'undefined')
                {
                    evt_type = 'onchange';
                }
                checkconditions(newval, name, type, evt_type);
            }

            function checkconditions(value, name, type, evt_type)
            {
                if (typeof evt_type === 'undefined')
                {
                    evt_type = 'onchange';
                }
                if (type == 'radio' || type == 'select-one')
                {
                    var hiddenformname='java'+name;
                    document.getElementById(hiddenformname).value=value;
                }
                else if (type == 'checkbox')
                {
                    if (document.getElementById('answer'+name).checked)
                    {
                        \$('#java'+name).val('Y');
                    } else
                    {
                        \$('#java'+name).val('');
                    }
                }
                else if (type == 'text' && name.match(/other\$/) && typeof document.getElementById('java'+name) !== 'undefined' && document.getElementById('java'+name) != null)
                {
                    \$('#java'+name).val(value);
                }
                ExprMgr_process_relevance_and_tailoring(evt_type,name,type);
                {$showQuestion}
            }
            \$(document).ready(function() {
                {$showQuestion}
            });
            \$(document).change(function() {
                {$showQuestion}
            });
            \$(document).bind('keydown',function(e) {
                        if (e.keyCode == 9) {
                            {$showQuestion}
                            return true;
                        }
                        return true;
                    });
        // -->
        </script>
EOD;
        $answer = $answers[0][1];
        //        $help = $answers[0][2];
        $qinfo = LimeExpressionManager::GetQuestionStatus($qid);
        $help = $qinfo['info']['help'];
        $question = $answers[0][0];
        $question['code'] = $answers[0][5];
        $question['class'] = getQuestionClass($qrows['type']);
        $question['essentials'] = 'id="question' . $qrows['qid'] . '"';
        $question['sgq'] = $ia[1];
        $question['aid'] = 'unknown';
        $question['sqid'] = 'unknown';
        if ($qrows['mandatory'] == 'Y') {
            $question['man_class'] = ' mandatory';
        } else {
            $question['man_class'] = '';
        }
        $redata = compact(array_keys(get_defined_vars()));
        $content = templatereplace(file_get_contents("{$thistpl}/startpage.pstpl"), array(), $redata);
        $content .= CHtml::form('index.php', 'post', array('id' => "limesurvey", 'name' => "limesurvey", 'autocomplete' => 'off'));
        $content .= templatereplace(file_get_contents("{$thistpl}/startgroup.pstpl"), array(), $redata);
        $question_template = file_get_contents("{$thistpl}/question.pstpl");
        // the following has been added for backwards compatiblity.
        if (substr_count($question_template, '{QUESTION_ESSENTIALS}') > 0) {
            // LS 1.87 and newer templates
            $content .= "\n" . templatereplace($question_template, array(), $redata, 'Unspecified', false, $qid) . "\n";
        } else {
            // LS 1.86 and older templates
            $content .= '<div ' . $question['essentials'] . ' class="' . $question['class'] . $question['man_class'] . '">';
            $content .= "\n" . templatereplace($question_template, array(), $redata, 'Unspecified', false, $qid) . "\n";
            $content .= "\n\t</div>\n";
        }
        $content .= templatereplace(file_get_contents("{$thistpl}/endgroup.pstpl"), array(), $redata) . $dummy_js;
        LimeExpressionManager::FinishProcessingGroup();
        $content .= LimeExpressionManager::GetRelevanceAndTailoringJavaScript();
        $content .= '<p>&nbsp;</form>';
        $content .= templatereplace(file_get_contents("{$thistpl}/endpage.pstpl"), array(), $redata);
        LimeExpressionManager::FinishProcessingPage();
        echo $content;
        if ($LEMdebugLevel >= 1) {
            echo LimeExpressionManager::GetDebugTimingMessage();
        }
        if ($LEMdebugLevel >= 2) {
            echo "<table><tr><td align='left'><b>Group/Question Validation Results:</b>" . $moveResult['message'] . "</td></tr></table>\n";
        }
        echo "</html>\n";
        exit;
    }
Пример #25
0
         $maxvalue = $qidattributes['multiflexible_max'];
     }
 }
 if (trim($qidattributes['multiflexible_step']) != '') {
     $stepvalue = $qidattributes['multiflexible_step'];
 } else {
     $stepvalue = 1;
 }
 if ($qidattributes['multiflexible_checkbox'] != 0) {
     $minvalue = 0;
     $maxvalue = 1;
     $stepvalue = 1;
 }
 foreach ($result[$key1] as $row) {
     $row = array_values($row);
     $fresult = Questions::model()->getQuestionsForStatistics('*', "parent_qid='{$flt['0']}' AND language = '{$language}' AND scale_id = 1", 'question_order, title');
     foreach ($fresult as $frow) {
         $myfield2 = $myfield . $row[0] . "_" . $frow['title'];
         echo "<!-- {$myfield2} - ";
         if (isset($_POST[$myfield2])) {
             echo $_POST[$myfield2];
         }
         echo " -->\n";
         if ($counter2 == 4) {
             echo "\t</tr>\n\t<tr>\n";
             $counter2 = 0;
         }
         echo "\t<td align='center'>" . "<input type='checkbox'  name='summary[]' value='{$myfield2}'";
         if (isset($summary) && array_search($myfield2, $summary) !== FALSE) {
             echo " checked='checked'";
         }
Пример #26
0
/**
* This function replaces the old insertans tags with new ones across a survey
*
* @param string $newsid  Old SID
* @param string $oldsid  New SID
* @param mixed $fieldnames Array  array('oldfieldname'=>'newfieldname')
*/
function translateInsertansTags($newsid, $oldsid, $fieldnames)
{
    uksort($fieldnames, create_function('$a,$b', 'return strlen($a) < strlen($b);'));
    Yii::app()->loadHelper('database');
    $newsid = sanitize_int($newsid);
    $oldsid = sanitize_int($oldsid);
    # translate 'surveyls_urldescription' and 'surveyls_url' INSERTANS tags in surveyls
    $sql = "SELECT surveyls_survey_id, surveyls_language, surveyls_urldescription, surveyls_url from {{surveys_languagesettings}}\n    WHERE surveyls_survey_id=" . $newsid . " AND (surveyls_urldescription LIKE '%{$oldsid}X%' OR surveyls_url LIKE '%{$oldsid}X%')";
    $result = dbExecuteAssoc($sql) or show_error("Can't read groups table in transInsertAns ");
    // Checked
    //while ($qentry = $res->FetchRow())
    foreach ($result->readAll() as $qentry) {
        $urldescription = $qentry['surveyls_urldescription'];
        $endurl = $qentry['surveyls_url'];
        $language = $qentry['surveyls_language'];
        foreach ($fieldnames as $sOldFieldname => $sNewFieldname) {
            $pattern = $sOldFieldname;
            $replacement = $sNewFieldname;
            $urldescription = preg_replace('/' . $pattern . '/', $replacement, $urldescription);
            $endurl = preg_replace('/' . $pattern . '/', $replacement, $endurl);
        }
        if (strcmp($urldescription, $qentry['surveyls_urldescription']) != 0 || strcmp($endurl, $qentry['surveyls_url']) != 0) {
            // Update Field
            $data = array('surveyls_urldescription' => $urldescription, 'surveyls_url' => $endurl);
            $where = array('surveyls_survey_id' => $newsid, 'surveyls_language' => $language);
            Surveys_languagesettings::update($data, $where);
        }
        // Enf if modified
    }
    // end while qentry
    # translate 'quotals_urldescrip' and 'quotals_url' INSERTANS tags in quota_languagesettings
    $sql = "SELECT quotals_id, quotals_urldescrip, quotals_url from {{quota_languagesettings}} qls, {{quota}} q\n    WHERE sid=" . $newsid . " AND q.id=qls.quotals_quota_id AND (quotals_urldescrip LIKE '%{$oldsid}X%' OR quotals_url LIKE '%{$oldsid}X%')";
    $result = dbExecuteAssoc($sql) or safeDie("Can't read quota table in transInsertAns");
    // Checked
    foreach ($result->readAll() as $qentry) {
        $urldescription = $qentry['quotals_urldescrip'];
        $endurl = $qentry['quotals_url'];
        foreach ($fieldnames as $sOldFieldname => $sNewFieldname) {
            $pattern = $sOldFieldname;
            $replacement = $sNewFieldname;
            $urldescription = preg_replace('/' . $pattern . '/', $replacement, $urldescription);
            $endurl = preg_replace('/' . $pattern . '/', $replacement, $endurl);
        }
        if (strcmp($urldescription, $qentry['quotals_urldescrip']) != 0 || strcmp($endurl, $qentry['quotals_url']) != 0) {
            // Update Field
            $sqlupdate = "UPDATE {{quota_languagesettings}} SET quotals_urldescrip='" . $urldescription . "', quotals_url='" . $endurl . "' WHERE quotals_id={$qentry['quotals_id']}";
            $updateres = dbExecuteAssoc($sqlupdate) or safeDie("Couldn't update INSERTANS in quota_languagesettings<br />{$sqlupdate}<br />");
            //Checked
        }
        // Enf if modified
    }
    // end while qentry
    # translate 'description' INSERTANS tags in groups
    $sql = "SELECT gid, language, group_name, description from {{groups}}\n    WHERE sid=" . $newsid . " AND description LIKE '%{$oldsid}X%' OR group_name LIKE '%{$oldsid}X%'";
    $res = dbExecuteAssoc($sql) or show_error("Can't read groups table in transInsertAns");
    // Checked
    //while ($qentry = $res->FetchRow())
    foreach ($res->readAll() as $qentry) {
        $gpname = $qentry['group_name'];
        $description = $qentry['description'];
        $gid = $qentry['gid'];
        $language = $qentry['language'];
        foreach ($fieldnames as $sOldFieldname => $sNewFieldname) {
            $pattern = $sOldFieldname;
            $replacement = $sNewFieldname;
            $gpname = preg_replace('/' . $pattern . '/', $replacement, $gpname);
            $description = preg_replace('/' . $pattern . '/', $replacement, $description);
        }
        if (strcmp($description, $qentry['description']) != 0 || strcmp($gpname, $qentry['group_name']) != 0) {
            // Update Fields
            $data = array('description' => $description, 'group_name' => $gpname);
            $where = array('gid' => $gid, 'language' => $language);
            Groups::model()->update($data, $where);
        }
        // Enf if modified
    }
    // end while qentry
    # translate 'question' and 'help' INSERTANS tags in questions
    $sql = "SELECT qid, language, question, help from {{questions}}\n    WHERE sid=" . $newsid . " AND (question LIKE '%{$oldsid}X%' OR help LIKE '%{$oldsid}X%')";
    $result = dbExecuteAssoc($sql) or die("Can't read question table in transInsertAns ");
    // Checked
    //while ($qentry = $res->FetchRow())
    $aResultData = $result->readAll();
    foreach ($aResultData as $qentry) {
        $question = $qentry['question'];
        $help = $qentry['help'];
        $qid = $qentry['qid'];
        $language = $qentry['language'];
        foreach ($fieldnames as $sOldFieldname => $sNewFieldname) {
            $pattern = $sOldFieldname;
            $replacement = $sNewFieldname;
            $question = preg_replace('/' . $pattern . '/', $replacement, $question);
            $help = preg_replace('/' . $pattern . '/', $replacement, $help);
        }
        if (strcmp($question, $qentry['question']) != 0 || strcmp($help, $qentry['help']) != 0) {
            // Update Field
            $data = array('question' => $question, 'help' => $help);
            $where = array('qid' => $qid, 'language' => $language);
            Questions::model()->updateByPk($where, $data);
        }
        // Enf if modified
    }
    // end while qentry
    # translate 'answer' INSERTANS tags in answers
    $result = Answers::model()->oldNewInsertansTags($newsid, $oldsid);
    //while ($qentry = $res->FetchRow())
    foreach ($result as $qentry) {
        $answer = $qentry['answer'];
        $code = $qentry['code'];
        $qid = $qentry['qid'];
        $language = $qentry['language'];
        foreach ($fieldnames as $sOldFieldname => $sNewFieldname) {
            $pattern = $sOldFieldname;
            $replacement = $sNewFieldname;
            $answer = preg_replace('/' . $pattern . '/', $replacement, $answer);
        }
        if (strcmp($answer, $qentry['answer']) != 0) {
            // Update Field
            $data = array('answer' => $answer, 'qid' => $qid);
            $where = array('code' => $code, 'language' => $language);
            Answers::model()->update($data, $where);
        }
        // Enf if modified
    }
    // end while qentry
}
Пример #27
0
 /**
  * Deletes a survey and all its data
  *
  * @access public
  * @param int $iSurveyID
  * @param bool @recursive
  * @return void
  */
 public function deleteSurvey($iSurveyID, $recursive = true)
 {
     Survey::model()->deleteByPk($iSurveyID);
     if ($recursive == true) {
         if (tableExists("{{survey_" . intval($iSurveyID) . "}}")) {
             Yii::app()->db->createCommand()->dropTable("{{survey_" . intval($iSurveyID) . "}}");
         }
         if (tableExists("{{survey_" . intval($iSurveyID) . "_timings}}")) {
             Yii::app()->db->createCommand()->dropTable("{{survey_" . intval($iSurveyID) . "_timings}}");
         }
         if (tableExists("{{tokens_" . intval($iSurveyID) . "}}")) {
             Yii::app()->db->createCommand()->dropTable("{{tokens_" . intval($iSurveyID) . "}}");
         }
         $oResult = Questions::model()->findAllByAttributes(array('sid' => $iSurveyID));
         foreach ($oResult as $aRow) {
             Answers::model()->deleteAllByAttributes(array('qid' => $aRow['qid']));
             Conditions::model()->deleteAllByAttributes(array('qid' => $aRow['qid']));
             Question_attributes::model()->deleteAllByAttributes(array('qid' => $aRow['qid']));
             Defaultvalues::model()->deleteAllByAttributes(array('qid' => $aRow['qid']));
         }
         Questions::model()->deleteAllByAttributes(array('sid' => $iSurveyID));
         Assessment::model()->deleteAllByAttributes(array('sid' => $iSurveyID));
         Groups::model()->deleteAllByAttributes(array('sid' => $iSurveyID));
         Surveys_languagesettings::model()->deleteAllByAttributes(array('surveyls_survey_id' => $iSurveyID));
         Survey_permissions::model()->deleteAllByAttributes(array('sid' => $iSurveyID));
         Saved_control::model()->deleteAllByAttributes(array('sid' => $iSurveyID));
         Survey_url_parameters::model()->deleteAllByAttributes(array('sid' => $iSurveyID));
         Quota::model()->deleteQuota(array('sid' => $iSurveyID), true);
     }
 }
 private function _reorderGroup($iSurveyID)
 {
     $AOrgData = array();
     parse_str($_POST['orgdata'], $AOrgData);
     $grouporder = 0;
     foreach ($AOrgData['list'] as $ID => $parent) {
         if ($parent == 'root' && $ID[0] == 'g') {
             Groups::model()->updateAll(array('group_order' => $grouporder), 'gid=:gid', array(':gid' => (int) substr($ID, 1)));
             $grouporder++;
         } elseif ($ID[0] == 'q') {
             if (!isset($questionorder[(int) substr($parent, 1)])) {
                 $questionorder[(int) substr($parent, 1)] = 0;
             }
             Questions::model()->updateAll(array('question_order' => $questionorder[(int) substr($parent, 1)], 'gid' => (int) substr($parent, 1)), 'qid=:qid', array(':qid' => (int) substr($ID, 1)));
             Questions::model()->updateAll(array('gid' => (int) substr($parent, 1)), 'parent_qid=:parent_qid', array(':parent_qid' => (int) substr($ID, 1)));
             $questionorder[(int) substr($parent, 1)]++;
         }
     }
     LimeExpressionManager::SetDirtyFlag();
     // so refreshes syntax highlighting
     Yii::app()->session['flashmessage'] = Yii::app()->lang->gT("The new question group/question order was successfully saved.");
     $this->getController()->redirect($this->getController()->createUrl('admin/survey/sa/view/surveyid/' . $iSurveyID));
 }
Пример #29
-1
 /**
  * 
  * @param type $iQuestionId
  * @param type $iSurveyId
  * @param type $iQuotaId
  * @return array
  */
 function getQuotaAnswers($iQuestionId, $iSurveyId, $iQuotaId)
 {
     $iQuestionId = sanitize_int($iQuestionId);
     $iSurveyId = sanitize_int($iSurveyId);
     $iQuotaId = sanitize_int($iQuotaId);
     $aData = $this->_getData($iSurveyId);
     $sBaseLang = $aData['sBaseLang'];
     $clang = $aData['clang'];
     $aQuestion = Questions::model()->findByPk(array('qid' => $iQuestionId, 'language' => $sBaseLang));
     $aQuestionType = $aQuestion['type'];
     if ($aQuestionType == 'M') {
         $aResults = Questions::model()->findAllByAttributes(array('parent_qid' => $iQuestionId));
         $aAnswerList = array();
         foreach ($aResults as $aDbAnsList) {
             $tmparrayans = array('Title' => $aQuestion['title'], 'Display' => substr($aDbAnsList['question'], 0, 40), 'code' => $aDbAnsList['title']);
             $aAnswerList[$aDbAnsList['title']] = $tmparrayans;
         }
     } elseif ($aQuestionType == 'G') {
         $aAnswerList = array('M' => array('Title' => $aQuestion['title'], 'Display' => $clang->gT("Male"), 'code' => 'M'), 'F' => array('Title' => $aQuestion['title'], 'Display' => $clang->gT("Female"), 'code' => 'F'));
     } elseif ($aQuestionType == 'L' || $aQuestionType == 'O' || $aQuestionType == '!') {
         $aAnsResults = Answers::model()->findAllByAttributes(array('qid' => $iQuestionId));
         $aAnswerList = array();
         foreach ($aAnsResults as $aDbAnsList) {
             $aAnswerList[$aDbAnsList['code']] = array('Title' => $aQuestion['title'], 'Display' => substr($aDbAnsList['answer'], 0, 40), 'code' => $aDbAnsList['code']);
         }
     } elseif ($aQuestionType == 'A') {
         $aAnsResults = Questions::model()->findAllByAttributes(array('parent_qid' => $iQuestionId));
         $aAnswerList = array();
         foreach ($aAnsResults as $aDbAnsList) {
             for ($x = 1; $x < 6; $x++) {
                 $tmparrayans = array('Title' => $aQuestion['title'], 'Display' => substr($aDbAnsList['question'], 0, 40) . ' [' . $x . ']', 'code' => $aDbAnsList['title']);
                 $aAnswerList[$aDbAnsList['title'] . "-" . $x] = $tmparrayans;
             }
         }
     } elseif ($aQuestionType == 'B') {
         $aAnsResults = Answers::model()->findAllByAttributes(array('qid' => $iQuestionId));
         $aAnswerList = array();
         foreach ($aAnsResults as $aDbAnsList) {
             for ($x = 1; $x < 11; $x++) {
                 $tmparrayans = array('Title' => $aQuestion['title'], 'Display' => substr($aDbAnsList['answer'], 0, 40) . ' [' . $x . ']', 'code' => $aDbAnsList['code']);
                 $aAnswerList[$aDbAnsList['code'] . "-" . $x] = $tmparrayans;
             }
         }
     } elseif ($aQuestionType == 'Y') {
         $aAnswerList = array('Y' => array('Title' => $aQuestion['title'], 'Display' => $clang->gT("Yes"), 'code' => 'Y'), 'N' => array('Title' => $aQuestion['title'], 'Display' => $clang->gT("No"), 'code' => 'N'));
     } elseif ($aQuestionType == 'I') {
         $slangs = Survey::model()->findByPk($iSurveyId)->additionalLanguages;
         array_unshift($slangs, $sBaseLang);
         while (list($key, $value) = each($slangs)) {
             $tmparrayans = array('Title' => $aQuestion['title'], 'Display' => getLanguageNameFromCode($value, false), $value);
             $aAnswerList[$value] = $tmparrayans;
         }
     }
     if (empty($aAnswerList)) {
         return array();
     } else {
         // Now we mark answers already used in this quota as such
         $aExistsingAnswers = Quota_members::model()->findAllByAttributes(array('sid' => $iSurveyId, 'qid' => $iQuestionId, 'quota_id' => $iQuotaId));
         foreach ($aExistsingAnswers as $aAnswerRow) {
             if (array_key_exists($aAnswerRow['code'], $aAnswerList)) {
                 $aAnswerList[$aAnswerRow['code']]['rowexists'] = '1';
             }
         }
         return $aAnswerList;
     }
 }