public function loadModel($id)
 {
     if (($model = Question::model()->findByPk($id)) === null) {
         throw new CHttpException(404, Yii::t('FaqModule.faq', 'Page was not found!'));
     }
     return $model;
 }
Ejemplo n.º 2
0
 /**
  * 批量操作
  *
  */
 public function actionBatch()
 {
     if ($this->method() == 'GET') {
         $command = trim($this->_request->getParam('command'));
         $ids = intval($this->_request->getParam('id'));
     } elseif ($this->method() == 'POST') {
         $command = $this->_request->getPost('command');
         $ids = $this->_request->getPost('id');
     } else {
         throw new CHttpException(404, Yii::t('admin', 'Only POST Or GET'));
     }
     empty($ids) && $this->message('error', Yii::t('admin', 'No Select'));
     switch ($command) {
         case 'delete':
             foreach ((array) $ids as $id) {
                 $questionModel = Question::model()->findByPk($id);
                 if ($questionModel) {
                     $questionModel->delete();
                 }
             }
             break;
         default:
             throw new CHttpException(404, Yii::t('admin', 'Error Operation'));
             break;
     }
     $this->message('success', Yii::t('admin', 'Batch Operate Success'));
 }
Ejemplo n.º 3
0
 private function search($search)
 {
     $criteria = new CDbCriteria();
     $criteria->addSearchCondition('content', $search);
     $questions = Question::model()->with('user', 'tags')->findAll($criteria);
     return $questions;
 }
