Beispiel #1
0
 /**
  * Store a newly created post in storage.
  *
  * @return Response
  */
 public function postAnswer($question_id)
 {
     $validate = Validator::make(Input::all(), Answer::$rules);
     if ($validate->passes()) {
         //get file from input
         $audio = Input::file('audio');
         //get file's temporary path in server
         $file_temporary_path = $audio->getPathname();
         //create MP3 Object
         $audio_file = new MP3($file_temporary_path);
         $duration = $audio_file->getDuration();
         #Do same thing in 1 line:
         #$duration = with(new MP3($audio->getPathname()))->getDuration();
         //check if audio is less than/equal to 120 Seconds, then save it!
         if ($duration <= 120) {
             //seconds
             $name = time() . '-' . $audio->getClientOriginalName();
             //Move file from temporary folder to PUBLIC folder.
             //PUBLIC folder because we want user have access to this file later.
             $avatar = $audio->move(public_path() . '/answers/', $name);
             $answer = new Answer();
             $answer->title = Input::get('title');
             $answer->info = Input::get('info');
             $answer->audio = $name;
             if (Auth::check()) {
                 $answer->user_id = Auth::id();
             } else {
                 $answer->user_id = 0;
             }
             $answer->save();
         }
         return Redirect::action('AnswerController@index');
     }
     return Redirect::back()->withErrors($validate)->withInput();
 }
 /** 
  * 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)));
 }
Beispiel #3
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());
     }
 }
 /**
  * Creates a new model.
  * If creation is successful, the browser will be redirected to the 'view' page.
  */
 public function actionCreate()
 {
     $answer = new Answer();
     if (isset($_POST['Answer'])) {
         $this->forcePostRequest();
         $_POST = Yii::app()->input->stripClean($_POST);
         $answer->attributes = $_POST['Answer'];
         $answer->content->populateByForm();
         $answer->post_type = "answer";
         if ($answer->validate()) {
             $answer->save();
             $this->redirect(array('//questionanswer/question/view', 'id' => $answer->question_id));
         }
     }
     /*$model=new Answer;
     
     		// Uncomment the following line if AJAX validation is needed
     		// $this->performAjaxValidation($model);
     
     		if(isset($_POST['Answer']))
     		{
     			$model->attributes=$_POST['Answer'];
     	        $model->created_by = Yii::app()->user->id;
     	        $model->post_type = "answer";
     
     			if($model->save())
     				$this->redirect(array('//questionanswer/question/view','id'=>$model->question_id));
     		}
     
     		$this->render('create',array(
     			'model'=>$model,
     		));*/
 }
 /**
  * Creates a new model.
  * If creation is successful, the browser will be redirected to the 'view' page.
  */
 public function actionCreate()
 {
     $model = new Answer();
     // Uncomment the following line if AJAX validation is needed
     // $this->performAjaxValidation($model);
     if (isset($_POST['Answer'])) {
         $model->attributes = $_POST['Answer'];
         if ($model->save()) {
             $this->redirect(array('view', 'id' => $model->id));
         }
     }
     $this->render('create', array('model' => $model));
 }
 public function postGuardar()
 {
     $bandera = false;
     $id = Input::get('idQues');
     $ans = Input::get('res');
     $answers = Answer::all();
     $question = Question::find($id);
     $cantidad = Question::count();
     foreach ($answers as $a) {
         if ($a->id_question == $id) {
             $bandera = true;
             $answer = $a;
             break;
         }
     }
     if (!$bandera) {
         $answer = new Answer();
         $answer->id_question = $id;
         $ids = Auth::id();
         $student = Student::where('id_user', '=', $ids)->get()->first();
         $answer->id_student = $student->id;
         $answer->answer = $ans;
         $answer->result = QuestionsController::verifyAnswer($question, $ans);
         $answer->save();
     } else {
         $answer->result = QuestionsController::verifyAnswer($question, $ans);
         $answer->answer = $ans;
         $answer->save();
     }
     if ($cantidad == $id) {
         return Redirect::to('questions/exam?endTest=yes');
         //"holi ".$id." ".$ans;
     } else {
         if ($cantidad > $id) {
             return Redirect::to('questions/exam?numberQIn=' . ++$id);
         }
     }
 }
 public function answerQuestion()
 {
     $validator = Validator::make(Input::all(), Answer::$rules);
     $question_id = Input::get('question_id');
     if ($validator->fails()) {
         return Redirect::route('single-question', $question_id)->withErrors($validator)->withInput();
     } else {
         $insertAnswer = new Answer();
         $insertAnswer->user_id = Auth::user()->user_id;
         $insertAnswer->question_id = $question_id;
         $insertAnswer->answer = Input::get('answer');
         $insertAnswer->save();
         $insertPoint = User::find(Auth::user()->user_id);
         $insertPoint->points = $insertPoint->points + 3;
         $insertPoint->save();
         return Redirect::route('single-question', $question_id)->with('global', 'Answer is successfully posted');
     }
 }
 public function actionAnswer($id)
 {
     // get chosen variant IDs
     $chosenAnswers = array_values($_POST);
     // add answers for all answer variants for the given poll
     $poll = Poll::findById($id);
     foreach ($poll->questions as $question) {
         foreach ($question->variants as $variant) {
             $answer = new Answer();
             $answer->variant = $variant;
             $answer->answer = in_array($variant->id, $chosenAnswers);
             $answer->save(false);
             // but do not commit
         }
     }
     Model::flush();
     // commit
     $this->redirect($this->url('poll.stat', array('id' => $id)));
 }
 public function actionView($qid)
 {
     Yii::app()->user->setReturnUrl(Yii::app()->request->urlReferrer);
     if (Yii::app()->user->isGuest) {
         Yii::app()->user->loginRequired();
     } else {
         $questionInfo = Question::model()->with('answers', 'user', 'tags')->findByPk($qid, array('order' => 'answers.likeCount DESC, answers.time ASC'));
         $bestAns = Answer::model()->findByPk($questionInfo->bestAnsId);
         $criteria = new CDbCriteria();
         $criteria->addCondition("userId=" . Yii::app()->user->id);
         $criteria->addCondition("questionId=" . $qid);
         if (LikeQue::model()->find($criteria) != NULL) {
             $ifLike = 1;
         } else {
             $ifLike = 0;
         }
         $myLike = LikeAns::model()->findAll('userId=:uid', array(':uid' => Yii::app()->user->id));
         $answerModel = new Answer();
         $data = array('question' => $questionInfo, 'bestAns' => $bestAns, 'answerModel' => $answerModel, 'ifLike' => $ifLike, 'myLike' => $myLike);
         if (isset($_POST['Answer'])) {
             $success = '回答成功~';
             $answerModel->attributes = $_POST['Answer'];
             $answerModel->questionId = $qid;
             $answerModel->userId = Yii::app()->user->id;
             $answerModel->time = date("Y-m-d H:i:s");
             $questionInfo->answerCount++;
             $answerModel->save();
             $questionInfo->save();
             if ($questionInfo->userId != Yii::app()->user->id) {
                 $userInfo = User::model()->findByPk(Yii::app()->user->id);
                 $userInfo->score += 2;
                 $userInfo->lv = $userInfo->getLevel();
                 $userInfo->save();
                 $success = $success . '积分+2~';
             }
             Yii::app()->user->setFlash('success', $success);
             $this->redirect(array('view', 'qid' => $qid));
         }
         $this->render('view', $data);
     }
 }
 public function actionReply($feedbackid)
 {
     if (Yii::app()->user->checkAccess('createAnswer') == false) {
         throw new CHttpException(403);
     }
     $feedback = Feedback::model()->findByPk($feedbackid);
     $answer = new Answer();
     if (isset($_POST['Answer'])) {
         $answer->attributes = Yii::app()->request->getPost('Answer');
         $answer->reply_time = date('Y-m-d');
         $answer->feedback_id = $feedbackid;
         if ($answer->save()) {
             $this->setFlashMessage(strtr('<strong>{link}</strong> 问题咨询回复成功', array('{link}' => CHtml::link(CHtml::encode($feedback->content), array('view', 'id' => $answer->primaryKey)))));
             $feedback->is_reply = 1;
             $feedback->save();
             $this->redirect(array('answer/index'));
         }
     }
     $this->breadcrumbs = array('问题咨询' => array('feedback/index'), '回复');
     $this->render('reply', array('answer' => $answer, 'feedback' => $feedback));
 }
Beispiel #11
0
 protected function _save($data)
 {
     $obj = new Answer();
     $condition = array('user_id' => $this->_user->id, 'topic_id' => $data->topic_id);
     $obj->where($condition)->get();
     if (isset($data->selected) and $data->selected) {
         foreach ($data->selected as $tid => $choose) {
             $newData = new StdClass();
             $newData->topic_id = $tid;
             $newData->aChoose = $choose;
             $this->_save($newData);
         }
     }
     $obj->aChoose = implode(',', $data->aChoose);
     $obj->topic_id = $data->topic_id;
     $obj->user_id = $this->_user->id;
     if ($obj->save()) {
         return $obj->to_array();
     } else {
         return array('error' => $obj->error->string);
     }
 }
