/** * Creates a new model. * If creation is successful, the browser will be redirected to the 'view' page. */ public function actionCreate() { $model = new QuestionVotes(); // Uncomment the following line if AJAX validation is needed // $this->performAjaxValidation($model); if (isset($_POST['QuestionVotes'])) { $model->attributes = $_POST['QuestionVotes']; // TODO: I'd like to figure out a way to instantiate the model // dynamically. I think they might do that with // the 'activity' module. For now this will do. switch ($model->vote_on) { case "question": $question_id = $model->post_id; break; case "answer": $obj = Answer::model()->findByPk($model->post_id); $question_id = $obj->question_id; break; } if (QuestionVotes::model()->castVote($model, $question_id)) { if ($_POST['QuestionVotes']['should_open_question'] == true) { $this->redirect(array('//questionanswer/question/view', 'id' => $question_id)); } else { $this->redirect(array('//questionanswer/question/index')); } } } $this->render('create', array('model' => $model)); }
/** * Controller action for viewing a questions. * Also provides functionality for creating an answer, * adding a comment and voting. */ public function actionView() { error_reporting(E_ALL); ini_set("display_errors", 1); $question = Question::model()->findByPk(Yii::app()->request->getParam('id')); if (isset($_POST['Answer'])) { $answerModel = new Answer(); $answerModel->attributes = $_POST['Answer']; $answerModel->created_by = Yii::app()->user->id; $answerModel->post_type = "answer"; $answerModel->question_id = $question->id; if ($answerModel->validate()) { $answerModel->save(); $this->redirect($this->createUrl('//questionanswer/main/view', array('id' => $question->id))); } } if (isset($_POST['Comment'])) { $commentModel = new Comment(); $commentModel->attributes = $_POST['Comment']; $commentModel->created_by = Yii::app()->user->id; $commentModel->post_type = "comment"; $commentModel->question_id = $question->id; if ($commentModel->validate()) { $commentModel->save(); $this->redirect($this->createUrl('//questionanswer/main/view', array('id' => $question->id))); } } // User has just voted on a question if (isset($_POST['QuestionVotes'])) { $questionVotesModel = new QuestionVotes(); $questionVotesModel->attributes = $_POST['QuestionVotes']; QuestionVotes::model()->castVote($questionVotesModel, $question->id); } $this->render('view', array('author' => $question->user->id, 'question' => $question, 'answers' => Answer::model()->overview($question->id), 'related' => Question::model()->related($question->id))); }
public function getBestAnswer() { //$sql = "select a.* from answer a left join answer_vote v on a.id=v.answerid where a.userId= 1 and v.value>0 group by a.id order by count(*) desc,a.addTime desc limit 1"; $sql = "select a.* from ew_answer a left join ew_entity e on a.voteableEntityId=e.id left join ew_vote v on e.id=v.voteableEntityId where a.userId= " . $this->id . " and v.value>0 order by a.addTime desc limit 1"; $answer = Answer::model()->findBySql($sql); return $answer; }
public function actionCheckAnswer() { $transaction = Yii::app()->db->beginTransaction(); try { $ac_models = new AnswerComments(); $ac_models->message = $_POST['CommentForm']['message']; $ac_models->answer_id = $_POST['CommentForm']['comment_id']; $ac_models->uid = Yii::app()->user->id; $ac_models->time = time(); if (!$ac_models->save()) { throw new Exception('评论失败'); } //在question中的 comment_count字段+1 if (!Answer::model()->updateByPk($ac_models->answer_id, array('comment_count' => new CDbExpression('comment_count+1')))) { throw new ErrorException('评论失败'); } $transaction->commit(); $this->redirect(Yii::app()->request->urlReferrer); //$this->success('评论成功'); } catch (Exception $e) { $transaction->rollBack(); //exit($e->getMessage()); $this->error($e->getMessage()); } }
public function actionBatchDelete() { if (Yii::app()->user->checkAccess('deleteFeedback') == false) { throw new CHttpException(403); } $idList = Yii::app()->request->getPost('id', array()); if (count($idList) > 0) { $criteria = new CDbCriteria(); $criteria->addInCondition('id', $idList); $feedbacks = Feedback::model()->findAll($criteria); $flag = 0; foreach ($feedbacks as $feedback) { if ($feedback->delete()) { $answer = Answer::model()->deleteAll('feedback_id=:feedbackID', array(':feedbackID' => $feedback->primaryKey)); $flag++; } } if ($flag > 0) { $this->setFlashMessage('问题咨询 已成功删除'); } else { $this->setFlashMessage('问题咨询 删除失败', 'warn'); } } else { $this->setFlashMessage('没有记录被选中', 'warn'); } $this->redirect(array('index')); }
public function getStatusText() { $id = $this->id; $answer = Answer::model()->find('feedback_id=:feedbackID', array(':feedbackID' => $id)); if ($this->is_reply == 0) { return '<font color="blue">未回复</font> <a href="index.php?r=answer/reply&feedbackid=' . $id . '">回复</a>'; } else { if ($this->is_reply == 1) { return '<font color="green">已回复</font> <a href="index.php?r=answer/view&id=' . $answer->primaryKey . '">查看回复</a>'; } } }
/** * 计算用户在本小组内回答问题的次数 * Enter description here ... * @param unknown_type $userId */ public function getUserAnswerCount($userId) { $group = $this->getOwner(); $answerCount = 0; foreach ($group->testQuestions as $question) { $answer = Answer::model()->findByAttributes(array('userId' => $userId, 'questionid' => $question->id)); if ($answer) { $answerCount++; } } return $answerCount; }
public function actionOwnerAns($uid) { if (Yii::app()->user->isGuest) { Yii::app()->user->loginRequired(); } else { $cri = new CDbCriteria(); $cri->with = array('question'); $cri->addCondition('t.userId=' . $uid); $cri->order = 'time DESC'; $viewModel = Answer::model()->findAll($cri); $myLike = LikeAns::model()->findAll('userId=:uid', array(':uid' => Yii::app()->user->id)); $this->render('ownerAns', array('viewModel' => $viewModel, 'uid' => $uid, 'myLike' => $myLike)); } }
/** * On rebuild of the search index, rebuild all user records * * @param type $event */ public static function onSearchRebuild($event) { foreach (Question::model()->findAll() as $obj) { HSearch::getInstance()->addModel($obj); print "q"; } foreach (Tag::model()->findAll() as $obj) { HSearch::getInstance()->addModel($obj); print "t"; } foreach (Answer::model()->findAll() as $obj) { HSearch::getInstance()->addModel($obj); print "a"; } foreach (Comment::model()->findAll() as $obj) { HSearch::getInstance()->addModel($obj); print "c"; } }
/** * 为帖子投票 * Enter description here ... * @param unknown_type $postid * @param unknown_type $value */ public function actionAnswer($answerid, $value = 0) { //$vote = new PostVote; $vote = AnswerVote::model()->findByAttributes(array('userId' => Yii::app()->user->id, 'answerid' => $answerid)); $answer = Answer::model()->with('question')->findByPk($answerid); if ($vote && $vote->value == $value) { //再点击赞同(反对),即取消第一次投的赞同(反对) $result = $vote->delete(); } else { //赞同(反对)被第一次点击 $vote or $vote = new AnswerVote(); $vote->answerid = $answerid; $vote->value = $value; $vote->userId = Yii::app()->user->id; $vote->addTime = time(); $result = $vote->save(); //发送系统通知给回答主人 if ($answer->userId != $vote->userId) { $notice = new Notice(); $notice->type = 'vote_answer'; $notice->setData(array('voteId' => $vote->getPrimaryKey())); $notice->userId = $answer->userId; $notice->save(); } } if ($result) { // $question = Question::model()->findByPk($answer->question) //修改答案投票次数统计 $answer->voteupNum = $answer->voteupCount; $answer->count_votedown = $answer->votedownCount; $answer->save(); //修改问题投票次数统计 $answer->question->updateVoteCount(); //修改用户被赞数量 $user = UserInfo::model()->findByPk($answer->userId); $user->answerVoteupNum = $user->getAnswerVoteupCount(); $user->save(); $score = $answer->voteupCount - $answer->votedownCount; $this->renderPartial('result', array('score' => $score, 'voteupers' => $answer->voteupers)); } }
public function actionGetAll() { $session_id = Yii::app()->request->getPost("session_id", NULL); $session = Session::model()->find('session_id=:session_id', array(':session_id' => $session_id)); $session_listenings = SessionListening::model()->findAll('session_id=:session_id', array(':session_id' => $session_id)); $all = array(); $all["session_id"] = $session->session_id; $all["session_name"] = $session->session_name; $all["session_order"] = $session->session_order; $all["mod_id"] = $session->mod_id; $all["listenings"] = array(); foreach ($session_listenings as $key => $session_listening) { $temp_listening_id = $session_listening->listening_id; $listening = Listening::model()->find('listening_id=:listening_id', array(':listening_id' => $temp_listening_id)); $all["listenings"][$key] = array('listening_id' => $listening->listening_id, 'listening_name' => $listening->listening_name, 'listening_repeat_number' => $listening->listening_repeat_number, 'listening_learning_guide_availability' => $listening->listening_learning_guide_availability); $criteria = new CDbCriteria(); $criteria->addCondition("listening_id=:listening_id"); $criteria->order = 'RAND()'; $criteria->params = array(':listening_id' => $listening->listening_id); $questions = Question::model()->findAll($criteria); //$questions=Question::model()->findAll('listening_id=:listening_id',array('listening_id'=>$listening->listening_id)); foreach ($questions as $key2 => $question) { $all["listenings"][$key]['questions'][$key2] = array('question_id' => $question->question_id, 'question_body' => $question->question_body, 'question_correct_answer_id' => $question->question_correct_answer_id); $criteria = new CDbCriteria(); $criteria->addCondition("question_id=:question_id"); $criteria->order = 'RAND()'; $criteria->params = array(':question_id' => $question->question_id); $answers = Answer::model()->findAll($criteria); //$answers=Answer::model()->findAll('question_id=:question_id',array(':question_id'=>$question->question_id)); foreach ($answers as $key3 => $answer) { $all["listenings"][$key]['questions'][$key2]['answers'][$key3] = array('answer_id' => $answer->answer_id, 'answer_body' => $answer->answer_body); } } } $this->renderJSON($all); }
if(isset($dualscaleheaderb) && $dualscaleheaderb != "") { $labeltitle2 = $dualscaleheaderb; } else { //get label text $labeltitle2 = ''; } echo " /> <strong>" ._showSpeaker($niceqtext." [".str_replace("'", "`", $row[1])."] - ".gT("Label").": ".$labeltitle2) ."</strong><br />\n"; $fresult = Answer::model()->getQuestionsForStatistics('*', "qid='$flt[0]' AND language = '$language' AND scale_id = 1", 'sortorder, code'); //this is for debugging only //echo $fquery; echo "\t<select name='{$surveyid}X{$flt[1]}X{$flt[0]}{$row[0]}#{1}[]' multiple='multiple' class='form-control'>\n"; //list answers foreach($fresult as $frow) { echo "\t<option value='{$frow['code']}'"; //pre-check if (isset($_POST[$myfield2]) && is_array($_POST[$myfield2]) && in_array($frow['code'], $_POST[$myfield2])) {echo " selected";} echo ">({$frow['code']}) ".flattenText($frow['answer'],true)."</option>\n";
/** * 修改被点赞的人员 */ public function afterSave() { parent::afterSave(); $to_user = ""; if ($this->model == "answer") { $to_user = Answer::model()->findByPk($this->pk_id)->create_user; } else { if ($this->model == "article") { $to_user = Article::model()->findByPk($this->pk_id)->create_user; } else { if ($this->model == "question") { $to_user = Question::model()->findByPk($this->pk_id)->create_user; } } } if ($to_user != "") { Vote::model()->updateByPk($this->id, array("to_user" => $to_user)); } }
function do_array($ia) { global $thissurvey; $aLastMoveResult = LimeExpressionManager::GetLastMoveResult(); $aMandatoryViolationSubQ = $aLastMoveResult['mandViolation'] && $ia[6] == 'Y' ? explode("|", $aLastMoveResult['unansweredSQs']) : array(); $repeatheadings = Yii::app()->getConfig("repeatheadings"); $minrepeatheadings = Yii::app()->getConfig("minrepeatheadings"); $extraclass = ""; $caption = ""; // Just leave empty, are replaced after $checkconditionFunction = "checkconditions"; $qquery = "SELECT other FROM {{questions}} WHERE qid={$ia[0]} AND language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "'"; $other = Yii::app()->db->createCommand($qquery)->queryScalar(); //Checked $aQuestionAttributes = getQuestionAttributeValues($ia[0]); if (trim($aQuestionAttributes['answer_width']) != '') { $answerwidth = $aQuestionAttributes['answer_width']; } else { $answerwidth = 20; } $columnswidth = 100 - $answerwidth; if ($aQuestionAttributes['use_dropdown'] == 1) { $useDropdownLayout = true; $extraclass .= " dropdown-list"; $caption = gT("An array with sub-question on each line. You have to select your answer."); } else { $useDropdownLayout = false; $caption = gT("An array with sub-question on each line. The answers are contained in the table header. "); } if (ctype_digit(trim($aQuestionAttributes['repeat_headings'])) && trim($aQuestionAttributes['repeat_headings'] != "")) { $repeatheadings = intval($aQuestionAttributes['repeat_headings']); $minrepeatheadings = 0; } $lresult = Answer::model()->findAll(array('order' => 'sortorder, code', 'condition' => 'qid=:qid AND language=:language AND scale_id=0', 'params' => array(':qid' => $ia[0], ':language' => $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']))); $labelans = array(); $labelcode = array(); foreach ($lresult as $lrow) { $labelans[] = $lrow->answer; $labelcode[] = $lrow->code; } if ($useDropdownLayout === false && count($lresult) > 0) { $sQuery = "SELECT count(qid) FROM {{questions}} WHERE parent_qid={$ia[0]} AND question like '%|%' "; $iCount = Yii::app()->db->createCommand($sQuery)->queryScalar(); if ($iCount > 0) { $right_exists = true; $answerwidth = $answerwidth / 2; } else { $right_exists = false; } // $right_exists is a flag to find out if there are any right hand answer parts. If there arent we can leave out the right td column if ($aQuestionAttributes['random_order'] == 1) { $ansquery = "SELECT * FROM {{questions}} WHERE parent_qid={$ia[0]} AND language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "' ORDER BY " . dbRandom(); } else { $ansquery = "SELECT * FROM {{questions}} WHERE parent_qid={$ia[0]} AND language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "' ORDER BY question_order"; } $ansresult = dbExecuteAssoc($ansquery); //Checked $aQuestions = $ansresult->readAll(); $anscount = count($aQuestions); $fn = 1; $numrows = count($labelans); if ($right_exists) { ++$numrows; $caption .= gT("After answers, a cell give some information. "); } if ($ia[6] != 'Y' && SHOW_NO_ANSWER == 1) { ++$numrows; $caption .= gT("The last cell are for no answer. "); } $cellwidth = round($columnswidth / $numrows, 1); $answer_start = "\n<table class=\"question subquestions-list questions-list {$extraclass}\" summary=\"{$caption}\">\n"; $answer_head_line = "\t<td> </td>\n"; foreach ($labelans as $ld) { $answer_head_line .= "\t<th>" . $ld . "</th>\n"; } if ($right_exists) { $answer_head_line .= "\t<td> </td>\n"; } if ($ia[6] != 'Y' && SHOW_NO_ANSWER == 1) { $answer_head_line .= "\t<th>" . gT('No answer') . "</th>\n"; } $answer_head = "\t<thead><tr class=\"dontread\">\n" . $answer_head_line . "</tr></thead>\n\t\n"; $answer = '<tbody>'; $trbc = ''; $inputnames = array(); foreach ($aQuestions as $ansrow) { if (isset($repeatheadings) && $repeatheadings > 0 && $fn - 1 > 0 && ($fn - 1) % $repeatheadings == 0) { if ($anscount - $fn + 1 >= $minrepeatheadings) { $answer .= "</tbody>\n<tbody>"; // Close actual body and open another one $answer .= "<tr class=\"dontread repeat headings\">{$answer_head_line}</tr>"; } } $myfname = $ia[1] . $ansrow['title']; $answertext = $ansrow['question']; $answertextsave = $answertext; if (strpos($answertext, '|')) { $answertext = substr($answertext, 0, strpos($answertext, '|')); } if (strpos($answertext, '|')) { $answerwidth = $answerwidth / 2; } /* Check the mandatory sub Q violation */ if (in_array($myfname, $aMandatoryViolationSubQ)) { $answertext = '<span class="errormandatory">' . $answertext . '</span>'; } // Get array_filter stuff // // TMSW - is this correct? $trbc = alternation($trbc, 'row'); list($htmltbody2, $hiddenfield) = return_array_filter_strings($ia, $aQuestionAttributes, $thissurvey, $ansrow, $myfname, $trbc, $myfname, "tr", "{$trbc} answers-list radio-list"); $fn++; $answer .= $htmltbody2; $answer .= "\t<th class=\"answertext\">\n{$answertext}" . $hiddenfield . "<input type=\"hidden\" name=\"java{$myfname}\" id=\"java{$myfname}\" value=\""; if (isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname])) { $answer .= $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname]; } $answer .= "\" />\n\t</th>\n"; $thiskey = 0; foreach ($labelcode as $ld) { $answer .= "\t\t\t<td class=\"answer_cell_00{$ld} answer-item radio-item\">\n" . "\t<input class=\"radio\" type=\"radio\" name=\"{$myfname}\" value=\"{$ld}\" id=\"answer{$myfname}-{$ld}\""; if (isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname]) && $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname] == $ld) { $answer .= CHECKED; } // --> START NEW FEATURE - SAVE $answer .= " onclick=\"{$checkconditionFunction}(this.value, this.name, this.type)\" />\n" . "<label class=\"hide read\" for=\"answer{$myfname}-{$ld}\">{$labelans[$thiskey]}</label>\n" . "\t</td>\n"; // --> END NEW FEATURE - SAVE $thiskey++; } if (strpos($answertextsave, '|')) { $answertext = substr($answertextsave, strpos($answertextsave, '|') + 1); $answer .= "\t<th class=\"answertextright\">{$answertext}</th>\n"; } elseif ($right_exists) { $answer .= "\t<td class=\"answertextright\"> </td>\n"; } if ($ia[6] != 'Y' && SHOW_NO_ANSWER == 1) { $answer .= "\t<td class=\"answer-item radio-item noanswer-item\">\n" . "\t<input class=\"radio\" type=\"radio\" name=\"{$myfname}\" value=\"\" id=\"answer{$myfname}-\" "; if (!isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname]) || $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname] == '') { $answer .= CHECKED; } // --> START NEW FEATURE - SAVE $answer .= " onclick=\"{$checkconditionFunction}(this.value, this.name, this.type)\" />\n" . "<label class=\"hide read\" for=\"answer{$myfname}-\">" . gT('No answer') . "</label>\n" . "\t</td>\n"; // --> END NEW FEATURE - SAVE } $answer .= "</tr>\n"; $inputnames[] = $myfname; //IF a MULTIPLE of flexi-redisplay figure, repeat the headings } $answer .= "</tbody>\n"; $answer_cols = "\t<colgroup class=\"col-responses\">\n" . "\t<col class=\"col-answers\" width=\"{$answerwidth}%\" />\n"; $odd_even = ''; foreach ($labelans as $c) { $odd_even = alternation($odd_even); $answer_cols .= "<col class=\"{$odd_even}\" width=\"{$cellwidth}%\" />\n"; } if ($right_exists) { $odd_even = alternation($odd_even); $answer_cols .= "<col class=\"answertextright {$odd_even}\" width=\"{$answerwidth}%\" />\n"; } if ($ia[6] != 'Y' && SHOW_NO_ANSWER == 1) { $odd_even = alternation($odd_even); $answer_cols .= "<col class=\"col-no-answer {$odd_even}\" width=\"{$cellwidth}%\" />\n"; } $answer_cols .= "\t</colgroup>\n"; $answer = $answer_start . $answer_cols . $answer_head . $answer . "</table>\n"; } elseif ($useDropdownLayout === true && count($lresult) > 0) { foreach ($lresult as $lrow) { $labels[] = array('code' => $lrow->code, 'answer' => $lrow->answer); } $sQuery = "SELECT count(question) FROM {{questions}} WHERE parent_qid={$ia[0]} AND question like '%|%' "; $iCount = Yii::app()->db->createCommand($sQuery)->queryScalar(); if ($iCount > 0) { $right_exists = true; $answerwidth = $answerwidth / 2; } else { $right_exists = false; } // $right_exists is a flag to find out if there are any right hand answer parts. If there arent we can leave out the right td column if ($aQuestionAttributes['random_order'] == 1) { $ansquery = "SELECT * FROM {{questions}} WHERE parent_qid={$ia[0]} AND language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "' ORDER BY " . dbRandom(); } else { $ansquery = "SELECT * FROM {{questions}} WHERE parent_qid={$ia[0]} AND language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "' ORDER BY question_order"; } $ansresult = dbExecuteAssoc($ansquery); //Checked $aQuestions = $ansresult->readAll(); $anscount = count($aQuestions); $fn = 1; $numrows = count($labels); if ($ia[6] != 'Y' && SHOW_NO_ANSWER == 1) { ++$numrows; } if ($right_exists) { ++$numrows; } $cellwidth = round($columnswidth / $numrows, 1); $answer_start = "\n<table class=\"question subquestions-list questions-list {$extraclass}\" summary=\"{$caption}\" >\n"; $answer = "\t<tbody>\n"; $trbc = ''; $inputnames = array(); foreach ($aQuestions as $ansrow) { $myfname = $ia[1] . $ansrow['title']; $trbc = alternation($trbc, 'row'); $answertext = $ansrow['question']; $answertextsave = $answertext; if (strpos($answertext, '|')) { $answertext = substr($answertext, 0, strpos($answertext, '|')); } if (strpos($answertext, '|')) { $answerwidth = $answerwidth / 2; } if ($ia[6] == 'Y' && in_array($myfname, $aMandatoryViolationSubQ)) { $answertext = '<span class="errormandatory">' . $answertext . '</span>'; } // Get array_filter stuff list($htmltbody2, $hiddenfield) = return_array_filter_strings($ia, $aQuestionAttributes, $thissurvey, $ansrow, $myfname, $trbc, $myfname, "tr", "{$trbc} question-item answer-item dropdown-item"); $answer .= $htmltbody2; $answer .= "\t<th class=\"answertext\">\n<label for=\"answer{$myfname}\">{$answertext}</label>" . $hiddenfield . "<input type=\"hidden\" name=\"java{$myfname}\" id=\"java{$myfname}\" value=\""; if (isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname])) { $answer .= $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname]; } $answer .= "\" />\n\t</th>\n"; $answer .= "\t<td >\n" . "<select name=\"{$myfname}\" id=\"answer{$myfname}\" onchange=\"{$checkconditionFunction}(this.value, this.name, this.type);\">\n"; // Dropdown representation is en exception - even if mandatory or SHOW_NO_ANSWER is disable a neutral option needs to be shown where the mandatory case asks actively if ($ia[6] != 'Y' && SHOW_NO_ANSWER == 1) { $sOptionText = gT('No answer'); } else { $sOptionText = gT('Please choose...'); } $answer .= "\t<option value=\"\" "; if (!isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname]) || $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname] == '') { $answer .= SELECTED; } $answer .= '>' . $sOptionText . "</option>\n"; foreach ($labels as $lrow) { $answer .= "\t<option value=\"" . $lrow['code'] . '" '; if (isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname]) && $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname] == $lrow['code']) { $answer .= SELECTED; } $answer .= '>' . flattenText($lrow['answer']) . "</option>\n"; } $answer .= "</select>\n"; if (strpos($answertextsave, '|')) { $answertext = substr($answertextsave, strpos($answertextsave, '|') + 1); $answer .= "\t<th class=\"answertextright\">{$answertext}</th>\n"; } elseif ($right_exists) { $answer .= "\t<td class=\"answertextright\"> </td>\n"; } $answer .= "</tr>\n"; $inputnames[] = $myfname; //IF a MULTIPLE of flexi-redisplay figure, repeat the headings $fn++; } $answer .= "\t</tbody>"; $answer = $answer_start . $answer . "\n</table>\n"; } else { $answer = "\n<p class=\"error\">" . gT("Error: There are no answer options for this question and/or they don't exist in this language.") . "</p>\n"; $inputnames = ''; } return array($answer, $inputnames); }
public function actioncancelnotanonymous() { $answer_id = $_POST["answer_id"]; $answerModel = Answer::model()->findByPk($answer_id); $return = array(); $return['message'] = "false"; if ($answerModel == NULL) { $tip = '没有此答案!'; } else { if (Yii::app()->user->isGuest) { $tip = '回答问题前,请先登录!'; } else { if ($answerModel->create_user != Yii::app()->user->id) { $tip = '你没有修改权限!'; } else { $answerModel->is_anonymous = 0; $return['message'] = $answerModel->save() ? "ok" : "false"; $tip = $return['message'] == "ok" ? '修改成功!' : '修改失败!'; } } } $return['tip'] = $tip; echo json_encode($return); }
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); Condition::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(array('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 = Condition::model()->findAllByAttributes($condition_data); $count_caseinsensitivedupes = count($result); if ($count_caseinsensitivedupes == 0) { $result = Condition::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 = Condition::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 = Condition::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 = Condition::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 = Condition::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 = Condition::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 = Condition::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 = Condition::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 = Condition::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 = Condition::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 = Condition::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("Condition successfully copied (some were skipped because they were duplicates)") . ')'); } else { $CopyConditionsMessage = CHtml::tag('div', array('class' => 'successheader'), '(' . $clang->gT("Condition 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 = Question::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 = Question::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 = Question::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 = Question::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 = Question::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 = Answer::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=:lang1" . " AND sq.language=:lang2" . " 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(":lang1", $sLanguage, PDO::PARAM_STR)->bindParam(":lang2", $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=:lang1\n AND sq.language=:lang2\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(":lang1", $sLanguage, PDO::PARAM_STR)->bindParam(":lang2", $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 = Question::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 = Answer::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 = Answer::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 = Question::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 = Answer::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 = Question::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 = Answer::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']}")), strip_tags($row['title']) . ':' . $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']}")), strip_tags($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 $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 = Condition::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) { App()->getClientScript()->registerScriptFile(Yii::app()->getConfig("adminscripts") . '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> </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()->renderPartial('/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> </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()->renderPartial('/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(), ' ') . 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 App()->getClientScript()->registerScriptFile(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} " . $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("Answer 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://manual.limesurvey.org/wiki/Using_regular_expressions\" target=\"_blank\">" . $clang->gT("Regular expression") . "</a></div>\n" . "\t</div>\n"; $aViewUrls['output'] .= "</div>\n"; // end conditiontarget div App()->getClientScript()->registerScriptFile(Yii::app()->getConfig("adminscripts") . 'conditions.js'); //App()->getClientScript()->registerScriptFile(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 Condition->Relevance: Must call LEM->ConvertConditionsToRelevance() whenever Condition is added or updated - what is best location for that action? }
function do_array($ia) { global $thissurvey; $aLastMoveResult = LimeExpressionManager::GetLastMoveResult(); $aMandatoryViolationSubQ = $aLastMoveResult['mandViolation'] && $ia[6] == 'Y' ? explode("|", $aLastMoveResult['unansweredSQs']) : array(); $repeatheadings = Yii::app()->getConfig("repeatheadings"); $minrepeatheadings = Yii::app()->getConfig("minrepeatheadings"); $extraclass = ""; $caption = ""; // Just leave empty, are replaced after $checkconditionFunction = "checkconditions"; $qquery = "SELECT other FROM {{questions}} WHERE qid={$ia[0]} AND language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "'"; $other = Yii::app()->db->createCommand($qquery)->queryScalar(); //Checked $aQuestionAttributes = QuestionAttribute::model()->getQuestionAttributes($ia[0]); if ($aQuestionAttributes['use_dropdown'] == 1) { $useDropdownLayout = true; $extraclass .= " dropdown-list"; $caption = gT("A table with a subquestion on each row. You have to select your answer."); } else { $useDropdownLayout = false; $caption = gT("A table with a subquestion on each row. The answer options are contained in the table header."); } if (ctype_digit(trim($aQuestionAttributes['repeat_headings'])) && trim($aQuestionAttributes['repeat_headings'] != "")) { $repeatheadings = intval($aQuestionAttributes['repeat_headings']); $minrepeatheadings = 0; } $lresult = Answer::model()->findAll(array('order' => 'sortorder, code', 'condition' => 'qid=:qid AND language=:language AND scale_id=0', 'params' => array(':qid' => $ia[0], ':language' => $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']))); $labelans = array(); $labelcode = array(); foreach ($lresult as $lrow) { $labelans[] = $lrow->answer; $labelcode[] = $lrow->code; } // No-dropdown layout if ($useDropdownLayout === false && count($lresult) > 0) { $answerwidth = trim($aQuestionAttributes['answer_width']) != '' ? $aQuestionAttributes['answer_width'] : 20; $columnswidth = 100 - $answerwidth; $sQuery = "SELECT count(qid) FROM {{questions}} WHERE parent_qid={$ia[0]} AND question like '%|%' "; $iCount = Yii::app()->db->createCommand($sQuery)->queryScalar(); if ($iCount > 0) { $right_exists = true; $answerwidth = $answerwidth / 2; } else { $right_exists = false; } // $right_exists is a flag to find out if there are any right hand answer parts. If there arent we can leave out the right td column if ($aQuestionAttributes['random_order'] == 1) { $ansquery = "SELECT * FROM {{questions}} WHERE parent_qid={$ia[0]} AND language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "' ORDER BY " . dbRandom(); } else { $ansquery = "SELECT * FROM {{questions}} WHERE parent_qid={$ia[0]} AND language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "' ORDER BY question_order"; } $ansresult = dbExecuteAssoc($ansquery); //Checked $aQuestions = $ansresult->readAll(); $anscount = count($aQuestions); $fn = 1; $numrows = count($labelans); if ($right_exists) { ++$numrows; $caption .= gT("After the answer options a cell does give some information."); } if ($ia[6] != 'Y' && SHOW_NO_ANSWER == 1) { ++$numrows; $caption .= gT("The last cell is for 'No answer'."); } $cellwidth = round($columnswidth / $numrows, 1); $sHeaders = doRender('/survey/questions/arrays/array/no_dropdown/rows/cells/thead', array('class' => '', 'content' => ' '), true); foreach ($labelans as $ld) { $sHeaders .= doRender('/survey/questions/arrays/array/no_dropdown/rows/cells/thead', array('class' => 'th-9', 'content' => $ld), true); } if ($right_exists) { $sHeaders .= doRender('/survey/questions/arrays/array/no_dropdown/rows/cells/thead', array('class' => '', 'content' => ' '), true); } if ($ia[6] != 'Y' && SHOW_NO_ANSWER == 1) { $sHeaders .= doRender('/survey/questions/arrays/array/no_dropdown/rows/cells/thead', array('class' => 'th-10', 'content' => gT('No answer')), true); } $answer = ''; $trbc = ''; $inputnames = array(); $sRows = ''; foreach ($aQuestions as $i => $ansrow) { if (isset($repeatheadings) && $repeatheadings > 0 && $fn - 1 > 0 && ($fn - 1) % $repeatheadings == 0) { if ($anscount - $fn + 1 >= $minrepeatheadings) { // Close actual body and open another one $sRows .= doRender('/survey/questions/arrays/array/no_dropdown/rows/repeat_header', array('sHeaders' => $sHeaders), true); } } $myfname = $ia[1] . $ansrow['title']; $answertext = $ansrow['question']; $answertext = strpos($answertext, '|') !== false ? substr($answertext, 0, strpos($answertext, '|')) : $answertext; $answertextsave = $answertext; if ($right_exists && strpos($ansrow['question'], '|') !== false) { $answertextright = substr($ansrow['question'], strpos($ansrow['question'], '|') + 1); } else { $answertextright = null; } $error = in_array($myfname, $aMandatoryViolationSubQ) ? true : false; /* Check the mandatory sub Q violation */ $value = isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname]) ? $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname] : ''; $sDisplayStyle = return_display_style($ia, $aQuestionAttributes, $thissurvey, $myfname); $thiskey = 0; $answer_tds = ''; $fn++; foreach ($labelcode as $ld) { $CHECKED = isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname]) && $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname] == $ld ? 'CHECKED' : ''; $answer_tds .= doRender('/survey/questions/arrays/array/no_dropdown/rows/cells/answer_td', array('myfname' => $myfname, 'ld' => $ld, 'label' => $labelans[$thiskey], 'CHECKED' => $CHECKED, 'checkconditionFunction' => $checkconditionFunction), true); $thiskey++; } /* if (strpos($answertextsave,'|')) { $answertext = substr($answertextsave,strpos($answertextsave,'|')+1); $sHeaders .= doRender('/survey/questions/arrays/array/no_dropdown/rows/cells/thead', array( 'class' => 'answertextright', 'content' => $answertext, ), true); } elseif ($right_exists) { $sHeaders .= doRender('/survey/questions/arrays/array/no_dropdown/rows/cells/thead', array( 'class' => 'answertextright', 'content' => ' ', ), true); } */ // NB: $ia[6] = mandatory $no_answer_td = ''; if ($ia[6] != 'Y' && SHOW_NO_ANSWER == 1) { $CHECKED = !isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname]) || $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname] == '' ? 'CHECKED' : ''; $no_answer_td .= doRender('/survey/questions/arrays/array/no_dropdown/rows/cells/answer_td', array('myfname' => $myfname, 'ld' => '', 'label' => gT('No answer'), 'CHECKED' => $CHECKED, 'checkconditionFunction' => $checkconditionFunction), true); } $sRows .= doRender('/survey/questions/arrays/array/no_dropdown/rows/answer_row', array('answer_tds' => $answer_tds, 'no_answer_td' => $no_answer_td, 'myfname' => $myfname, 'answertext' => $answertext, 'answertextright' => $right_exists ? $answertextright : null, 'right_exists' => $right_exists, 'value' => $value, 'error' => $error, 'zebra' => 2 - $i % 2), true); $inputnames[] = $myfname; } $odd_even = ''; $sColumns = ''; foreach ($labelans as $c) { $odd_even = alternation($odd_even); $sColumns .= doRender('/survey/questions/arrays/array/no_dropdown/columns/col', array('class' => $odd_even, 'cellwidth' => $cellwidth), true); } if ($right_exists) { $odd_even = alternation($odd_even); $sColumns .= doRender('/survey/questions/arrays/array/no_dropdown/columns/col', array('class' => 'answertextright ' . $odd_even, 'cellwidth' => $answerwidth), true); } if ($ia[6] != 'Y' && SHOW_NO_ANSWER == 1) { $odd_even = alternation($odd_even); $sColumns .= doRender('/survey/questions/arrays/array/no_dropdown/columns/col', array('class' => 'col-no-answer ' . $odd_even, 'cellwidth' => $cellwidth), true); } $answer = doRender('/survey/questions/arrays/array/no_dropdown/answer', array('answerwidth' => $answerwidth, 'anscount' => $anscount, 'sRows' => $sRows, 'extraclass' => $extraclass, 'sHeaders' => $sHeaders, 'sColumns' => $sColumns), true); } elseif ($useDropdownLayout === true && count($lresult) > 0) { $answerwidth = trim($aQuestionAttributes['answer_width']) != '' ? $aQuestionAttributes['answer_width'] : 50; $columnswidth = 100 - $answerwidth; foreach ($lresult as $lrow) { $labels[] = array('code' => $lrow->code, 'answer' => $lrow->answer); } $sQuery = "SELECT count(question) FROM {{questions}} WHERE parent_qid={$ia[0]} AND question like '%|%' "; $iCount = Yii::app()->db->createCommand($sQuery)->queryScalar(); if ($iCount > 0) { $right_exists = true; $answerwidth = $answerwidth / 2; } else { $right_exists = false; } // $right_exists is a flag to find out if there are any right hand answer parts. If there arent we can leave out the right td column if ($aQuestionAttributes['random_order'] == 1) { $ansquery = "SELECT * FROM {{questions}} WHERE parent_qid={$ia[0]} AND language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "' ORDER BY " . dbRandom(); } else { $ansquery = "SELECT * FROM {{questions}} WHERE parent_qid={$ia[0]} AND language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "' ORDER BY question_order"; } $ansresult = dbExecuteAssoc($ansquery); //Checked $aQuestions = $ansresult->readAll(); $anscount = count($aQuestions); $fn = 1; $trbc = ''; $inputnames = array(); $sRows = ""; foreach ($aQuestions as $j => $ansrow) { $myfname = $ia[1] . $ansrow['title']; $answertext = $ansrow['question']; $answertext = strpos($answertext, '|') !== false ? substr($answertext, 0, strpos($answertext, '|')) : $answertext; $error = in_array($myfname, $aMandatoryViolationSubQ) ? true : false; /* Check the mandatory sub Q violation */ $value = isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname]) ? $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname] : ''; $sDisplayStyle = return_display_style($ia, $aQuestionAttributes, $thissurvey, $myfname); if ($right_exists && strpos($ansrow['question'], '|') !== false) { $answertextright = substr($ansrow['question'], strpos($ansrow['question'], '|') + 1); } else { $answertextright = null; } $options = array(); /* Dropdown representation : first choice (activated) must be Please choose... if there are no actual answer */ $showNoAnswer = $ia[6] != 'Y' && SHOW_NO_ANSWER == 1; // Tag if we must show no-answer if (!isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname]) || $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname] === '') { $options[] = array('text' => gT('Please choose...'), 'value' => '', 'selected' => ''); $showNoAnswer = false; } // Real options foreach ($labels as $i => $lrow) { $options[] = array('value' => $lrow['code'], 'selected' => $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname] == $lrow['code'] ? SELECTED : '', 'text' => flattenText($lrow['answer'])); } /* Add the now answer if needed */ if ($showNoAnswer) { $options[] = array('text' => gT('No answer'), 'value' => '', 'selected' => $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname] === '' ? SELECTED : ''); } unset($showNoAnswer); $sRows .= doRender('/survey/questions/arrays/array/dropdown/rows/answer_row', array('myfname' => $myfname, 'answertext' => $answertext, 'value' => $value, 'error' => $error, 'checkconditionFunction' => $checkconditionFunction, 'right_exists' => $right_exists, 'answertextright' => $answertextright, 'options' => $options, 'zebra' => 2 - $j % 2), true); $inputnames[] = $myfname; $fn++; } $answer = doRender('/survey/questions/arrays/array/dropdown/answer', array('extraclass' => $extraclass, 'sRows' => $sRows, 'answerwidth' => $answerwidth, 'columnswidth' => $columnswidth, 'right_exists' => $right_exists), true); } else { $answer = doRender('/survey/questions/arrays/array/dropdown/empty', array(), true); $inputnames = ''; } return array($answer, $inputnames); }
/** * 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 App()->getClientScript()->registerScriptFile(Yii::app()->getConfig('adminscripts') . 'statistics.js'); App()->getClientScript()->registerScriptFile(Yii::app()->getConfig('adminscripts') . 'json-js/json2.min.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 = Question::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() == "complete") { $selecthide = "selected='selected'"; $selectshow = ""; $selectinc = ""; } elseif (incompleteAnsFilterState() == "incomplete") { $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 = Question::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 = Question::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 = Question::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 = Question::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 = Question::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 = Question::model()->getQuestionsForStatistics('title, question', "parent_qid={$flt['0']} AND language = '{$language}'", 'question_order'); $aData['result'][$key1] = $result; break; case ";": //ARRAY (Multi Flex) (Text) $result = Question::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 = Question::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 = Question::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 = Question::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 = Question::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 = Answer::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 = Answer::model()->getQuestionsForStatistics('code, answer', "qid={$flt['0']} AND language = '{$language}'", 'sortorder, answer'); $aData['result'][$key1] = $result; break; case "1": // MULTI SCALE //get answers $result = Question::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 = QuestionAttribute::model()->getQuestionsForStatistics('value', "qid={$flt['0']} AND attribute = 'dualscale_headerA'", ''); $aData['dshresults'][$key1][$key] = $dshresult; $fresult = Answer::model()->getQuestionsForStatistics('*', "qid={$flt['0']} AND language = '{$language}' AND scale_id = 0", 'sortorder, code'); $aData['fresults'][$key1][$key] = $fresult; $dshresult2 = QuestionAttribute::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 = Question::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 = Answer::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']; $helper = new statistics_helper(); switch ($outputType) { case 'html': $statisticsoutput .= $helper->generate_statistics($surveyid, $summary, $summary, $usegraph, $outputType, 'DD', $statlang); break; case 'pdf': $helper->generate_statistics($surveyid, $summary, $summary, $usegraph, $outputType, 'I', $statlang); exit; break; case 'xls': $helper->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); }
public static function deleteAllById($questionsIds) { if (!is_array($questionsIds)) { $questionsIds = array($questionsIds); } Yii::app()->db->createCommand()->delete(Condition::model()->tableName(), array('in', 'qid', $questionsIds)); Yii::app()->db->createCommand()->delete(QuestionAttribute::model()->tableName(), array('in', 'qid', $questionsIds)); Yii::app()->db->createCommand()->delete(Answer::model()->tableName(), array('in', 'qid', $questionsIds)); Yii::app()->db->createCommand()->delete(Question::model()->tableName(), array('in', 'parent_qid', $questionsIds)); Yii::app()->db->createCommand()->delete(Question::model()->tableName(), array('in', 'qid', $questionsIds)); Yii::app()->db->createCommand()->delete(DefaultValue::model()->tableName(), array('in', 'qid', $questionsIds)); Yii::app()->db->createCommand()->delete(QuotaMember::model()->tableName(), array('in', 'qid', $questionsIds)); }
<?php Yii::app()->clientScript->registerScript('searchView', "\n\$('#select-all').click(function(event) { \n if(this.checked) {\n // Iterate each checkbox\n \$(':checkbox').each(function() {\n this.checked = true; \n });\n } else {\n \$(':checkbox').each(function() {\n this.checked = false; \n });\n }\n})\n"); Yii::app()->clientScript->registerCss('checkBoxListColumn', "\n #filter input {\n float: left;\n margin-right: 10px;\n}\n.checkboxgroup{\n overflow:auto;\n}\n.checkboxgroup div{\n width:420px;\n float:left;\n} \n"); ?> <h1> Colonnes à exporter </h1> <br> <?php $form = $this->beginWidget('CActiveForm', array('action' => Yii::app()->createUrl($this->route))); ?> <label><input type="checkbox" name="select-all" id="select-all" />Sélectionner tout</label> <div class="checkboxgroup"> <?php $fiches = Answer::model()->getNomsFichesByFilter($models); foreach ($fiches as $key => $value) { echo "<h3>Fiche " . $value . "</h3>"; echo CHtml::checkBoxList('filter', 'addFilter', Answer::model()->getAllQuestionsByFilterName($models, $value), array('labelOptions' => array('style' => 'display:inline'), 'separator' => '', 'template' => '<div>{input} {label}</div><br>')); } ?> </div><br> <?php echo CHtml::submitButton('Exporter', array('name' => 'exporter', 'class' => 'btn btn-default')); $this->endWidget();
private function query($type, $action, $iSurveyID, $tolang, $baselang, $id1 = "", $id2 = "", $iScaleID = "", $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 SurveyLanguageSetting::model()->findAllByPk(array('surveyls_survey_id' => $iSurveyID, 'surveyls_language' => $baselang)); case 'group': case 'group_desc': return QuestionGroup::model()->findAllByAttributes(array('sid' => $iSurveyID, 'language' => $baselang), array('order' => 'gid')); case 'question': case 'question_help': return Question::model()->with('parents', 'groups')->findAllByAttributes(array('sid' => $iSurveyID, 'language' => $baselang, 'parent_qid' => 0), array('order' => 'groups.group_order, t.question_order, t.scale_id')); case 'subquestion': return Question::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 Answer::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 SurveyLanguageSetting::model()->updateByPk(array('surveyls_survey_id' => $iSurveyID, 'surveyls_language' => $tolang), array('surveyls_title' => $new)); case 'description': return SurveyLanguageSetting::model()->updateByPk(array('surveyls_survey_id' => $iSurveyID, 'surveyls_language' => $tolang), array('surveyls_description' => $new)); case 'welcome': return SurveyLanguageSetting::model()->updateByPk(array('surveyls_survey_id' => $iSurveyID, 'surveyls_language' => $tolang), array('surveyls_welcometext' => $new)); case 'end': return SurveyLanguageSetting::model()->updateByPk(array('surveyls_survey_id' => $iSurveyID, 'surveyls_language' => $tolang), array('surveyls_endtext' => $new)); case 'emailinvite': return SurveyLanguageSetting::model()->updateByPk(array('surveyls_survey_id' => $iSurveyID, 'surveyls_language' => $tolang), array('surveyls_email_invite_subj' => $new)); case 'emailinvitebody': return SurveyLanguageSetting::model()->updateByPk(array('surveyls_survey_id' => $iSurveyID, 'surveyls_language' => $tolang), array('surveyls_email_invite' => $new)); case 'emailreminder': return SurveyLanguageSetting::model()->updateByPk(array('surveyls_survey_id' => $iSurveyID, 'surveyls_language' => $tolang), array('surveyls_email_remind_subj' => $new)); case 'emailreminderbody': return SurveyLanguageSetting::model()->updateByPk(array('surveyls_survey_id' => $iSurveyID, 'surveyls_language' => $tolang), array('surveyls_email_remind' => $new)); case 'emailconfirmation': return SurveyLanguageSetting::model()->updateByPk(array('surveyls_survey_id' => $iSurveyID, 'surveyls_language' => $tolang), array('surveyls_email_confirm_subj' => $new)); case 'emailconfirmationbody': return SurveyLanguageSetting::model()->updateByPk(array('surveyls_survey_id' => $iSurveyID, 'surveyls_language' => $tolang), array('surveyls_email_confirm' => $new)); case 'emailregistration': return SurveyLanguageSetting::model()->updateByPk(array('surveyls_survey_id' => $iSurveyID, 'surveyls_language' => $tolang), array('surveyls_email_register_subj' => $new)); case 'emailregistrationbody': return SurveyLanguageSetting::model()->updateByPk(array('surveyls_survey_id' => $iSurveyID, 'surveyls_language' => $tolang), array('surveyls_email_register' => $new)); case 'email_confirm': return SurveyLanguageSetting::model()->updateByPk(array('surveyls_survey_id' => $iSurveyID, 'surveyls_language' => $tolang), array('surveyls_email_confirm_subject' => $new)); case 'email_confirmbody': return SurveyLanguageSetting::model()->updateByPk(array('surveyls_survey_id' => $iSurveyID, 'surveyls_language' => $tolang), array('surveyls_email_confirm' => $new)); case 'group': return QuestionGroup::model()->updateByPk(array('gid' => $id1, 'language' => $tolang), array('group_name' => $new), 'sid=:sid', array(':sid' => $iSurveyID)); case 'group_desc': return QuestionGroup::model()->updateByPk(array('gid' => $id1, 'language' => $tolang), array('description' => $new), 'sid=:sid', array(':sid' => $iSurveyID)); case 'question': return Question::model()->updateByPk(array('qid' => $id1, 'language' => $tolang), array('question' => $new), 'sid=:sid AND parent_qid=0', array(':sid' => $iSurveyID)); case 'question_help': return Question::model()->updateByPk(array('qid' => $id1, 'language' => $tolang), array('help' => $new), 'sid=:sid AND parent_qid=0', array(':sid' => $iSurveyID)); case 'subquestion': return Question::model()->updateByPk(array('qid' => $id1, 'language' => $tolang), array('question' => $new), 'sid=:sid', array(':sid' => $iSurveyID)); case 'answer': return Answer::model()->updateByPk(array('qid' => $id1, 'code' => $id2, 'language' => $tolang, 'scale_id' => $iScaleID), array('answer' => $new)); } } }
/** * 验证用户具体发帖权限,并不影响其他权限 * @param type $uid 验证的用户 * @param type $type 验证的类型 * @param type $field 是否检查总数 * @return type */ public static function check($type, $field = false, $uid = '') { if (!$uid) { $uid = Yii::app()->user->id; } if (!$uid) { if (zmf::config('officalUid')) { return array('status' => 1, 'msg' => ''); } return array('status' => 0, 'msg' => '用户不存在'); } $uinfo = Users::getUserInfo($uid); if (!$uinfo) { return array('status' => 0, 'msg' => '用户不存在'); } if (!$uinfo['groupid']) { return array('status' => 0, 'msg' => '无组织用户'); } $groupInfo = UserPower::model()->find('groupid=:gid', array(':gid' => $uinfo['groupid'])); if (!$groupInfo) { return array('status' => 0, 'msg' => '无组织用户'); } $num = $groupInfo->getAttribute($type); if ($num === null) { return array('status' => 0, 'msg' => '无法完成验证的type:' . $type); } elseif ($num === 0) { return array('status' => 0, 'msg' => '不允许'); } elseif ($field) { switch ($field) { case 'addPost': $totalNum = $groupInfo['postNum']; $hasNum = Posts::model()->count('uid=:uid AND cTime>=:cTime', array(':uid' => $uid, ':cTime' => $ctime)); break; case 'addQuestion': $totalNum = $groupInfo['questionNum']; $hasNum = Question::model()->count('uid=:uid AND cTime>=:cTime', array(':uid' => $uid, ':cTime' => $ctime)); break; case 'addAnswer': $totalNum = $groupInfo['answerNum']; $hasNum = Answer::model()->count('uid=:uid AND cTime>=:cTime', array(':uid' => $uid, ':cTime' => $ctime)); break; case 'addPoiPost': $totalNum = $groupInfo['poiPostNum']; $hasNum = PoiPost::model()->count('uid=:uid AND cTime>=:cTime', array(':uid' => $uid, ':cTime' => $ctime)); break; case 'addPoiTips': $totalNum = $groupInfo['poiTipsNum']; $hasNum = PoiTips::model()->count('uid=:uid AND cTime>=:cTime', array(':uid' => $uid, ':cTime' => $ctime)); break; case 'addImage': $totalNum = $groupInfo['imageNum']; $hasNum = Attachments::model()->count('uid=:uid AND cTime>=:cTime', array(':uid' => $uid, ':cTime' => $ctime)); break; case 'addComment': $totalNum = $groupInfo['commentNum']; $hasNum = Comments::model()->count('uid=:uid AND cTime>=:cTime', array(':uid' => $uid, ':cTime' => $ctime)); break; case 'addPlan': $totalNum = $groupInfo['planNum']; $hasNum = Plans::model()->count('uid=:uid AND cTime>=:cTime', array(':uid' => $uid, ':cTime' => $ctime)); break; case 'yueban': $totalNum = $groupInfo['yuebanNum']; $hasNum = Posts::model()->count('uid=:uid AND cTime>=:cTime', array(':uid' => $uid, ':cTime' => $ctime)); break; } if (!$totalNum) { return array('status' => 1, 'msg' => '无限制'); } else { if ($hasNum >= $totalNum) { return array('status' => 0, 'msg' => '已超出限制:' . $totalNum); } else { return array('status' => 1, 'msg' => ''); } } } else { return array('status' => 1, 'msg' => ''); } }
/** * Import survey from an TSV file template that does not require or allow assigning of GID or QID values. * NOTE: This currently only supports import of one language * @global type $connect * @global type $dbprefix * @global type $clang * @global type $timeadjust * @param type $sFullFilePath * @return type * * @author TMSWhite */ function TSVImportSurvey($sFullFilePath) { $clang = Yii::app()->lang; $insertdata = array(); $results = array(); $results['error'] = false; $baselang = 'en'; // TODO set proper default $encoding = ''; $handle = fopen($sFullFilePath, 'r'); $bom = fread($handle, 2); rewind($handle); $aAttributeList = questionAttributes(); // Excel tends to save CSV as UTF-16, which PHP does not properly detect if ($bom === chr(0xff) . chr(0xfe) || $bom === chr(0xfe) . chr(0xff)) { // UTF16 Byte Order Mark present $encoding = 'UTF-16'; } else { $file_sample = fread($handle, 1000) + 'e'; //read first 1000 bytes // + e is a workaround for mb_string bug rewind($handle); $encoding = mb_detect_encoding($file_sample, 'UTF-8, UTF-7, ASCII, EUC-JP,SJIS, eucJP-win, SJIS-win, JIS, ISO-2022-JP'); } if ($encoding && $encoding != 'UTF-8') { stream_filter_append($handle, 'convert.iconv.' . $encoding . '/UTF-8'); } $file = stream_get_contents($handle); fclose($handle); // fix Excel non-breaking space $file = str_replace("0xC20xA0", ' ', $file); $filelines = explode("\n", $file); $row = array_shift($filelines); $headers = explode("\t", $row); $rowheaders = array(); foreach ($headers as $header) { $rowheaders[] = trim($header); } // remove BOM from the first header cell, if needed $rowheaders[0] = preg_replace("/^\\W+/", "", $rowheaders[0]); if (preg_match('/class$/', $rowheaders[0])) { $rowheaders[0] = 'class'; // second attempt to remove BOM } $adata = array(); foreach ($filelines as $rowline) { $rowarray = array(); $row = explode("\t", $rowline); for ($i = 0; $i < count($rowheaders); ++$i) { $val = isset($row[$i]) ? $row[$i] : ''; // if Excel was used, it surrounds strings with quotes and doubles internal double quotes. Fix that. if (preg_match('/^".*"$/', $val)) { $val = str_replace('""', '"', substr($val, 1, -1)); } $rowarray[$rowheaders[$i]] = $val; } $adata[] = $rowarray; } $results['defaultvalues'] = 0; $results['answers'] = 0; $results['surveys'] = 0; $results['languages'] = 0; $results['questions'] = 0; $results['subquestions'] = 0; $results['question_attributes'] = 0; $results['groups'] = 0; $results['importwarnings'] = array(); // these aren't used here, but are needed to avoid errors in post-import display $results['assessments'] = 0; $results['quota'] = 0; $results['quotamembers'] = 0; $results['quotals'] = 0; // collect information about survey and its language settings $surveyinfo = array(); $surveyls = array(); foreach ($adata as $row) { switch ($row['class']) { case 'S': if (isset($row['text']) && $row['name'] != 'datecreated') { $surveyinfo[$row['name']] = $row['text']; } break; case 'SL': if (!isset($surveyls[$row['language']])) { $surveyls[$row['language']] = array(); } if (isset($row['text'])) { $surveyls[$row['language']][$row['name']] = $row['text']; } break; } } $iOldSID = 1; if (isset($surveyinfo['sid'])) { $iOldSID = (int) $surveyinfo['sid']; } // Create the survey entry $surveyinfo['startdate'] = NULL; $surveyinfo['active'] = 'N'; // unset($surveyinfo['datecreated']); $iNewSID = Survey::model()->insertNewSurvey($surveyinfo); //or safeDie($clang->gT("Error").": Failed to insert survey<br />"); if (!$iNewSID) { $results['error'] = Survey::model()->getErrors(); $results['bFailed'] = true; return $results; } $surveyinfo['sid'] = $iNewSID; $results['surveys']++; $results['newsid'] = $iNewSID; $gid = 0; $gseq = 0; // group_order $qid = 0; $qseq = 0; // question_order $qtype = 'T'; $aseq = 0; // answer sortorder // set the language for the survey $_title = 'Missing Title'; foreach ($surveyls as $_lang => $insertdata) { $insertdata['surveyls_survey_id'] = $iNewSID; $insertdata['surveyls_language'] = $_lang; if (isset($insertdata['surveyls_title'])) { $_title = $insertdata['surveyls_title']; } else { $insertdata['surveyls_title'] = $_title; } $result = SurveyLanguageSetting::model()->insertNewSurvey($insertdata); // if (!$result) { $results['error'][] = $clang->gT("Error") . " : " . $clang->gT("Failed to insert survey language"); break; } $results['languages']++; } $ginfo = array(); $qinfo = array(); $sqinfo = array(); if (isset($surveyinfo['language'])) { $baselang = $surveyinfo['language']; // the base language } $rownumber = 1; $lastglang = ''; foreach ($adata as $row) { $rownumber += 1; switch ($row['class']) { case 'G': // insert group $insertdata = array(); $insertdata['sid'] = $iNewSID; $gname = !empty($row['name']) ? $row['name'] : 'G' . $gseq; $glang = !empty($row['language']) ? $row['language'] : $baselang; // when a multi-lang tsv-file without information on the group id/number (old style) is imported, // we make up this information by giving a number 0..[numberofgroups-1] per language. // the number and order of groups per language should be the same, so we can also import these files if ($lastglang != $glang) { $iGroupcounter = 0; } $lastglang = $glang; //use group id/number from file. if missing, use an increasing number (s.a.) $sGroupseq = !empty($row['type/scale']) ? $row['type/scale'] : 'G' . $iGroupcounter++; $insertdata['group_name'] = $gname; $insertdata['grelevance'] = isset($row['relevance']) ? $row['relevance'] : ''; $insertdata['description'] = isset($row['text']) ? $row['text'] : ''; $insertdata['language'] = $glang; // For multi language survey: same gid/sort order across all languages if (isset($ginfo[$sGroupseq])) { $gid = $ginfo[$sGroupseq]['gid']; $insertdata['gid'] = $gid; $insertdata['group_order'] = $ginfo[$sGroupseq]['group_order']; } else { $insertdata['group_order'] = $gseq; } $newgid = QuestionGroup::model()->insertRecords($insertdata); if (!$newgid) { $results['error'][] = $clang->gT("Error") . " : " . $clang->gT("Failed to insert group") . ". " . $clang->gT("Text file row number ") . $rownumber . " (" . $gname . ")"; break; } if (!isset($ginfo[$sGroupseq])) { $results['groups']++; $gid = $newgid; $ginfo[$sGroupseq]['gid'] = $gid; $ginfo[$sGroupseq]['group_order'] = $gseq++; } $qseq = 0; // reset the question_order break; case 'Q': // insert question $insertdata = array(); $insertdata['sid'] = $iNewSID; $qtype = isset($row['type/scale']) ? $row['type/scale'] : 'T'; $qname = isset($row['name']) ? $row['name'] : 'Q' . $qseq; $insertdata['gid'] = $gid; $insertdata['type'] = $qtype; $insertdata['title'] = $qname; $insertdata['question'] = isset($row['text']) ? $row['text'] : ''; $insertdata['relevance'] = isset($row['relevance']) ? $row['relevance'] : ''; $insertdata['preg'] = isset($row['validation']) ? $row['validation'] : ''; $insertdata['help'] = isset($row['help']) ? $row['help'] : ''; $insertdata['language'] = isset($row['language']) ? $row['language'] : $baselang; $insertdata['mandatory'] = isset($row['mandatory']) ? $row['mandatory'] : ''; $lastother = $insertdata['other'] = isset($row['other']) ? $row['other'] : 'N'; // Keep trace of other settings for sub question $insertdata['same_default'] = isset($row['same_default']) ? $row['same_default'] : 0; $insertdata['parent_qid'] = 0; // For multi numeric survey : same name, add the gid to have same name on different gid. Bad for EM. $fullqname = "G{$gid}_" . $qname; if (isset($qinfo[$fullqname])) { $qseq = $qinfo[$fullqname]['question_order']; $qid = $qinfo[$fullqname]['qid']; $insertdata['qid'] = $qid; $insertdata['question_order'] = $qseq; } else { $insertdata['question_order'] = $qseq; } // Insert question and keep the qid for multi language survey $result = Question::model()->insertRecords($insertdata); if (!$result) { $results['error'][] = $clang->gT("Error") . " : " . $clang->gT("Could not insert question") . ". " . $clang->gT("Text file row number ") . $rownumber . " (" . $qname . ")"; break; } $newqid = $result; if (!isset($qinfo[$fullqname])) { $results['questions']++; $qid = $newqid; // save this for later $qinfo[$fullqname]['qid'] = $qid; $qinfo[$fullqname]['question_order'] = $qseq++; } $aseq = 0; //reset the answer sortorder $sqseq = 0; //reset the sub question sortorder // insert question attributes foreach ($row as $key => $val) { switch ($key) { case 'class': case 'type/scale': case 'name': case 'text': case 'validation': case 'relevance': case 'help': case 'language': case 'mandatory': case 'other': case 'same_default': case 'default': break; default: if ($key != '' && $val != '') { $insertdata = array(); $insertdata['qid'] = $qid; // check if attribute is a i18n attribute. If yes, set language, else set language to null in attribute table if (isset($aAttributeList[$qtype][$key]['i18n']) && $aAttributeList[$qtype][$key]['i18n'] == 1) { $insertdata['language'] = isset($row['language']) ? $row['language'] : $baselang; } else { $insertdata['language'] = NULL; } $insertdata['attribute'] = $key; $insertdata['value'] = $val; $result = QuestionAttribute::model()->insertRecords($insertdata); // if (!$result) { $results['importwarnings'][] = $clang->gT("Warning") . " : " . $clang->gT("Failed to insert question attribute") . ". " . $clang->gT("Text file row number ") . $rownumber . " ({$key})"; break; } $results['question_attributes']++; } break; } } // insert default value if (isset($row['default'])) { $insertdata = array(); $insertdata['qid'] = $qid; $insertdata['language'] = isset($row['language']) ? $row['language'] : $baselang; $insertdata['defaultvalue'] = $row['default']; $result = DefaultValue::model()->insertRecords($insertdata); if (!$result) { $results['importwarnings'][] = $clang->gT("Warning") . " : " . $clang->gT("Failed to insert default value") . ". " . $clang->gT("Text file row number ") . $rownumber; break; } $results['defaultvalues']++; } break; case 'SQ': $sqname = isset($row['name']) ? $row['name'] : 'SQ' . $sqseq; if ($qtype == 'O' || $qtype == '|') { // these are fake rows to show naming of comment and filecount fields } elseif ($sqname == 'other' && $lastother == "Y") { if ($qtype == "!" || $qtype == "L") { // only used to set default value for 'other' in these cases if (isset($row['default'])) { $insertdata = array(); $insertdata['qid'] = $qid; $insertdata['specialtype'] = 'other'; $insertdata['language'] = isset($row['language']) ? $row['language'] : $baselang; $insertdata['defaultvalue'] = $row['default']; $result = DefaultValue::model()->insertRecords($insertdata); if (!$result) { $results['importwarnings'][] = $clang->gT("Warning") . " : " . $clang->gT("Failed to insert default value") . ". " . $clang->gT("Text file row number ") . $rownumber; break; } $results['defaultvalues']++; } } } else { $insertdata = array(); $scale_id = isset($row['type/scale']) ? $row['type/scale'] : 0; $insertdata['sid'] = $iNewSID; $insertdata['gid'] = $gid; $insertdata['parent_qid'] = $qid; $insertdata['type'] = $qtype; $insertdata['title'] = $sqname; $insertdata['question'] = isset($row['text']) ? $row['text'] : ''; $insertdata['relevance'] = isset($row['relevance']) ? $row['relevance'] : ''; $insertdata['preg'] = isset($row['validation']) ? $row['validation'] : ''; $insertdata['help'] = isset($row['help']) ? $row['help'] : ''; $insertdata['language'] = isset($row['language']) ? $row['language'] : $baselang; $insertdata['mandatory'] = isset($row['mandatory']) ? $row['mandatory'] : ''; $insertdata['scale_id'] = $scale_id; // For multi nueric language, qid is needed, why not gid. name is not unique. $fullsqname = "G{$gid}Q{$qid}_{$scale_id}_{$sqname}"; if (isset($sqinfo[$fullsqname])) { $qseq = $sqinfo[$fullsqname]['question_order']; $sqid = $sqinfo[$fullsqname]['sqid']; $insertdata['question_order'] = $qseq; $insertdata['qid'] = $sqid; } else { $insertdata['question_order'] = $qseq; } // Insert sub question and keep the sqid for multi language survey $newsqid = Question::model()->insertRecords($insertdata); if (!$newsqid) { $results['error'][] = $clang->gT("Error") . " : " . $clang->gT("Could not insert subquestion") . ". " . $clang->gT("Text file row number ") . $rownumber . " (" . $qname . ")"; break; } if (!isset($sqinfo[$fullsqname])) { $sqinfo[$fullsqname]['question_order'] = $qseq++; $sqid = $newsqid; // save this for later $sqinfo[$fullsqname]['sqid'] = $sqid; $results['subquestions']++; } // insert default value if (isset($row['default'])) { $insertdata = array(); $insertdata['qid'] = $qid; $insertdata['sqid'] = $sqid; $insertdata['scale_id'] = $scale_id; $insertdata['language'] = isset($row['language']) ? $row['language'] : $baselang; $insertdata['defaultvalue'] = $row['default']; $result = DefaultValue::model()->insertRecords($insertdata); if (!$result) { $results['importwarnings'][] = $clang->gT("Warning") . " : " . $clang->gT("Failed to insert default value") . ". " . $clang->gT("Text file row number ") . $rownumber; break; } $results['defaultvalues']++; } } break; case 'A': $insertdata = array(); $insertdata['qid'] = $qid; $insertdata['code'] = isset($row['name']) ? $row['name'] : 'A' . $aseq; $insertdata['answer'] = isset($row['text']) ? $row['text'] : ''; $insertdata['scale_id'] = isset($row['type/scale']) ? $row['type/scale'] : 0; $insertdata['language'] = isset($row['language']) ? $row['language'] : $baselang; $insertdata['assessment_value'] = (int) (isset($row['relevance']) ? $row['relevance'] : ''); $insertdata['sortorder'] = ++$aseq; $result = Answer::model()->insertRecords($insertdata); // or safeDie("Error: Failed to insert answer<br />"); if (!$result) { $results['error'][] = $clang->gT("Error") . " : " . $clang->gT("Could not insert answer") . ". " . $clang->gT("Text file row number ") . $rownumber; } $results['answers']++; break; } } // Delete the survey if error found if (is_array($results['error'])) { $result = Survey::model()->deleteSurvey($iNewSID); } else { LimeExpressionManager::SetSurveyId($iNewSID); LimeExpressionManager::RevertUpgradeConditionsToRelevance($iNewSID); LimeExpressionManager::UpgradeConditionsToRelevance($iNewSID); } return $results; }
/** * RPC Routine to return properties of a question of a survey. * Returns string * * @access public * @param string $sSessionKey Auth credentials * @param int $iQuestionID Id of the question to get properties * @param array $aQuestionSettings The properties to get * @param string $sLanguage Optional parameter language for multilingual questions * @return array The requested values */ public function get_question_properties($sSessionKey, $iQuestionID, $aQuestionSettings, $sLanguage = NULL) { if ($this->_checkSessionKey($sSessionKey)) { Yii::app()->loadHelper("surveytranslator"); $oQuestion = Question::model()->findByAttributes(array('qid' => $iQuestionID)); if (!isset($oQuestion)) { return array('status' => 'Error: Invalid questionid'); } $iSurveyID = $oQuestion->sid; if (Permission::model()->hasSurveyPermission($iSurveyID, 'survey', 'read')) { if (is_null($sLanguage)) { $sLanguage = Survey::model()->findByPk($iSurveyID)->language; } if (!array_key_exists($sLanguage, getLanguageDataRestricted())) { return array('status' => 'Error: Invalid language'); } $oQuestion = Question::model()->findByAttributes(array('qid' => $iQuestionID, 'language' => $sLanguage)); if (!isset($oQuestion)) { return array('status' => 'Error: Invalid questionid'); } $aBasicDestinationFields = Question::model()->tableSchema->columnNames; array_push($aBasicDestinationFields, 'available_answers'); array_push($aBasicDestinationFields, 'subquestions'); array_push($aBasicDestinationFields, 'attributes'); array_push($aBasicDestinationFields, 'attributes_lang'); array_push($aBasicDestinationFields, 'answeroptions'); array_push($aBasicDestinationFields, 'defaultvalue'); $aQuestionSettings = array_intersect($aQuestionSettings, $aBasicDestinationFields); if (empty($aQuestionSettings)) { return array('status' => 'No valid Data'); } $aResult = array(); foreach ($aQuestionSettings as $sPropertyName) { if ($sPropertyName == 'available_answers' || $sPropertyName == 'subquestions') { $oSubQuestions = Question::model()->findAllByAttributes(array('parent_qid' => $iQuestionID, 'language' => $sLanguage), array('order' => 'title')); if (count($oSubQuestions) > 0) { $aData = array(); foreach ($oSubQuestions as $oSubQuestion) { if ($sPropertyName == 'available_answers') { $aData[$oSubQuestion['title']] = $oSubQuestion['question']; } else { $aData[$oSubQuestion['qid']]['title'] = $oSubQuestion['title']; $aData[$oSubQuestion['qid']]['question'] = $oSubQuestion['question']; $aData[$oSubQuestion['qid']]['scale_id'] = $oSubQuestion['scale_id']; } } $aResult[$sPropertyName] = $aData; } else { $aResult[$sPropertyName] = 'No available answers'; } } else { if ($sPropertyName == 'attributes') { $oAttributes = QuestionAttribute::model()->findAllByAttributes(array('qid' => $iQuestionID, 'language' => null), array('order' => 'attribute')); if (count($oAttributes) > 0) { $aData = array(); foreach ($oAttributes as $oAttribute) { $aData[$oAttribute['attribute']] = $oAttribute['value']; } $aResult['attributes'] = $aData; } else { $aResult['attributes'] = 'No available attributes'; } } else { if ($sPropertyName == 'attributes_lang') { $oAttributes = QuestionAttribute::model()->findAllByAttributes(array('qid' => $iQuestionID, 'language' => $sLanguage), array('order' => 'attribute')); if (count($oAttributes) > 0) { $aData = array(); foreach ($oAttributes as $oAttribute) { $aData[$oAttribute['attribute']] = $oAttribute['value']; } $aResult['attributes_lang'] = $aData; } else { $aResult['attributes_lang'] = 'No available attributes'; } } else { if ($sPropertyName == 'answeroptions') { $oAttributes = Answer::model()->findAllByAttributes(array('qid' => $iQuestionID, 'language' => $sLanguage), array('order' => 'sortorder')); if (count($oAttributes) > 0) { $aData = array(); foreach ($oAttributes as $oAttribute) { $aData[$oAttribute['code']]['answer'] = $oAttribute['answer']; $aData[$oAttribute['code']]['assessment_value'] = $oAttribute['assessment_value']; $aData[$oAttribute['code']]['scale_id'] = $oAttribute['scale_id']; } $aResult['answeroptions'] = $aData; } else { $aResult['answeroptions'] = 'No available answer options'; } } else { if ($sPropertyName == 'defaultvalue') { $aResult['defaultvalue'] = DefaultValue::model()->findByAttributes(array('qid' => $iQuestionID, 'language' => $sLanguage))->defaultvalue; } else { $aResult[$sPropertyName] = $oQuestion->{$sPropertyName}; } } } } } } return $aResult; } else { return array('status' => 'No permission'); } } else { return array('status' => 'Invalid session key'); } }
/** * * @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']; $this->_checkPermissions($iSurveyId, 'read'); $aQuestion = Question::model()->findByPk(array('qid' => $iQuestionId, 'language' => $sBaseLang)); $aQuestionType = $aQuestion['type']; if ($aQuestionType == 'M') { $aResults = Question::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' => gT("Male"), 'code' => 'M'), 'F' => array('Title' => $aQuestion['title'], 'Display' => gT("Female"), 'code' => 'F')); } elseif ($aQuestionType == 'L' || $aQuestionType == 'O' || $aQuestionType == '!') { $aAnsResults = Answer::model()->findAllByAttributes(array('qid' => $iQuestionId, 'language' => $sBaseLang)); $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 = Question::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 = Answer::model()->findAllByAttributes(array('qid' => $iQuestionId, 'language' => $sBaseLang)); $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' => gT("Yes"), 'code' => 'Y'), 'N' => array('Title' => $aQuestion['title'], 'Display' => 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 = QuotaMember::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; } }
/** * 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 = Question::model()->findAllByAttributes(array('sid' => $iSurveyID)); foreach ($oResult as $aRow) { Answer::model()->deleteAllByAttributes(array('qid' => $aRow['qid'])); Condition::model()->deleteAllByAttributes(array('qid' => $aRow['qid'])); QuestionAttribute::model()->deleteAllByAttributes(array('qid' => $aRow['qid'])); DefaultValue::model()->deleteAllByAttributes(array('qid' => $aRow['qid'])); } Question::model()->deleteAllByAttributes(array('sid' => $iSurveyID)); Assessment::model()->deleteAllByAttributes(array('sid' => $iSurveyID)); QuestionGroup::model()->deleteAllByAttributes(array('sid' => $iSurveyID)); SurveyLanguageSetting::model()->deleteAllByAttributes(array('surveyls_survey_id' => $iSurveyID)); Permission::model()->deleteAllByAttributes(array('entity_id' => $iSurveyID, 'entity' => 'survey')); SavedControl::model()->deleteAllByAttributes(array('sid' => $iSurveyID)); SurveyURLParameter::model()->deleteAllByAttributes(array('sid' => $iSurveyID)); //Remove any survey_links to the CPDB SurveyLink::model()->deleteLinksBySurvey($iSurveyID); Quota::model()->deleteQuota(array('sid' => $iSurveyID), true); } }
/** * 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); SurveyLanguageSetting::model()->updateRecord($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 $where = array('gid' => $gid, 'language' => $language); $oGroup = QuestionGroup::model()->findByAttributes($where); $oGroup->description = $description; $oGroup->group_name = $gpname; $oGroup->save(); } // 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); Question::model()->updateByPk($where, $data); } // Enf if modified } // end while qentry # translate 'answer' INSERTANS tags in answers $result = Answer::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); Answer::model()->update($data, $where); } // Enf if modified } // end while qentry }
/** * Show printable survey */ function index($surveyid, $lang = null) { $surveyid = sanitize_int($surveyid); if (!Permission::model()->hasSurveyPermission($surveyid, 'surveycontent', 'read')) { $aData['surveyid'] = $surveyid; App()->getClientScript()->registerPackage('jquery-superfish'); $message['title'] = gT('Access denied!'); $message['message'] = gT('You do not have sufficient rights to access this page.'); $message['class'] = "error"; $this->_renderWrappedTemplate('survey', array("message" => $message), $aData); } else { $aSurveyInfo = getSurveyInfo($surveyid, $lang); if (!$aSurveyInfo) { $this->getController()->error('Invalid survey ID'); } SetSurveyLanguage($surveyid, $lang); $sLanguageCode = App()->language; $templatename = $aSurveyInfo['template']; $welcome = $aSurveyInfo['surveyls_welcometext']; $end = $aSurveyInfo['surveyls_endtext']; $surveyname = $aSurveyInfo['surveyls_title']; $surveydesc = $aSurveyInfo['surveyls_description']; $surveyactive = $aSurveyInfo['active']; $surveytable = "{{survey_" . $aSurveyInfo['sid'] . "}}"; $surveyexpirydate = $aSurveyInfo['expires']; $surveyfaxto = $aSurveyInfo['faxto']; $dateformattype = $aSurveyInfo['surveyls_dateformat']; Yii::app()->loadHelper('surveytranslator'); if (!is_null($surveyexpirydate)) { $dformat = getDateFormatData($dateformattype); $dformat = $dformat['phpdate']; $expirytimestamp = strtotime($surveyexpirydate); $expirytimeofday_h = date('H', $expirytimestamp); $expirytimeofday_m = date('i', $expirytimestamp); $surveyexpirydate = date($dformat, $expirytimestamp); if (!empty($expirytimeofday_h) || !empty($expirytimeofday_m)) { $surveyexpirydate .= ' – ' . $expirytimeofday_h . ':' . $expirytimeofday_m; } sprintf(gT("Please submit by %s"), $surveyexpirydate); } else { $surveyexpirydate = ''; } //Fix $templatename : control if print_survey.pstpl exist if (is_file(getTemplatePath($templatename) . DIRECTORY_SEPARATOR . 'print_survey.pstpl')) { $templatename = $templatename; // Change nothing } elseif (is_file(getTemplatePath(Yii::app()->getConfig("defaulttemplate")) . DIRECTORY_SEPARATOR . 'print_survey.pstpl')) { $templatename = Yii::app()->getConfig("defaulttemplate"); } else { $templatename = "default"; } $sFullTemplatePath = getTemplatePath($templatename) . DIRECTORY_SEPARATOR; $sFullTemplateUrl = getTemplateURL($templatename) . "/"; define('PRINT_TEMPLATE_DIR', $sFullTemplatePath, true); define('PRINT_TEMPLATE_URL', $sFullTemplateUrl, true); LimeExpressionManager::StartSurvey($surveyid, 'survey', NULL, false, LEM_PRETTY_PRINT_ALL_SYNTAX); $moveResult = LimeExpressionManager::NavigateForwards(); $condition = "sid = '{$surveyid}' AND language = '{$sLanguageCode}'"; $degresult = QuestionGroup::model()->getAllGroups($condition, array('group_order')); //xiao, if (!isset($surveyfaxto) || !$surveyfaxto and isset($surveyfaxnumber)) { $surveyfaxto = $surveyfaxnumber; //Use system fax number if none is set in survey. } $headelements = getPrintableHeader(); //if $showsgqacode is enabled at config.php show table name for reference $showsgqacode = Yii::app()->getConfig("showsgqacode"); if (isset($showsgqacode) && $showsgqacode == true) { $surveyname = $surveyname . "<br />[" . gT('Database') . " " . gT('table') . ": {$surveytable}]"; } else { $surveyname = $surveyname; } $survey_output = array('SITENAME' => Yii::app()->getConfig("sitename"), 'SURVEYNAME' => $surveyname, 'SURVEYDESCRIPTION' => $surveydesc, 'WELCOME' => $welcome, 'END' => $end, 'THEREAREXQUESTIONS' => 0, 'SUBMIT_TEXT' => gT("Submit Your Survey."), 'SUBMIT_BY' => $surveyexpirydate, 'THANKS' => gT("Thank you for completing this survey."), 'HEADELEMENTS' => $headelements, 'TEMPLATEURL' => PRINT_TEMPLATE_URL, 'FAXTO' => $surveyfaxto, 'PRIVACY' => '', 'GROUPS' => ''); $survey_output['FAX_TO'] = ''; if (!empty($surveyfaxto) && $surveyfaxto != '000-00000000') { $survey_output['FAX_TO'] = gT("Please fax your completed survey to:") . " {$surveyfaxto}"; } $total_questions = 0; $mapquestionsNumbers = array(); $answertext = ''; // otherwise can throw an error on line 1617 $fieldmap = createFieldMap($surveyid, 'full', false, false, $sLanguageCode); // ========================================================= // START doin the business: foreach ($degresult->readAll() as $degrow) { // --------------------------------------------------- // START doing groups $deqresult = Question::model()->getQuestions($surveyid, $degrow['gid'], $sLanguageCode, 0, '"I"'); $deqrows = array(); //Create an empty array in case FetchRow does not return any rows foreach ($deqresult->readAll() as $deqrow) { $deqrows[] = $deqrow; } // Get table output into array // Perform a case insensitive natural sort on group name then question title of a multidimensional array usort($deqrows, 'groupOrderThenQuestionOrder'); if ($degrow['description']) { $group_desc = $degrow['description']; } else { $group_desc = ''; } $group = array('GROUPNAME' => $degrow['group_name'], 'GROUPDESCRIPTION' => $group_desc, 'QUESTIONS' => ''); // A group can have only hidden questions. In that case you don't want to see the group's header/description either. $bGroupHasVisibleQuestions = false; $gid = $degrow['gid']; //Alternate bgcolor for different groups if (!isset($group['ODD_EVEN']) || $group['ODD_EVEN'] == ' g-row-even') { $group['ODD_EVEN'] = ' g-row-odd'; } else { $group['ODD_EVEN'] = ' g-row-even'; } //Loop through questions foreach ($deqrows as $deqrow) { // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // START doing questions $qidattributes = getQuestionAttributeValues($deqrow['qid'], $deqrow['type']); if ($qidattributes['hidden'] == 1 && $deqrow['type'] != '*') { continue; } $bGroupHasVisibleQuestions = true; //GET ANY CONDITIONS THAT APPLY TO THIS QUESTION $printablesurveyoutput = ''; $sExplanation = ''; //reset conditions explanation $s = 0; // TMSW Condition->Relevance: show relevance instead of this whole section to create $explanation $scenarioresult = Condition::model()->getScenarios($deqrow['qid']); $scenarioresult = $scenarioresult->readAll(); //Loop through distinct scenarios, thus grouping them together. foreach ($scenarioresult as $scenariorow) { if ($s == 0 && count($scenarioresult) > 1) { $sExplanation .= '<p class="scenario">' . " -------- Scenario {$scenariorow['scenario']} --------</p>\n\n"; } if ($s > 0) { $sExplanation .= '<p class="scenario">' . ' -------- ' . gT("or") . " Scenario {$scenariorow['scenario']} --------</p>\n\n"; } $x = 0; $conditions1 = "qid={$deqrow['qid']} AND scenario={$scenariorow['scenario']}"; $distinctresult = Condition::model()->getSomeConditions(array('cqid', 'method', 'cfieldname'), $conditions1, array('cqid'), array('cqid', 'method', 'cfieldname')); //Loop through each condition for a particular scenario. foreach ($distinctresult->readAll() as $distinctrow) { $condition = "qid = '{$distinctrow['cqid']}' AND parent_qid = 0 AND language = '{$sLanguageCode}'"; $subresult = Question::model()->find($condition); if ($x > 0) { $sExplanation .= ' <em class="scenario-and-separator">' . gT('and') . '</em> '; } if (trim($distinctrow['method']) == '') { $distinctrow['method'] = '=='; } if ($distinctrow['cqid']) { // cqid != 0 ==> previous answer match if ($distinctrow['method'] == '==') { $sExplanation .= gT("Answer was") . " "; } elseif ($distinctrow['method'] == '!=') { $sExplanation .= gT("Answer was NOT") . " "; } elseif ($distinctrow['method'] == '<') { $sExplanation .= gT("Answer was less than") . " "; } elseif ($distinctrow['method'] == '<=') { $sExplanation .= gT("Answer was less than or equal to") . " "; } elseif ($distinctrow['method'] == '>=') { $sExplanation .= gT("Answer was greater than or equal to") . " "; } elseif ($distinctrow['method'] == '>') { $sExplanation .= gT("Answer was greater than") . " "; } elseif ($distinctrow['method'] == 'RX') { $sExplanation .= gT("Answer matched (regexp)") . " "; } else { $sExplanation .= gT("Answer was") . " "; } } if (!$distinctrow['cqid']) { // cqid == 0 ==> token attribute match $tokenData = getTokenFieldsAndNames($surveyid); preg_match('/^{TOKEN:([^}]*)}$/', $distinctrow['cfieldname'], $extractedTokenAttr); $sExplanation .= "Your " . $tokenData[strtolower($extractedTokenAttr[1])]['description'] . " "; if ($distinctrow['method'] == '==') { $sExplanation .= gT("is") . " "; } elseif ($distinctrow['method'] == '!=') { $sExplanation .= gT("is NOT") . " "; } elseif ($distinctrow['method'] == '<') { $sExplanation .= gT("is less than") . " "; } elseif ($distinctrow['method'] == '<=') { $sExplanation .= gT("is less than or equal to") . " "; } elseif ($distinctrow['method'] == '>=') { $sExplanation .= gT("is greater than or equal to") . " "; } elseif ($distinctrow['method'] == '>') { $sExplanation .= gT("is greater than") . " "; } elseif ($distinctrow['method'] == 'RX') { $sExplanation .= gT("is matched (regexp)") . " "; } else { $sExplanation .= gT("is") . " "; } $answer_section = ' ' . $distinctrow['value'] . ' '; } $conresult = Condition::model()->getConditionsQuestions($distinctrow['cqid'], $deqrow['qid'], $scenariorow['scenario'], $sLanguageCode); $conditions = array(); foreach ($conresult->readAll() as $conrow) { $postans = ""; $value = $conrow['value']; switch ($conrow['type']) { case "Y": switch ($conrow['value']) { case "Y": $conditions[] = gT("Yes"); break; case "N": $conditions[] = gT("No"); break; } break; case "G": switch ($conrow['value']) { case "M": $conditions[] = gT("Male"); break; case "F": $conditions[] = gT("Female"); break; } // switch break; case "A": case "B": case ":": case ";": case "5": $conditions[] = $conrow['value']; break; case "C": switch ($conrow['value']) { case "Y": $conditions[] = gT("Yes"); break; case "U": $conditions[] = gT("Uncertain"); break; case "N": $conditions[] = gT("No"); break; } // switch break; case "E": switch ($conrow['value']) { case "I": $conditions[] = gT("Increase"); break; case "D": $conditions[] = gT("Decrease"); break; case "S": $conditions[] = gT("Same"); break; } case "1": $labelIndex = preg_match("/^[^#]+#([01]{1})\$/", $conrow['cfieldname']); if ($labelIndex == 0) { // TIBO $condition = "qid='{$conrow['cqid']}' AND code='{$conrow['value']}' AND scale_id=0 AND language='{$sLanguageCode}'"; $fresult = Answer::model()->getAllRecords($condition); foreach ($fresult->readAll() as $frow) { $postans = $frow['answer']; $conditions[] = $frow['answer']; } // while } elseif ($labelIndex == 1) { $condition = "qid='{$conrow['cqid']}' AND code='{$conrow['value']}' AND scale_id=1 AND language='{$sLanguageCode}'"; $fresult = Answer::model()->getAllRecords($condition); foreach ($fresult->readAll() as $frow) { $postans = $frow['answer']; $conditions[] = $frow['answer']; } // while } break; case "L": case "!": case "O": case "R": $condition = "qid='{$conrow['cqid']}' AND code='{$conrow['value']}' AND language='{$sLanguageCode}'"; $ansresult = Answer::model()->findAll($condition); foreach ($ansresult as $ansrow) { $conditions[] = $ansrow['answer']; } if ($conrow['value'] == "-oth-") { $conditions[] = gT("Other"); } $conditions = array_unique($conditions); break; case "M": case "P": $condition = " parent_qid='{$conrow['cqid']}' AND title='{$conrow['value']}' AND language='{$sLanguageCode}'"; $ansresult = Question::model()->findAll($condition); foreach ($ansresult as $ansrow) { $conditions[] = $ansrow['question']; } $conditions = array_unique($conditions); break; case "N": case "K": $conditions[] = $value; break; case "F": case "H": default: $value = substr($conrow['cfieldname'], strpos($conrow['cfieldname'], "X" . $conrow['cqid']) + strlen("X" . $conrow['cqid']), strlen($conrow['cfieldname'])); $condition = " qid='{$conrow['cqid']}' AND code='{$conrow['value']}' AND language='{$sLanguageCode}'"; $fresult = Answer::model()->getAllRecords($condition); foreach ($fresult->readAll() as $frow) { $postans = $frow['answer']; $conditions[] = $frow['answer']; } // while break; } // switch // Now let's complete the answer text with the answer_section $answer_section = ""; switch ($conrow['type']) { case "A": case "B": case "C": case "E": case "F": case "H": case "K": $thiscquestion = $fieldmap[$conrow['cfieldname']]; $condition = "parent_qid='{$conrow['cqid']}' AND title='{$thiscquestion['aid']}' AND language='{$sLanguageCode}'"; $ansresult = Question::model()->findAll($condition); foreach ($ansresult as $ansrow) { $answer_section = " (" . $ansrow['question'] . ")"; } break; case "1": // dual: (Label 1), (Label 2) $labelIndex = substr($conrow['cfieldname'], -1); $thiscquestion = $fieldmap[$conrow['cfieldname']]; $condition = "parent_qid='{$conrow['cqid']}' AND title='{$thiscquestion['aid']}' AND language='{$sLanguageCode}'"; $ansresult = Question::model()->findAll($condition); $cqidattributes = getQuestionAttributeValues($conrow['cqid']); if ($labelIndex == 0) { if (trim($cqidattributes['dualscale_headerA'][$sLanguageCode]) != '') { $header = gT($cqidattributes['dualscale_headerA'][$sLanguageCode]); } else { $header = '1'; } } elseif ($labelIndex == 1) { if (trim($cqidattributes['dualscale_headerB'][$sLanguageCode]) != '') { $header = gT($cqidattributes['dualscale_headerB'][$sLanguageCode]); } else { $header = '2'; } } foreach ($ansresult as $ansrow) { $answer_section = " (" . $ansrow->question . " " . sprintf(gT("Label %s"), $header) . ")"; } break; case ":": case ";": //multi flexi: ( answer [label] ) $thiscquestion = $fieldmap[$conrow['cfieldname']]; $condition = "parent_qid='{$conrow['cqid']}' AND title='{$thiscquestion['aid']}' AND language='{$sLanguageCode}'"; $ansresult = Question::model()->findAll($condition); foreach ($ansresult as $ansrow) { $condition = "qid = '{$conrow['cqid']}' AND code = '{$conrow['value']}' AND language= '{$sLanguageCode}'"; $fresult = Answer::model()->findAll($condition); foreach ($fresult as $frow) { //$conditions[]=$frow['title']; $answer_section = " (" . $ansrow->question . "[" . $frow['answer'] . "])"; } // while } break; case "R": // (Rank 1), (Rank 2)... TIBO $thiscquestion = $fieldmap[$conrow['cfieldname']]; $rankid = $thiscquestion['aid']; $answer_section = " (" . gT("RANK") . " {$rankid})"; break; default: // nothing to add break; } } if (count($conditions) > 1) { $sExplanation .= "'" . implode("' <em class='scenario-or-separator'>" . gT("or") . "</em> '", $conditions) . "'"; } elseif (count($conditions) == 1) { $sExplanation .= "'" . $conditions[0] . "'"; } unset($conditions); // Following line commented out because answer_section was lost, but is required for some question types //$explanation .= " ".gT("to question")." '".$mapquestionsNumbers[$distinctrow['cqid']]."' $answer_section "; if ($distinctrow['cqid']) { $sExplanation .= " <span class='scenario-at-separator'>" . gT("at question") . "</span> '" . $mapquestionsNumbers[$distinctrow['cqid']] . " [" . $subresult['title'] . "]' (" . strip_tags($subresult['question']) . "{$answer_section})"; } else { $sExplanation .= " " . $distinctrow['value']; } //$distinctrow $x++; } $s++; } $qinfo = LimeExpressionManager::GetQuestionStatus($deqrow['qid']); $relevance = trim($qinfo['info']['relevance']); $sEquation = $qinfo['relEqn']; if (trim($relevance) != '' && trim($relevance) != '1') { if (isset($qidattributes['printable_help'][$sLanguageCode]) && $qidattributes['printable_help'][$sLanguageCode] != '') { $sExplanation = $qidattributes['printable_help'][$sLanguageCode]; } elseif ($sExplanation == '') { $sExplanation = $sEquation; $sEquation = ' '; // No need to show it twice } $sExplanation = "<b>" . gT('Only answer this question if the following conditions are met:') . "</b><br/> " . $sExplanation; if (Yii::app()->getConfig('showrelevance')) { $sExplanation .= "<span class='printable_equation'><br>" . $sEquation . "</span>"; } } else { $sExplanation = ''; } ++$total_questions; //TIBO map question qid to their q number $mapquestionsNumbers[$deqrow['qid']] = $total_questions; //END OF GETTING CONDITIONS $qid = $deqrow['qid']; $fieldname = "{$surveyid}" . "X" . "{$gid}" . "X" . "{$qid}"; if (isset($showsgqacode) && $showsgqacode == true) { $deqrow['question'] = $deqrow['question'] . "<br />" . gT("ID:") . " {$fieldname} <br />" . gT("Question code:") . " " . $deqrow['title']; } $question = array('QUESTION_NUMBER' => $total_questions, 'QUESTION_CODE' => $deqrow['title'], 'QUESTION_TEXT' => preg_replace('/(?:<br ?\\/?>|<\\/(?:p|h[1-6])>)$/is', '', $deqrow['question']), 'QUESTION_SCENARIO' => $sExplanation, 'QUESTION_MANDATORY' => '', 'QUESTION_ID' => $deqrow['qid'], 'QUESTION_CLASS' => getQuestionClass($deqrow['type']), 'QUESTION_TYPE_HELP' => $qinfo['validTip'], 'QUESTION_MAN_MESSAGE' => '', 'QUESTION_VALID_MESSAGE' => '', 'QUESTION_FILE_VALID_MESSAGE' => '', 'QUESTIONHELP' => '', 'ANSWER' => ''); $showqnumcode = Yii::app()->getConfig('showqnumcode'); if ($showqnumcode == 'choose' && ($aSurveyInfo['showqnumcode'] == 'N' || $aSurveyInfo['showqnumcode'] == 'X') || $showqnumcode == 'number' || $showqnumcode == 'none') { $question['QUESTION_CODE'] = ''; } if ($showqnumcode == 'choose' && ($aSurveyInfo['showqnumcode'] == 'C' || $aSurveyInfo['showqnumcode'] == 'X') || $showqnumcode == 'code' || $showqnumcode == 'none') { $question['QUESTION_NUMBER'] = ''; } if ($question['QUESTION_TYPE_HELP'] != "") { $question['QUESTION_TYPE_HELP'] .= "<br />\n"; } if ($deqrow['mandatory'] == 'Y') { $question['QUESTION_MANDATORY'] = gT('*'); $question['QUESTION_CLASS'] .= ' mandatory'; } //DIFFERENT TYPES OF DATA FIELD HERE if ($deqrow['help']) { $question['QUESTIONHELP'] = $deqrow['help']; } if (!empty($qidattributes['page_break'])) { $question['QUESTION_CLASS'] .= ' breakbefore '; } if (isset($qidattributes['maximum_chars']) && $qidattributes['maximum_chars'] != '') { $question['QUESTION_CLASS'] = "max-chars-{$qidattributes['maximum_chars']} " . $question['QUESTION_CLASS']; } switch ($deqrow['type']) { // ================================================================== case "5": //5 POINT CHOICE $question['QUESTION_TYPE_HELP'] .= gT('Please choose *only one* of the following:'); $question['ANSWER'] .= "\n\t<ul>\n"; for ($i = 1; $i <= 5; $i++) { $question['ANSWER'] .= "\t\t<li>\n\t\t\t" . self::_input_type_image('radio', $i) . "\n\t\t\t{$i} " . self::_addsgqacode("({$i})") . "\n\t\t</li>\n"; } $question['ANSWER'] .= "\t</ul>\n"; break; // ================================================================== // ================================================================== case "D": //DATE $question['QUESTION_TYPE_HELP'] .= gT('Please enter a date:'); $question['ANSWER'] .= "\t" . self::_input_type_image('text', $question['QUESTION_TYPE_HELP'], 30, 1); break; // ================================================================== // ================================================================== case "G": //GENDER $question['QUESTION_TYPE_HELP'] .= gT("Please choose *only one* of the following:"); $question['ANSWER'] .= "\n\t<ul>\n"; $question['ANSWER'] .= "\t\t<li>\n\t\t\t" . self::_input_type_image('radio', gT("Female")) . "\n\t\t\t" . gT("Female") . " " . self::_addsgqacode("(F)") . "\n\t\t</li>\n"; $question['ANSWER'] .= "\t\t<li>\n\t\t\t" . self::_input_type_image('radio', gT("Male")) . "\n\t\t\t" . gT("Male") . " " . self::_addsgqacode("(M)") . "\n\t\t</li>\n"; $question['ANSWER'] .= "\t</ul>\n"; break; // ================================================================== // ================================================================== case "L": //LIST drop-down/radio-button list // ================================================================== //LIST drop-down/radio-button list // ================================================================== case "!": //List - dropdown if (isset($qidattributes['display_columns']) && trim($qidattributes['display_columns']) != '') { $dcols = $qidattributes['display_columns']; } else { $dcols = 0; } if (isset($qidattributes['category_separator']) && trim($qidattributes['category_separator']) != '') { $optCategorySeparator = $qidattributes['category_separator']; } else { unset($optCategorySeparator); } $question['QUESTION_TYPE_HELP'] .= gT("Please choose *only one* of the following:"); $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $sLanguageCode, $surveyid); $dearesult = Answer::model()->getAllRecords(" qid='{$deqrow['qid']}' AND language='{$sLanguageCode}' ", array('sortorder', 'answer')); $dearesult = $dearesult->readAll(); $deacount = count($dearesult); if ($deqrow['other'] == "Y") { $deacount++; } $wrapper = setupColumns(0, $deacount); $question['ANSWER'] = $wrapper['whole-start']; $rowcounter = 0; $colcounter = 1; foreach ($dearesult as $dearow) { if (isset($optCategorySeparator)) { list($category, $answer) = explode($optCategorySeparator, $dearow['answer']); if ($category != '') { $dearow['answer'] = "({$category}) {$answer} " . self::_addsgqacode("(" . $dearow['code'] . ")"); } else { $dearow['answer'] = $answer . self::_addsgqacode(" (" . $dearow['code'] . ")"); } $question['ANSWER'] .= "\t" . $wrapper['item-start'] . "\t\t" . self::_input_type_image('radio', $dearow['answer']) . "\n\t\t\t" . $dearow['answer'] . "\n" . $wrapper['item-end']; } else { $question['ANSWER'] .= "\t" . $wrapper['item-start'] . "\t\t" . self::_input_type_image('radio', $dearow['answer']) . "\n\t\t\t" . $dearow['answer'] . self::_addsgqacode(" (" . $dearow['code'] . ")") . "\n" . $wrapper['item-end']; } ++$rowcounter; if ($rowcounter == $wrapper['maxrows'] && $colcounter < $wrapper['cols']) { if ($colcounter == $wrapper['cols'] - 1) { $question['ANSWER'] .= $wrapper['col-devide-last']; } else { $question['ANSWER'] .= $wrapper['col-devide']; } $rowcounter = 0; ++$colcounter; } } if ($deqrow['other'] == 'Y') { if (trim($qidattributes["other_replace_text"][$sLanguageCode]) == '') { $qidattributes["other_replace_text"][$sLanguageCode] = gT("Other"); } // $printablesurveyoutput .="\t".$wrapper['item-start']."\t\t".self::_input_type_image('radio' , gT("Other"))."\n\t\t\t".gT("Other")."\n\t\t\t<input type='text' size='30' readonly='readonly' />\n".$wrapper['item-end']; $question['ANSWER'] .= $wrapper['item-start-other'] . self::_input_type_image('radio', gT($qidattributes["other_replace_text"][$sLanguageCode])) . ' ' . gT($qidattributes["other_replace_text"][$sLanguageCode]) . self::_addsgqacode(" (-oth-)") . "\n\t\t\t" . self::_input_type_image('other') . self::_addsgqacode(" (" . $deqrow['sid'] . "X" . $deqrow['gid'] . "X" . $deqrow['qid'] . "other)") . "\n" . $wrapper['item-end']; } $question['ANSWER'] .= $wrapper['whole-end']; //Let's break the presentation into columns. break; // ================================================================== // ================================================================== case "O": //LIST WITH COMMENT $question['QUESTION_TYPE_HELP'] .= gT("Please choose *only one* of the following:"); $dearesult = Answer::model()->getAllRecords(" qid='{$deqrow['qid']}' AND language='{$sLanguageCode}'", array('sortorder', 'answer')); $question['ANSWER'] = "\t<ul>\n"; foreach ($dearesult->readAll() as $dearow) { $question['ANSWER'] .= "\t\t<li>\n\t\t\t" . self::_input_type_image('radio', $dearow['answer']) . "\n\t\t\t" . $dearow['answer'] . self::_addsgqacode(" (" . $dearow['code'] . ")") . "\n\t\t</li>\n"; } $question['ANSWER'] .= "\t</ul>\n"; $question['ANSWER'] .= "\t<p class=\"comment\">\n\t\t" . gT("Make a comment on your choice here:") . "\n"; $question['ANSWER'] .= "\t\t" . self::_input_type_image('textarea', gT("Make a comment on your choice here:"), 50, 8) . self::_addsgqacode(" (" . $deqrow['sid'] . "X" . $deqrow['gid'] . "X" . $deqrow['qid'] . "comment)") . "\n\t</p>\n"; break; // ================================================================== // ================================================================== case "R": //RANKING Type Question $rearesult = Answer::model()->getAllRecords(" qid='{$deqrow['qid']}' AND language='{$sLanguageCode}'", array('sortorder', 'answer')); $rearesult = $rearesult->readAll(); $reacount = count($rearesult); $question['QUESTION_TYPE_HELP'] .= gT("Please number each box in order of preference from 1 to") . " {$reacount}"; $question['QUESTION_TYPE_HELP'] .= self::_min_max_answers_help($qidattributes, $sLanguageCode, $surveyid); $question['ANSWER'] = "\n<ul>\n"; foreach ($rearesult as $rearow) { $question['ANSWER'] .= "\t<li>\n\t" . self::_input_type_image('rank', '', 4, 1) . "\n\t\t " . $rearow['answer'] . self::_addsgqacode(" (" . $fieldname . $rearow['code'] . ")") . "\n\t</li>\n"; } $question['ANSWER'] .= "\n</ul>\n"; break; // ================================================================== // ================================================================== case "M": //Multiple choice (Quite tricky really!) if (trim($qidattributes['display_columns']) != '') { $dcols = $qidattributes['display_columns']; } else { $dcols = 0; } $question['QUESTION_TYPE_HELP'] .= gT("Please choose *all* that apply:"); $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $sLanguageCode, $surveyid); $mearesult = Question::model()->getAllRecords(" parent_qid='{$deqrow['qid']}' AND language='{$sLanguageCode}' ", array('question_order')); $mearesult = $mearesult->readAll(); $meacount = count($mearesult); if ($deqrow['other'] == 'Y') { $meacount++; } $wrapper = setupColumns($dcols, $meacount); $question['ANSWER'] = $wrapper['whole-start']; $rowcounter = 0; $colcounter = 1; foreach ($mearesult as $mearow) { $question['ANSWER'] .= $wrapper['item-start'] . self::_input_type_image('checkbox', $mearow['question']) . "\n\t\t" . $mearow['question'] . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . ") ") . $wrapper['item-end']; ++$rowcounter; if ($rowcounter == $wrapper['maxrows'] && $colcounter < $wrapper['cols']) { if ($colcounter == $wrapper['cols'] - 1) { $question['ANSWER'] .= $wrapper['col-devide-last']; } else { $question['ANSWER'] .= $wrapper['col-devide']; } $rowcounter = 0; ++$colcounter; } } if ($deqrow['other'] == "Y") { if (trim($qidattributes['other_replace_text'][$sLanguageCode]) == '') { $qidattributes["other_replace_text"][$sLanguageCode] = "Other"; } if (!isset($mearow['answer'])) { $mearow['answer'] = ""; } $question['ANSWER'] .= $wrapper['item-start-other'] . self::_input_type_image('checkbox', $mearow['answer']) . gT($qidattributes["other_replace_text"][$sLanguageCode]) . ":\n\t\t" . self::_input_type_image('other') . self::_addsgqacode(" (" . $fieldname . "other) ") . $wrapper['item-end']; } $question['ANSWER'] .= $wrapper['whole-end']; // } break; // ================================================================== // ================================================================== case "P": //Multiple choice with comments $question['QUESTION_TYPE_HELP'] .= gT("Please choose all that apply and provide a comment:"); $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $sLanguageCode, $surveyid); $mearesult = Question::model()->getAllRecords("parent_qid='{$deqrow['qid']}' AND language='{$sLanguageCode}'", array('question_order')); // $printablesurveyoutput .="\t\t\t<u>".gT("Please choose all that apply and provide a comment:")."</u><br />\n"; $j = 0; $longest_string = 0; foreach ($mearesult->readAll() as $mearow) { $longest_string = longestString($mearow['question'], $longest_string); $question['ANSWER'] .= "\t<li><span>\n\t\t" . self::_input_type_image('checkbox', $mearow['question']) . $mearow['question'] . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . ") ") . "</span>\n\t\t" . self::_input_type_image('text', 'comment box', 60) . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . "comment) ") . "\n\t</li>\n"; $j++; } if ($deqrow['other'] == "Y") { $question['ANSWER'] .= "\t<li class=\"other\">\n\t\t<div class=\"other-replacetext\">" . gT('Other:') . self::_input_type_image('other', '', 1) . "</div>" . self::_input_type_image('othercomment', 'comment box', 50) . self::_addsgqacode(" (" . $fieldname . "other) ") . "\n\t</li>\n"; $j++; } $question['ANSWER'] = "\n<ul>\n" . $question['ANSWER'] . "</ul>\n"; break; // ================================================================== // ================================================================== case "Q": //MULTIPLE SHORT TEXT $width = 60; // ================================================================== // ================================================================== case "K": //MULTIPLE NUMERICAL $question['QUESTION_TYPE_HELP'] = ""; $width = isset($width) ? $width : 16; // if (!empty($qidattributes['equals_num_value'])) // { // $question['QUESTION_TYPE_HELP'] .= "* ".sprintf(gT('Total of all entries must equal %d'),$qidattributes['equals_num_value'])."<br />\n"; // } // if (!empty($qidattributes['max_num_value'])) // { // $question['QUESTION_TYPE_HELP'] .= sprintf(gT('Total of all entries must not exceed %d'), $qidattributes['max_num_value'])."<br />\n"; // } // if (!empty($qidattributes['min_num_value'])) // { // $question['QUESTION_TYPE_HELP'] .= sprintf(gT('Total of all entries must be at least %s'),$qidattributes['min_num_value'])."<br />\n"; // } $question['QUESTION_TYPE_HELP'] .= gT("Please write your answer(s) here:"); $longest_string = 0; $mearesult = Question::model()->getAllRecords("parent_qid='{$deqrow['qid']}' AND language='{$sLanguageCode}'", array('question_order')); foreach ($mearesult->readAll() as $mearow) { $longest_string = longestString($mearow['question'], $longest_string); if (isset($qidattributes['slider_layout']) && $qidattributes['slider_layout'] == 1) { $mearow['question'] = explode(':', $mearow['question']); $mearow['question'] = $mearow['question'][0]; } $question['ANSWER'] .= "\t<li>\n\t\t<span>" . $mearow['question'] . "</span>\n\t\t" . self::_input_type_image('text', $mearow['question'], $width) . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . ") ") . "\n\t</li>\n"; } $question['ANSWER'] = "\n<ul>\n" . $question['ANSWER'] . "</ul>\n"; break; // ================================================================== // ================================================================== case "S": //SHORT TEXT $question['QUESTION_TYPE_HELP'] .= gT("Please write your answer here:"); $question['ANSWER'] = self::_input_type_image('text', $question['QUESTION_TYPE_HELP'], 50); break; // ================================================================== // ================================================================== case "T": //LONG TEXT $question['QUESTION_TYPE_HELP'] .= gT("Please write your answer here:"); $question['ANSWER'] = self::_input_type_image('textarea', $question['QUESTION_TYPE_HELP'], '100%', 8); break; // ================================================================== // ================================================================== case "U": //HUGE TEXT $question['QUESTION_TYPE_HELP'] .= gT("Please write your answer here:"); $question['ANSWER'] = self::_input_type_image('textarea', $question['QUESTION_TYPE_HELP'], '100%', 30); break; // ================================================================== // ================================================================== case "N": //NUMERICAL $prefix = ""; $suffix = ""; if ($qidattributes['prefix'][$sLanguageCode] != "") { $prefix = $qidattributes['prefix'][$sLanguageCode]; } if ($qidattributes['suffix'][$sLanguageCode] != "") { $suffix = $qidattributes['suffix'][$sLanguageCode]; } $question['QUESTION_TYPE_HELP'] .= gT("Please write your answer here:"); $question['ANSWER'] = "<ul>\n\t<li>\n\t\t<span>{$prefix}</span>\n\t\t" . self::_input_type_image('text', $question['QUESTION_TYPE_HELP'], 20) . "\n\t\t<span>{$suffix}</span>\n\t\t</li>\n\t</ul>"; break; // ================================================================== // ================================================================== case "Y": //YES/NO $question['QUESTION_TYPE_HELP'] .= gT("Please choose *only one* of the following:"); $question['ANSWER'] = "\n<ul>\n\t<li>\n\t\t" . self::_input_type_image('radio', gT('Yes')) . "\n\t\t" . gT('Yes') . self::_addsgqacode(" (Y)") . "\n\t</li>\n"; $question['ANSWER'] .= "\n\t<li>\n\t\t" . self::_input_type_image('radio', gT('No')) . "\n\t\t" . gT('No') . self::_addsgqacode(" (N)") . "\n\t</li>\n</ul>\n"; break; // ================================================================== // ================================================================== case "A": //ARRAY (5 POINT CHOICE) $condition = "parent_qid = '{$deqrow['qid']}' AND language= '{$sLanguageCode}'"; $question['QUESTION_TYPE_HELP'] .= gT("Please choose the appropriate response for each item:"); $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $sLanguageCode, $surveyid); $question['ANSWER'] = "\n <table>\n <thead>\n <tr>\n <td> </td>\n <th style='font-family:Arial,helvetica,sans-serif;font-weight:normal;'>1 " . self::_addsgqacode(" (1)") . "</th>\n <th style='font-family:Arial,helvetica,sans-serif;font-weight:normal;'>2 " . self::_addsgqacode(" (2)") . "</th>\n <th style='font-family:Arial,helvetica,sans-serif;font-weight:normal;'>3 " . self::_addsgqacode(" (3)") . "</th>\n <th style='font-family:Arial,helvetica,sans-serif;font-weight:normal;'>4 " . self::_addsgqacode(" (4)") . "</th>\n <th style='font-family:Arial,helvetica,sans-serif;font-weight:normal;'>5" . self::_addsgqacode(" (5)") . "</th>\n </tr>\n </thead>\n <tbody>"; $j = 0; $rowclass = 'array1'; $mearesult = Question::model()->getAllRecords($condition, array('question_order')); foreach ($mearesult->readAll() as $mearow) { $question['ANSWER'] .= "\t\t<tr class=\"{$rowclass}\">\n"; $rowclass = alternation($rowclass, 'row'); //semantic differential question type? if (strpos($mearow['question'], '|')) { $answertext = substr($mearow['question'], 0, strpos($mearow['question'], '|')) . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . ")") . " "; } else { $answertext = $mearow['question'] . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . ")"); } $question['ANSWER'] .= "\t\t\t<th class=\"answertext\">{$answertext}</th>\n"; for ($i = 1; $i <= 5; $i++) { $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio', $i) . "</td>\n"; } $answertext .= $mearow['question']; //semantic differential question type? if (strpos($mearow['question'], '|')) { $answertext2 = substr($mearow['question'], strpos($mearow['question'], '|') + 1); $question['ANSWER'] .= "\t\t\t<th class=\"answertextright\">{$answertext2}</td>\n"; } $question['ANSWER'] .= "\t\t</tr>\n"; $j++; } $question['ANSWER'] .= "\t</tbody>\n</table>\n"; break; // ================================================================== // ================================================================== case "B": //ARRAY (10 POINT CHOICE) $question['QUESTION_TYPE_HELP'] .= gT("Please choose the appropriate response for each item:"); $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $sLanguageCode, $surveyid); $question['ANSWER'] .= "\n<table>\n\t<thead>\n\t\t<tr>\n\t\t\t<td> </td>\n"; for ($i = 1; $i <= 10; $i++) { $question['ANSWER'] .= "\t\t\t<th>{$i}" . self::_addsgqacode(" ({$i})") . "</th>\n"; } $question['ANSWER'] .= "\t</thead>\n\n\t<tbody>\n"; $j = 0; $rowclass = 'array1'; $mearesult = Question::model()->getAllRecords(" parent_qid='{$deqrow['qid']}' AND language='{$sLanguageCode}' ", array('question_order')); foreach ($mearesult->readAll() as $mearow) { $question['ANSWER'] .= "\t\t<tr class=\"{$rowclass}\">\n\t\t\t<th class=\"answertext\">{$mearow['question']}" . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . ")") . "</th>\n"; $rowclass = alternation($rowclass, 'row'); for ($i = 1; $i <= 10; $i++) { $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio', $i) . "</td>\n"; } $question['ANSWER'] .= "\t\t</tr>\n"; $j++; } $question['ANSWER'] .= "\t</tbody>\n</table>\n"; break; // ================================================================== // ================================================================== case "C": //ARRAY (YES/UNCERTAIN/NO) $question['QUESTION_TYPE_HELP'] .= gT("Please choose the appropriate response for each item:"); $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $sLanguageCode, $surveyid); $question['ANSWER'] = ' <table> <thead> <tr> <td> </td> <th>' . gT("Yes") . self::_addsgqacode(" (Y)") . '</th> <th>' . gT("Uncertain") . self::_addsgqacode(" (U)") . '</th> <th>' . gT("No") . self::_addsgqacode(" (N)") . '</th> </tr> </thead> <tbody> '; $j = 0; $rowclass = 'array1'; $mearesult = Question::model()->getAllRecords(" parent_qid='{$deqrow['qid']}' AND language='{$sLanguageCode}' ", array('question_order')); foreach ($mearesult->readAll() as $mearow) { $question['ANSWER'] .= "\t\t<tr class=\"{$rowclass}\">\n"; $question['ANSWER'] .= "\t\t\t<th class=\"answertext\">{$mearow['question']}" . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . ")") . "</th>\n"; $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio', gT("Yes")) . "</td>\n"; $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio', gT("Uncertain")) . "</td>\n"; $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio', gT("No")) . "</td>\n"; $question['ANSWER'] .= "\t\t</tr>\n"; $j++; $rowclass = alternation($rowclass, 'row'); } $question['ANSWER'] .= "\t</tbody>\n</table>\n"; break; case "E": //ARRAY (Increase/Same/Decrease) $question['QUESTION_TYPE_HELP'] .= gT("Please choose the appropriate response for each item:"); $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $sLanguageCode, $surveyid); $question['ANSWER'] = ' <table> <thead> <tr> <td> </td> <th>' . gT("Increase") . self::_addsgqacode(" (I)") . '</th> <th>' . gT("Same") . self::_addsgqacode(" (S)") . '</th> <th>' . gT("Decrease") . self::_addsgqacode(" (D)") . '</th> </tr> </thead> <tbody> '; $j = 0; $rowclass = 'array1'; $mearesult = Question::model()->getAllRecords(" parent_qid='{$deqrow['qid']}' AND language='{$sLanguageCode}' ", array('question_order')); foreach ($mearesult->readAll() as $mearow) { $question['ANSWER'] .= "\t\t<tr class=\"{$rowclass}\">\n"; $question['ANSWER'] .= "\t\t\t<th class=\"answertext\">{$mearow['question']}" . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . ")") . "</th>\n"; $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio', gT("Increase")) . "</td>\n"; $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio', gT("Same")) . "</td>\n"; $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio', gT("Decrease")) . "</td>\n"; $question['ANSWER'] .= "\t\t</tr>\n"; $j++; $rowclass = alternation($rowclass, 'row'); } $question['ANSWER'] .= "\t</tbody>\n</table>\n"; break; // ================================================================== // ================================================================== case ":": //ARRAY (Multi Flexible) (Numbers) $headstyle = "style='padding-left: 20px; padding-right: 7px'"; if (trim($qidattributes['multiflexible_max']) != '' && trim($qidattributes['multiflexible_min']) == '') { $maxvalue = $qidattributes['multiflexible_max']; $minvalue = 1; } if (trim($qidattributes['multiflexible_min']) != '' && trim($qidattributes['multiflexible_max']) == '') { $minvalue = $qidattributes['multiflexible_min']; $maxvalue = $qidattributes['multiflexible_min'] + 10; } if (trim($qidattributes['multiflexible_min']) == '' && trim($qidattributes['multiflexible_max']) == '') { $minvalue = 1; $maxvalue = 10; } if (trim($qidattributes['multiflexible_min']) != '' && trim($qidattributes['multiflexible_max']) != '') { if ($qidattributes['multiflexible_min'] < $qidattributes['multiflexible_max']) { $minvalue = $qidattributes['multiflexible_min']; $maxvalue = $qidattributes['multiflexible_max']; } } if (trim($qidattributes['multiflexible_step']) != '') { $stepvalue = $qidattributes['multiflexible_step']; } else { $stepvalue = 1; } if ($qidattributes['multiflexible_checkbox'] != 0) { $checkboxlayout = true; } else { $checkboxlayout = false; } $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $sLanguageCode, $surveyid); $question['ANSWER'] .= "\n<table>\n\t<thead>\n\t\t<tr>\n\t\t\t<td> </td>\n"; $fresult = Question::model()->getAllRecords(" parent_qid='{$deqrow['qid']}' and scale_id=1 AND language='{$sLanguageCode}' ", array('question_order')); $fresult = $fresult->readAll(); $fcount = count($fresult); $fwidth = "120"; $i = 0; //array to temporary store X axis question codes $xaxisarray = array(); foreach ($fresult as $frow) { $question['ANSWER'] .= "\t\t\t<th>{$frow['question']}</th>\n"; $i++; //add current question code $xaxisarray[$i] = $frow['title']; } $question['ANSWER'] .= "\t\t</tr>\n\t</thead>\n\n\t<tbody>\n"; $a = 1; //Counter for pdfoutput $rowclass = 'array1'; $mearesult = Question::model()->getAllRecords(" parent_qid='{$deqrow['qid']}' and scale_id=0 AND language='{$sLanguageCode}' ", array('question_order')); $result = $mearesult->readAll(); foreach ($result as $frow) { $question['ANSWER'] .= "\t<tr class=\"{$rowclass}\">\n"; $rowclass = alternation($rowclass, 'row'); $answertext = $frow['question']; if (strpos($answertext, '|')) { $answertext = substr($answertext, 0, strpos($answertext, '|')); } $question['ANSWER'] .= "\t\t\t\t\t<th class=\"answertext\">{$answertext}</th>\n"; //$printablesurveyoutput .="\t\t\t\t\t<td>"; for ($i = 1; $i <= $fcount; $i++) { $question['ANSWER'] .= "\t\t\t<td>\n"; if ($checkboxlayout === false) { $question['ANSWER'] .= "\t\t\t\t" . self::_input_type_image('text', '', 4) . self::_addsgqacode(" (" . $fieldname . $frow['title'] . "_" . $xaxisarray[$i] . ") ") . "\n"; } else { $question['ANSWER'] .= "\t\t\t\t" . self::_input_type_image('checkbox') . self::_addsgqacode(" (" . $fieldname . $frow['title'] . "_" . $xaxisarray[$i] . ") ") . "\n"; } $question['ANSWER'] .= "\t\t\t</td>\n"; } $answertext = $frow['question']; if (strpos($answertext, '|')) { $answertext = substr($answertext, strpos($answertext, '|') + 1); $question['ANSWER'] .= "\t\t\t<th class=\"answertextright\">{$answertext}</th>\n"; } $question['ANSWER'] .= "\t\t</tr>\n"; $a++; } $question['ANSWER'] .= "\t</tbody>\n</table>\n"; break; // ================================================================== // ================================================================== case ";": //ARRAY (Multi Flexible) (text) $headstyle = "style='padding-left: 20px; padding-right: 7px'"; $mearesult = Question::model()->getAllRecords(" parent_qid='{$deqrow['qid']}' AND scale_id=0 AND language='{$sLanguageCode}' ", array('question_order')); $mearesult = $mearesult->readAll(); $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $sLanguageCode, $surveyid); $question['ANSWER'] .= "\n<table>\n\t<thead>\n\t\t<tr>\n\t\t\t<td> </td>\n"; $fresult = Question::model()->getAllRecords(" parent_qid='{$deqrow['qid']}' AND scale_id=1 AND language='{$sLanguageCode}' ", array('question_order')); $fresult = $fresult->readAll(); $fcount = count($fresult); $fwidth = "120"; $i = 0; //array to temporary store X axis question codes $xaxisarray = array(); foreach ($fresult as $frow) { $question['ANSWER'] .= "\t\t\t<th>{$frow['question']}</th>\n"; $i++; //add current question code $xaxisarray[$i] = $frow['title']; } $question['ANSWER'] .= "\t\t</tr>\n\t</thead>\n\n<tbody>\n"; $a = 1; $rowclass = 'array1'; foreach ($mearesult as $mearow) { $question['ANSWER'] .= "\t\t<tr class=\"{$rowclass}\">\n"; $rowclass = alternation($rowclass, 'row'); $answertext = $mearow['question']; if (strpos($answertext, '|')) { $answertext = substr($answertext, 0, strpos($answertext, '|')); } $question['ANSWER'] .= "\t\t\t<th class=\"answertext\">{$answertext}</th>\n"; for ($i = 1; $i <= $fcount; $i++) { $question['ANSWER'] .= "\t\t\t<td>\n"; $question['ANSWER'] .= "\t\t\t\t" . self::_input_type_image('text', '', 23) . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . "_" . $xaxisarray[$i] . ") ") . "\n"; $question['ANSWER'] .= "\t\t\t</td>\n"; } $answertext = $mearow['question']; if (strpos($answertext, '|')) { $answertext = substr($answertext, strpos($answertext, '|') + 1); $question['ANSWER'] .= "\t\t\t\t<th class=\"answertextright\">{$answertext}</th>\n"; } $question['ANSWER'] .= "\t\t</tr>\n"; $a++; } $question['ANSWER'] .= "\t</tbody>\n</table>\n"; break; // ================================================================== // ================================================================== case "F": //ARRAY (Flexible Labels) $question['QUESTION_TYPE_HELP'] .= gT("Please choose the appropriate response for each item:"); $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $sLanguageCode, $surveyid); $fresult = Answer::model()->getAllRecords(" scale_id=0 AND qid='{$deqrow['qid']}' AND language='{$sLanguageCode}'", array('sortorder', 'code')); $fresult = $fresult->readAll(); $fcount = count($fresult); $fwidth = "120"; $i = 1; $column_headings = array(); foreach ($fresult as $frow) { $column_headings[] = $frow['answer'] . self::_addsgqacode(" (" . $frow['code'] . ")"); } if (trim($qidattributes['answer_width']) != '') { $iAnswerWidth = 100 - $qidattributes['answer_width']; } else { $iAnswerWidth = 80; } if (count($column_headings) > 0) { $col_width = round($iAnswerWidth / count($column_headings)); } else { $heading = ''; } $question['ANSWER'] .= "\n<table>\n\t<thead>\n\t\t<tr>\n"; $question['ANSWER'] .= "\t\t\t<td> </td>\n"; foreach ($column_headings as $heading) { $question['ANSWER'] .= "\t\t\t<th style=\"width:{$col_width}%;\">{$heading}</th>\n"; } $i++; $question['ANSWER'] .= "\t\t</tr>\n\t</thead>\n\n\t<tbody>\n"; $counter = 1; $rowclass = 'array1'; $mearesult = Question::model()->getAllRecords(" parent_qid='{$deqrow['qid']}' AND language='{$sLanguageCode}' ", array('question_order')); foreach ($mearesult->readAll() as $mearow) { $question['ANSWER'] .= "\t\t<tr class=\"{$rowclass}\">\n"; $rowclass = alternation($rowclass, 'row'); if (trim($answertext) == '') { $answertext = ' '; } //semantic differential question type? if (strpos($mearow['question'], '|')) { $answertext = substr($mearow['question'], 0, strpos($mearow['question'], '|')) . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . ")") . " "; } else { $answertext = $mearow['question'] . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . ")"); } if (trim($qidattributes['answer_width']) != '') { $sInsertStyle = ' style="width:' . $qidattributes['answer_width'] . '%" '; } else { $sInsertStyle = ''; } $question['ANSWER'] .= "\t\t\t<th {$sInsertStyle} class=\"answertext\">{$answertext}</th>\n"; for ($i = 1; $i <= $fcount; $i++) { $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio') . "</td>\n"; } $counter++; $answertext = $mearow['question']; //semantic differential question type? if (strpos($mearow['question'], '|')) { $answertext2 = substr($mearow['question'], strpos($mearow['question'], '|') + 1); $question['ANSWER'] .= "\t\t\t<th class=\"answertextright\">{$answertext2}</th>\n"; } $question['ANSWER'] .= "\t\t</tr>\n"; } $question['ANSWER'] .= "\t</tbody>\n</table>\n"; break; // ================================================================== // ================================================================== case "1": //ARRAY (Flexible Labels) multi scale $leftheader = $qidattributes['dualscale_headerA'][$sLanguageCode]; $rightheader = $qidattributes['dualscale_headerB'][$sLanguageCode]; $headstyle = 'style="padding-left: 20px; padding-right: 7px"'; $question['QUESTION_TYPE_HELP'] .= gT("Please choose the appropriate response for each item:"); $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $sLanguageCode, $surveyid); $question['ANSWER'] .= "\n<table>\n\t<thead>\n"; $condition = "qid= '{$deqrow['qid']}' AND language= '{$sLanguageCode}' AND scale_id=0"; $fresult = Answer::model()->getAllRecords($condition, array('sortorder', 'code')); $fresult = $fresult->readAll(); $fcount = count($fresult); $fwidth = "120"; $l1 = 0; $printablesurveyoutput2 = "\t\t\t<td> </td>\n"; $myheader2 = ''; foreach ($fresult as $frow) { $printablesurveyoutput2 .= "\t\t\t<th>{$frow['answer']}" . self::_addsgqacode(" (" . $frow['code'] . ")") . "</th>\n"; $myheader2 .= "<td></td>"; $l1++; } // second scale $printablesurveyoutput2 .= "\t\t\t<td> </td>\n"; //$fquery1 = "SELECT * FROM {{answers}} WHERE qid='{$deqrow['qid']}' AND language='{$sLanguageCode}' AND scale_id=1 ORDER BY sortorder, code"; // $fresult1 = Yii::app()->db->createCommand($fquery1)->query(); $fresult1 = Answer::model()->getAllRecords(" qid='{$deqrow['qid']}' AND language='{$sLanguageCode}' AND scale_id=1 ", array('sortorder', 'code')); $fresult1 = $fresult1->readAll(); $fcount1 = count($fresult1); $fwidth = "120"; $l2 = 0; //array to temporary store second scale question codes $scale2array = array(); foreach ($fresult1 as $frow1) { $printablesurveyoutput2 .= "\t\t\t<th>{$frow1['answer']}" . self::_addsgqacode(" (" . $frow1['code'] . ")") . "</th>\n"; //add current question code $scale2array[$l2] = $frow1['code']; $l2++; } // build header if needed if ($leftheader != '' || $rightheader != '') { $myheader = "\t\t\t<td> </td>"; $myheader .= "\t\t\t<th colspan=\"" . $l1 . "\">{$leftheader}</th>\n"; if ($rightheader != '') { // $myheader .= "\t\t\t\t\t" .$myheader2; $myheader .= "\t\t\t<td> </td>"; $myheader .= "\t\t\t<th colspan=\"" . $l2 . "\">{$rightheader}</td>\n"; } $myheader .= "\t\t\t\t</tr>\n"; } else { $myheader = ''; } $question['ANSWER'] .= $myheader . "\t\t</tr>\n\n\t\t<tr>\n"; $question['ANSWER'] .= $printablesurveyoutput2; $question['ANSWER'] .= "\t\t</tr>\n\t</thead>\n\n\t<tbody>\n"; $rowclass = 'array1'; //counter for each subquestion $sqcounter = 0; $mearesult = Question::model()->getAllRecords(" parent_qid={$deqrow['qid']} AND language='{$sLanguageCode}' ", array('question_order')); foreach ($mearesult->readAll() as $mearow) { $question['ANSWER'] .= "\t\t<tr class=\"{$rowclass}\">\n"; $rowclass = alternation($rowclass, 'row'); $answertext = $mearow['question'] . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . "#0) / (" . $fieldname . $mearow['title'] . "#1)"); if (strpos($answertext, '|')) { $answertext = substr($answertext, 0, strpos($answertext, '|')); } $question['ANSWER'] .= "\t\t\t<th class=\"answertext\">{$answertext}</th>\n"; for ($i = 1; $i <= $fcount; $i++) { $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio') . "</td>\n"; } $question['ANSWER'] .= "\t\t\t<td> </td>\n"; for ($i = 1; $i <= $fcount1; $i++) { $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio') . "</td>\n"; } $answertext = $mearow['question']; if (strpos($answertext, '|')) { $answertext = substr($answertext, strpos($answertext, '|') + 1); $question['ANSWER'] .= "\t\t\t<th class=\"answertextright\">{$answertext}</th>\n"; } $question['ANSWER'] .= "\t\t</tr>\n"; //increase subquestion counter $sqcounter++; } $question['ANSWER'] .= "\t</tbody>\n</table>\n"; break; // ================================================================== // ================================================================== case "H": //ARRAY (Flexible Labels) by Column //$headstyle="style='border-left-style: solid; border-left-width: 1px; border-left-color: #AAAAAA'"; $headstyle = "style='padding-left: 20px; padding-right: 7px'"; $condition = "parent_qid= '{$deqrow['qid']}' AND language= '{$sLanguageCode}'"; $fresult = Question::model()->getAllRecords($condition, array('question_order', 'title')); $fresult = $fresult->readAll(); $question['QUESTION_TYPE_HELP'] .= gT("Please choose the appropriate response for each item:"); $question['ANSWER'] .= "\n<table>\n\t<thead>\n\t\t<tr>\n\t\t\t<td> </td>\n"; $fcount = count($fresult); $fwidth = "120"; $i = 0; foreach ($fresult as $frow) { $question['ANSWER'] .= "\t\t\t<th>{$frow['question']}" . self::_addsgqacode(" (" . $fieldname . $frow['title'] . ")") . "</th>\n"; $i++; } $question['ANSWER'] .= "\t\t</tr>\n\t</thead>\n\n\t<tbody>\n"; $a = 1; $rowclass = 'array1'; $mearesult = Answer::model()->getAllRecords(" qid='{$deqrow['qid']}' AND scale_id=0 AND language='{$sLanguageCode}' ", array('sortorder', 'code')); foreach ($mearesult->readAll() as $mearow) { //$_POST['type']=$type; $question['ANSWER'] .= "\t\t<tr class=\"{$rowclass}\">\n"; $rowclass = alternation($rowclass, 'row'); $question['ANSWER'] .= "\t\t\t<th class=\"answertext\">{$mearow['answer']}" . self::_addsgqacode(" (" . $mearow['code'] . ")") . "</th>\n"; //$printablesurveyoutput .="\t\t\t\t\t<td>"; for ($i = 1; $i <= $fcount; $i++) { $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio') . "</td>\n"; } //$printablesurveyoutput .="\t\t\t\t\t</tr></table></td>\n"; $question['ANSWER'] .= "\t\t</tr>\n"; $a++; } $question['ANSWER'] .= "\t</tbody>\n</table>\n"; break; case "|": // File Upload $question['QUESTION_TYPE_HELP'] .= "Kindly attach the aforementioned documents along with the survey"; break; // === END SWITCH =================================================== } $question['QUESTION_TYPE_HELP'] = self::_star_replace($question['QUESTION_TYPE_HELP']); $group['QUESTIONS'] .= self::_populate_template('question', $question); } if ($bGroupHasVisibleQuestions) { $survey_output['GROUPS'] .= self::_populate_template('group', $group); } } $survey_output['THEREAREXQUESTIONS'] = str_replace('{NUMBEROFQUESTIONS}', $total_questions, gT('There are {NUMBEROFQUESTIONS} questions in this survey')); // START recursive tag stripping. // PHP 5.1.0 introduced the count parameter for preg_replace() and thus allows this procedure to run with only one regular expression. // Previous version of PHP needs two regular expressions to do the same thing and thus will run a bit slower. $server_is_newer = version_compare(PHP_VERSION, '5.1.0', '>'); $rounds = 0; while ($rounds < 1) { $replace_count = 0; if ($server_is_newer) { $survey_output['GROUPS'] = preg_replace(array('/<td>(?: | | )?<\\/td>/isU', '/<th[^>]*>(?: | | )?<\\/th>/isU', '/<([^ >]+)[^>]*>(?: | |\\r\\n|\\n\\r|\\n|\\r|\\t| )*<\\/\\1>/isU'), array('[[EMPTY-TABLE-CELL]]', '[[EMPTY-TABLE-CELL-HEADER]]', ''), $survey_output['GROUPS'], -1, $replace_count); } else { $survey_output['GROUPS'] = preg_replace(array('/<td>(?: | | )?<\\/td>/isU', '/<th[^>]*>(?: | | )?<\\/th>/isU', '/<([^ >]+)[^>]*>(?: | |\\r\\n|\\n\\r|\\n|\\r|\\t| )*<\\/\\1>/isU'), array('[[EMPTY-TABLE-CELL]]', '[[EMPTY-TABLE-CELL-HEADER]]', ''), $survey_output['GROUPS']); $replace_count = preg_match('/<([^ >]+)[^>]*>(?: | |\\r\\n|\\n\\r|\\n|\\r|\\t| )*<\\/\\1>/isU', $survey_output['GROUPS']); } if ($replace_count == 0) { ++$rounds; $survey_output['GROUPS'] = preg_replace(array('/\\[\\[EMPTY-TABLE-CELL\\]\\]/', '/\\[\\[EMPTY-TABLE-CELL-HEADER\\]\\]/', '/\\n(?:\\t*\\n)+/'), array('<td> </td>', '<th> </th>', "\n"), $survey_output['GROUPS']); } } $survey_output['GROUPS'] = preg_replace('/(<div[^>]*>){NOTEMPTY}(<\\/div>)/', '\\1 \\2', $survey_output['GROUPS']); // END recursive empty tag stripping. echo self::_populate_template('survey', $survey_output); } // End print }
public function getAnswerByWeight($weight) { $criteria = new CDbCriteria(); $criteria->condition = "questionId=:questionId and weight=:weight"; $criteria->params = array(':questionId' => $this->questionId, ':weight' => $weight); $answer = Answer::model()->find($criteria); return $answer; }
public function init() { parent::init(); $app = Yii::app(); if (isset($_GET['lang'])) { $app->language = $_GET['lang']; $app->session['_lang'] = $app->language; } elseif (isset($app->session['_lang'])) { $app->language = $app->session['_lang']; } if (isset($_GET['id']) && Yii::app()->controller->id == "questionnaire") { $criteria = new EMongoCriteria(); $ficheQuestion = Questionnaire::model()->findByPk(new MongoId($_GET['id'])); $_SESSION['idQuestion'] = $ficheQuestion; if (isset($_SESSION['activeProfil'])) { if (Yii::app()->urlManager->parseUrl(Yii::app()->request) == "questionnaire/update") { if ($_SESSION['idQuestion']->type == "clinique") { if (!Yii::app()->user->isAuthorizedCreate($_SESSION['activeProfil'], "clinique")) { Yii::app()->user->setFlash(TbAlert::TYPE_ERROR, Yii::t('common', 'notAllowCreateClinicalPatientForm')); $this->redirect(array('answer/affichepatient')); } } if ($_SESSION['idQuestion']->type == "genetique") { if (!Yii::app()->user->isAuthorizedCreate($_SESSION['activeProfil'], "genetique")) { Yii::app()->user->setFlash(TbAlert::TYPE_ERROR, Yii::t('common', 'notAllowCreateGeneticPatientForm')); $this->redirect(array('answer/affichepatient')); } } if ($_SESSION['idQuestion']->type == "neuropathologique") { if (!Yii::app()->user->isAuthorizedCreate($_SESSION['activeProfil'], "neuropathologique")) { Yii::app()->user->setFlash(TbAlert::TYPE_ERROR, Yii::t('common', 'notAllowCreateNeuropathologicalPatientForm')); $this->redirect(array('answer/affichepatient')); } } } } } if (isset($_GET['id']) && Yii::app()->controller->id == "answer") { $criteria = new EMongoCriteria(); $fiche = Answer::model()->findByPk(new MongoId($_GET['id'])); $_SESSION['id'] = $fiche; if (isset($_SESSION['activeProfil'])) { if (Yii::app()->urlManager->parseUrl(Yii::app()->request) == "answer/view" || Yii::app()->urlManager->parseUrl(Yii::app()->request) == "answer/update") { if ($_SESSION['id']->type == "clinique") { if (Yii::app()->urlManager->parseUrl(Yii::app()->request) == "answer/view") { if (!Yii::app()->user->isAuthorizedView($_SESSION['activeProfil'], "clinique")) { Yii::app()->user->setFlash(TbAlert::TYPE_ERROR, Yii::t('common', 'notAllowViewClinicalPatientForm')); $this->redirect(array('answer/affichepatient')); } elseif ($_SESSION['activeProfil'] == "clinicien" && Yii::app()->user->id != $_SESSION['id']->login) { Yii::app()->user->setFlash(TbAlert::TYPE_ERROR, Yii::t('common', 'notAllowViewSelfClinicalPatientForm')); $this->redirect(array('answer/affichepatient')); } } if (Yii::app()->urlManager->parseUrl(Yii::app()->request) == "answer/update") { if (!Yii::app()->user->isAuthorizedUpdate($_SESSION['activeProfil'], "clinique")) { Yii::app()->user->setFlash(TbAlert::TYPE_ERROR, Yii::t('common', 'notAllowUpdateClinicalPatientForm')); $this->redirect(array('answer/affichepatient')); } } } if ($_SESSION['id']->type == "neuropathologique") { if (Yii::app()->urlManager->parseUrl(Yii::app()->request) == "answer/view") { if (!Yii::app()->user->isAuthorizedView($_SESSION['activeProfil'], "neuropathologique")) { Yii::app()->user->setFlash(TbAlert::TYPE_ERROR, Yii::t('common', 'notAllowViewNeuropathologicalPatientForm')); $this->redirect(array('answer/affichepatient')); } } if (Yii::app()->urlManager->parseUrl(Yii::app()->request) == "answer/update") { if (!Yii::app()->user->isAuthorizedUpdate($_SESSION['activeProfil'], "neuropathologique")) { Yii::app()->user->setFlash(TbAlert::TYPE_ERROR, Yii::t('common', 'notAllowUpdateNeuropathologicalPatientForm')); $this->redirect(array('answer/affichepatient')); } } } if ($_SESSION['id']->type == "genetique") { if (Yii::app()->urlManager->parseUrl(Yii::app()->request) == "answer/view") { if (!Yii::app()->user->isAuthorizedView($_SESSION['activeProfil'], "genetique")) { Yii::app()->user->setFlash(TbAlert::TYPE_ERROR, Yii::t('common', 'notAllowViewGeneticPatientForm')); $this->redirect(array('answer/affichepatient')); } } if (Yii::app()->urlManager->parseUrl(Yii::app()->request) == "answer/update") { if (!Yii::app()->user->isAuthorizedUpdate($_SESSION['activeProfil'], "genetique")) { Yii::app()->user->setFlash(TbAlert::TYPE_ERROR, Yii::t('common', 'notAllowUpdateGeneticPatientForm')); $this->redirect(array('answer/affichepatient')); } } } } } } if (isset($_POST['activeProfil'])) { if ($_POST['activeProfil'] === "newProfil") { $this->redirect('index.php?r=site/updatesubscribe'); } else { $app->user->setState('activeProfil', $_POST['activeProfil']); $_SESSION['activeProfil'] = $_POST['activeProfil']; if (Yii::app()->controller->id == "rechercheFiche" && Yii::app()->user->getActiveProfil() == "clinicien") { Yii::app()->user->setFlash(TbAlert::TYPE_ERROR, Yii::t('common', 'notAllowSearchPatientForm')); $this->redirect('index.php?r=site/index'); } if (Yii::app()->controller->id == "user" || Yii::app()->controller->id == "formulaire" || Yii::app()->controller->id == "fiche" || Yii::app()->controller->id == "questionBloc" || Yii::app()->controller->id == "administration" || Yii::app()->controller->id == "auditTrail" || Yii::app()->urlManager->parseUrl(Yii::app()->request) == "admin/admin") { if (Yii::app()->user->getActiveProfil() != "administrateur") { Yii::app()->user->setFlash(TbAlert::TYPE_ERROR, Yii::t('common', 'notAllowManagement')); $this->redirect('index.php?r=site/index'); } } if (Yii::app()->urlManager->parseUrl(Yii::app()->request) == "answer/view" || Yii::app()->urlManager->parseUrl(Yii::app()->request) == "answer/update") { if ($_SESSION['id']->type == "clinique") { if (Yii::app()->urlManager->parseUrl(Yii::app()->request) == "answer/view") { if (!Yii::app()->user->isAuthorizedView($_SESSION['activeProfil'], "clinique")) { Yii::app()->user->setFlash(TbAlert::TYPE_ERROR, Yii::t('common', 'notAllowViewClinicalPatientForm')); $this->redirect(array('answer/affichepatient')); } elseif ($_SESSION['activeProfil'] == "clinicien" && Yii::app()->user->id != $_SESSION['id']->login) { Yii::app()->user->setFlash(TbAlert::TYPE_ERROR, Yii::t('common', 'notAllowViewSelfClinicalPatientForm')); $this->redirect(array('answer/affichepatient')); } $this->redirect('index.php?r=answer/view&id=' . $_SESSION['id']->_id); } if (Yii::app()->urlManager->parseUrl(Yii::app()->request) == "answer/update") { if (!Yii::app()->user->isAuthorizedUpdate($_SESSION['activeProfil'], "clinique")) { Yii::app()->user->setFlash(TbAlert::TYPE_ERROR, Yii::t('common', 'notAllowUpdateClinicalPatientForm')); $this->redirect(array('answer/affichepatient')); } else { $this->redirect('index.php?r=answer/update&id=' . $_SESSION['id']->_id); } } } if ($_SESSION['id']->type == "neuropathologique") { if (Yii::app()->urlManager->parseUrl(Yii::app()->request) == "answer/view") { if (!Yii::app()->user->isAuthorizedView($_SESSION['activeProfil'], "neuropathologique")) { Yii::app()->user->setFlash(TbAlert::TYPE_ERROR, Yii::t('common', 'notAllowViewNeuropathologicalPatientForm')); $this->redirect(array('answer/affichepatient')); } else { $this->redirect('index.php?r=answer/view&id=' . $_SESSION['id']->_id); } } if (Yii::app()->urlManager->parseUrl(Yii::app()->request) == "answer/update") { if (!Yii::app()->user->isAuthorizedUpdate($_SESSION['activeProfil'], "neuropathologique")) { Yii::app()->user->setFlash(TbAlert::TYPE_ERROR, Yii::t('common', 'notAllowUpdateNeuropathologicalPatientForm')); $this->redirect(array('answer/affichepatient')); } else { $this->redirect('index.php?r=answer/update&id=' . $_SESSION['id']->_id); } } } if ($_SESSION['id']->type == "genetique") { if (Yii::app()->urlManager->parseUrl(Yii::app()->request) == "answer/view") { if (!Yii::app()->user->isAuthorizedView($_SESSION['activeProfil'], "genetique")) { Yii::app()->user->setFlash(TbAlert::TYPE_ERROR, Yii::t('common', 'notAllowViewGeneticPatientForm')); $this->redirect(array('answer/affichepatient')); } else { $this->redirect('index.php?r=answer/view&id=' . $_SESSION['id']->_id); } } if (Yii::app()->urlManager->parseUrl(Yii::app()->request) == "answer/update") { if (!Yii::app()->user->isAuthorizedUpdate($_SESSION['activeProfil'], "genetique")) { Yii::app()->user->setFlash(TbAlert::TYPE_ERROR, Yii::t('common', 'notAllowUpdateGeneticPatientForm')); $this->redirect(array('answer/affichepatient')); } else { $this->redirect('index.php?r=answer/update&id=' . $_SESSION['id']->_id); } } } } if (Yii::app()->urlManager->parseUrl(Yii::app()->request) == "questionnaire/update") { if ($_SESSION['idQuestion']->type == "clinique") { if (Yii::app()->urlManager->parseUrl(Yii::app()->request) == "questionnaire/update") { if (!Yii::app()->user->isAuthorizedCreate($_SESSION['activeProfil'], "clinique")) { Yii::app()->user->setFlash(TbAlert::TYPE_ERROR, Yii::t('common', 'notAllowCreateClinicalPatientForm')); $this->redirect(array('answer/affichepatient')); } else { $this->redirect('index.php?r=questionnaire/update&id=' . $_SESSION['idQuestion']->_id); } } } if ($_SESSION['idQuestion']->type == "neuropathologique") { if (Yii::app()->urlManager->parseUrl(Yii::app()->request) == "questionnaire/update") { if (!Yii::app()->user->isAuthorizedCreate($_SESSION['activeProfil'], "neuropathologique")) { Yii::app()->user->setFlash(TbAlert::TYPE_ERROR, Yii::t('common', 'notAllowCreateNeuropathologicalPatientForm')); $this->redirect(array('answer/affichepatient')); } else { $this->redirect('index.php?r=questionnaire/update&id=' . $_SESSION['idQuestion']->_id); } } } if ($_SESSION['idQuestion']->type == "genetique") { if (Yii::app()->urlManager->parseUrl(Yii::app()->request) == "questionnaire/update") { if (!Yii::app()->user->isAuthorizedCreate($_SESSION['activeProfil'], "genetique")) { Yii::app()->user->setFlash(TbAlert::TYPE_ERROR, Yii::t('common', 'notAllowCreateGeneticPatientForm')); $this->redirect(array('answer/affichepatient')); } else { $this->redirect('index.php?r=questionnaire/update&id=' . $_SESSION['idQuestion']->_id); } } } } } } }