Ejemplo n.º 4
0
 public function actionCheckQuestion()
 {
     $transaction = Yii::app()->db->beginTransaction();
     try {
         $qc_models = new QuestionComments();
         $qc_models->message = $_POST['CommentForm']['message'];
         $qc_models->question_id = $_POST['CommentForm']['comment_id'];
         //查看该问题是否已经被锁定
         if ($this->is_lock($qc_models->question_id)) {
             throw new Exception("该问题已经被锁定!");
         }
         $qc_models->uid = Yii::app()->user->id;
         $qc_models->time = time();
         if (!$qc_models->save()) {
             throw new Exception('评论失败');
         }
         //在question中的 comment_count字段+1
         if (!Question::model()->updateByPk($qc_models->question_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 loadModel($id)
 {
     if (($model = Question::model()->findByPk($id)) === null) {
         throw new CHttpException(404, 'Страница не найдена');
     }
     return $model;
 }
Ejemplo n.º 6
0
 /**
  * 验证回答
  */
 public function actionCheckAnswer()
 {
     //登入判断
     $this->checkAuth();
     $model = new AnswerForm();
     if (isset($_POST['ajax']) && $_POST['ajax'] === 'answer-form') {
         echo CActiveForm::validate($model);
         Yii::app()->end();
     }
     //var_dump($_POST['AnswerForm']);
     //启用事物处理 因为需要插入 Answer表及Question字段中的answer_count 字段
     $transaction = Yii::app()->db->beginTransaction();
     try {
         $answer_model = new Answer();
         $answer_model->answer_content = $_POST['AnswerForm']['answer_content'];
         $answer_model->question_id = $_POST['AnswerForm']['question_id'];
         $answer_model->uid = Yii::app()->user->id;
         $answer_model->add_time = time();
         $answer_model->ip = Yii::app()->request->userHostAddress;
         if (!$answer_model->save()) {
             throw new ErrorException('回答失败1');
         }
         //更改question表中的answer_count 信息
         if (!Question::model()->updateByPk($answer_model->question_id, array('answer_count' => new CDbExpression('answer_count+1')))) {
             throw new ErrorException('回答失败2');
         }
         $transaction->commit();
         $this->redirect(Yii::app()->request->urlReferrer);
         //$this->success('回答成功');
     } catch (Exception $e) {
         $transaction->rollBack();
         //exit($e->getMessage());
         $this->error($e->getMessage());
     }
 }
Ejemplo n.º 7
0
 public function run()
 {
     App()->loadHelper('surveytranslator');
     $aData['issuperadmin'] = false;
     if (Permission::model()->hasGlobalPermission('superadmin', 'read')) {
         $aData['issuperadmin'] = true;
     }
     // We get the last survey visited by user
     $setting_entry = 'last_survey_' . Yii::app()->user->getId();
     $lastsurvey = getGlobalSetting($setting_entry);
     $survey = Survey::model()->findByPk($lastsurvey);
     if ($lastsurvey != null && $survey) {
         $aData['showLastSurvey'] = true;
         $iSurveyID = $lastsurvey;
         $surveyinfo = $survey->surveyinfo;
         $aData['surveyTitle'] = $surveyinfo['surveyls_title'] . "(" . gT("ID") . ":" . $iSurveyID . ")";
         $aData['surveyUrl'] = $this->getController()->createUrl("admin/survey/sa/view/surveyid/{$iSurveyID}");
     } else {
         $aData['showLastSurvey'] = false;
     }
     // We get the last question visited by user
     $setting_entry = 'last_question_' . Yii::app()->user->getId();
     $lastquestion = getGlobalSetting($setting_entry);
     // the question group of this question
     $setting_entry = 'last_question_gid_' . Yii::app()->user->getId();
     $lastquestiongroup = getGlobalSetting($setting_entry);
     // the sid of this question : last_question_sid_1
     $setting_entry = 'last_question_sid_' . Yii::app()->user->getId();
     $lastquestionsid = getGlobalSetting($setting_entry);
     $survey = Survey::model()->findByPk($lastquestionsid);
     if ($lastquestion && $lastquestiongroup && $survey) {
         $baselang = $survey->language;
         $aData['showLastQuestion'] = true;
         $qid = $lastquestion;
         $gid = $lastquestiongroup;
         $sid = $lastquestionsid;
         $qrrow = Question::model()->findByAttributes(array('qid' => $qid, 'gid' => $gid, 'sid' => $sid, 'language' => $baselang));
         if ($qrrow) {
             $aData['last_question_name'] = $qrrow['title'];
             if ($qrrow['question']) {
                 $aData['last_question_name'] .= ' : ' . $qrrow['question'];
             }
             $aData['last_question_link'] = $this->getController()->createUrl("admin/questions/sa/view/surveyid/{$sid}/gid/{$gid}/qid/{$qid}");
         } else {
             $aData['showLastQuestion'] = false;
         }
     } else {
         $aData['showLastQuestion'] = false;
     }
     $aData['countSurveyList'] = count(getSurveyList(true));
     // We get the home page display setting
     $aData['bShowSurveyList'] = getGlobalSetting('show_survey_list') == "show";
     $aData['bShowSurveyListSearch'] = getGlobalSetting('show_survey_list_search') == "show";
     $aData['bShowLogo'] = getGlobalSetting('show_logo') == "show";
     $aData['oSurveySearch'] = new Survey('search');
     $aData['bShowLastSurveyAndQuestion'] = getGlobalSetting('show_last_survey_and_question') == "show";
     $aData['iBoxesByRow'] = (int) getGlobalSetting('boxes_by_row');
     $aData['sBoxesOffSet'] = (string) getGlobalSetting('boxes_offset');
     $this->_renderWrappedTemplate('super', 'welcome', $aData);
 }
Ejemplo n.º 8
0
 protected function loadQuestion($questId)
 {
     if ($this->_question === null) {
         $this->_question = Question::model()->findByPk($questId);
         if ($this->_question === null) {
             throw new CHttpException(404, 'The requested Question does not exists');
         }
     }
     return $this->_question;
 }
Ejemplo n.º 9
0
 /**
  * 判断数据是否存在
  * 
  * return \$this->model
  */
 public function loadModel()
 {
     if ($this->model === null) {
         if (isset($_GET['id'])) {
             $this->model = Question::model()->with('user')->findbyPk($_GET['id']);
         }
         if ($this->model === null) {
             throw new CHttpException(404, Yii::t('common', 'The requested page does not exist.'));
         }
     }
     return $this->model;
 }
Ejemplo n.º 10
0
 public function actionQuestion($questionid)
 {
     $question = Question::model()->findByPk($questionid);
     $question->viewNum = $question->viewNum + 1;
     if ($question->save()) {
         $questionView = new QuestionView();
         $questionView->userId = Yii::app()->user->isGuest ? 0 : Yii::app()->user->id;
         $questionView->ip = Yii::app()->request->getUserHostAddress();
         $questionView->questionid = $questionid;
         $questionView->save();
     }
 }
Ejemplo n.º 11
0
 /**
  * Delete all files related to this repsonse.
  */
 public function getFiles()
 {
     $questions = Question::model()->findAllByAttributes(array('sid' => $this->dynamicId, 'type' => '|'));
     $files = array();
     foreach ($questions as $question) {
         $field = "{$question->sid}X{$question->gid}X{$question->qid}";
         $data = json_decode(stripslashes($this->getAttribute($field)), true);
         if (is_array($data)) {
             $files = array_merge($files, $data);
         }
     }
     return $files;
 }
Ejemplo n.º 12
0
/**
* fixes the numbering of questions
* This can happen if question 1 have subquestion code 1 and have question 11 in same survey and group (then same SGQA)
* @param int $fixnumbering
* @todo can call this function (no $_GET, but getParam) AND do it with Yii
*/
function fixNumbering($iQuestionID, $iSurveyID)
{
    Yii::app()->loadHelper("database");
    LimeExpressionManager::RevertUpgradeConditionsToRelevance($iSurveyID);
    //Fix a question id - requires renumbering a question
    $iQuestionID = (int) $iQuestionID;
    $iMaxQID = Question::model()->getMaxId('qid', true);
    // Always refresh as we insert new qid's
    $iNewQID = $iMaxQID + 1;
    // Not sure we can do this in MSSQL ?
    $sQuery = "UPDATE {{questions}} SET qid={$iNewQID} WHERE qid={$iQuestionID}";
    Yii::app()->db->createCommand($sQuery)->query();
    // Update subquestions
    $sQuery = "UPDATE {{questions}} SET parent_qid={$iNewQID} WHERE parent_qid={$iQuestionID}";
    Yii::app()->db->createCommand($sQuery)->query();
    //Update conditions.. firstly conditions FOR this question
    $sQuery = "UPDATE {{conditions}} SET qid={$iNewQID} WHERE qid={$iQuestionID}";
    Yii::app()->db->createCommand($sQuery)->query();
    //Update default values
    $sQuery = "UPDATE {{defaultvalues}} SET qid={$iNewQID} WHERE qid={$iQuestionID}";
    Yii::app()->db->createCommand($sQuery)->query();
    $sQuery = "UPDATE {{defaultvalues}} SET sqid={$iNewQID} WHERE sqid={$iQuestionID}";
    Yii::app()->db->createCommand($sQuery)->query();
    //Update quotas
    $sQuery = "UPDATE {{quota_members}} SET qid={$iNewQID} WHERE qid={$iQuestionID}";
    Yii::app()->db->createCommand($sQuery)->query();
    //Update url params
    $sQuery = "UPDATE {{survey_url_parameters}} SET targetqid={$iNewQID} WHERE targetqid={$iQuestionID}";
    Yii::app()->db->createCommand($sQuery)->query();
    $sQuery = "UPDATE {{survey_url_parameters}} SET targetsqid={$iNewQID} WHERE targetsqid={$iQuestionID}";
    Yii::app()->db->createCommand($sQuery)->query();
    //Now conditions based upon this question
    $sQuery = "SELECT cqid, cfieldname FROM {{conditions}} WHERE cqid={$iQuestionID}";
    $sResult = Yii::app()->db->createCommand($sQuery)->query();
    foreach ($sResult->readAll() as $row) {
        $aSwitcher[] = array("cqid" => $row['cqid'], "cfieldname" => $row['cfieldname']);
    }
    if (isset($aSwitcher)) {
        foreach ($aSwitcher as $aSwitch) {
            $sQuery = "UPDATE {{conditions}}\n            SET cqid={$iNewQID},\n            cfieldname='" . str_replace("X" . $iQuestionID, "X" . $iNewQID, $aSwitch['cfieldname']) . "'\n            WHERE cqid={$iQuestionID}";
            $sResult = db_execute_assosc($sQuery);
        }
    }
    //Now question_attributes
    $sQuery = "UPDATE {{question_attributes}} SET qid={$iNewQID} WHERE qid={$iQuestionID}";
    Yii::app()->db->createCommand($sQuery)->query();
    //Now answers
    $sQuery = "UPDATE {{answers}} SET qid={$iNewQID} WHERE qid={$iQuestionID}";
    Yii::app()->db->createCommand($sQuery)->query();
    LimeExpressionManager::UpgradeConditionsToRelevance($iSurveyID);
}
Ejemplo n.º 13
0
 public function actionOwnerQue($uid)
 {
     Yii::app()->user->setReturnUrl(Yii::app()->request->url);
     if (Yii::app()->user->isGuest) {
         Yii::app()->user->loginRequired();
     } else {
         $cri = new CDbCriteria();
         $cri->addCondition('userId=' . $uid);
         $cri->order = 'createTime DESC';
         $viewModel = Question::model()->findAll($cri);
         $myLike = LikeQue::model()->findAll('userId=:uid', array(':uid' => Yii::app()->user->id));
         $this->render('ownerQue', array('viewModel' => $viewModel, 'uid' => $uid, 'myLike' => $myLike));
     }
 }
Ejemplo n.º 14
0
 /**
  * 删除信息
  * 多表删除  事物处理
  * 删除 question 中信息
  * 删除 answer 表中信息
  * 删除 question 
  * 更新topic中次数
  */
 public function actionDelete($id)
 {
     $transaction = Yii::app()->db->beginTransaction();
     try {
         //删除question 表信息
         if (!Question::model()->deleteByPk($id)) {
             throw new Exception("删除question表失败");
         }
         //删除 topic_question 表 首先把 topic  id 查找出来
         //获取topic id
         $topic_ids = TopicQuestion::model()->findAll(array('select' => 'topic_id', 'condition' => 'question_id=:question_id', 'params' => array(':question_id' => $id)));
         //更新 topic次数
         foreach ($topic_ids as $model) {
             //更新topic 次数
             if (!Topic::model()->updateByPk($model->topic_id, array('discuss_count' => new CDbExpression('discuss_count-1')))) {
                 throw new ErrorException('更新失败');
             }
         }
         //删除topic_question 表中信息
         if (false === TopicQuestion::model()->deleteAll('question_id=:question_id', array('question_id' => $id))) {
             throw new ErrorException('删除topic_question中信息失败');
         }
         //删除question_comment 中信息
         if (false === QuestionComments::model()->deleteAll('question_id=:question_id', array('question_id' => $id))) {
             throw new ErrorException('删除question_comment中信息失败');
         }
         //获取answer_comment 中id
         $answer_comment_models = Answer::model()->findAll(array('select' => 'id', 'condition' => 'question_id=:question_id', 'params' => array(':question_id' => $id)));
         //删除answer_comment 中信息
         foreach ($answer_comment_models as $answer_comment_model) {
             if (false === AnswerComments::model()->deleteAll('answer_id=:answer_id', array(':answer_id' => $answer_comment_model->id))) {
                 throw new ErrorException('删除answer_comment中信息失败');
             }
         }
         //删除answer 表中信息
         if (false === Answer::model()->deleteAll('question_id=:question_id', array('question_id' => $id))) {
             throw new ErrorException('删除answer中信息失败');
         }
         //删除question_focus 中信息
         if (false === QuestionFocus::model()->deleteAll('question_id=:question_id', array('question_id' => $id))) {
             throw new ErrorException('删除question_focus 中信息失败');
         }
         $transaction->commit();
         $this->success('删除成功');
     } catch (Exception $e) {
         $transaction->rollBack();
         exit($e->getMessage());
         $this->error($e->getMessage());
     }
 }
Ejemplo n.º 15
0
 public function canPublish()
 {
     $level = $this->getLevel();
     if ($level >= 10) {
         return true;
     }
     $criteria = new CDbCriteria();
     $criteria->addCondition('userId=' . $this->id);
     $criteria->addCondition('TO_DAYS(createTime)=TO_DAYS(NOW())');
     $count = Question::model()->count($criteria);
     if ($count < $level) {
         return true;
     }
     return false;
 }
Ejemplo n.º 16
0
 public function run()
 {
     App()->loadHelper('surveytranslator');
     App()->getClientScript()->registerPackage('panel-clickable');
     App()->getClientScript()->registerPackage('panels-animation');
     $aData['issuperadmin'] = false;
     if (Permission::model()->hasGlobalPermission('superadmin', 'read')) {
         $aData['issuperadmin'] = true;
     }
     // We get the last survey visited by user
     $setting_entry = 'last_survey_' . Yii::app()->user->getId();
     $lastsurvey = getGlobalSetting($setting_entry);
     if ($lastsurvey != null) {
         $aData['showLastSurvey'] = true;
         $iSurveyID = $lastsurvey;
         $surveyinfo = Survey::model()->findByPk($iSurveyID)->surveyinfo;
         $aData['surveyTitle'] = $surveyinfo['surveyls_title'] . "(" . gT("ID") . ":" . $iSurveyID . ")";
         $aData['surveyUrl'] = $this->getController()->createUrl("admin/survey/sa/view/surveyid/{$iSurveyID}");
     } else {
         $aData['showLastSurvey'] = false;
     }
     // We get the last question visited by user
     $setting_entry = 'last_question_' . Yii::app()->user->getId();
     $lastquestion = getGlobalSetting($setting_entry);
     // the question group of this question
     $setting_entry = 'last_question_gid_' . Yii::app()->user->getId();
     $lastquestiongroup = getGlobalSetting($setting_entry);
     // the sid of this question : last_question_sid_1
     $setting_entry = 'last_question_sid_' . Yii::app()->user->getId();
     $lastquestionsid = getGlobalSetting($setting_entry);
     if ($lastquestion != null && $lastquestiongroup != null) {
         $baselang = Survey::model()->findByPk($iSurveyID)->language;
         $aData['showLastQuestion'] = true;
         $qid = $lastquestion;
         $gid = $lastquestiongroup;
         $sid = $lastquestionsid;
         $qrrow = Question::model()->findByAttributes(array('qid' => $qid, 'gid' => $gid, 'sid' => $sid, 'language' => $baselang));
         $aData['last_question_name'] = $qrrow['title'];
         if ($qrrow['question']) {
             $aData['last_question_name'] .= ' : ' . $qrrow['question'];
         }
         $aData['last_question_link'] = $this->getController()->createUrl("admin/questions/sa/view/surveyid/{$iSurveyID}/gid/{$gid}/qid/{$qid}");
     } else {
         $aData['showLastQuestion'] = false;
     }
     $aData['countSurveyList'] = count(getSurveyList(true));
     $this->_renderWrappedTemplate('super', 'welcome', $aData);
 }
 protected function beforeAction($action)
 {
     $actions = array('index', 'create');
     if (in_array($action->id, $actions)) {
         $this->question_id = (int) Yii::app()->getRequest()->getParam('question_id');
         if (!$this->question_id) {
             throw new CHttpException(400, 'Не установлен ID ыопроса');
         }
         if (($this->question = Question::model()->findByPk($this->question_id)) === null) {
             throw new CHttpException(404, 'Вопрос не найден');
         }
         if (!in_array($this->question->type, array(Question::TYPE_VARIANT, Question::TYPE_MULTIPLE))) {
             throw new CHttpException(400, 'Для данного типа вопросов не предусмотрено добавление вариантов ответа');
         }
     }
     return parent::beforeAction($action);
 }
Ejemplo n.º 18
0
 /**
  * testing method return array type
  */
 public function testTypeFunction()
 {
     $model = new Question();
     $questionForm = new QuestionForm();
     $questionForm->id = "q1";
     $questionForm->label = "Question 1";
     $questionForm->type = "input";
     $questionForm->style = "";
     $questionForm->values = "";
     $questionForm->precomment = "";
     $questionForm->precomment_fr = $questionForm->precomment;
     $questionForm->help = "";
     $model->setAttributesByQuestionForm($questionForm);
     $this->assertInternalType('object', $model->model());
     $this->assertInternalType('array', $model->rules());
     $this->assertInternalType('array', $model->attributeLabels());
     $this->assertInternalType('object', $model);
 }
 /**
  * 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";
     }
 }
Ejemplo n.º 20
0
 public function run()
 {
     $ids = Yii::app()->request->getParam('id');
     $command = Yii::app()->request->getParam('command');
     empty($ids) && $this->controller->message('error', Yii::t('admin', 'No Select'));
     if (!is_array($ids)) {
         $ids = array($ids);
     }
     $criteria = new CDbCriteria();
     $criteria->addInCondition('id', $ids);
     switch ($command) {
         case 'delete':
             //删除
             Question::model()->deleteAll($criteria);
             break;
         default:
             throw new CHttpException(404, Yii::t('admin', 'Error Operation'));
     }
     $this->controller->message('success', Yii::t('admin', 'Batch Operate Success'));
 }
Ejemplo n.º 21
0
 /**
  * Displays a particular model.
  * @param integer $id the ID of the model to be displayed
  */
 public function actionView($id)
 {
     $video = $this->loadModel($id);
     $lesson = $video->lesson;
     if ($lesson->is_active == 0) {
         if (!Yii::app()->user->checkAccess('adminOwnLesson', array('lesson' => $lesson)) && !Yii::app()->user->checkAccess('adminLesson')) {
             throw new CHttpException(403, Yii::t('yii', 'You are not authorized to perform this action.'));
         }
     }
     $criteria = new CDbCriteria();
     $criteria->addCondition(array('id_lesson' => $lesson->getPrimaryKey()));
     $criteria->order = 'id DESC';
     $count = Question::model()->count($criteria);
     $questionPages = new CPagination($count);
     // results per page
     $questionPages->pageSize = Yii::app()->params['nQuestionsInLessonPage'];
     $questionPages->applyLimit($criteria);
     $questions = Question::model()->findAll($criteria);
     $banners = Banner::model()->findAll('is_active = 1');
     $this->render('view', array('model' => $this->loadModel($id), 'lesson' => $lesson, 'questions' => $questions, 'questionPages' => $questionPages, 'banners' => $banners));
 }
Ejemplo n.º 22
0
 /**
  * This is the default 'index' action that is invoked
  * when an action is not explicitly requested by users.
  */
 public function actionIndex($tab = 'new')
 {
     Yii::app()->user->setReturnUrl(Yii::app()->request->url);
     $cri = new CDbCriteria();
     switch ($tab) {
         case 'new':
             $cri->with = array('user', 'tags');
             $cri->order = 'createTime DESC';
             break;
         case 'dayHot':
             $cri->with = array('user', 'tags');
             $cri->addCondition('createTime>=NOW()-INTERVAL 1 day');
             $cri->order = 'answerCount+likeCount DESC';
             $cri->limit = 100;
             break;
         case 'weekHot':
             $cri->with = array('user', 'tags');
             $cri->addCondition('createTime>=NOW()-INTERVAL 7 day');
             $cri->order = 'answerCount+likeCount DESC';
             $cri->limit = 100;
             break;
         case 'monthHot':
             $cri->with = array('user', 'tags');
             $cri->addCondition('createTime>=NOW()-INTERVAL 30 day');
             $cri->order = 'answerCount+likeCount DESC';
             $cri->limit = 100;
             break;
         case 'unsolved':
             $cri->with = array('user', 'tags');
             $cri->addCondition('bestAnsId=0');
             $cri->order = 't.credit DESC';
             break;
         case 'all':
             $cri->with = array('user', 'tags');
             break;
     }
     $viewModel = Question::model()->findAll($cri);
     $myLike = LikeQue::model()->findAll('userId=:uid', array(':uid' => Yii::app()->user->id));
     $this->render('index', array('viewModel' => $viewModel, 'myLike' => $myLike));
 }
/**
* fixes the numbering of questions
* This can happen if question 1 have subquestion code 1 and have question 11 in same survey and group (then same SGQA)
* @param int $fixnumbering
* @todo can call this function (no $_GET, but getParam) AND do it with Yii
*/
function fixNumbering($fixnumbering, $iSurveyID)
{
    Yii::app()->loadHelper("database");
    LimeExpressionManager::RevertUpgradeConditionsToRelevance($iSurveyID);
    //Fix a question id - requires renumbering a question
    $oldqid = (int) $fixnumbering;
    $lastqid = Question::model()->getMaxId('qid', true);
    // Always refresh as we insert new qid's
    $newqid = $lastqid + 1;
    // Not sure we can do this in MSSQL ?
    $query = "UPDATE {{questions}} SET qid={$newqid} WHERE qid={$oldqid}";
    $result = db_execute_assosc($query);
    // Update subquestions
    $query = "UPDATE {{questions}} SET parent_qid={$newqid} WHERE parent_qid={$oldqid}";
    $result = db_execute_assosc($query);
    //Update conditions.. firstly conditions FOR this question
    $query = "UPDATE {{conditions}} SET qid={$newqid} WHERE qid={$oldqid}";
    $result = db_execute_assosc($query);
    //Now conditions based upon this question
    $query = "SELECT cqid, cfieldname FROM {{conditions}} WHERE cqid={$oldqid}";
    $result = dbExecuteAssoc($query);
    foreach ($result->readAll() as $row) {
        $switcher[] = array("cqid" => $row['cqid'], "cfieldname" => $row['cfieldname']);
    }
    if (isset($switcher)) {
        foreach ($switcher as $switch) {
            $query = "UPDATE {{conditions}}\n            SET cqid={$newqid},\n            cfieldname='" . str_replace("X" . $oldqid, "X" . $newqid, $switch['cfieldname']) . "'\n            WHERE cqid={$oldqid}";
            $result = db_execute_assosc($query);
        }
    }
    // TMSW Condition->Relevance:  (1) Call LEM->ConvertConditionsToRelevance()when done. (2) Should relevance for old conditions be removed first?
    //Now question_attributes
    $query = "UPDATE {{question_attributes}} SET qid={$newqid} WHERE qid={$oldqid}";
    $result = db_execute_assosc($query);
    //Now answers
    $query = "UPDATE {{answers}} SET qid={$newqid} WHERE qid={$oldqid}";
    $result = db_execute_assosc($query);
    LimeExpressionManager::UpgradeConditionsToRelevance($iSurveyID);
}
Ejemplo n.º 24
0
 public function actionAnswer()
 {
     $answer = new Answer();
     if (isset($_POST['Answer'])) {
         $answer->attributes = $_POST['Answer'];
         $answer->id_account = Yii::app()->user->getId();
         if ($answer->save()) {
             $question = $answer->question;
             $lesson = $question->lesson;
             $criteria = new CDbCriteria();
             $criteria->addCondition(array('id_lesson' => $lesson->getPrimaryKey()));
             $criteria->order = 'id DESC';
             $count = Question::model()->count($criteria);
             $questionPages = new CPagination($count);
             // results per page
             $questionPages->pageSize = Yii::app()->params['nQuestionsInLessonPage'];
             $questionPages->applyLimit($criteria);
             $questions = Question::model()->findAll($criteria);
             $this->renderPartial('/_questions_answers', array('lesson' => $lesson, 'questions' => $questions, 'questionPages' => $questionPages));
         } else {
             echo '-1';
         }
     }
 }
Ejemplo n.º 25
0
 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);
 }
Ejemplo n.º 26
0
 private function _array_filter_help($qidattributes, $surveyprintlang, $surveyid)
 {
     $output = "";
     if (!empty($qidattributes['array_filter'])) {
         $newquestiontext = Question::model()->findByAttributes(array('title' => $qidattributes['array_filter'], 'language' => $surveyprintlang, 'sid' => $surveyid))->getAttribute('question');
         $output .= "\n<p class='extrahelp'>\n            " . sprintf(gT("Only answer this question for the items you selected in question %s ('%s')"), $qidattributes['array_filter'], flattenText(breakToNewline($newquestiontext))) . "\n            </p>\n";
     }
     if (!empty($qidattributes['array_filter_exclude'])) {
         $newquestiontext = Question::model()->findByAttributes(array('title' => $qidattributes['array_filter_exclude'], 'language' => $surveyprintlang, 'sid' => $surveyid))->getAttribute('question');
         $output .= "\n    <p class='extrahelp'>\n            " . sprintf(gT("Only answer this question for the items you did not select in question %s ('%s')"), $qidattributes['array_filter_exclude'], breakToNewline($newquestiontext)) . "\n            </p>\n";
     }
     return $output;
 }
Ejemplo n.º 27
0
/**
* Replaces EM variable codes in a current survey with a new one
*
* @param mixed $iSurveyID The survey ID
* @param mixed $aCodeMap The codemap array (old_code=>new_code)
*/
function replaceExpressionCodes($iSurveyID, $aCodeMap)
{
    $arQuestions = Question::model()->findAll("sid=:sid", array(':sid' => $iSurveyID));
    foreach ($arQuestions as $arQuestion) {
        $bModified = false;
        foreach ($aCodeMap as $sOldCode => $sNewCode) {
            // Don't search/replace old codes that are too short or were numeric (because they would not have been usable in EM expressions anyway)
            if (strlen($sOldCode) > 1 && !is_numeric($sOldCode[0])) {
                $sOldCode = preg_quote($sOldCode, '/');
                $arQuestion->relevance = preg_replace("~{[^}]*\\K{$sOldCode}(?=[^}]*?})~", $sNewCode, $arQuestion->relevance, -1, $iCount);
                $bModified = $bModified || $iCount;
                $arQuestion->question = preg_replace("~{[^}]*\\K{$sOldCode}(?=[^}]*?})~", $sNewCode, $arQuestion->question, -1, $iCount);
                $bModified = $bModified || $iCount;
            }
        }
        if ($bModified) {
            $arQuestion->save();
        }
    }
    $arGroups = QuestionGroup::model()->findAll("sid=:sid", array(':sid' => $iSurveyID));
    foreach ($arGroups as $arGroup) {
        $bModified = false;
        foreach ($aCodeMap as $sOldCode => $sNewCode) {
            $sOldCode = preg_quote($sOldCode, '/');
            $arGroup->grelevance = preg_replace("~{[^}]*\\K{$sOldCode}(?=[^}]*?})~", $sNewCode, $arGroup->grelevance, -1, $iCount);
            $bModified = $bModified || $iCount;
            $arGroup->description = preg_replace("~{[^}]*\\K{$sOldCode}(?=[^}]*?})~", $sNewCode, $arGroup->description, -1, $iCount);
            $bModified = $bModified || $iCount;
        }
        if ($bModified) {
            $arGroup->save();
        }
    }
}
Ejemplo n.º 28
0
 private function _reorderGroup($iSurveyID)
 {
     $AOrgData = array();
     parse_str($_POST['orgdata'], $AOrgData);
     $grouporder = 0;
     foreach ($AOrgData['list'] as $ID => $parent) {
         if ($parent == 'root' && $ID[0] == 'g') {
             QuestionGroup::model()->updateAll(array('group_order' => $grouporder), 'gid=:gid', array(':gid' => (int) substr($ID, 1)));
             $grouporder++;
         } elseif ($ID[0] == 'q') {
             if (!isset($questionorder[(int) substr($parent, 1)])) {
                 $questionorder[(int) substr($parent, 1)] = 0;
             }
             Question::model()->updateAll(array('question_order' => $questionorder[(int) substr($parent, 1)], 'gid' => (int) substr($parent, 1)), 'qid=:qid', array(':qid' => (int) substr($ID, 1)));
             Question::model()->updateAll(array('gid' => (int) substr($parent, 1)), 'parent_qid=:parent_qid', array(':parent_qid' => (int) substr($ID, 1)));
             $questionorder[(int) substr($parent, 1)]++;
         }
     }
     LimeExpressionManager::SetDirtyFlag();
     // so refreshes syntax highlighting
     Yii::app()->session['flashmessage'] = gT("The new question group/question order was successfully saved.");
     $this->getController()->redirect(array('admin/survey/sa/view/surveyid/' . $iSurveyID));
 }
Ejemplo n.º 29
0
 /**
  * RPC Routine to return the ids and info of (sub-)questions of a survey/group.
  * Returns array of ids and info.
  *
  * @access public
  * @param string $sSessionKey Auth credentials
  * @param int $iSurveyID Id of the survey to list questions
  * @param int $iGroupID Optional id of the group to list questions
  * @param string $sLanguage Optional parameter language for multilingual questions
  * @return array The list of questions
  */
 public function list_questions($sSessionKey, $iSurveyID, $iGroupID = NULL, $sLanguage = NULL)
 {
     if ($this->_checkSessionKey($sSessionKey)) {
         Yii::app()->loadHelper("surveytranslator");
         $oSurvey = Survey::model()->findByPk($iSurveyID);
         if (!isset($oSurvey)) {
             return array('status' => 'Error: Invalid survey ID');
         }
         if (Permission::model()->hasSurveyPermission($iSurveyID, 'survey', 'read')) {
             if (is_null($sLanguage)) {
                 $sLanguage = $oSurvey->language;
             }
             if (!array_key_exists($sLanguage, getLanguageDataRestricted())) {
                 return array('status' => 'Error: Invalid language');
             }
             if ($iGroupID != NULL) {
                 $oGroup = QuestionGroup::model()->findByAttributes(array('gid' => $iGroupID));
                 $sGroupSurveyID = $oGroup['sid'];
                 if ($sGroupSurveyID != $iSurveyID) {
                     return array('status' => 'Error: IMissmatch in surveyid and groupid');
                 } else {
                     $aQuestionList = Question::model()->findAllByAttributes(array("sid" => $iSurveyID, "gid" => $iGroupID, "language" => $sLanguage));
                 }
             } else {
                 $aQuestionList = Question::model()->findAllByAttributes(array("sid" => $iSurveyID, "language" => $sLanguage));
             }
             if (count($aQuestionList) == 0) {
                 return array('status' => 'No questions found');
             }
             foreach ($aQuestionList as $oQuestion) {
                 $aData[] = array('id' => $oQuestion->primaryKey) + $oQuestion->attributes;
             }
             return $aData;
         } else {
             return array('status' => 'No permission');
         }
     } else {
         return array('status' => 'Invalid session key');
     }
 }
Ejemplo n.º 30
0
 /**
  *
  * @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;
     }
 }