Beispiel #12
0
 /**
  * Store a newly created post in storage.
  *
  * @return Response
  */
 public function store()
 {
     $validate = Validator::make(Input::all(), Answer::$rules);
     if ($validate->passes()) {
         $audio = Input::file('audio');
         $name = time() . "-" . $audio->getClientOriginalName();
         $avatar = $audio->move("./answers/", $name);
         $audio = Input::file('audio');
         $name = time() . "-" . $audio->getClientOriginalName();
         $avatar = $audio->move("./answers/", $name);
         $answer = new Answer();
         $answer->title = Input::get('title');
         $answer->info = Input::get('info');
         $answer->audio = $name;
         if (Auth::check()) {
             $answer->user_id = Auth::id();
         } else {
             $answer->user_id = 0;
         }
         $answer->save();
         return Redirect::route('answer.admin..index');
     }
     return Redirect::back()->withErrors($validate)->withInput();
 }
 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';
         }
     }
 }
 /**
  * abstract function which creates the form to create / edit the answers of the question
  * @param FormValidator $form
  */
 function processAnswersCreation($form)
 {
     $questionWeighting = $nbrGoodAnswers = 0;
     $objAnswer = new Answer($this->id);
     $nb_answers = $form->getSubmitValue('nb_answers');
     // Score total
     $answer_score = trim($form->getSubmitValue('weighting[1]'));
     // Reponses correctes
     $nbr_corrects = 0;
     for ($i = 1; $i <= $nb_answers; $i++) {
         $goodAnswer = trim($form->getSubmitValue('correct[' . $i . ']'));
         if ($goodAnswer) {
             $nbr_corrects++;
         }
     }
     // Set question weighting (score total)
     $questionWeighting = $answer_score;
     // Set score per answer
     $nbr_corrects = $nbr_corrects == 0 ? 1 : $nbr_corrects;
     $answer_score = $nbr_corrects == 0 ? 0 : $answer_score;
     $answer_score = $answer_score / $nbr_corrects;
     //$answer_score �quivaut � la valeur d'une bonne r�ponse
     // cr�ation variable pour r�cuperer la valeur de la coche pour la prise en compte des n�gatifs
     $test = $form->getSubmitValue('pts');
     for ($i = 1; $i <= $nb_answers; $i++) {
         $answer = trim($form->getSubmitValue('answer[' . $i . ']'));
         $comment = trim($form->getSubmitValue('comment[' . $i . ']'));
         $goodAnswer = trim($form->getSubmitValue('correct[' . $i . ']'));
         if ($goodAnswer) {
             $weighting = abs($answer_score);
         } else {
             if ($test == 1) {
                 $weighting = 0;
             } else {
                 $weighting = -abs($answer_score);
             }
         }
         $objAnswer->createAnswer($answer, $goodAnswer, $comment, $weighting, $i);
     }
     // saves the answers into the data base
     $objAnswer->save();
     // sets the total weighting of the question --> sert � donner le score total pendant l'examen
     $this->updateWeighting($questionWeighting);
     $this->save();
 }
 /**
  * Function which creates the form to create/edit the answers of the question
  * @param FormValidator $form
  */
 public function processAnswersCreation($form)
 {
     $answer = $form->getSubmitValue('answer');
     // Due the ckeditor transform the elements to their HTML value
     //$answer = api_html_entity_decode($answer, ENT_QUOTES, $charset);
     //$answer = htmlentities(api_utf8_encode($answer));
     // remove the :: eventually written by the user
     $answer = str_replace('::', '', $answer);
     // remove starting and ending space and &nbsp;
     $answer = api_preg_replace("/ /", " ", $answer);
     // start and end separator
     $blankStartSeparator = self::getStartSeparator($form->getSubmitValue('select_separator'));
     $blankEndSeparator = self::getEndSeparator($form->getSubmitValue('select_separator'));
     $blankStartSeparatorRegexp = self::escapeForRegexp($blankStartSeparator);
     $blankEndSeparatorRegexp = self::escapeForRegexp($blankEndSeparator);
     // remove spaces at the beginning and the end of text in square brackets
     $answer = preg_replace_callback("/" . $blankStartSeparatorRegexp . "[^]]+" . $blankEndSeparatorRegexp . "/", function ($matches) use($blankStartSeparator, $blankEndSeparator) {
         $matchingResult = $matches[0];
         $matchingResult = trim($matchingResult, $blankStartSeparator);
         $matchingResult = trim($matchingResult, $blankEndSeparator);
         $matchingResult = trim($matchingResult);
         // remove forbidden chars
         $matchingResult = str_replace("/\\/", "", $matchingResult);
         $matchingResult = str_replace('/"/', "", $matchingResult);
         return $blankStartSeparator . $matchingResult . $blankEndSeparator;
     }, $answer);
     // get the blanks weightings
     $nb = preg_match_all('/' . $blankStartSeparatorRegexp . '[^' . $blankStartSeparatorRegexp . ']*' . $blankEndSeparatorRegexp . '/', $answer, $blanks);
     if (isset($_GET['editQuestion'])) {
         $this->weighting = 0;
     }
     /* if we have some [tobefound] in the text
        build the string to save the following in the answers table
        <p>I use a [computer] and a [pen].</p>
        becomes
        <p>I use a [computer] and a [pen].</p>::100,50:100,50@1
            ++++++++-------**
            --- -- --- -- -
            A B  (C) (D)(E)
        +++++++ : required, weighting of each words
        ------- : optional, input width to display, 200 if not present
        ** : equal @1 if "Allow answers order switches" has been checked, @ otherwise
        A : weighting for the word [computer]
        B : weighting for the word [pen]
        C : input width for the word [computer]
        D : input width for the word [pen]
        E : equal @1 if "Allow answers order switches" has been checked, @ otherwise
        */
     if ($nb > 0) {
         $answer .= '::';
         // weighting
         for ($i = 0; $i < $nb; ++$i) {
             // enter the weighting of word $i
             $answer .= $form->getSubmitValue('weighting[' . $i . ']');
             // not the last word, add ","
             if ($i != $nb - 1) {
                 $answer .= ",";
             }
             // calculate the global weighting for the question
             $this->weighting += $form->getSubmitValue('weighting[' . $i . ']');
         }
         // input width
         $answer .= ":";
         for ($i = 0; $i < $nb; ++$i) {
             // enter the width of input for word $i
             $answer .= $form->getSubmitValue('sizeofinput[' . $i . ']');
             // not the last word, add ","
             if ($i != $nb - 1) {
                 $answer .= ",";
             }
         }
     }
     // write the blank separator code number
     // see function getAllowedSeparator
     /*
        0 [...]
        1 {...}
        2 (...)
        3 *...*
        4 #...#
        5 %...%
        6 $...$
     */
     $answer .= ":" . $form->getSubmitValue('select_separator');
     // Allow answers order switches
     $is_multiple = $form->getSubmitValue('multiple_answer');
     $answer .= '@' . $is_multiple;
     $this->save();
     $objAnswer = new Answer($this->id);
     $objAnswer->createAnswer($answer, 0, '', 0, 1);
     $objAnswer->save();
 }
 /**
  * Receives the unique answer question type creation form data and creates
  * or updates the answers from that question
  * @param FormValidator $form
  */
 public function processAnswersCreation($form)
 {
     $questionWeighting = $nbrGoodAnswers = 0;
     $correct = $form->getSubmitValue('correct');
     $objAnswer = new Answer($this->id);
     $nb_answers = $form->getSubmitValue('nb_answers');
     for ($i = 1; $i <= $nb_answers; $i++) {
         $answer = trim($form->getSubmitValue('answer[' . $i . ']'));
         $comment = trim($form->getSubmitValue('comment[' . $i . ']'));
         $weighting = trim($form->getSubmitValue('weighting[' . $i . ']'));
         $scenario = $form->getSubmitValue('scenario');
         //$list_destination = $form -> getSubmitValue('destination'.$i);
         //$destination_str = $form -> getSubmitValue('destination'.$i);
         $try = $scenario['try' . $i];
         $lp = $scenario['lp' . $i];
         $destination = $scenario['destination' . $i];
         $url = trim($scenario['url' . $i]);
         /*
                     How we are going to parse the destination value
         
                    here we parse the destination value which is a string
                     1@@3@@2;4;4;@@http://www.chamilo.org
         
                     where: try_again@@lp_id@@selected_questions@@url
         
                    try_again = is 1 || 0
                    lp_id = id of a learning path (0 if dont select)
                    selected_questions= ids of questions
                    url= an url
         
                     $destination_str='';
                     foreach ($list_destination as $destination_id)
                     {
                         $destination_str.=$destination_id.';';
                     }*/
         $goodAnswer = $correct == $i ? true : false;
         if ($goodAnswer) {
             $nbrGoodAnswers++;
             $weighting = abs($weighting);
             if ($weighting > 0) {
                 $questionWeighting += $weighting;
             }
         }
         if (empty($try)) {
             $try = 0;
         }
         if (empty($lp)) {
             $lp = 0;
         }
         if (empty($destination)) {
             $destination = 0;
         }
         if ($url == '') {
             $url = 0;
         }
         //1@@1;2;@@2;4;4;@@http://www.chamilo.org
         $dest = $try . '@@' . $lp . '@@' . $destination . '@@' . $url;
         $objAnswer->createAnswer($answer, $goodAnswer, $comment, $weighting, $i, null, null, $dest);
     }
     // saves the answers into the data base
     $objAnswer->save();
     // sets the total weighting of the question
     $this->updateWeighting($questionWeighting);
     $this->save();
 }
