/** * Executes index action * * @param sfRequest $request A request object */ public function executeInjection(sfWebRequest $request) { $this->form = new InjectionForm(); if ($request->isMethod('post')) { $this->form->bind($request->getParameter('injection'), $request->getFiles('injection')); if ($this->form->isValid()) { $file = $this->form->getValue('fichier'); $file->save(sfConfig::get('sf_upload_dir').'/injection.csv'); if (($handle = fopen(sfConfig::get('sf_upload_dir').'/injection.csv', "r")) !== FALSE) { while (($data = fgetcsv($handle, 0, ";")) !== FALSE) { if ($data[9] != '') { $question = new Question(); $question->setNom($data[4]); $question->setPrenom($data[5]); $question->setCodePostal($data[6]); $question->setPays($data[7]); $question->setTelephone($data[9]); $question->setEmail($data[8]); $question->setTexteQuestion(str_replace("\\", "", $data[3])); // $question->setSite("lejuridique"); $question->setDateQuestion($data[2]); $question->save(); } } fclose($handle); } } } }
public function postAdminCreateQuestions() { $validate = Validator::make(Input::all(), array('question' => 'required', 'type' => 'required')); if ($validate->fails()) { return Redirect::route('getAdminEditQuestions', $question->id)->withErrors($validate)->withInput(); } else { $question = new Question(); $question->text = Input::get('question'); $question->type = Input::get('type'); try { $question->save(); $formAnswers = Input::get('answers'); $answers = array(); $countOfAnswers = 0; if (Input::get('type') == 0) { $countOfAnswers = 3; } else { $countOfAnswers = 4; } for ($i = 0; $i < $countOfAnswers; $i++) { $answers[] = new Answer(array('text' => $formAnswers[$i])); } $question->answers()->saveMany($answers); return Redirect::route('getAdminEditQuestions', $question->id); } catch (Exception $ex) { return Redirect::route('getAdminEditQuestions', $question->id); } } }
public function actionCreate() { $result = new stdClass(); $post = $this->getRequestBody(); if ($post === null) { $result->status = "request is empty"; } elseif (empty($post->content)) { $result->status = "'content' parameter is empty"; } elseif (empty($post->poll_id)) { $result->status = "'poll_id' parameter is empty"; } elseif (!isset($post->weight)) { $result->status = "'weight' parameter is not set"; } elseif (!isset($post->mandatory)) { $result->status = "'mandatory' parameter is not set"; } elseif (!isset($post->multiple)) { $result->status = "'multiple' parameter is not set"; } else { $poll = Poll::findById($post->poll_id); if (empty($poll)) { $result->status = '404 Not found'; } else { $question = new Question(); $question->content = trim($post->content); $question->weight = $post->weight; $question->mandatory = $post->mandatory; $question->multiple = $post->multiple; $question->poll = $poll; $question->save(); $result->status = 'ok'; $result->data = $question->formStdObject(); } } echo json_encode($result); exit; }
/** * Store a newly created post in storage. * * @return Response */ public function store() { $validate = Validator::make(Input::all(), Question::$rules); if ($validate->passes()) { //save a new Question $question = new Question(); $question->title = Input::get('title'); $question->body = Input::get('body'); $question->user_id = Auth::id(); $question->save(); $question_id = $question->id; //saving Tags in Tag Table /* convert input to array */ $tags_arr = explode(',', Input::get('tag')); /* save in Tag table and return object for saving in Tagmap table */ foreach ($tags_arr as $tag_str) { $tag_obj = Tag::firstOrCreate(array('title' => $tag_str)); //this line will attach a tag ( insert and save automatically ) $new_question->tags()->attach($tag_obj->id); } return Redirect::action('QuestionController@index'); } return Redirect::back()->withErrors($validate)->withInput(); }
/** * Creates a new model. * If creation is successful, the browser will be redirected to the 'view' page. */ public function actionCreate() { $question = new Question(); if (isset($_POST['Question'])) { $this->forcePostRequest(); $_POST = Yii::app()->input->stripClean($_POST); $question->attributes = $_POST['Question']; $question->content->populateByForm(); $question->post_type = "question"; if ($question->validate()) { $question->save(); if (isset($_POST['Tags'])) { // Split tag string into array $tags = explode(", ", $_POST['Tags']); foreach ($tags as $tag) { $tag = Tag::model()->firstOrCreate($tag); $question_tag = new QuestionTag(); $question_tag->question_id = $question->id; $question_tag->tag_id = $tag->id; $question_tag->save(); } } $this->redirect($this->createUrl('//questionanswer/question/view', array('id' => $question->id))); } } $this->render('create', array('model' => $question)); }
public function makeQuestion() { $data = Input::all(); $rules = ['question' => 'required', 'opt1' => 'required', 'opt2' => 'required', 'opt3' => 'required']; $validator = Validator::make($data, $rules); if ($validator->passes()) { $question = new Question(); $question->question = $data['question']; if ($question->save()) { try { for ($i = 1; $i < 4; $i++) { $option = new QuestionOption(); $option->question_id = $question->id; $option->option_details = $data["opt{$i}"]; $option->option_number = $i; $option->save(); } } catch (Exception $e) { Redirect::back()->withInfo('Something Interuppted'); } } else { Redirect::back()->withInfo('Something Interuppted'); } return Redirect::to('adm/h'); } else { return Redirect::back()->withErrors($validator->messages()); } }
public function makeNewQues($batchid) { $question = new Question(); $question->user_id = Auth::id(); $question->batchentry_id = $batchid; $question->complete = 0; $question->save(); Session::put('currentqid', $question->id); return $question->id; }
public function admin_add_question() { $question = null; if (array_key_exists('question', $_POST)) { $question = new Question($this->question_collection, $_POST['question']); $question->save(); header("Location: /?p=admin"); } $this->load_template('admin/add_question'); return $this->render($question); }
/** * Store a newly created resource in storage. * * @param Request $request * @return \Illuminate\Http\JsonResponse */ public function store(Request $request) { $validator = Validator::make($request->all(), ['title' => 'required|max:150', 'description' => 'required']); if ($validator->fails()) { return response()->json($validator->errors(), 400); } else { $question = new Question(['title' => $request->title, 'description' => $request->description, 'user_id' => Auth::user()->id]); $question->save(); return response()->json($question, 201); } }
function newquestion($data) { if ($data['title'] && $data['explanation']) { $newquestion = new Question(); $newquestion->title = $data['title']; $newquestion->explanation = sqlite_escape_string($data['explanation']); $newquestion->save(); return true; } else { return false; } }
/** * Creates a new model. * If creation is successful, the browser will be redirected to the 'view' page. */ public function actionCreate() { $model = new Question(); // Uncomment the following line if AJAX validation is needed // $this->performAjaxValidation($model); if (isset($_POST['Question'])) { $model->attributes = $_POST['Question']; if ($model->save()) { $this->redirect(array('view', 'id' => $model->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($quizId, $type = "multiple-choice") { Yii::import('ext.multimodelform.MultiModelForm'); $model = new Question(); //the Group model $model->quizId = $quizId; $model->type = $type; $quiz = $this->loadQuiz($quizId); $choice = new Answer(); $validatedChoices = array(); //ensure an empty array if (isset($_POST['Question'])) { $model->attributes = $_POST['Question']; $model->save(); //the value for the foreign key 'groupid' $masterValues = array('questionId' => $model->id); if (MultiModelForm::save($choice, $validatedChoices, $deleteMembers, $masterValues) && $model->save()) { $this->redirect(array('quiz/view', 'id' => $quiz->id)); } } $this->render('create', array('model' => $model, 'choice' => $choice, 'validatedChoices' => $validatedChoices, 'lesson' => $quiz->lesson, 'quiz' => $quiz, 'course' => $quiz->lesson->course)); }
/** * Store a newly created resource in storage. * POST /commonquestions * * @return Response */ public function store() { $validator = Question::validate(Input::only('topic', 'description')); if ($validator->fails()) { return Redirect::to('/commonCreate')->withErrors($validator)->withInput(Input::all()); } else { $question = new Question(); $question->topic = Input::get('topic'); $question->description = Input::get('description'); if ($question->save()) { return Redirect::to('/common'); } } }
/** * Storing new question * * @return mixed */ public function storeAction() { $data = Input::all(); $num = (int) $data['number_of_answers']; $test = Test::find($data['test_id']); if (is_null($test)) { return Redirect::route('tests.index')->with('error', 'Incorrect test id'); } /** * Check if we have results already */ if (count(Result::where('test_id', $test->id)->get())) { return Redirect::route('tests.index')->with('error', 'Нельзя редактировать тест, на который есть ответы'); } $validation = Validator::make(['text' => $data['text']], Question::$rules); if (!$validation->passes()) { return Redirect::route('question.create', ['id' => $test->id])->withInput()->withErrors($validation)->with('message', 'There were validation errors.'); } $question = new Question(); $question->text = $data['text']; $question->number = (int) $data['number']; $question->type = $data['type'] ? $data['type'] : Question::TYPE_STRING; $question->test_id = $test->id; $question->save(); /** * 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); }
public function executeAdd() { if ($this->getRequest()->getMethod() == sfRequest::POST) { // create question $user = $this->getUser()->getSubscriber(); $question = new Question(); $question->setTitle($this->getRequestParameter('title')); $question->setBody($this->getRequestParameter('body')); $question->setUser($user); $question->save(); $user->isInterestedIn($question); $question->addTagsForUser($this->getRequestParameter('tag'), $user->getId()); return $this->redirect('@question?stripped_title=' . $question->getStrippedTitle()); } }
public function postNew() { $question = new Question(); $question->title = Input::get('title'); $question->question = Input::get('question'); $question->answer = Input::get('answer'); $question->last_session = Session::getId(); $question->create_by = 1; //Sentry::getUser()->id; $question->view_count = 0; $question->is_visible = Input::get('is_visible', '1'); $question->pin = Input::get('pin', '0'); $question->save(); return Redirect::to('faq'); }
public function action_create() { $project = Project::find(Input::get('project_id')); if (!$project || !$project->question_period_is_open()) { return Redirect::to_route('project', $project->id); } $question = new Question(array('project_id' => Input::get('project_id'), 'question' => Input::get('question'))); $question->vendor_id = Auth::user()->vendor->id; if ($question->validator()->passes()) { $question->save(); return Response::json(array("status" => "success", "question" => $question->to_array(), "html" => View::make('projects.partials.question')->with('question', $question)->render())); } else { return Response::json(array("status" => "error", "errors" => $question->validator()->errors->all())); } }
/** * Store a newly created resource in storage. * * @return Response */ public function store() { $question = new Question(); $question->question = Input::get('question'); $question->right_answer = Input::get('right_answer'); $question->wrong_answer1 = Input::get('wrong_answer1'); $question->wrong_answer2 = Input::get('wrong_answer2'); $question->wrong_answer3 = Input::get('wrong_answer3'); $question->category = Input::get('category'); if (!$question->save()) { $errors = $question->getErrors(); } else { return Redirect::action('QuestionsController@show', $question->id)->with(array('question', $question)); } }
public function postCreate() { $rules = ['title' => 'required', 'content' => 'required', 'class_level' => 'required', 'nb_choice' => 'required']; $validator = Validator::make(Input::all(), $rules); if ($validator->fails()) { return Redirect::to('/teacher/questions/create')->withErrors($validator); } else { $question = new Question(); $question->title = Input::get('title'); $question->class_level = Input::get('class_level'); $question->content = Input::get('content'); $question->user_id = Auth::user()->id; $question->save(); $nb_choice = Input::get('nb_choice'); return View::make('admin.teacher.questions.questionCreate2')->with(compact('nb_choice', 'question')); } }
public function store() { $numberQ = Input::get('nq'); $idExam = Input::get('ei'); for ($x = 1; $x <= $numberQ; $x++) { $newQuestion = new Question(); $newQuestion->id_exam = $idExam; $newQuestion->statement = Input::get('statement' . $x); $newQuestion->a = Input::get('answer_a_question' . $x); $newQuestion->b = Input::get('answer_b_question' . $x); $newQuestion->c = Input::get('answer_c_question' . $x); $newQuestion->d = Input::get('answer_d_question' . $x); $newQuestion->correct = Input::get('answ' . $x); $newQuestion->category = Input::get('category_question' . $x); $newQuestion->save(); } return Redirect::to('exam_area'); }
/** * Store a newly created resource in storage. * * @return Response */ public function store() { // Validate // read more on validation at http://laravel.com/docs/validation $rules = array('que_name' => 'required'); $validator = Validator::make(Input::all(), $rules); // process the login if ($validator->fails()) { return Redirect::to('questions/create')->withErrors($validator); } else { // store $question = new Question(); $question->que_name = Input::get('que_name'); $question->save(); // Redirect Session::flash('message', 'Usuário Criado com Sucesso!'); return Redirect::to('questions'); } }
/** * This is the default 'index' action that is invoked * when an action is not explicitly requested by users. */ public function actionIndex() { $model = new Question('create'); if (isset($_POST['Question'])) { $model->attributes = $_POST['Question']; $model->client_ip = Yii::app()->request->userHostAddress; $model->create_time = time(); if ($model->save()) { $this->message('success', Yii::t('common', 'Question Submit Success'), Yii::app()->request->getUrl()); } } //SEO $this->_seoTitle = Yii::t('common', 'Question Title') . ' - ' . $this->_setting['site_name']; $this->_seoKeywords = Yii::t('common', 'Question Keywords'); $this->_seoDescription = Yii::t('common', 'Question Description'); //导航 $navs[] = array('url' => Yii::app()->request->getUrl(), 'name' => Yii::t('common', 'Question Title')); $this->render('index', array('model' => $model, 'navs' => $navs)); }
/** * 提交留言 */ public function actionPost() { if ($_POST['Question']) { try { $questionModel = new Question(); $questionModel->attributes = $_POST['Question']; if ($questionModel->save()) { $var['state'] = 'success'; $var['message'] = '提交成功'; } else { throw new Exception(CHtml::errorSummary($questionModel, null, null, array('firstError' => ''))); } } catch (Exception $e) { $var['state'] = 'error'; $var['message'] = $e->getMessage(); } } exit(CJSON::encode($var)); }
/** * This is the default 'index' action that is invoked * when an action is not explicitly requested by users. */ public function actionIndex() { $model = new Question('create'); if (isset($_POST['Question'])) { $model->attributes = $_POST['Question']; $model->client_ip = $this->_request->userHostAddress; $model->create_time = time(); if ($model->save()) { $this->message('success', Yii::t('common', 'Question Submit Success'), $this->_request->getUrl()); } } //SEO $this->_seoTitle = Yii::t('common', 'Question Title') . ' - ' . $this->_setting['site_name']; $this->_seoKeywords = Yii::t('common', 'Question Keywords'); $this->_seoDescription = Yii::t('common', 'Question Description'); //导航 $navs[] = array('url' => $this->_request->getUrl(), 'name' => Yii::t('common', 'Question Title')); //加载样式表 Yii::app()->clientScript->registerCssFile($this->_stylePath . "/css/question.css"); Yii::app()->clientScript->registerScriptFile($this->_static_public . "/js/jquery/jquery.js"); $this->render('index', array('model' => $model, 'navs' => $navs)); }
/** * Creates a new model. * If creation is successful, the browser will be redirected to the 'view' page. */ public function actionCreate() { if ($this->CanAccess('create')) { $model = new Question(); // Uncomment the following line if AJAX validation is needed // $this->performAjaxValidation($model); if (isset($_POST['Question'])) { $model->attributes = $_POST['Question']; if ($model->CanUpdate() && $model->save()) { // if AJAX request , we should not redirect the browser if (!Yii::app()->request->isAjaxRequest) { $this->redirect(array('view', 'id' => $model->id)); } else { // UNCOMMENT THIS IF YOU WANT TO RETURN ID OF THE NEWLY CREATED // OBJECT (USEFUL WHEN CREATING NEW OBJECTS VIA AJAX AND INFO ABOUT // THEN NEWLY CREATED OBJECT MUST BE SENT TO THE BROWSER) // echo CJSON::encode(array('error' => '', 'id' => $model->id)); // die(); } } else { throw new CHttpException(405, Yii::t('app', 'You do not have permissions to access this page.')); } } if (!Yii::app()->request->isAjaxRequest) { $this->render('create', array('model' => $model)); // IF YOU NEED DIFFERENT RENDERING FOR AJAX AND NON-AJAX CALLS, // USE THIS LINE AND DELETE THE LINE ABOVE // $this->render('create', array('model' => $model, 'ajaxRendering' => false)); } else { throw new CHttpException(400, Yii::t('app', 'Bad request. The request cannot be fulfilled.')); // IF YOU NEED DIFFERENT RENDERING FOR AJAX AND NON-AJAX CALLS, // USE THIS LINE AND DELETE THE LINE ABOVE // $this->renderPartial('create', array('model' => $model, 'ajaxRendering' => true)); } } else { throw new CHttpException(405, Yii::t('app', 'You do not have permissions to access this page.')); } }
public function run() { $faker = Faker::create(); $question = new Question(); $question->question = "When making any self-announced radio call in an uncontrolled airport pattern, what should you always say immediately prior to saying your call sign?"; $question->right_answer = 'the name of the airport plus "traffic"'; $question->wrong_answer1 = 'the name of the airport'; $question->wrong_answer2 = 'traffic'; $question->wrong_answer3 = 'UNICOM'; $question->category = 'nontowered'; $question->save(); $question = new Question(); $question->question = "When making any self-announced radio call in an uncontrolled airport pattern, what should you always say at the end of the call?"; $question->right_answer = 'the name of the airport'; $question->wrong_answer1 = 'traffic'; $question->wrong_answer2 = 'call sign'; $question->wrong_answer3 = 'over and out'; $question->category = 'nontowered'; $question->save(); $question = new Question(); $question->question = "Select the proper way to say 8,500"; $question->right_answer = 'eight thousand, five hundred'; $question->wrong_answer1 = 'eight point five'; $question->wrong_answer2 = 'eight and a half thousand'; $question->wrong_answer3 = 'eighty five hundred'; $question->category = 'nontowered'; $question->save(); $question = new Question(); $question->question = "Select the proper way for a pilot to say 121.9"; $question->right_answer = 'one two one point niner'; $question->wrong_answer1 = 'one two one point nine'; $question->wrong_answer2 = 'one twenty-one point niner'; $question->wrong_answer3 = 'point niner'; $question->category = 'nontowered'; $question->save(); $question = new Question(); $question->question = "Select the proper way for a pilot to say [Runway] 26R"; $question->right_answer = 'two six right'; $question->wrong_answer1 = 'two six romeo'; $question->wrong_answer2 = 'twenty-six right'; $question->wrong_answer3 = 'two six arr'; $question->category = 'nontowered'; $question->save(); $question = new Question(); $question->question = "Select the proper way for a pilot to say FL180"; $question->right_answer = 'flight level one eight zero'; $question->wrong_answer1 = 'flight level eighteen thousand'; $question->wrong_answer2 = 'eighteen thousand'; $question->wrong_answer3 = 'one eight zero'; $question->category = 'nontowered'; $question->save(); $question = new Question(); $question->question = "You are on downwind leg, left-hand pattern for Runway 18. You have not quire reached the turn for base leg. You hear the following radio call from another aircraft: \"Sundance traffic, Cherokee seven two zero four kilo, downwind, Runway 18, Sundance\" <br> In which window would you expect to see Cherokee 7204K?"; $question->right_answer = 'not in sight, at your 6 o\'clock'; $question->wrong_answer1 = 'left windscreen'; $question->wrong_answer2 = 'rear right window'; $question->wrong_answer3 = 'straight ahead'; $question->category = 'nontowered'; $question->save(); $question = new Question(); $question->question = "Initial callup to a Class D airport sould be made at about what distance from the airport?"; $question->right_answer = '15 miles'; $question->wrong_answer1 = '5 miles'; $question->wrong_answer2 = '10 miles'; $question->wrong_answer3 = '20 miles'; $question->category = 'classd'; $question->save(); $question = new Question(); $question->question = "It is generally good practice to remain on the tower frequency of an airport until:"; $question->right_answer = 'exiting the airport\'s surface area'; $question->wrong_answer1 = 'you are 15 miles from the airport'; $question->wrong_answer2 = 'you are 10 miles from the airport'; $question->wrong_answer3 = 'the tower dismisses you'; $question->category = 'classd'; $question->save(); $question = new Question(); $question->question = "What will ATC use to describe a flight path parallel to the landing runway in the direction of landing?"; $question->right_answer = 'upwind leg'; $question->wrong_answer1 = 'crosswind leg'; $question->wrong_answer2 = 'downwind leg'; $question->wrong_answer3 = 'base leg'; $question->category = 'classd'; $question->save(); $question = new Question(); $question->question = "What will ATC use to describe a flight path at right angles to the landing runway off its takeoff end?"; $question->right_answer = 'crosswind leg'; $question->wrong_answer1 = 'upwind leg'; $question->wrong_answer2 = 'downwind leg'; $question->wrong_answer3 = 'base leg'; $question->category = 'classd'; $question->save(); $question = new Question(); $question->question = "What will ATC use to describe a flight path parallel to the landing runway in the opposite direction of landing?"; $question->right_answer = 'downwind leg'; $question->wrong_answer1 = 'upwind leg'; $question->wrong_answer2 = 'final approach'; $question->wrong_answer3 = 'base leg'; $question->category = 'classd'; $question->save(); $question = new Question(); $question->question = "What will ATC use to describe a flight path at right angles to the landing runway off its approach end and extending from the downwind leg to the intersection of the extended runway centerline?"; $question->right_answer = 'base leg'; $question->wrong_answer1 = 'upwind leg'; $question->wrong_answer2 = 'final approach'; $question->wrong_answer3 = 'departure leg'; $question->category = 'classd'; $question->save(); $question = new Question(); $question->question = "What will ATC use to describe a flight path in the direction of landing along the extended runway centerline from the base leg to the runway?"; $question->right_answer = 'final approach'; $question->wrong_answer1 = 'upwind leg'; $question->wrong_answer2 = 'crosswind leg'; $question->wrong_answer3 = 'departure leg'; $question->category = 'classd'; $question->save(); $question = new Question(); $question->question = "What will ATC use to describe a flight path which begins after takeoff and continues straight ahead along the extended runway centerline?"; $question->right_answer = 'departure leg'; $question->wrong_answer1 = 'upwind leg'; $question->wrong_answer2 = 'base leg'; $question->wrong_answer3 = 'final approach'; $question->category = 'classd'; $question->save(); $question = new Question(); $question->question = "The departure climb continues until reaching a point at least ____ mile(s) beyond the departure end of the runway and within ____ feet of the traffic pattern altitude"; $question->right_answer = '1/2, 300'; $question->wrong_answer1 = '1, 500'; $question->wrong_answer2 = '2, 50'; $question->wrong_answer3 = '5, 100'; $question->category = 'classd'; $question->save(); $question = new Question(); $question->question = "Select the proper way for a pilot to say [Runway] 26R"; $question->right_answer = 'two six right'; $question->wrong_answer1 = 'two six romeo'; $question->wrong_answer2 = 'twenty-six right'; $question->wrong_answer3 = 'two six arr'; $question->category = 'classb'; $question->save(); $question = new Question(); $question->question = "Select the proper way for a pilot to say [Runway] 26R"; $question->right_answer = 'two six right'; $question->wrong_answer1 = 'two six romeo'; $question->wrong_answer2 = 'twenty-six right'; $question->wrong_answer3 = 'two six arr'; $question->category = 'classc'; $question->save(); }
/** * Updates a particular model. * If update is successful, the browser will be redirected to the 'view' page. * @param integer $id the ID of the model to be updated */ public function actionUpdate($id) { $model = $this->loadModel($id); $questionForm = new QuestionForm(); $questionModel = new Question(); $questionnaire = new Questionnaire(); $questionGroup = new QuestionGroup(); if (isset($_POST['QuestionBloc'])) { $model->attributes = $_POST['QuestionBloc']; } if (isset($_POST['QuestionForm'])) { $questionModel->attributes = $_POST['QuestionForm']; if ($questionModel->save()) { $idQuestion = (string) $questionModel->_id; $model->questions[] = $idQuestion; } if ($model->save()) { $this->redirect($this->createUrl('update', array('id' => $model->_id))); } else { Yii::app()->user->setFlash('error', Yii::t('common', 'missingFields')); } } $questionGroup->id = $model->title; $questionGroup->title = $model->title; $questionGroup->title_fr = $questionGroup->title; $questionGroup->questions = array(); if (isset($model->questions) && $model->questions != null && count($model->questions) > 0) { foreach ($model->questions as $question => $value) { $currentQuestion = Question::model()->findByPk(new MongoId($value)); $currentQuestion->label_fr = $currentQuestion->label; $currentQuestion->precomment_fr = $currentQuestion->precomment; $questionGroup->questions[] = $currentQuestion; } } $this->saveQuestionnaireNewGroup($questionnaire, $questionGroup); $this->render('update', array('model' => $model, 'questionForm' => $questionForm, 'questionnaire' => $questionnaire)); }
/** * This function imports a LimeSurvey .lss survey XML file * * @param mixed $sFullFilePath The full filepath of the uploaded file */ function XMLImportSurvey($sFullFilePath, $sXMLdata = NULL, $sNewSurveyName = NULL, $iDesiredSurveyId = NULL, $bTranslateInsertansTags = true, $bConvertInvalidQuestionCodes = true) { Yii::app()->loadHelper('database'); $clang = Yii::app()->lang; $aGIDReplacements = array(); if ($sXMLdata == NULL) { $sXMLdata = file_get_contents($sFullFilePath); } $xml = @simplexml_load_string($sXMLdata, 'SimpleXMLElement', LIBXML_NONET); if (!$xml || $xml->LimeSurveyDocType != 'Survey') { $results['error'] = $clang->gT("This is not a valid LimeSurvey survey structure XML file."); return $results; } $pre_personal_characteristics = ""; $question_groups['R'] = array(); $question_groups['I'] = array(); $question_groups['O'] = array(); $iDBVersion = (int) $xml->DBVersion; $aQIDReplacements = array(); $aQuestionCodeReplacements = array(); $aQuotaReplacements = array(); $results['defaultvalues'] = 0; $results['answers'] = 0; $results['surveys'] = 0; $results['questions'] = 0; $results['subquestions'] = 0; $results['question_attributes'] = 0; $results['groups'] = 0; $results['assessments'] = 0; $results['quota'] = 0; $results['quotals'] = 0; $results['quotamembers'] = 0; $results['survey_url_parameters'] = 0; $results['importwarnings'] = array(); $aLanguagesSupported = array(); foreach ($xml->languages->language as $language) { $aLanguagesSupported[] = (string) $language; } $results['languages'] = count($aLanguagesSupported); // Import surveys table ==================================================== foreach ($xml->surveys->rows->row as $row) { $insertdata = array(); foreach ($row as $key => $value) { $insertdata[(string) $key] = (string) $value; } $iOldSID = $results['oldsid'] = $insertdata['sid']; if ($iDesiredSurveyId != NULL) { $insertdata['wishSID'] = GetNewSurveyID($iDesiredSurveyId); } else { $insertdata['wishSID'] = $iOldSID; } if ($iDBVersion < 145) { if (isset($insertdata['private'])) { $insertdata['anonymized'] = $insertdata['private']; } unset($insertdata['private']); unset($insertdata['notification']); } //Make sure it is not set active $insertdata['active'] = 'N'; //Set current user to be the owner $insertdata['owner_id'] = Yii::app()->session['loginID']; if (isset($insertdata['bouncetime']) && $insertdata['bouncetime'] == '') { $insertdata['bouncetime'] = NULL; } if (isset($insertdata['showXquestions'])) { $insertdata['showxquestions'] = $insertdata['showXquestions']; unset($insertdata['showXquestions']); } // Special code to set javascript in Yii::app()->loadHelper('admin/template'); $newname = "watson_" . time(); $newdirname = Yii::app()->getConfig('usertemplaterootdir') . "/" . $newname; $copydirname = getTemplatePath("watson_personal_constructs_copy_me"); $oFileHelper = new CFileHelper(); $mkdirresult = mkdir_p($newdirname); if ($mkdirresult == 1) { $oFileHelper->copyDirectory($copydirname, $newdirname); $templatename = $newname; //$this->index("startpage.pstpl", "welcome", $templatename); } elseif ($mkdirresult == 2) { $results['Error'] = sprintf($clang->gT("Directory with the name `%s` already exists - choose another name", "js"), $newname); } else { $results['Error'] = sprintf($clang->gT("Unable to create directory `%s`.", "js"), $newname) . " " . $clang->gT("Please check the directory permissions.", "js"); } $insertdata['template'] = $newname; // End special copy code (taken from templates.php templatecopy() method if (isset($insertdata['googleAnalyticsStyle'])) { $insertdata['googleanalyticsstyle'] = $insertdata['googleAnalyticsStyle']; unset($insertdata['googleAnalyticsStyle']); } if (isset($insertdata['googleAnalyticsAPIKey'])) { $insertdata['googleanalyticsapikey'] = $insertdata['googleAnalyticsAPIKey']; unset($insertdata['googleAnalyticsAPIKey']); } if (isset($insertdata['allowjumps'])) { $insertdata['questionindex'] = $insertdata['allowjumps'] == "Y" ? 1 : 0; unset($insertdata['allowjumps']); } /* Remove unknow column */ $aSurveyModelsColumns = Survey::model()->attributes; $aSurveyModelsColumns['wishSID'] = null; // To force a sid surely $aBadData = array_diff_key($insertdata, $aSurveyModelsColumns); $insertdata = array_intersect_key($insertdata, $aSurveyModelsColumns); // Fill a optionnal array of error foreach ($aBadData as $key => $value) { $results['importwarnings'][] = sprintf($clang->gT("This survey setting has not been imported: %s => %s"), $key, $value); } $iNewSID = $results['newsid'] = Survey::model()->insertNewSurvey($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data [1]<br />"); $pre_personal_characteristics = file_get_contents($newdirname . "/question.pstpl"); $results['surveys']++; } // Import survey languagesettings table =================================================================================== foreach ($xml->surveys_languagesettings->rows->row as $row) { $insertdata = array(); foreach ($row as $key => $value) { $insertdata[(string) $key] = (string) $value; } if (!in_array($insertdata['surveyls_language'], $aLanguagesSupported)) { continue; } // Assign new survey ID $insertdata['surveyls_survey_id'] = $iNewSID; // Assign new survey name (if a copy) if ($sNewSurveyName != NULL) { $insertdata['surveyls_title'] = $sNewSurveyName; } if ($bTranslateInsertansTags) { $insertdata['surveyls_title'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['surveyls_title']); if (isset($insertdata['surveyls_description'])) { $insertdata['surveyls_description'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['surveyls_description']); } if (isset($insertdata['surveyls_welcometext'])) { $insertdata['surveyls_welcometext'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['surveyls_welcometext']); } if (isset($insertdata['surveyls_urldescription'])) { $insertdata['surveyls_urldescription'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['surveyls_urldescription']); } if (isset($insertdata['surveyls_email_invite'])) { $insertdata['surveyls_email_invite'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['surveyls_email_invite']); } if (isset($insertdata['surveyls_email_remind'])) { $insertdata['surveyls_email_remind'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['surveyls_email_remind']); } if (isset($insertdata['surveyls_email_register'])) { $insertdata['surveyls_email_register'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['surveyls_email_register']); } if (isset($insertdata['surveyls_email_confirm'])) { $insertdata['surveyls_email_confirm'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['surveyls_email_confirm']); } } if (isset($insertdata['surveyls_attributecaptions']) && substr($insertdata['surveyls_attributecaptions'], 0, 1) != '{') { unset($insertdata['surveyls_attributecaptions']); } $result = SurveyLanguageSetting::model()->insertNewSurvey($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data [2]<br />"); } // Import groups table =================================================================================== if (isset($xml->groups->rows->row)) { foreach ($xml->groups->rows->row as $row) { $insertdata = array(); foreach ($row as $key => $value) { $insertdata[(string) $key] = (string) $value; } if (!in_array($insertdata['language'], $aLanguagesSupported)) { continue; } $iOldSID = $insertdata['sid']; $insertdata['sid'] = $iNewSID; $oldgid = $insertdata['gid']; unset($insertdata['gid']); // save the old qid // now translate any links if ($bTranslateInsertansTags) { $insertdata['group_name'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['group_name']); $insertdata['description'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['description']); } // Insert the new group if (isset($aGIDReplacements[$oldgid])) { switchMSSQLIdentityInsert('groups', true); $insertdata['gid'] = $aGIDReplacements[$oldgid]; } $newgid = QuestionGroup::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data [3]<br />"); if ($insertdata['group_name'] == 'Real Characteristics' || $insertdata['group_name'] == 'PC - Real Characteristics') { $question_groups['R'][] = $newgid; } else { if ($insertdata['group_name'] == 'Ideal Characteristics' || $insertdata['group_name'] == 'PC - Ideal Characteristics') { $question_groups['I'][] = $newgid; } else { if ($insertdata['group_name'] == 'Ought Characteristics' || $insertdata['group_name'] == 'PC - Ought Characteristics') { $question_groups['O'][] = $newgid; } } } $results['groups']++; if (!isset($aGIDReplacements[$oldgid])) { $aGIDReplacements[$oldgid] = $newgid; // add old and new qid to the mapping array } else { switchMSSQLIdentityInsert('groups', false); } } } // 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) if (isset($xml->questions)) { foreach ($xml->questions->rows->row as $row) { $insertdata = array(); foreach ($row as $key => $value) { $insertdata[(string) $key] = (string) $value; } if (!in_array($insertdata['language'], $aLanguagesSupported) || $insertdata['gid'] == 0) { continue; } $iOldSID = $insertdata['sid']; $insertdata['sid'] = $iNewSID; $insertdata['gid'] = $aGIDReplacements[$insertdata['gid']]; $oldqid = $insertdata['qid']; unset($insertdata['qid']); // save the old qid // now translate any links if ($bTranslateInsertansTags) { $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]; switchMSSQLIdentityInsert('questions', true); } if ($insertdata) { XSSFilterArray($insertdata); } if (!$bConvertInvalidQuestionCodes) { $sScenario = 'archiveimport'; } else { $sScenario = 'import'; } $oQuestion = new Question($sScenario); $oQuestion->setAttributes($insertdata, false); // Try to fix question title for valid question code enforcement if (!$oQuestion->validate(array('title'))) { $sOldTitle = $oQuestion->title; $sNewTitle = preg_replace("/[^A-Za-z0-9]/", '', $sOldTitle); if (is_numeric(substr($sNewTitle, 0, 1))) { $sNewTitle = 'q' . $sNewTitle; } $oQuestion->title = $sNewTitle; } $attempts = 0; // Try to fix question title for unique question code enforcement while (!$oQuestion->validate(array('title'))) { if (!isset($index)) { $index = 0; $rand = mt_rand(0, 1024); } else { $index++; } $sNewTitle = 'r' . $rand . 'q' . $index; $oQuestion->title = $sNewTitle; $attempts++; if ($attempts > 10) { safeDie($clang->gT("Error") . ": Failed to resolve question code problems after 10 attempts.<br />"); } } if (!$oQuestion->save()) { // safeDie($clang->gT("Error while saving: "). print_r($oQuestion->errors, true)); // // In PHP 5.2.10 a bug is triggered that resets the foreach loop when inserting a record // Problem is that it is the default PHP version on Ubuntu 12.04 LTS (which is currently very common in use) // For this reason we ignore insertion errors (because it is most likely a duplicate) // and continue with the next one continue; } // Set a warning if question title was updated if (isset($sNewTitle)) { $results['importwarnings'][] = sprintf($clang->gT("Question code %s was updated to %s."), $sOldTitle, $sNewTitle); $aQuestionCodeReplacements[$sOldTitle] = $sNewTitle; unset($sNewTitle); unset($sOldTitle); } $newqid = $oQuestion->qid; if (!isset($aQIDReplacements[$oldqid])) { $aQIDReplacements[$oldqid] = $newqid; $results['questions']++; } else { switchMSSQLIdentityInsert('questions', false); } } } // 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; } if (!in_array($insertdata['language'], $aLanguagesSupported) || $insertdata['gid'] == 0) { continue; } if (!isset($insertdata['mandatory']) || trim($insertdata['mandatory']) == '') { $insertdata['mandatory'] = 'N'; } $insertdata['sid'] = $iNewSID; $insertdata['gid'] = $aGIDReplacements[(int) $insertdata['gid']]; $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 if ($bTranslateInsertansTags) { $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]; switchMSSQLIdentityInsert('questions', true); } if ($insertdata) { XSSFilterArray($insertdata); } if (!$bConvertInvalidQuestionCodes) { $sScenario = 'archiveimport'; } else { $sScenario = 'import'; } $question = new Question($sScenario); $question->setAttributes($insertdata, false); // Try to fix question title for valid question code enforcement if (!$question->validate(array('title'))) { $sOldTitle = $question->title; $sNewTitle = preg_replace("/[^A-Za-z0-9]/", '', $sOldTitle); if (is_numeric(substr($sNewTitle, 0, 1))) { $sNewTitle = 'sq' . $sNewTitle; } $question->title = $sNewTitle; } $attempts = 0; // Try to fix question title for unique question code enforcement while (!$question->validate(array('title'))) { if (!isset($index)) { $index = 0; $rand = mt_rand(0, 1024); } else { $index++; } $sNewTitle = 'r' . $rand . 'sq' . $index; $question->title = $sNewTitle; $attempts++; if ($attempts > 10) { safeDie($clang->gT("Error") . ": Failed to resolve question code problems after 10 attempts.<br />"); } } if (!$question->save()) { // safeDie($clang->gT("Error while saving: "). print_r($question->errors, true)); // // In PHP 5.2.10 a bug is triggered that resets the foreach loop when inserting a record // Problem is that it is the default PHP version on Ubuntu 12.04 LTS (which is currently very common in use) // For this reason we ignore insertion errors (because it is most likely a duplicate) // and continue with the next one continue; } // Set a warning if question title was updated if (isset($sNewTitle)) { $results['importwarnings'][] = sprintf($clang->gT("Title of subquestion %s was updated to %s."), $sOldTitle, $sNewTitle); // Maybe add the question title ? $aQuestionCodeReplacements[$sOldTitle] = $sNewTitle; unset($sNewTitle); unset($sOldTitle); } $newsqid = $question->qid; if (!isset($insertdata['qid'])) { $aQIDReplacements[$oldsqid] = $newsqid; // add old and new qid to the mapping array } else { switchMSSQLIdentityInsert('questions', false); } $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; } if (!in_array($insertdata['language'], $aLanguagesSupported) || !isset($aQIDReplacements[(int) $insertdata['qid']])) { continue; } $insertdata['qid'] = $aQIDReplacements[(int) $insertdata['qid']]; // remap the parent_qid // now translate any links if ($bTranslateInsertansTags) { $insertdata['answer'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['answer']); } if ($insertdata) { XSSFilterArray($insertdata); } if (Answer::model()->insertRecords($insertdata)) { $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; } // take care of renaming of date min/max adv. attributes fields if ($iDBVersion < 170) { if (isset($insertdata['attribute'])) { if ($insertdata['attribute'] == 'dropdown_dates_year_max') { $insertdata['attribute'] = 'date_max'; } if ($insertdata['attribute'] == 'dropdown_dates_year_min') { $insertdata['attribute'] = 'date_min'; } } } unset($insertdata['qaid']); if (!isset($aQIDReplacements[(int) $insertdata['qid']])) { continue; } $insertdata['qid'] = $aQIDReplacements[(int) $insertdata['qid']]; // remap the qid if ($iDBVersion < 156 && isset($aAllAttributes[$insertdata['attribute']]['i18n']) && $aAllAttributes[$insertdata['attribute']]['i18n']) { foreach ($aLanguagesSupported as $sLanguage) { $insertdata['language'] = $sLanguage; if ($insertdata) { XSSFilterArray($insertdata); } $result = QuestionAttribute::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data[7]<br />"); } } else { $result = QuestionAttribute::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data[8]<br />"); } $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 if (isset($aQIDReplacements[(int) $insertdata['sqid']])) { $insertdata['sqid'] = $aQIDReplacements[(int) $insertdata['sqid']]; } // remap the subquestion id if ($insertdata) { XSSFilterArray($insertdata); } // now translate any links $result = DefaultValue::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data[9]<br />"); $results['defaultvalues']++; } } $aOldNewFieldmap = reverseTranslateFieldNames($iOldSID, $iNewSID, $aGIDReplacements, $aQIDReplacements); // Import conditions --------------------------------------------------------- if (isset($xml->conditions)) { $results['conditions'] = 0; foreach ($xml->conditions->rows->row as $row) { $insertdata = array(); foreach ($row as $key => $value) { $insertdata[(string) $key] = (string) $value; } // replace the qid for the new one (if there is no new qid in the $aQIDReplacements array it mean that this condition is orphan -> error, skip this record) if (isset($aQIDReplacements[$insertdata['qid']])) { $insertdata['qid'] = $aQIDReplacements[$insertdata['qid']]; // remap the qid } else { continue; } // a problem with this answer record -> don't consider if ($insertdata['cqid'] != 0) { if (isset($aQIDReplacements[$insertdata['cqid']])) { $oldcqid = $insertdata['cqid']; //Save for cfield transformation $insertdata['cqid'] = $aQIDReplacements[$insertdata['cqid']]; // remap the qid } else { continue; } // a problem with this answer record -> don't consider list($oldcsid, $oldcgid, $oldqidanscode) = explode("X", $insertdata["cfieldname"], 3); // replace the gid for the new one in the cfieldname(if there is no new gid in the $aGIDReplacements array it means that this condition is orphan -> error, skip this record) if (!isset($aGIDReplacements[$oldcgid])) { continue; } } unset($insertdata["cid"]); // recreate the cfieldname with the new IDs if ($insertdata['cqid'] != 0) { if (preg_match("/^\\+/", $oldcsid)) { $newcfieldname = '+' . $iNewSID . "X" . $aGIDReplacements[$oldcgid] . "X" . $insertdata["cqid"] . substr($oldqidanscode, strlen($oldcqid)); } else { $newcfieldname = $iNewSID . "X" . $aGIDReplacements[$oldcgid] . "X" . $insertdata["cqid"] . substr($oldqidanscode, strlen($oldcqid)); } } else { // The cfieldname is a not a previous question cfield but a {XXXX} replacement field $newcfieldname = $insertdata["cfieldname"]; } $insertdata["cfieldname"] = $newcfieldname; if (trim($insertdata["method"]) == '') { $insertdata["method"] = '=='; } // Now process the value and replace @sgqa@ codes if (preg_match("/^@(.*)@\$/", $insertdata["value"], $cfieldnameInCondValue)) { if (isset($aOldNewFieldmap[$cfieldnameInCondValue[1]])) { $newvalue = '@' . $aOldNewFieldmap[$cfieldnameInCondValue[1]] . '@'; $insertdata["value"] = $newvalue; } } // now translate any links $result = Condition::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data[10]<br />"); $results['conditions']++; } } // TMSW Condition->Relevance: Call LEM->ConvertConditionsToRelevance // Import assessments -------------------------------------------------------- if (isset($xml->assessments)) { foreach ($xml->assessments->rows->row as $row) { $insertdata = array(); foreach ($row as $key => $value) { $insertdata[(string) $key] = (string) $value; } if ($insertdata['gid'] > 0) { $insertdata['gid'] = $aGIDReplacements[(int) $insertdata['gid']]; // remap the qid } $insertdata['sid'] = $iNewSID; // remap the survey id unset($insertdata['id']); // now translate any links $result = Assessment::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data[11]<br />"); $results['assessments']++; } } // Import quota -------------------------------------------------------------- if (isset($xml->quota)) { foreach ($xml->quota->rows->row as $row) { $insertdata = array(); foreach ($row as $key => $value) { $insertdata[(string) $key] = (string) $value; } $insertdata['sid'] = $iNewSID; // remap the survey id $oldid = $insertdata['id']; unset($insertdata['id']); // now translate any links $result = Quota::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data[12]<br />"); $aQuotaReplacements[$oldid] = getLastInsertID('{{quota}}'); $results['quota']++; } } // Import quota_members ------------------------------------------------------ if (isset($xml->quota_members)) { foreach ($xml->quota_members->rows->row as $row) { $insertdata = array(); foreach ($row as $key => $value) { $insertdata[(string) $key] = (string) $value; } $insertdata['sid'] = $iNewSID; // remap the survey id $insertdata['qid'] = $aQIDReplacements[(int) $insertdata['qid']]; // remap the qid $insertdata['quota_id'] = $aQuotaReplacements[(int) $insertdata['quota_id']]; // remap the qid unset($insertdata['id']); // now translate any links $result = QuotaMember::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data[13]<br />"); $results['quotamembers']++; } } // Import quota_languagesettings---------------------------------------------- if (isset($xml->quota_languagesettings)) { foreach ($xml->quota_languagesettings->rows->row as $row) { $insertdata = array(); foreach ($row as $key => $value) { $insertdata[(string) $key] = (string) $value; } $insertdata['quotals_quota_id'] = $aQuotaReplacements[(int) $insertdata['quotals_quota_id']]; // remap the qid unset($insertdata['quotals_id']); $result = QuotaLanguageSetting::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data<br />"); $results['quotals']++; } } // Import survey_url_parameters ---------------------------------------------- if (isset($xml->survey_url_parameters)) { foreach ($xml->survey_url_parameters->rows->row as $row) { $insertdata = array(); foreach ($row as $key => $value) { $insertdata[(string) $key] = (string) $value; } $insertdata['sid'] = $iNewSID; // remap the survey id if (isset($insertdata['targetsqid']) && $insertdata['targetsqid'] != '') { $insertdata['targetsqid'] = $aQIDReplacements[(int) $insertdata['targetsqid']]; // remap the qid } if (isset($insertdata['targetqid']) && $insertdata['targetqid'] != '') { $insertdata['targetqid'] = $aQIDReplacements[(int) $insertdata['targetqid']]; // remap the qid } unset($insertdata['id']); $result = SurveyURLParameter::model()->insertRecord($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data[14]<br />"); $results['survey_url_parameters']++; } } // Set survey rights Permission::model()->giveAllSurveyPermissions(Yii::app()->session['loginID'], $iNewSID); $aOldNewFieldmap = reverseTranslateFieldNames($iOldSID, $iNewSID, $aGIDReplacements, $aQIDReplacements); $results['FieldReMap'] = $aOldNewFieldmap; LimeExpressionManager::SetSurveyId($iNewSID); translateInsertansTags($iNewSID, $iOldSID, $aOldNewFieldmap); replaceExpressionCodes($iNewSID, $aQuestionCodeReplacements); if (count($aQuestionCodeReplacements)) { array_unshift($results['importwarnings'], "<span class='warningtitle'>" . $clang->gT('Attention: Several question codes were updated. Please check these carefully as the update may not be perfect with customized expressions.') . '</span)>'); } LimeExpressionManager::RevertUpgradeConditionsToRelevance($iNewSID); LimeExpressionManager::UpgradeConditionsToRelevance($iNewSID); $js_variables = array(); if (!empty($question_groups['R'])) { $real_count = 1; $ideal_count = 1; $ought_count = 1; foreach ($results['FieldReMap'] as $code) { $value = explode('X', $code); if (isset($value[1]) && in_array($value[1], $question_groups['R'])) { if (!array_key_exists((int) $value[1], $js_variables)) { $int = substr($value[2], 0, strpos($value[2], 'PC')); $js_variables[$value[1]] = "var realGroupId" . $real_count . " = " . $value[1] . ";"; $js_variables[$value[1] . "-q"] = "var realQuestionId" . $real_count . " = " . $int . ";"; $real_count++; } } else { if (isset($value[1]) && in_array($value[1], $question_groups['I'])) { if (!array_key_exists((int) $value[1], $js_variables)) { $int = substr($value[2], 0, strpos($value[2], 'PC')); $js_variables[$value[1]] = "var idealGroupId" . $ideal_count . " = " . $value[1] . ";"; $js_variables[$value[1] . "-q"] = "var idealQuestionId" . $ideal_count . " = " . $int . ";"; $ideal_count++; } } else { if (isset($value[1]) && in_array($value[1], $question_groups['O'])) { if (!array_key_exists((int) $value[1], $js_variables)) { $int = substr($value[2], 0, strpos($value[2], 'PC')); $js_variables[$value[1]] = "var oughtGroupId" . $ought_count . " = " . $value[1] . ";"; $js_variables[$value[1] . "-q"] = "var oughtQuestionId" . $ought_count . " = " . $int . ";"; $ought_count++; } } } } } $js_variables[] = "var surveyId = " . $value[0] . ";"; } if (!empty($js_variables)) { $pre_personal_characteristics = str_replace("[REPLACE_ME]", implode(PHP_EOL, $js_variables), $pre_personal_characteristics); } else { $pre_personal_characteristics = '<div {QUESTION_ESSENTIALS} class="{QUESTION_CLASS}{QUESTION_MAN_CLASS}{QUESTION_INPUT_ERROR_CLASS}"> <div class="survey-question"> <div class="survey-question-text"> <span class="asterisk">{QUESTION_MANDATORY}</span><span class="qnumcode"> {QUESTION_NUMBER} {QUESTION_CODE} </span>{QUESTION_TEXT}<br /><span class="questionhelp">{QUESTION_HELP}</span> {QUESTION_MAN_MESSAGE} {QUESTION_VALID_MESSAGE} {QUESTION_FILE_VALID_MESSAGE} </div> <div class="survey-question-answer">{ANSWER}</div> <div class="survey-question-help">{QUESTIONHELP}</div> </div> <div class="survey-question-space"></div> </div>'; } file_put_contents($newdirname . "/question.pstpl", $pre_personal_characteristics); return $results; }
public function actionCreatequestion() { $questionModel = new Question(); if (isset($_POST["Question"])) { $questionModel->attributes = $_POST["Question"]; $questionModel->content = htmlspecialchars($_POST["Question"]["content"]); $questionModel->title = htmlspecialchars($_POST["Question"]["title"]); $questionModel->create_time = time(); $questionModel->update_time = time(); $questionModel->create_user = Yii::app()->user->id; if ($questionModel->save()) { Question::model()->inserNotify($questionModel->id); $topic_ids = ""; $topicArray = explode(",", trim($questionModel->topic_ids, ",")); $topic_ids .= ","; for ($i = 0; $i < count($topicArray); $i++) { $model = Topic::model()->find("name='" . $topicArray[$i] . "'"); if ($model == NULL) { $newModel = new Topic(); $newModel->name = $topicArray[$i]; $newModel->create_user = Yii::app()->user->id; $newModel->create_time = time(); if ($newModel->save()) { $topic_ids .= $newModel->id . ","; } } else { $topic_ids .= $model->id . ","; } } Question::model()->updateByPk($questionModel->id, array("topic_ids" => $topic_ids)); } echo CJSON::encode($questionModel->getErrors()); } }
function confirm($id) { $question = new Question($id); $question->r_status = 'confirm'; $question->save(); $question2 = new Question(); $question2->from_array($question->to_array()); $question2->r_id = $question->user_id; $question2->user_id = $question->r_id; $question2->id = ''; $question2->save(); redirect('questions'); }