Beispiel #17
0
/**
* This function imports a LimeSurvey .lsq question XML file
*
* @param mixed $sFullFilePath  The full filepath of the uploaded file
* @param mixed $iNewSID The new survey id
* @param mixed $newgid The new question group id -the question will always be added after the last question in the group
*/
function XMLImportQuestion($sFullFilePath, $iNewSID, $newgid)
{
    $clang = Yii::app()->lang;
    $aLanguagesSupported = array();
    // this array will keep all the languages supported for the survey
    $sBaseLanguage = Survey::model()->findByPk($iNewSID)->language;
    $aLanguagesSupported[] = $sBaseLanguage;
    // adds the base language to the list of supported languages
    $aLanguagesSupported = array_merge($aLanguagesSupported, Survey::model()->findByPk($iNewSID)->additionalLanguages);
    $sXMLdata = file_get_contents($sFullFilePath);
    $xml = simplexml_load_string($sXMLdata, 'SimpleXMLElement', LIBXML_NONET);
    if ($xml->LimeSurveyDocType != 'Question') {
        safeDie('This is not a valid LimeSurvey question structure XML file.');
    }
    $iDBVersion = (int) $xml->DBVersion;
    $aQIDReplacements = array();
    $aSQIDReplacements = array(0 => 0);
    $results['defaultvalues'] = 0;
    $results['answers'] = 0;
    $results['question_attributes'] = 0;
    $results['subquestions'] = 0;
    $importlanguages = array();
    foreach ($xml->languages->language as $language) {
        $importlanguages[] = (string) $language;
    }
    if (!in_array($sBaseLanguage, $importlanguages)) {
        $results['fatalerror'] = $clang->gT("The languages of the imported question file must at least include the base language of this survey.");
        return $results;
    }
    // First get an overview of fieldnames - it's not useful for the moment but might be with newer versions
    /*
        $fieldnames=array();
        foreach ($xml->questions->fields->fieldname as $fieldname )
        {
        $fieldnames[]=(string)$fieldname;
        };*/
    // Import questions table ===================================================================================
    // We have to run the question table data two times - first to find all main questions
    // then for subquestions (because we need to determine the new qids for the main questions first)
    $query = "SELECT MAX(question_order) AS maxqo FROM {{questions}} WHERE sid={$iNewSID} AND gid={$newgid}";
    $res = Yii::app()->db->createCommand($query)->query();
    $resrow = $res->read();
    $newquestionorder = $resrow['maxqo'] + 1;
    if (is_null($newquestionorder)) {
        $newquestionorder = 0;
    } else {
        $newquestionorder++;
    }
    foreach ($xml->questions->rows->row as $row) {
        $insertdata = array();
        foreach ($row as $key => $value) {
            $insertdata[(string) $key] = (string) $value;
        }
        $iOldSID = $insertdata['sid'];
        $insertdata['sid'] = $iNewSID;
        $insertdata['gid'] = $newgid;
        $insertdata['question_order'] = $newquestionorder;
        $oldqid = $insertdata['qid'];
        unset($insertdata['qid']);
        // save the old qid
        // now translate any links
        $insertdata['title'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['title']);
        $insertdata['question'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['question']);
        $insertdata['help'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['help']);
        // Insert the new question
        if (isset($aQIDReplacements[$oldqid])) {
            $insertdata['qid'] = $aQIDReplacements[$oldqid];
        }
        $ques = new Question();
        if ($insertdata) {
            XSSFilterArray($insertdata);
        }
        foreach ($insertdata as $k => $v) {
            $ques->{$k} = $v;
        }
        $result = $ques->save();
        if (!$result) {
            $results['fatalerror'] = CHtml::errorSummary($ques, $clang->gT("The question could not be imported for the following reasons:"));
            return $results;
        }
        if (!isset($aQIDReplacements[$oldqid])) {
            $newqid = getLastInsertID($ques->tableName());
            $aQIDReplacements[$oldqid] = $newqid;
            // add old and new qid to the mapping array
        }
    }
    // Import subquestions --------------------------------------------------------------
    if (isset($xml->subquestions)) {
        foreach ($xml->subquestions->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            $insertdata['sid'] = $iNewSID;
            $insertdata['gid'] = $newgid;
            $oldsqid = (int) $insertdata['qid'];
            unset($insertdata['qid']);
            // save the old qid
            $insertdata['parent_qid'] = $aQIDReplacements[(int) $insertdata['parent_qid']];
            // remap the parent_qid
            // now translate any links
            $insertdata['question'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['question']);
            if (isset($insertdata['help'])) {
                $insertdata['help'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['help']);
            }
            if (isset($aQIDReplacements[$oldsqid])) {
                $insertdata['qid'] = $aQIDReplacements[$oldsqid];
            }
            if ($insertdata) {
                XSSFilterArray($insertdata);
            }
            $ques = new Question();
            foreach ($insertdata as $k => $v) {
                $ques->{$k} = $v;
            }
            $result = $ques->save();
            $newsqid = getLastInsertID($ques->tableName());
            if (!isset($insertdata['qid'])) {
                $aQIDReplacements[$oldsqid] = $newsqid;
                // add old and new qid to the mapping array
            }
            $results['subquestions']++;
        }
    }
    // Import answers --------------------------------------------------------------
    if (isset($xml->answers)) {
        foreach ($xml->answers->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            $insertdata['qid'] = $aQIDReplacements[(int) $insertdata['qid']];
            // remap the parent_qid
            // now translate any links
            $answers = new Answer();
            if ($insertdata) {
                XSSFilterArray($insertdata);
            }
            foreach ($insertdata as $k => $v) {
                $answers->{$k} = $v;
            }
            $result = $answers->save();
            $results['answers']++;
        }
    }
    // Import questionattributes --------------------------------------------------------------
    if (isset($xml->question_attributes)) {
        $aAllAttributes = questionAttributes(true);
        foreach ($xml->question_attributes->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            unset($insertdata['qaid']);
            $insertdata['qid'] = $aQIDReplacements[(int) $insertdata['qid']];
            // remap the parent_qid
            if ($iDBVersion < 156 && isset($aAllAttributes[$insertdata['attribute']]['i18n']) && $aAllAttributes[$insertdata['attribute']]['i18n']) {
                foreach ($importlanguages as $sLanguage) {
                    $insertdata['language'] = $sLanguage;
                    $attributes = new QuestionAttribute();
                    if ($insertdata) {
                        XSSFilterArray($insertdata);
                    }
                    foreach ($insertdata as $k => $v) {
                        $attributes->{$k} = $v;
                    }
                    $result = $attributes->save();
                }
            } else {
                $attributes = new QuestionAttribute();
                if ($insertdata) {
                    XSSFilterArray($insertdata);
                }
                foreach ($insertdata as $k => $v) {
                    $attributes->{$k} = $v;
                }
                $result = $attributes->save();
            }
            $results['question_attributes']++;
        }
    }
    // Import defaultvalues --------------------------------------------------------------
    if (isset($xml->defaultvalues)) {
        $results['defaultvalues'] = 0;
        foreach ($xml->defaultvalues->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            $insertdata['qid'] = $aQIDReplacements[(int) $insertdata['qid']];
            // remap the qid
            $insertdata['sqid'] = $aSQIDReplacements[(int) $insertdata['sqid']];
            // remap the subquestion id
            // now translate any links
            $default = new DefaultValue();
            if ($insertdata) {
                XSSFilterArray($insertdata);
            }
            foreach ($insertdata as $k => $v) {
                $default->{$k} = $v;
            }
            $result = $default->save();
            $results['defaultvalues']++;
        }
    }
    LimeExpressionManager::SetDirtyFlag();
    // so refreshes syntax highlighting
    $results['newqid'] = $newqid;
    $results['questions'] = 1;
    $results['labelsets'] = 0;
    $results['labels'] = 0;
    return $results;
}
 public function postAnswer()
 {
     $registerData = Input::all();
     $registerRules = array('answer' => 'required');
     $registerValidator = Validator::make($registerData, $registerRules);
     if ($registerValidator->fails()) {
         return Redirect::back()->withInput()->withErrors($registerValidator);
     }
     if ($registerValidator->passes()) {
         $q_data = Question::find(Input::get('special'));
         $answer = new Answer();
         $answer->user_id = Auth::user()->id;
         $answer->question_id = Input::get('special');
         $answer->description = Input::get('answer');
         $answer->question_title = $q_data->title;
         $answer->save();
         // sent email to notify the user who asked the question
         //$q_data = Question::find(Input::get('special'));
         $user_data = User::find($q_data->user_id);
         $mailData = array('name' => $user_data->name, 'q_id' => $q_data->id, 'q_slug' => $q_data->slug);
         $mailMan = array('email' => $user_data->email);
         Mail::send('emails.question_alert', $mailData, function ($message) use($mailMan) {
             $message->subject("ubexchange question alert");
             $message->to($mailMan['email']);
         });
         return Redirect::back()->with('alertMessage', "answer posted successfully.");
     }
 }
Beispiel #19
0
 /**
  * 创建回答
  */
 public function actionCreateanswer()
 {
     $modelAnswer = new Answer();
     if (isset($_POST['Answer'])) {
         $modelAnswer->attributes = $_POST['Answer'];
         $modelAnswer->create_time = time();
         $modelAnswer->create_user = Yii::app()->user->id;
         $modelAnswer->is_anonymous = is_array($_POST['Answer']['is_anonymous']) ? 1 : 0;
         $questionModel = Question::model()->findByPk($modelAnswer->question_id);
         if ($questionModel == NULL) {
             throw new CHttpException(404, '没有此问题!');
         } else {
             if (Yii::app()->user->isGuest) {
                 throw new CHttpException(404, '回答问题前,请先登录!');
             }
         }
         if ($modelAnswer->save()) {
             $this->redirect(array('question', "id" => $modelAnswer->question_id, "#" => "form"));
         }
     }
 }
 /**
  * abstract function which creates the form to create / edit the answers of the question
  * @param FormValidator $form
  */
 function processAnswersCreation($form)
 {
     if (!self::isAnswered()) {
         $table = Database::get_course_table(TABLE_QUIZ_ANSWER);
         Database::delete($table, array('c_id = ? AND question_id = ?' => array($this->course['real_id'], $this->id)));
         $answer = $form->getSubmitValue('answer');
         $formula = $form->getSubmitValue('formula');
         $lowestValues = $form->getSubmitValue('lowestValue');
         $highestValues = $form->getSubmitValue('highestValue');
         $answerVariations = $form->getSubmitValue('answerVariations');
         $this->weighting = $form->getSubmitValue('weighting');
         // Create as many answers as $answerVariations
         for ($j = 0; $j < $answerVariations; $j++) {
             $auxAnswer = $answer;
             $auxFormula = $formula;
             $nb = preg_match_all('/\\[[^\\]]*\\]/', $auxAnswer, $blanks);
             if ($nb > 0) {
                 for ($i = 0; $i < $nb; ++$i) {
                     $blankItem = $blanks[0][$i];
                     $replace = array("[", "]");
                     $newBlankItem = str_replace($replace, "", $blankItem);
                     $newBlankItem = "[" . trim($newBlankItem) . "]";
                     // take random float values when one or both edge values have a decimal point
                     $randomValue = strpos($lowestValues[$i], '.') !== false || strpos($highestValues[$i], '.') !== false ? mt_rand($lowestValues[$i] * 100, $highestValues[$i] * 100) / 100 : mt_rand($lowestValues[$i], $highestValues[$i]);
                     $auxAnswer = str_replace($blankItem, $randomValue, $auxAnswer);
                     $auxFormula = str_replace($blankItem, $randomValue, $auxFormula);
                 }
                 $math = new EvalMath();
                 $result = $math->evaluate($auxFormula);
                 $result = number_format($result, 2, ".", "");
                 // Remove decimal trailing zeros
                 $result = rtrim($result, "0");
                 // If it is an integer (ends in .00) remove the decimal point
                 if (mb_substr($result, -1) === ".") {
                     $result = str_replace(".", "", $result);
                 }
                 // Attach formula
                 $auxAnswer .= " [" . $result . "]@@" . $formula;
             }
             $this->save();
             $objAnswer = new Answer($this->id);
             $objAnswer->createAnswer($auxAnswer, 1, '', $this->weighting, '');
             $objAnswer->position = array();
             $objAnswer->save();
         }
     }
 }
 /**
  * Fills the course database with some required content and example content.
  * @param int Course (int) ID
  * @param string Course directory name (e.g. 'ABC')
  * @param string Language used for content (e.g. 'spanish')
  * @param bool Whether to fill the course with example content
  * @return bool False on error, true otherwise
  * @version 1.2
  * @assert (null, '', '', null) === false
  * @assert (1, 'ABC', null, null) === false
  * @assert (1, 'TEST', 'spanish', true) === true
  */
 public static function fill_db_course($course_id, $course_repository, $language, $fill_with_exemplary_content = null)
 {
     if (is_null($fill_with_exemplary_content)) {
         $fill_with_exemplary_content = api_get_setting('course.example_material_course_creation') != 'false';
     }
     $course_id = intval($course_id);
     if (empty($course_id)) {
         return false;
     }
     $entityManager = Database::getManager();
     $course = $entityManager->getRepository('ChamiloCoreBundle:Course')->find($course_id);
     $tools = array();
     $settingsManager = CourseManager::getCourseSettingsManager();
     $settingsManager->setCourse($course);
     $toolList = CourseManager::getToolList();
     $toolList = $toolList->getTools();
     /** @var Chamilo\CourseBundle\Tool\BaseTool $tool */
     foreach ($toolList as $tool) {
         $visibility = self::string2binary(api_get_setting_in_list('course.active_tools_on_create', $tool->getName()));
         $toolObject = new CTool();
         $toolObject->setName($tool->getName())->setCategory($tool->getCategory())->setLink($tool->getLink())->setImage($tool->getImage())->setVisibility($visibility)->setAdmin(0)->setTarget($tool->getTarget());
         $tools[] = $toolObject;
         $settings = $settingsManager->loadSettings($tool->getName());
         $settingsManager->saveSettings($tool->getName(), $settings);
     }
     $course->setTools($tools);
     $entityManager->persist($course);
     $entityManager->flush($course);
     $courseInfo = api_get_course_info_by_id($course_id);
     $now = api_get_utc_datetime(time());
     $tbl_course_homepage = Database::get_course_table(TABLE_TOOL_LIST);
     $TABLEINTROS = Database::get_course_table(TABLE_TOOL_INTRO);
     $TABLEGROUPCATEGORIES = Database::get_course_table(TABLE_GROUP_CATEGORY);
     $TABLEITEMPROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY);
     $TABLETOOLAGENDA = Database::get_course_table(TABLE_AGENDA);
     $TABLETOOLANNOUNCEMENTS = Database::get_course_table(TABLE_ANNOUNCEMENT);
     $TABLETOOLDOCUMENT = Database::get_course_table(TABLE_DOCUMENT);
     $TABLETOOLLINK = Database::get_course_table(TABLE_LINK);
     $TABLEQUIZ = Database::get_course_table(TABLE_QUIZ_TEST);
     $TABLEQUIZQUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
     $TABLEQUIZQUESTIONLIST = Database::get_course_table(TABLE_QUIZ_QUESTION);
     $TABLEQUIZANSWERSLIST = Database::get_course_table(TABLE_QUIZ_ANSWER);
     $TABLESETTING = Database::get_course_table(TABLE_COURSE_SETTING);
     $TABLEFORUMCATEGORIES = Database::get_course_table(TABLE_FORUM_CATEGORY);
     $TABLEFORUMS = Database::get_course_table(TABLE_FORUM);
     $TABLEFORUMTHREADS = Database::get_course_table(TABLE_FORUM_THREAD);
     $TABLEFORUMPOSTS = Database::get_course_table(TABLE_FORUM_POST);
     $TABLEGRADEBOOK = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
     $TABLEGRADEBOOKLINK = Database::get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
     $TABLEGRADEBOOKCERT = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CERTIFICATE);
     $visible_for_all = 1;
     $visible_for_course_admin = 0;
     $visible_for_platform_admin = 2;
     /*    Course tools  */
     $alert = api_get_setting('exercise.email_alert_manager_on_new_quiz');
     if ($alert === 'true') {
         $defaultEmailExerciseAlert = 1;
     } else {
         $defaultEmailExerciseAlert = 0;
     }
     /* course_setting table (courseinfo tool)   */
     $settings = ['email_alert_manager_on_new_doc' => ['default' => 0, 'category' => 'work'], 'email_alert_on_new_doc_dropbox' => ['default' => 0, 'category' => 'dropbox'], 'allow_user_edit_agenda' => ['default' => 0, 'category' => 'agenda'], 'allow_user_edit_announcement' => ['default' => 0, 'category' => 'announcement'], 'email_alert_manager_on_new_quiz' => ['default' => $defaultEmailExerciseAlert, 'category' => 'quiz'], 'allow_user_image_forum' => ['default' => 1, 'category' => 'forum'], 'course_theme' => ['default' => '', 'category' => 'theme'], 'allow_learning_path_theme' => ['default' => 1, 'category' => 'theme'], 'allow_open_chat_window' => ['default' => 1, 'category' => 'chat'], 'email_alert_to_teacher_on_new_user_in_course' => ['default' => 0, 'category' => 'registration'], 'allow_user_view_user_list' => ['default' => 1, 'category' => 'user'], 'display_info_advance_inside_homecourse' => ['default' => 1, 'category' => 'thematic_advance'], 'email_alert_students_on_new_homework' => ['default' => 0, 'category' => 'work'], 'enable_lp_auto_launch' => ['default' => 0, 'category' => 'learning_path'], 'pdf_export_watermark_text' => ['default' => '', 'category' => 'learning_path'], 'allow_public_certificates' => ['default' => api_get_setting('course.allow_public_certificates') === 'true' ? 1 : '', 'category' => 'certificates'], 'documents_default_visibility' => ['default' => 'visible', 'category' => 'document']];
     /*$counter = 1;
       foreach ($settings as $variable => $setting) {
           Database::query(
               "INSERT INTO $TABLESETTING (id, c_id, variable, value, category)
                VALUES ($counter, $course_id, '".$variable."', '".$setting['default']."', '".$setting['category']."')"
           );
           $counter++;
       }*/
     /* Course homepage tools for platform admin only */
     /* Group tool */
     Database::query("INSERT INTO {$TABLEGROUPCATEGORIES}  (c_id, id, title , description, max_student, self_reg_allowed, self_unreg_allowed, groups_per_user, display_order)\n             VALUES ({$course_id}, '2', '" . self::lang2db(get_lang('DefaultGroupCategory')) . "', '', '8', '0', '0', '0', '0');");
     /*    Example Material  */
     $language_interface = !empty($language_interface) ? $language_interface : api_get_setting('language.platform_language');
     // Example material should be in the same language as the course is.
     $language_interface_original = $language_interface;
     $now = api_get_utc_datetime();
     $files = [['path' => '/shared_folder', 'title' => get_lang('UserFolders'), 'filetype' => 'folder', 'size' => 0], ['path' => '/chat_files', 'title' => get_lang('ChatFiles'), 'filetype' => 'folder', 'size' => 0]];
     $counter = 1;
     foreach ($files as $file) {
         self::insertDocument($course_id, $counter, $file);
         $counter++;
     }
     $sys_course_path = api_get_path(SYS_COURSE_PATH);
     $perm = api_get_permissions_for_new_directories();
     $perm_file = api_get_permissions_for_new_files();
     $chat_path = $sys_course_path . $course_repository . '/document/chat_files';
     if (!is_dir($chat_path)) {
         @mkdir($chat_path, api_get_permissions_for_new_directories());
     }
     /*    Documents   */
     if ($fill_with_exemplary_content) {
         $files = [['path' => '/images', 'title' => get_lang('Images'), 'filetype' => 'folder', 'size' => 0], ['path' => '/images/gallery', 'title' => get_lang('DefaultCourseImages'), 'filetype' => 'folder', 'size' => 0], ['path' => '/audio', 'title' => get_lang('Audio'), 'filetype' => 'folder', 'size' => 0], ['path' => '/flash', 'title' => get_lang('Flash'), 'filetype' => 'folder', 'size' => 0], ['path' => '/video', 'title' => get_lang('Video'), 'filetype' => 'folder', 'size' => 0], ['path' => '/certificates', 'title' => get_lang('Certificates'), 'filetype' => 'folder', 'size' => 0]];
         foreach ($files as $file) {
             self::insertDocument($course_id, $counter, $file);
             $counter++;
         }
         // FILL THE COURSE DOCUMENT WITH DEFAULT COURSE PICTURES
         $folders_to_copy_from_default_course = array('images', 'audio', 'flash', 'video', 'certificates');
         $default_course_path = api_get_path(SYS_CODE_PATH) . 'default_course_document/';
         $default_document_array = array();
         foreach ($folders_to_copy_from_default_course as $folder) {
             $default_course_folder_path = $default_course_path . $folder . '/';
             $files = self::browse_folders($default_course_folder_path, array(), $folder);
             $sorted_array = self::sort_pictures($files, 'dir');
             $sorted_array = array_merge($sorted_array, self::sort_pictures($files, 'file'));
             $default_document_array[$folder] = $sorted_array;
         }
         //Light protection (adding index.html in every document folder)
         $htmlpage = "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"utf-8\">\n <title>Not authorized</title>\n  </head>\n  <body>\n  </body>\n</html>";
         $example_cert_id = 0;
         if (is_array($default_document_array) && count($default_document_array) > 0) {
             foreach ($default_document_array as $media_type => $array_media) {
                 $path_documents = "/{$media_type}/";
                 //hack until feature #5242 is implemented
                 if ($media_type == 'images') {
                     $media_type = 'images/gallery';
                     $images_folder = $sys_course_path . $course_repository . "/document/images/";
                     if (!is_dir($images_folder)) {
                         //Creating index.html
                         mkdir($images_folder, $perm);
                         $fd = fopen($images_folder . 'index.html', 'w');
                         fwrite($fd, $htmlpage);
                         @chmod($images_folder . 'index.html', $perm_file);
                     }
                 }
                 $course_documents_folder = $sys_course_path . $course_repository . "/document/{$media_type}/";
                 $default_course_path = api_get_path(SYS_CODE_PATH) . 'default_course_document' . $path_documents;
                 if (!is_dir($course_documents_folder)) {
                     // Creating index.html
                     mkdir($course_documents_folder, $perm);
                     $fd = fopen($course_documents_folder . 'index.html', 'w');
                     fwrite($fd, $htmlpage);
                     @chmod($course_documents_folder . 'index.html', $perm_file);
                 }
                 if (is_array($array_media) && count($array_media) > 0) {
                     foreach ($array_media as $key => $value) {
                         if (isset($value['dir']) && !empty($value['dir'])) {
                             if (!is_dir($course_documents_folder . $value['dir'])) {
                                 //Creating folder
                                 mkdir($course_documents_folder . $value['dir'], $perm);
                                 //Creating index.html (for light protection)
                                 $index_html = $course_documents_folder . $value['dir'] . '/index.html';
                                 $fd = fopen($index_html, 'w');
                                 fwrite($fd, $htmlpage);
                                 @chmod($index_html, $perm_file);
                                 //Inserting folder in the DB
                                 $folder_path = substr($value['dir'], 0, strlen($value['dir']) - 1);
                                 $temp = explode('/', $folder_path);
                                 $title = $temp[count($temp) - 1];
                                 //hack until feature #5242 is implemented
                                 if ($title == 'gallery') {
                                     $title = get_lang('DefaultCourseImages');
                                 }
                                 if ($media_type == 'images/gallery') {
                                     $folder_path = 'gallery/' . $folder_path;
                                 }
                                 Database::query("INSERT INTO {$TABLETOOLDOCUMENT} (c_id, path,title,filetype,size)\n                                        VALUES ({$course_id},'{$path_documents}" . $folder_path . "','" . $title . "','folder','0')");
                                 $image_id = Database::insert_id();
                                 Database::query("INSERT INTO {$TABLEITEMPROPERTY} (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility)\n                                        VALUES ({$course_id},'document',1,'{$now}','{$now}',{$image_id},'DocumentAdded',1,NULL,NULL,0)");
                             }
                         }
                         if (isset($value['file']) && !empty($value['file'])) {
                             if (!file_exists($course_documents_folder . $value['file'])) {
                                 //Copying file
                                 copy($default_course_path . $value['file'], $course_documents_folder . $value['file']);
                                 chmod($course_documents_folder . $value['file'], $perm_file);
                                 //echo $default_course_path.$value['file']; echo ' - '; echo $course_documents_folder.$value['file']; echo '<br />';
                                 $temp = explode('/', $value['file']);
                                 $file_size = filesize($course_documents_folder . $value['file']);
                                 //hack until feature #5242 is implemented
                                 if ($media_type == 'images/gallery') {
                                     $value["file"] = 'gallery/' . $value["file"];
                                 }
                                 //Inserting file in the DB
                                 Database::query("INSERT INTO {$TABLETOOLDOCUMENT} (c_id, path,title,filetype,size)\n                                        VALUES ({$course_id},'{$path_documents}" . $value["file"] . "','" . $temp[count($temp) - 1] . "','file','{$file_size}')");
                                 $image_id = Database::insert_id();
                                 if ($image_id) {
                                     $sql = "UPDATE {$TABLETOOLDOCUMENT} SET id = iid WHERE iid = {$image_id}";
                                     Database::query($sql);
                                     if ($path_documents . $value['file'] == '/certificates/default.html') {
                                         $example_cert_id = $image_id;
                                     }
                                     Database::query("INSERT INTO {$TABLEITEMPROPERTY} (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility)\n                                            VALUES ({$course_id},'document',1,'{$now}','{$now}',{$image_id},'DocumentAdded',1,NULL,NULL,1)");
                                     $docId = Database::insert_id();
                                     if ($docId) {
                                         $sql = "UPDATE {$TABLEITEMPROPERTY} SET id = iid WHERE iid = {$docId}";
                                         Database::query($sql);
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
         }
         $agenda = new Agenda();
         $agenda->setType('course');
         $agenda->set_course($courseInfo);
         $agenda->addEvent($now, $now, 0, get_lang('AgendaCreationTitle'), get_lang('AgendaCreationContenu'));
         /*  Links tool */
         $link = new Link();
         $link->setCourse($courseInfo);
         $links = [['c_id' => $course_id, 'url' => 'http://www.google.com', 'title' => 'Google', 'description' => get_lang('Google'), 'category_id' => 0, 'on_homepage' => 0, 'target' => '_self', 'session_id' => 0], ['c_id' => $course_id, 'url' => 'http://www.wikipedia.org', 'title' => 'Wikipedia', 'description' => get_lang('Wikipedia'), 'category_id' => 0, 'on_homepage' => 0, 'target' => '_self', 'session_id' => 0]];
         foreach ($links as $params) {
             $link->save($params);
         }
         /* Announcement tool */
         AnnouncementManager::add_announcement(get_lang('AnnouncementExampleTitle'), get_lang('AnnouncementEx'), ['everyone' => 'everyone'], null, null, $now);
         $manager = Database::getManager();
         /* Introduction text */
         $intro_text = '<p style="text-align: center;">
                         <img src="' . api_get_path(REL_CODE_PATH) . 'img/mascot.png" alt="Mr. Chamilo" title="Mr. Chamilo" />
                         <h2>' . self::lang2db(get_lang('IntroductionText')) . '</h2>
                      </p>';
         $toolIntro = new Chamilo\CourseBundle\Entity\CToolIntro();
         $toolIntro->setCId($course_id)->setId(TOOL_COURSE_HOMEPAGE)->setSessionId(0)->setIntroText($intro_text);
         $manager->persist($toolIntro);
         $toolIntro = new Chamilo\CourseBundle\Entity\CToolIntro();
         $toolIntro->setCId($course_id)->setId(TOOL_STUDENTPUBLICATION)->setSessionId(0)->setIntroText(get_lang('IntroductionTwo'));
         $manager->persist($toolIntro);
         $toolIntro = new Chamilo\CourseBundle\Entity\CToolIntro();
         $toolIntro->setCId($course_id)->setId(TOOL_WIKI)->setSessionId(0)->setIntroText(get_lang('IntroductionWiki'));
         $manager->persist($toolIntro);
         $manager->flush();
         /*  Exercise tool */
         $exercise = new Exercise($course_id);
         $exercise->exercise = get_lang('ExerciceEx');
         $html = '<table width="100%" border="0" cellpadding="0" cellspacing="0">
                     <tr>
                     <td width="110" valign="top" align="left">
                         <img src="' . api_get_path(WEB_CODE_PATH) . 'default_course_document/images/mr_dokeos/thinking.jpg">
                     </td>
                     <td valign="top" align="left">' . get_lang('Antique') . '</td></tr>
                 </table>';
         $exercise->type = 1;
         $exercise->setRandom(0);
         $exercise->active = 1;
         $exercise->results_disabled = 0;
         $exercise->description = $html;
         $exercise->save();
         $exercise_id = $exercise->id;
         $question = new MultipleAnswer();
         $question->question = get_lang('SocraticIrony');
         $question->description = get_lang('ManyAnswers');
         $question->weighting = 10;
         $question->position = 1;
         $question->course = $courseInfo;
         $question->save($exercise_id);
         $questionId = $question->id;
         $answer = new Answer($questionId, $courseInfo['real_id']);
         $answer->createAnswer(get_lang('Ridiculise'), 0, get_lang('NoPsychology'), -5, 1);
         $answer->createAnswer(get_lang('AdmitError'), 0, get_lang('NoSeduction'), -5, 2);
         $answer->createAnswer(get_lang('Force'), 1, get_lang('Indeed'), 5, 3);
         $answer->createAnswer(get_lang('Contradiction'), 1, get_lang('NotFalse'), 5, 4);
         $answer->save();
         /* Forum tool */
         require_once api_get_path(SYS_CODE_PATH) . 'forum/forumfunction.inc.php';
         $params = ['forum_category_title' => get_lang('ExampleForumCategory'), 'forum_category_comment' => ''];
         $forumCategoryId = store_forumcategory($params, $courseInfo, false);
         $params = ['forum_category' => $forumCategoryId, 'forum_title' => get_lang('ExampleForum'), 'forum_comment' => '', 'default_view_type_group' => ['default_view_type' => 'flat']];
         $forumId = store_forum($params, $courseInfo, true);
         $forumInfo = get_forum_information($forumId, $courseInfo['real_id']);
         $params = ['post_title' => get_lang('ExampleThread'), 'forum_id' => $forumId, 'post_text' => get_lang('ExampleThreadContent'), 'calification_notebook_title' => '', 'numeric_calification' => '', 'weight_calification' => '', 'forum_category' => $forumCategoryId, 'thread_peer_qualify' => 0];
         store_thread($forumInfo, $params, $courseInfo, false);
         /* Gradebook tool */
         $course_code = $courseInfo['code'];
         // father gradebook
         Database::query("INSERT INTO {$TABLEGRADEBOOK} (name, description, user_id, course_code, parent_id, weight, visible, certif_min_score, session_id, document_id)\n                VALUES ('{$course_code}','',1,'{$course_code}',0,100,0,75,NULL,{$example_cert_id})");
         $gbid = Database::insert_id();
         Database::query("INSERT INTO {$TABLEGRADEBOOK} (name, description, user_id, course_code, parent_id, weight, visible, certif_min_score, session_id, document_id)\n                VALUES ('{$course_code}','',1,'{$course_code}',{$gbid},100,1,75,NULL,{$example_cert_id})");
         $gbid = Database::insert_id();
         Database::query("INSERT INTO {$TABLEGRADEBOOKLINK} (type, ref_id, user_id, course_code, category_id, created_at, weight, visible, locked)\n                VALUES (1,{$exercise_id},1,'{$course_code}',{$gbid},'{$now}',100,1,0)");
     }
     //Installing plugins in course
     $app_plugin = new AppPlugin();
     $app_plugin->install_course_plugins($course_id);
     $language_interface = $language_interface_original;
     return true;
 }
 /**
  * abstract function which creates the form to create / edit the answers of the question
  * @param the formvalidator instance
  * @param the answers number to display
  */
 function processAnswersCreation($form)
 {
     $questionWeighting = $nbrGoodAnswers = 0;
     $objAnswer = new Answer($this->id);
     $nb_answers = $form->getSubmitValue('nb_answers');
     for ($i = 1; $i <= $nb_answers; $i++) {
         $answer = trim(str_replace(['<p>', '</p>'], '', $form->getSubmitValue('answer[' . $i . ']')));
         $comment = trim(str_replace(['<p>', '</p>'], '', $form->getSubmitValue('comment[' . $i . ']')));
         $weighting = trim($form->getSubmitValue('weighting[' . $i . ']'));
         $goodAnswer = trim($form->getSubmitValue('correct[' . $i . ']'));
         if ($goodAnswer) {
             $weighting = abs($weighting);
         } else {
             $weighting = abs($weighting);
             $weighting = -$weighting;
         }
         if ($weighting > 0) {
             $questionWeighting += $weighting;
         }
         $objAnswer->createAnswer($answer, $goodAnswer, $comment, $weighting, $i);
     }
     // saves the answers into the data base
     $objAnswer->save();
     // sets the total weighting of the question
     $this->updateWeighting($questionWeighting);
     $this->save();
 }
Beispiel #23
0
 function questionaire_save()
 {
     /*echo '<pre>';
     		print_r($_POST);
     		echo '</pre>';
     		exit();*/
     foreach ($_POST['question_id'] as $key => $value) {
         if ($_POST['type'][$key] == "text" || $_POST['type'][$key] == "textarea" || $_POST['type'][$key] == "radio" || $_POST['type'][$key] == "scale") {
             if (@$_POST['answer'][$value]) {
                 $answer = new Answer();
                 if (is_login()) {
                     $answer->where('user_id', $this->session->userdata('id'));
                     $answer->where('questionaire_id', $value)->get();
                     $answer->user_id = $this->session->userdata('id');
                 }
                 $answer->questionaire_id = $value;
                 $answer->answer = $_POST['answer'][$value];
                 $answer->save();
             }
         } elseif ($_POST['type'][$key] == "radio") {
             if (@$_POST['answer'][$value]) {
                 $answer = new Answer();
                 if (is_login()) {
                     $answer->where('user_id', $this->session->userdata('id'));
                     $answer->where('questionaire_id', $value)->get();
                     $answer->user_id = $this->session->userdata('id');
                 }
                 $answer->questionaire_id = $value;
                 $answer->choice_id = $_POST['answer'][$value];
                 $answer->save();
             }
         } elseif ($_POST['type'][$key] == "checkbox") {
             if (@$_POST['answer'][$value]) {
                 $answer = new Answer();
                 $answer->where('user_id', $this->session->userdata('id'));
                 $answer->where('questionaire_id', $value)->get()->delete_all();
                 foreach ($_POST['answer'][$value] as $key => $ans) {
                     if (is_login()) {
                         $answer = new Answer();
                         $answer->user_id = $this->session->userdata('id');
                     }
                     $answer->questionaire_id = $value;
                     $answer->choice_id = $ans;
                     $answer->save();
                 }
             }
         } elseif ($_POST['type'][$key] == "grid") {
             if (@$_POST['answer'][$value]) {
                 foreach ($_POST['answer'][$value] as $key => $ans) {
                     $answer = new Answer();
                     if (is_login()) {
                         $answer->where('user_id', $this->session->userdata('id'));
                         $answer->where('choice_id', $key);
                         $answer->where('questionaire_id', $value)->get();
                         $answer->user_id = $this->session->userdata('id');
                     }
                     $answer->questionaire_id = $value;
                     $answer->choice_id = $key;
                     $answer->answer = $ans;
                     $answer->save();
                 }
             }
         }
     }
 }
 /**
  * Load editing of answer options specific screen only.
  *
  * @access public
  * @param int $surveyid
  * @param int $gid
  * @param int $qid
  * @return void
  */
 public function _editansweroptions($surveyid, $gid, $qid)
 {
     Yii::app()->loadHelper('database');
     $surveyid = sanitize_int($surveyid);
     $qid = sanitize_int($qid);
     $gid = sanitize_int($gid);
     // Get languages select on survey.
     $anslangs = Survey::model()->findByPk($surveyid)->additionalLanguages;
     $baselang = Survey::model()->findByPk($surveyid)->language;
     $qrow = Question::model()->findByAttributes(array('qid' => $qid, 'language' => $baselang));
     $qtype = $qrow['type'];
     $qtypes = getQuestionTypeList('', 'array');
     $scalecount = $qtypes[$qtype]['answerscales'];
     // Check if there is at least one answer
     for ($i = 0; $i < $scalecount; $i++) {
         $ans = new CDbCriteria();
         $ans->addCondition("qid={$qid}")->addCondition("scale_id={$i}")->addCondition("language='{$baselang}'");
         $qresult = Answer::model()->count($ans);
         if ((int) $qresult == 0) {
             $oAnswer = new Answer();
             $oAnswer->qid = $qid;
             $oAnswer->code = 'A1';
             $oAnswer->answer = "";
             $oAnswer->language = $baselang;
             $oAnswer->sortorder = 0;
             $oAnswer->scale_id = $i;
             $oAnswer->save();
         }
     }
     // Check that there are answers for every language supported by the survey
     for ($i = 0; $i < $scalecount; $i++) {
         foreach ($anslangs as $language) {
             $ans = new CDbCriteria();
             $ans->addCondition("qid={$qid}")->addCondition("scale_id={$i}")->addCondition("language='{$language}'");
             $iAnswerCount = Answer::model()->count($ans);
             // Means that no record for the language exists in the answers table
             if (empty($iAnswerCount)) {
                 foreach (Answer::model()->findAllByAttributes(array('qid' => $qid, 'scale_id' => $i, 'language' => $baselang)) as $answer) {
                     $oAnswer = new Answer();
                 }
                 $oAnswer->qid = $answer->qid;
                 $oAnswer->code = $answer->code;
                 $oAnswer->answer = $answer->answer;
                 $oAnswer->language = $language;
                 $oAnswer->sortorder = $answer->sortorder;
                 $oAnswer->scale_id = $i;
                 $oAnswer->assessment_value = $answer->assessment_value;
                 $oAnswer->save();
             }
         }
     }
     // Makes an array with ALL the languages supported by the survey -> $anslangs
     array_unshift($anslangs, $baselang);
     // Delete the answers in languages not supported by the survey
     $criteria = new CDbCriteria();
     $criteria->addColumnCondition(array('qid' => $qid));
     $criteria->addNotInCondition('language', $anslangs);
     $languageresult = Answer::model()->deleteAll($criteria);
     if (!isset($_POST['ansaction'])) {
         // Check if any nulls exist. If they do, redo the sortorders
         $ans = new CDbCriteria();
         $ans->addCondition("qid={$qid}")->addCondition("scale_id={$i}")->addCondition("language='{$baselang}'");
         $cacount = Answer::model()->count($ans);
         if (!empty($cacount)) {
             Answer::model()->updateSortOrder($qid, Survey::model()->findByPk($surveyid)->language);
         }
     }
     Yii::app()->loadHelper('admin/htmleditor');
     $row = Answer::model()->findByAttributes(array('qid' => $qid, 'language' => Survey::model()->findByPk($surveyid)->language), array('order' => 'sortorder desc'));
     if (!is_null($row)) {
         $maxsortorder = $row->sortorder + 1;
     } else {
         $maxsortorder = 1;
     }
     $aData['surveyid'] = $surveyid;
     $aData['gid'] = $gid;
     $aData['qid'] = $qid;
     $aData['anslangs'] = $anslangs;
     $aData['scalecount'] = $scalecount;
     // The following line decides if the assessment input fields are visible or not
     $sumresult1 = Survey::model()->with(array('languagesettings' => array('condition' => 'surveyls_language=language')))->together()->findByAttributes(array('sid' => $surveyid));
     if (is_null($sumresult1)) {
         $this->getController()->error('Invalid survey ID');
     }
     $surveyinfo = $sumresult1->attributes;
     $surveyinfo = array_merge($surveyinfo, $sumresult1->defaultlanguage->attributes);
     $surveyinfo = array_map('flattenText', $surveyinfo);
     $assessmentvisible = $surveyinfo['assessments'] == 'Y' && $qtypes[$qtype]['assessable'] == 1;
     $aData['assessmentvisible'] = $assessmentvisible;
     $aData['activated'] = $activated = $surveyinfo['active'];
     $results = array();
     foreach ($anslangs as $anslang) {
         for ($scale_id = 0; $scale_id < $scalecount; $scale_id++) {
             $criteria = new CDbCriteria();
             $criteria->condition = 'qid = :qid AND language = :language AND scale_id = :scale_id';
             $criteria->order = 'sortorder, code ASC';
             $criteria->params = array(':qid' => $qid, ':language' => $anslang, ':scale_id' => $scale_id);
             $results[$anslang][$scale_id] = Answer::model()->findAll($criteria);
             //$aData['results'][$anslang][$scale_id] = Answer::model()->findAll($criteria);
             foreach ($results[$anslang][$scale_id] as $row) {
                 $row->code = htmlspecialchars($row->code);
                 $row->answer = htmlspecialchars($row->answer);
             }
             $aData['tableId'][$anslang][$scale_id] = 'answers_' . $anslang . '_' . $scale_id;
         }
     }
     $aData['results'] = $results;
     $aData['viewType'] = 'answerOptions';
     $aData['formId'] = 'editanswersform';
     $aData['formName'] = 'editanswersform';
     $aData['pageTitle'] = gT('Edit answer options');
     $aViewUrls['_subQuestionsAndAnwsersJsVariables'][] = $aData;
     $aViewUrls['answerOptions_view'][] = $aData;
     return $aViewUrls;
 }
             if ($debug > 0) {
                 echo str_repeat('&nbsp;', 4) . '$answerType is HOT_SPOT' . "<br />\n";
             }
             $reponse[$i] = trim($reponse[$i]);
             $comment[$i] = trim($comment[$i]);
             $weighting[$i] = $weighting[$i];
             //it can be float
             if ($weighting[$i]) {
                 $questionWeighting += $weighting[$i];
             }
             // creates answer
             $objAnswer->createAnswer($reponse[$i], '', $comment[$i], $weighting[$i], $i, $hotspot_coordinates[$i], $hotspot_type[$i]);
         }
         // end for()
         // saves the answers into the data base
         $objAnswer->save();
         // sets the total weighting of the question
         $objQuestion->updateWeighting($questionWeighting);
         $objQuestion->save($exerciseId);
         $editQuestion = $questionId;
         unset($modifyAnswers);
         echo '<script type="text/javascript">window.location.href="' . $hotspot_admin_url . '&message=ItemUpdated"</script>';
     }
     if ($debug > 0) {
         echo '$modifyIn was set - end' . "<br />\n";
     }
 } else {
     if ($debug > 0) {
         echo '$submitAnswers or $buttonBack was set' . "<br />\n";
     }
     $questionWeighting = $nbrGoodAnswers = 0;
 public function savepage6data()
 {
     $aa = Input::except(array('_token', 'back', 'save', 'next'));
     $afc = Input::file();
     $count = 0;
     foreach ($aa as $key => $value) {
         $ids = explode("|", $key);
         //var_dump($ids);
         if (isset($ids[0]) && $ids[0] != "file") {
             if (isset($ids[1]) && $ids[1] != "") {
                 $ans = Answer::find($ids[1]);
                 $ans->answer_text = $value;
                 $ans->save();
             } else {
                 $ans = new Answer();
                 $ans->question_id = $ids[0];
                 if (isset($ids[2]) && $ids[2] != "") {
                     $ans->choice_id = $ids[2];
                 }
                 $ans->user_id = Session::get('userid');
                 $ans->answer_text = $value;
                 $ans->save();
             }
         }
     }
     foreach ($afc as $key => $value) {
         $ids = explode("|", $key);
         if (isset($ids[0]) && $ids[0] == "file") {
             //If file Values are not printing then please check if
             // form has FIle=true
             //dd(Input::file($key));
             $userid = Session::get('userid');
             $event = Session::get('event');
             $fileTblObj = new fileHandler();
             $ans = Answer::find($ids[2]);
             if (isset($afc[$key])) {
                 if (Input::file($key)->isValid()) {
                     $count++;
                     $destinationPath = 'app/uploads/' . $event . '/' . $userid . '/6';
                     // upload path
                     $extension = Input::file($key)->getClientOriginalExtension();
                     // getting image extension
                     $name = Input::file($key)->getClientOriginalName();
                     $curFilesize = Input::file($key)->getClientSize();
                     $mime = Input::file($key)->getMimeType();
                     // dd($mime);
                     //$fileName = $name; // renameing image
                     //$exstFileSize = Input::file($destinationPath, $fileName);
                     if (!File::exists($destinationPath . "/" . $count . $name)) {
                         //creating details for saving inthe file_handler Table
                         $fileTblObj->user_id = $userid;
                         $fileTblObj->eventName = $event;
                         $fileTblObj->fileName = $count . $name;
                         $fileTblObj->formPage = 6;
                         $fileTblObj->filePath = $destinationPath . "/";
                         $fileTblObj->mime = $mime;
                         $ans->answer_text = 'Yes';
                         $ans->save();
                         Input::file($key)->move($destinationPath, $count . $name);
                         // uploading file to given path
                         //Save filedetails
                         $fileTblObj->save();
                         Session::flash('success', 'Upload successfully');
                     } else {
                         if (File::size($destinationPath . "/" . $name) != $curFilesize) {
                             $fileDtls = $fileTblObj->where('uid', $userid)->where('fileName', $name)->where('formPage', 6)->first();
                             Input::file($key)->move($destinationPath, $name);
                             $ans->answer_text = 'Yes';
                             $ans->save();
                             $fileTblObj->where('id', $fileDtls->id)->update(array('updated_at' => date("Y-m-d h:m:s", time())));
                         }
                     }
                     //return Redirect::to('upload');
                 }
             } else {
                 if ($ans->answer_text == '') {
                     $ans->answer_text = 'No';
                     $ans->save();
                 }
             }
         }
     }
 }
Beispiel #27
0
 /**
  * Update the answers
  */
 public function updateAction()
 {
     $data = Input::all();
     $num = (int) $data['number_of_answers'];
     $test = Test::find($data['test_id']);
     $question = Question::find($data['id']);
     if (is_null($test) || is_null($question) || $test->id != $question->test->id) {
         return Redirect::route('tests.index')->with('error', 'Incorrect id');
     }
     $validation = Validator::make(['text' => $data['text']], Question::$rules);
     if (!$validation->passes()) {
         return Redirect::route('question.edit', ['id' => $question->id])->withInput()->withErrors($validation)->with('message', 'There were validation errors.');
     }
     $oldType = $question->type;
     $question->text = $data['text'];
     $question->number = $data['number'];
     $question->type = $data['type'] ? $data['type'] : Question::TYPE_STRING;
     $question->save();
     /**
      * Erase all old answers
      */
     DB::table('answer')->where('question_id', $question->id)->delete();
     /**
      * Create answers
      */
     for ($i = 1; $i <= $num; $i++) {
         if (!isset($data['a_' . $i . '_text']) || !trim($data['a_' . $i . '_text'])) {
             continue;
         }
         $answer = new Answer();
         $answer->question_id = $question->id;
         $answer->text = trim($data['a_' . $i . '_text']);
         $answer->weight = (int) $data['a_' . $i . '_weight'];
         if ($question->type == Question::TYPE_CHECKBOX) {
             $answer->is_correct = isset($data['a_' . $i . '_correct']) ? true : false;
         } elseif ($question->type == Question::TYPE_RADIO) {
             $answer->is_correct = isset($data['a_0_correct']) && $data['a_0_correct'] == $i ? true : false;
         }
         if ($answer->is_correct && !$answer->weight) {
             $answer->weight = 1;
         }
         if (!$answer->is_correct) {
             $answer->weight = 0;
         }
         $answer->save();
     }
     return Redirect::route('tests.show', $test->id);
 }
 /**
  * abstract function which creates the form to create / edit the answers of the question
  * @param FormValidator $form
  */
 public function processAnswersCreation($form)
 {
     $nb_matches = $form->getSubmitValue('nb_matches');
     $nb_options = $form->getSubmitValue('nb_options');
     $this->weighting = 0;
     $position = 0;
     $objAnswer = new Answer($this->id);
     // Insert the options
     for ($i = 1; $i <= $nb_options; ++$i) {
         $position++;
         $option = $form->getSubmitValue('option[' . $i . ']');
         $objAnswer->createAnswer($option, 0, '', 0, $position);
     }
     // Insert the answers
     for ($i = 1; $i <= $nb_matches; ++$i) {
         $position++;
         $answer = $form->getSubmitValue('answer[' . $i . ']');
         $matches = $form->getSubmitValue('matches[' . $i . ']');
         $weighting = $form->getSubmitValue('weighting[' . $i . ']');
         $this->weighting += $weighting;
         $objAnswer->createAnswer($answer, $matches, '', $weighting, $position);
     }
     $objAnswer->save();
     $this->save();
 }
Beispiel #29
0
/**
 * Handles a given Excel spreadsheets as in the template provided
 */
function lp_upload_quiz_action_handling()
{
    global $debug;
    $_course = api_get_course_info();
    $courseId = $_course['real_id'];
    if (!isset($_POST['submit_upload_quiz'])) {
        return;
    }
    // Get the extension of the document.
    $path_info = pathinfo($_FILES['user_upload_quiz']['name']);
    // Check if the document is an Excel document
    if ($path_info['extension'] != 'xls') {
        return;
    }
    // Read the Excel document
    $data = new Spreadsheet_Excel_Reader();
    // Set output Encoding.
    $data->setOutputEncoding(api_get_system_encoding());
    // Reading the xls document.
    $data->read($_FILES['user_upload_quiz']['tmp_name']);
    $correctScore = isset($_POST['correct_score']) ? $_POST['correct_score'] : null;
    $incorrectScore = isset($_POST['incorrect_score']) ? $_POST['incorrect_score'] : null;
    $useCustomScore = isset($_POST['user_custom_score']) ? true : false;
    $propagateNegative = 0;
    if ($useCustomScore && !empty($incorrectScore)) {
        if ($incorrectScore < 0) {
            $propagateNegative = 1;
        }
    }
    // Variables
    $quiz_index = 0;
    $question_title_index = array();
    $question_name_index_init = array();
    $question_name_index_end = array();
    $score_index = array();
    $feedback_true_index = array();
    $feedback_false_index = array();
    $number_questions = 0;
    $question_description_index = array();
    // Reading all the first column items sequentially to create breakpoints
    for ($i = 1; $i <= $data->sheets[0]['numRows']; $i++) {
        if ($data->sheets[0]['cells'][$i][1] == 'Quiz' && $i == 1) {
            $quiz_index = $i;
            // Quiz title position, only occurs once
        } elseif ($data->sheets[0]['cells'][$i][1] == 'Question') {
            $question_title_index[] = $i;
            // Question title position line
            $question_name_index_init[] = $i + 1;
            // Questions name 1st position line
            $number_questions++;
        } elseif ($data->sheets[0]['cells'][$i][1] == 'Score') {
            $question_name_index_end[] = $i - 1;
            // Question name position
            $score_index[] = $i;
            // Question score position
        } elseif ($data->sheets[0]['cells'][$i][1] == 'FeedbackTrue') {
            $feedback_true_index[] = $i;
            // FeedbackTrue position (line)
        } elseif ($data->sheets[0]['cells'][$i][1] == 'FeedbackFalse') {
            $feedback_false_index[] = $i;
            // FeedbackFalse position (line)
        } elseif ($data->sheets[0]['cells'][$i][1] == 'EnrichQuestion') {
            $question_description_index[] = $i;
        }
    }
    // Variables
    $quiz = array();
    $question = array();
    $new_answer = array();
    $score_list = array();
    $feedback_true_list = array();
    $feedback_false_list = array();
    $question_description = array();
    // Getting questions.
    $k = $z = $q = $l = $m = 0;
    for ($i = 1; $i <= $data->sheets[0]['numRows']; $i++) {
        if (is_array($data->sheets[0]['cells'][$i])) {
            $column_data = $data->sheets[0]['cells'][$i];
            // Fill all column with data to have a full array
            for ($x = 1; $x <= $data->sheets[0]['numCols']; $x++) {
                if (empty($column_data[$x])) {
                    $data->sheets[0]['cells'][$i][$x] = '';
                }
            }
            // Array filled with data
            $column_data = $data->sheets[0]['cells'][$i];
        } else {
            $column_data = '';
        }
        // Fill quiz data
        if ($quiz_index == $i) {
            // The title always in the first position
            $quiz = $column_data;
        } elseif (in_array($i, $question_title_index)) {
            //a complete line where 1st column is 'Question'
            $question[$k] = $column_data;
            $k++;
        } elseif (in_array($i, $score_index)) {
            //a complete line where 1st column is 'Score'
            $score_list[$z] = $column_data;
            $z++;
        } elseif (in_array($i, $feedback_true_index)) {
            //a complete line where 1st column is 'FeedbackTrue'
            $feedback_true_list[$q] = $column_data;
            $q++;
        } elseif (in_array($i, $feedback_false_index)) {
            //a complete line where 1st column is 'FeedbackFalse' for wrong answers
            $feedback_false_list[$l] = $column_data;
            $l++;
        } elseif (in_array($i, $question_description_index)) {
            //a complete line where 1st column is 'EnrichQuestion'
            $question_description[$m] = $column_data;
            $m++;
        }
    }
    // Get answers
    for ($i = 0; $i < count($question_name_index_init); $i++) {
        for ($j = $question_name_index_init[$i]; $j <= $question_name_index_end[$i]; $j++) {
            if (is_array($data->sheets[0]['cells'][$j])) {
                $column_data = $data->sheets[0]['cells'][$j];
                // Fill all column with data
                for ($x = 1; $x <= $data->sheets[0]['numCols']; $x++) {
                    if (empty($column_data[$x])) {
                        $data->sheets[0]['cells'][$j][$x] = '';
                    }
                }
                $column_data = $data->sheets[0]['cells'][$j];
                // Array filled of data
                if (is_array($data->sheets[0]['cells'][$j]) && count($data->sheets[0]['cells'][$j]) > 0) {
                    $new_answer[$i][$j] = $data->sheets[0]['cells'][$j];
                }
            }
        }
    }
    // Quiz title.
    $quiz_title = $quiz[2];
    if ($quiz_title != '') {
        // Variables
        $type = 2;
        $random = $active = $results = $max_attempt = $expired_time = 0;
        // Make sure feedback is enabled (3 to disable), otherwise the fields
        // added to the XLS are not shown, which is confusing
        $feedback = 0;
        // Quiz object
        $exercise = new Exercise();
        //
        $quiz_id = $exercise->createExercise($quiz_title, $expired_time, $type, $random, $active, $results, $max_attempt, $feedback, $propagateNegative);
        if ($quiz_id) {
            // insert into the item_property table
            api_item_property_update($_course, TOOL_QUIZ, $quiz_id, 'QuizAdded', api_get_user_id());
            // Import questions.
            for ($i = 0; $i < $number_questions; $i++) {
                // Question name
                $question_title = $question[$i][2];
                $question_description_text = "<p></p>";
                if (isset($question_description[$i][2])) {
                    // Question description.
                    $question_description_text = "<p>" . $question_description[$i][2] . "</p>";
                }
                // Unique answers are the only question types available for now
                // through xls-format import
                $question_id = null;
                $detectQuestionType = detectQuestionType($new_answer[$i], $score_list);
                /** @var Question $answer */
                switch ($detectQuestionType) {
                    case FREE_ANSWER:
                        $answer = new FreeAnswer();
                        break;
                    case GLOBAL_MULTIPLE_ANSWER:
                        $answer = new GlobalMultipleAnswer();
                        break;
                    case MULTIPLE_ANSWER:
                        $answer = new MultipleAnswer();
                        break;
                    case UNIQUE_ANSWER:
                    default:
                        $answer = new UniqueAnswer();
                        break;
                }
                if ($question_title != '') {
                    $question_id = $answer->create_question($quiz_id, $question_title, $question_description_text, 0, $answer->type);
                }
                $total = 0;
                if (is_array($new_answer[$i]) && !empty($question_id)) {
                    $id = 1;
                    $answers_data = $new_answer[$i];
                    $globalScore = null;
                    $objAnswer = new Answer($question_id, $courseId);
                    $globalScore = $score_list[$i][3];
                    // Calculate the number of correct answers to divide the
                    // score between them when importing from CSV
                    $numberRightAnswers = 0;
                    foreach ($answers_data as $answer_data) {
                        if (strtolower($answer_data[3]) == 'x') {
                            $numberRightAnswers++;
                        }
                    }
                    foreach ($answers_data as $answer_data) {
                        $answerValue = $answer_data[2];
                        $correct = 0;
                        $score = 0;
                        if (strtolower($answer_data[3]) == 'x') {
                            $correct = 1;
                            $score = $score_list[$i][3];
                            $comment = $feedback_true_list[$i][2];
                        } else {
                            $comment = $feedback_false_list[$i][2];
                            $floatVal = (double) $answer_data[3];
                            if (is_numeric($floatVal)) {
                                $score = $answer_data[3];
                            }
                        }
                        if ($useCustomScore) {
                            if ($correct) {
                                $score = $correctScore;
                            } else {
                                $score = $incorrectScore;
                            }
                        }
                        // Fixing scores:
                        switch ($detectQuestionType) {
                            case GLOBAL_MULTIPLE_ANSWER:
                                $score /= $numberRightAnswers;
                                break;
                            case UNIQUE_ANSWER:
                                break;
                            case MULTIPLE_ANSWER:
                                if (!$correct) {
                                    //$total = $total - $score;
                                }
                                break;
                        }
                        $objAnswer->createAnswer($answerValue, $correct, $comment, $score, $id);
                        $total += $score;
                        $id++;
                    }
                    $objAnswer->save();
                    $questionObj = Question::read($question_id, $courseId);
                    switch ($detectQuestionType) {
                        case GLOBAL_MULTIPLE_ANSWER:
                            $questionObj->updateWeighting($globalScore);
                            break;
                        case UNIQUE_ANSWER:
                        case MULTIPLE_ANSWER:
                        default:
                            $questionObj->updateWeighting($total);
                            break;
                    }
                    $questionObj->save();
                } else {
                    if ($detectQuestionType === FREE_ANSWER) {
                        $questionObj = Question::read($question_id, $courseId);
                        $globalScore = $score_list[$i][3];
                        $questionObj->updateWeighting($globalScore);
                        $questionObj->save();
                    }
                }
            }
        }
        if (isset($_SESSION['lpobject'])) {
            if ($debug > 0) {
                error_log('New LP - SESSION[lpobject] is defined', 0);
            }
            $oLP = unserialize($_SESSION['lpobject']);
            if (is_object($oLP)) {
                if ($debug > 0) {
                    error_log('New LP - oLP is object', 0);
                }
                if (empty($oLP->cc) or $oLP->cc != api_get_course_id()) {
                    if ($debug > 0) {
                        error_log('New LP - Course has changed, discard lp object', 0);
                    }
                    $oLP = null;
                    Session::erase('oLP');
                    Session::erase('lpobject');
                } else {
                    $_SESSION['oLP'] = $oLP;
                }
            }
        }
        if (isset($_SESSION['oLP']) && isset($_GET['lp_id'])) {
            $previous = $_SESSION['oLP']->select_previous_item_id();
            $parent = 0;
            // Add a Quiz as Lp Item
            $_SESSION['oLP']->add_item($parent, $previous, TOOL_QUIZ, $quiz_id, $quiz_title, '');
            // Redirect to home page for add more content
            header('location: ../newscorm/lp_controller.php?' . api_get_cidreq() . '&action=add_item&type=step&lp_id=' . Security::remove_XSS($_GET['lp_id']));
            exit;
        } else {
            //  header('location: exercise.php?' . api_get_cidreq());
            echo '<script>window.location.href = "' . api_get_path(WEB_CODE_PATH) . 'exercice/admin.php?' . api_get_cidReq() . '&exerciseId=' . $quiz_id . '&session_id=' . api_get_session_id() . '"</script>';
        }
    }
}
 /**
  * save answers by this questionnaire.
  * for each question group then question save answer
  * //copy the questionnaire into answer
  * //then fill it with answers
  * @param questionnaire
  */
 public function saveQuestionnaireAnswers($model)
 {
     if (isset($_SESSION['datapatient'])) {
         $patients = $_SESSION['datapatient'];
     }
     $answer = new Answer();
     $answer->creator = ucfirst(Yii::app()->user->getPrenom()) . " " . strtoupper(Yii::app()->user->getNom());
     $answer->last_updated = DateTime::createFromFormat('d/m/Y', date('d/m/Y'));
     $answer->copy($model);
     $answer->type = $model->type;
     $answer->login = Yii::app()->user->id;
     $answer->id_patient = (string) $patients->id;
     $flagNoInputToSave = true;
     foreach ($answer->answers_group as $answer_group) {
         foreach ($answer_group->answers as $answerQuestion) {
             $input = $answer_group->id . "_" . $answerQuestion->id;
             if (isset($_POST['Questionnaire'][$input])) {
                 $flagNoInputToSave = false;
                 if ($answerQuestion->type != "number" && $answerQuestion->type != "expression" && $answerQuestion->type != "date") {
                     $answerQuestion->setAnswer($_POST['Questionnaire'][$input]);
                 } elseif ($answerQuestion->type == "date") {
                     $answerQuestion->setAnswerDate($_POST['Questionnaire'][$input]);
                 } else {
                     $answerQuestion->setAnswerNumerique($_POST['Questionnaire'][$input]);
                 }
             }
             //if array, specific save action
             if ($answerQuestion->type == "array") {
                 //construct each id input an dget the result to store it
                 $rows = $answerQuestion->rows;
                 $arrows = split(",", $rows);
                 $cols = $answerQuestion->columns;
                 $arcols = split(",", $cols);
                 $answerArray = "";
                 foreach ($arrows as $row) {
                     foreach ($arcols as $col) {
                         $idunique = $idquestiongroup . "_" . $question->id . "_" . $row . "_" . $col;
                         if (isset($_POST['Questionnaire'][$idunique])) {
                             $answerArray .= $_POST['Questionnaire'][$idunique] . ",";
                         }
                     }
                 }
                 $answerQuestion->setAnswer($answerArray);
             }
         }
     }
     if ($flagNoInputToSave == false) {
         if ($answer->save()) {
             Yii::app()->user->setFlash('success', Yii::t('common', 'patientFormSaved'));
         } else {
             Yii::app()->user->setFlash('error', Yii::t('common', 'patientFormNotSaved'));
             Yii::log("pb save answer" . print_r($answer->getErrors()), CLogger::LEVEL_ERROR);
         }
     } else {
         Yii::app()->user->setFlash('error', Yii::t('common', 'patientFormNotSaved'));
         //null result
         $answer = null;
     }
     return $answer;
 }