/**
  * Saves an answer
  * @param  array $params Holds an array with {(int)article_id, (text)answer}
  * @return boolean		 TRUE on success, FALSE on params not set
  */
 public function saveAnswer($params)
 {
     if (!is_array($params) || count($params) < 1) {
         return false;
     }
     $em = $this->getEntityManager();
     $answer = new Answers();
     $answer->setArticleId($params['article_id']);
     $answer->setArticleAnswer($params['answer']);
     $answer->setCreatedOn(new \DateTime());
     $em->persist($answer);
     $em->flush();
     return true;
 }
 public function actionSaveAnswer()
 {
     $request = CJSON::decode(file_get_contents('php://input'));
     if ($request) {
         echo CJSON::encode(Answers::saveAnswer($request));
     }
 }
Exemple #3
0
 public static function saveAnswer($request)
 {
     $userId = Yii::app()->user->id;
     if ($userId && isset($request['answerId'])) {
         $currentAnswer = Answers::model()->current()->find('userId=?', [$userId]);
         if ($currentAnswer) {
             $currentAnswer->isCurrent = false;
             if ($request['answerId'] != $currentAnswer->dictonaryId) {
                 $currentAnswer->isError = true;
                 $errAns = new ErrorAnswers();
                 $errAns->userId = $userId;
                 $errAns->dictonaryId = $currentAnswer->dictonaryId;
                 $errAns->answerId = $request['answerId'];
                 if ($errAns->save()) {
                     return ['success' => true, 'reenter' => true, 'error' => $currentAnswer->isError];
                     Yii::app()->end();
                 } else {
                     var_dump($errAns->getErrors());
                 }
             } else {
                 $currentAnswer->isOk = true;
             }
             if ($currentAnswer->save()) {
                 return ['success' => true, 'reenter' => false, 'question' => Dictonary::getQuestion($userId), 'error' => $currentAnswer->isError, 'ok' => $currentAnswer->isOk];
                 Yii::app()->end();
             } else {
                 var_dump($currentAnswer->getErrors());
             }
         }
     }
     return ['success' => false, 'error' => 'ошибка при сохранении ответа'];
 }
    public function actionPools()
    {
        $pool = Pools::model()->with('answers')->findByPk($_POST['poolId']);
        if(!PoolsIp::model()->count('ip = :ip AND pool_id = :id', array(':ip'=>$_SERVER['REMOTE_ADDR'], ':id'=>$pool->id)))
        {
            if(isset($_POST['value']))
            {
                $pool->hits++;
                $poolsIp = new PoolsIp();
                $poolsIp->answer_id = $_POST['value'];
                $poolsIp->pool_id = $pool->id;
                $poolsIp->ip = $_SERVER['REMOTE_ADDR'];

                $answer = Answers::model()->findByPk($_POST['value']);
                $answer->hits++;

                $answer->save();
                $poolsIp->save();
                $pool->save();

                $refreshedPools = Pools::model()->with('answers')->findByPk($_POST['poolId']);

                $this->renderPartial('pool', array('pool'=>$refreshedPools), false, false);
            }
        }
    }
 public function newAction()
 {
     $response = new ApiResponse();
     if ($this->request->isPost()) {
         $answer = new Answers();
         $answer->id = uniqid();
         $answer->content = $this->request->getPost('content');
         $answer->users_id = $this->request->getPost('users_id');
         $answer->questions_id = $this->request->getPost('questions_id');
         if ($this->request->hasFiles() == true) {
             $baseLocation = 'files/';
             foreach ($this->request->getUploadedFiles() as $file) {
                 $photos = new Photos();
                 $unique_filename = $answer->id;
                 $photos->size = $file->getSize();
                 $photos->original_name = $file->getName();
                 $photos->file_name = $unique_filename;
                 $photos->extension = $file->getExtension();
                 $location = $baseLocation . $unique_filename . "." . $file->getExtension();
                 $photos->public_link = $location;
                 try {
                     if (!$photos->save()) {
                         $response->setResponseError($photos->getMessages());
                     } else {
                         //Move the file into the application
                         $file->moveTo($location);
                         $answer->photo = $photos->public_link;
                     }
                 } catch (PDOException $e) {
                     $response->setResponseError($e->getMessage());
                 }
             }
         }
         try {
             if ($answer->save() == false) {
                 $response->setResponseError($answer->getMessages());
             } else {
                 $response->setResponse($answer->id);
             }
         } catch (PDOException $e) {
             $response->setResponseError($e->getMessage());
         }
     } else {
         $response->setResponseError('Wrong HTTP Method');
     }
     return $response;
 }
Exemple #6
0
 /**
  * Returns the data model based on the primary key given in the GET variable.
  * If the data model is not found, an HTTP exception will be raised.
  * @param integer $id the ID of the model to be loaded
  * @return Answers the loaded model
  * @throws CHttpException
  */
 public function loadModel($id)
 {
     $model = Answers::model()->findByPk($id);
     if ($model === null) {
         throw new CHttpException(404, 'The requested page does not exist.');
     }
     return $model;
 }
Exemple #7
0
function getansersx($questionid, $sid, $projectid)
{
    $criteria = new CDbCriteria();
    $criteria->condition = "sectionid={$sid} and questionid={$questionid} and  projectid={$projectid}";
    $ans = Answers::model()->find($criteria);
    if ($ans) {
        return $ans->Answer;
    }
}
 static function getCreateplate($category)
 {
     global $wgEnableAnswers;
     if (!empty($wgEnableAnswers)) {
         return Answers::getUnansweredCategory();
     }
     $categoryKey = 'newpagelayout-' . $category;
     $categoryCreateplate = wfMsgForContent($categoryKey);
     if (!wfEmptyMsg($categoryKey, $categoryCreateplate)) {
         return $categoryCreateplate;
     }
     return wfMsgForContent('newpagelayout');
 }
Exemple #9
0
 public static function getQuestion($userId = null)
 {
     if ($userId) {
         $db = Yii::app()->db;
         $_question = [];
         $all = [];
         $fields = (double) rand() / (double) getrandmax() > 0.5 ? ['answer' => 'nameRu as answer', 'question' => 'nameEn'] : ['answer' => 'nameEn as answer', 'question' => 'nameRu'];
         $currentAnswer = Answers::model()->current()->find('userId=?', [$userId]);
         if ($currentAnswer === null) {
             $_question = $db->createCommand('SELECT id,' . implode(',', $fields) . ' FROM `Dictonary` WHERE id NOT IN (SELECT dictonaryId From Answers WHERE userId = ' . (int) $userId . ') ORDER BY RAND() LIMIT 1;')->queryRow();
             if (isset($_question['id'])) {
                 $currentAnswer = new Answers();
                 $currentAnswer->userId = $userId;
                 $currentAnswer->dictonaryId = $_question['id'];
                 $currentAnswer->isCurrent = true;
                 if ($currentAnswer->save() === false) {
                     var_dump($currentAnswer->getErrors());
                 }
             }
         } else {
             $_question = $db->createCommand('SELECT id,' . implode(',', $fields) . ' FROM `Dictonary` WHERE id = ' . $currentAnswer->dictonaryId)->queryRow();
         }
         if (count($_question) > 0) {
             $question = $_question[$fields['question']];
             unset($_question[$fields['question']]);
         }
         $all = $db->createCommand()->select('id,' . $fields['answer'])->from('Dictonary')->where('id!=:userId', array(':userId' => $_question['id']))->order('RAND()')->limit(3)->queryAll();
         $all[] = $_question;
         shuffle($all);
         shuffle($all);
         if (count($_question) > 0 && count($all) > 0) {
             return ['success' => true, 'question' => $question, 'answers' => $all, 'error' => ErrorAnswers::getCount(Yii::app()->user->id), 'ok' => Answers::getCount($userId, Answers::FLAG_OK)];
         } else {
             return ['success' => true, 'question' => false, 'answers' => false, 'error' => ErrorAnswers::getCount(Yii::app()->user->id), 'ok' => Answers::getCount($userId, Answers::FLAG_OK)];
         }
     } else {
         return ['success' => false];
     }
 }
 /**
  * Creates a new model.
  * If creation is successful, the browser will be redirected to the 'view' page.
  */
 public function actionCreate()
 {
     $model = new Pools();
     $answers = new Answers();
     if (isset($_POST['Pools'])) {
         $model->attributes = $_POST['Pools'];
         if ($model->save()) {
             if (isset($_POST['Answers_name'])) {
                 foreach ($_POST['Answers_name'] as $answer) {
                     $variant = new Answers();
                     $variant->name = $answer;
                     $variant->pool_id = $model->id;
                     $variant->save();
                 }
                 Yii::app()->user->setFlash('success', Yii::t('main', 'Данные успешно сохранены!'));
                 $this->redirect(array('update', 'id' => $model->id));
             }
         } else {
             Yii::app()->user->setFlash('error', Yii::t('main', 'Ошибка!'));
         }
     }
     $this->render('create', array('answers' => $answers, 'model' => $model));
 }
 /**
  * This is the default 'index' action that is invoked
  * when an action is not explicitly requested by users.
  */
 public function actionIndex()
 {
     //echo CJSON::encode(Dictonary::getQuestion(1));
     //        exit();
     $user = ['login' => false];
     if (!Yii::app()->user->getId()) {
         $model = new LoginForm();
         $model->attributes = ['username' => isset(Yii::app()->request->cookies['name']->value) ? Yii::app()->request->cookies['name']->value : '', 'password' => isset(Yii::app()->request->cookies['uuid']->value) ? Yii::app()->request->cookies['uuid']->value : ''];
         if ($model->validate() && $model->login()) {
             $user = ['uuid' => Yii::app()->user->getState('uuid'), 'name' => Yii::app()->user->name, 'login' => true];
         }
     } else {
         $user = ['uuid' => Yii::app()->user->getState('uuid'), 'name' => Yii::app()->user->name, 'login' => true];
     }
     if (isset($user['uuid'])) {
         $this->render('index', ['data' => ['user' => $user, 'countQuestions' => Yii::app()->db->createCommand('SELECT count(id) FROM Dictonary')->queryScalar(), 'current' => Answers::getCount(Yii::app()->user->id, Answers::FLAG_CURRENT), 'error' => ErrorAnswers::getCount(Yii::app()->user->id), 'ok' => Answers::getCount(Yii::app()->user->id, Answers::FLAG_OK), 'question' => Dictonary::getQuestion(Yii::app()->user->id)]]);
     } else {
         $this->render('index', ['data' => ['user' => $user, 'countQuestions' => Yii::app()->db->createCommand('SELECT count(id) FROM Dictonary')->queryScalar(), 'current' => 0, 'error' => 0, 'ok' => 0, 'question' => false]]);
     }
 }
Exemple #12
0
 public static function createUser($request)
 {
     if (isset($request['name'])) {
         $model = Users::model()->find('LOWER(name)=?', [$request['name']]);
         if (!$model) {
             $model = new Users();
             $model->name = $request['name'];
             if (!$model->save()) {
                 return ['success' => false, 'error' => CVarDumper::dumpAsString($model->getErrors())];
                 Yii::app()->end();
             }
         }
         $model->setCookies();
         $login = new LoginForm();
         $login->attributes = ['username' => $model->name, 'password' => $model->uuid];
         if ($login->validate() && $login->login()) {
             return ['success' => true, 'user' => ['uuid' => $model->uuid, 'name' => $model->name, 'login' => true], 'question' => Dictonary::getQuestion($model->id), 'error' => ErrorAnswers::getCount($model->id), 'ok' => Answers::getCount($model->id, Answers::FLAG_OK)];
         }
     }
     return ['success' => false, 'error' => 'Не смогли получить данные'];
 }
 /**
  * Show printable survey
  */
 function index($surveyid, $lang = null)
 {
     $surveyid = sanitize_int($surveyid);
     //echo '<pre>'.print_r($_SESSION,true).'</pre>';
     // PRESENT SURVEY DATAENTRY SCREEN
     if (isset($_POST['printableexport'])) {
         Yii::import("application.libraries.admin.pdf");
         $pdf = new PDF($pdforientation, 'mm', 'A4');
         $pdf->SetFont($pdfdefaultfont, '', $pdffontsize);
         $pdf->AddPage();
     }
     // Set the language of the survey, either from GET parameter of session var
     if (isset($lang)) {
         $lang = preg_replace("/[^a-zA-Z0-9-]/", "", $lang);
         if ($lang) {
             $surveyprintlang = $lang;
         }
     } else {
         $surveyprintlang = getBaseLanguageFromSurveyID((int) $surveyid);
     }
     $_POST['surveyprintlang'] = $surveyprintlang;
     // Setting the selected language for printout
     $clang = new limesurvey_lang($surveyprintlang);
     $desrow = Survey::model()->with(array('languagesettings' => array('condition' => 'surveyls_language=:language', 'params' => array(':language' => $surveyprintlang))))->findByAttributes(array('sid' => $surveyid));
     if (is_null($desrow)) {
         $this->getController()->error('Invalid survey ID');
     }
     $desrow = array_merge($desrow->attributes, $desrow->languagesettings[0]->attributes);
     //echo '<pre>'.print_r($desrow,true).'</pre>';
     $template = $desrow['template'];
     $welcome = $desrow['surveyls_welcometext'];
     $end = $desrow['surveyls_endtext'];
     $surveyname = $desrow['surveyls_title'];
     $surveydesc = $desrow['surveyls_description'];
     $surveyactive = $desrow['active'];
     $surveytable = "{{survey_" . $desrow['sid'] . "}}";
     $surveyexpirydate = $desrow['expires'];
     $surveystartdate = $desrow['startdate'];
     $surveyfaxto = $desrow['faxto'];
     $dateformattype = $desrow['surveyls_dateformat'];
     if (isset($_POST['printableexport'])) {
         $pdf->titleintopdf($surveyname, $surveydesc);
     }
     Yii::app()->loadHelper('surveytranslator');
     $dformat = getDateFormatData($dateformattype);
     $dformat = $dformat['phpdate'];
     $expirytimestamp = strtotime($surveyexpirydate);
     $expirytimeofday_h = date('H', $expirytimestamp);
     $expirytimeofday_m = date('i', $expirytimestamp);
     $surveyexpirydate = date($dformat, $expirytimestamp);
     if (!empty($expirytimeofday_h) || !empty($expirytimeofday_m)) {
         $surveyexpirydate .= ' &ndash; ' . $expirytimeofday_h . ':' . $expirytimeofday_m;
     }
     //define('PRINT_TEMPLATE' , '/templates/print/' , true);
     if (is_file(Yii::app()->getConfig('usertemplaterootdir') . DIRECTORY_SEPARATOR . $template . DIRECTORY_SEPARATOR . 'print_survey.pstpl')) {
         define('PRINT_TEMPLATE_DIR', Yii::app()->getConfig('usertemplaterootdir') . DIRECTORY_SEPARATOR . $template . DIRECTORY_SEPARATOR, true);
         define('PRINT_TEMPLATE_URL', Yii::app()->getConfig('usertemplaterooturl') . '/' . $template . '/', true);
     } elseif (is_file(Yii::app()->getConfig('usertemplaterootdir') . '/' . $template . '/print_survey.pstpl')) {
         define('PRINT_TEMPLATE_DIR', Yii::app()->getConfig('standardtemplaterootdir') . DIRECTORY_SEPARATOR . $template . DIRECTORY_SEPARATOR, true);
         define('PRINT_TEMPLATE_URL', Yii::app()->getConfig('standardtemplaterooturl') . '/' . $template . '/', true);
     } else {
         define('PRINT_TEMPLATE_DIR', Yii::app()->getConfig('standardtemplaterootdir') . DIRECTORY_SEPARATOR . 'default' . DIRECTORY_SEPARATOR, true);
         define('PRINT_TEMPLATE_URL', Yii::app()->getConfig('standardtemplaterooturl') . '/default/', true);
     }
     LimeExpressionManager::StartSurvey($surveyid, 'survey', NULL, false, LEM_PRETTY_PRINT_ALL_SYNTAX);
     $moveResult = LimeExpressionManager::NavigateForwards();
     $condition = "sid = '{$surveyid}' AND language = '{$surveyprintlang}'";
     $degresult = Groups::model()->getAllGroups($condition, array('group_order'));
     //xiao,
     if (!isset($surveyfaxto) || !$surveyfaxto and isset($surveyfaxnumber)) {
         $surveyfaxto = $surveyfaxnumber;
         //Use system fax number if none is set in survey.
     }
     $headelements = getPrintableHeader();
     //if $showsgqacode is enabled at config.php show table name for reference
     $showsgqacode = Yii::app()->getConfig("showsgqacode");
     if (isset($showsgqacode) && $showsgqacode == true) {
         $surveyname = $surveyname . "<br />[" . $clang->gT('Database') . " " . $clang->gT('table') . ": {$surveytable}]";
     } else {
         $surveyname = $surveyname;
     }
     $survey_output = array('SITENAME' => Yii::app()->getConfig("sitename"), 'SURVEYNAME' => $surveyname, 'SURVEYDESCRIPTION' => $surveydesc, 'WELCOME' => $welcome, 'END' => $end, 'THEREAREXQUESTIONS' => 0, 'SUBMIT_TEXT' => $clang->gT("Submit Your Survey."), 'SUBMIT_BY' => $surveyexpirydate, 'THANKS' => $clang->gT("Thank you for completing this survey."), 'HEADELEMENTS' => $headelements, 'TEMPLATEURL' => PRINT_TEMPLATE_URL, 'FAXTO' => $surveyfaxto, 'PRIVACY' => '', 'GROUPS' => '');
     $survey_output['FAX_TO'] = '';
     if (!empty($surveyfaxto) && $surveyfaxto != '000-00000000') {
         $survey_output['FAX_TO'] = $clang->gT("Please fax your completed survey to:") . " {$surveyfaxto}";
     }
     if ($surveystartdate != '') {
         $survey_output['SUBMIT_BY'] = sprintf($clang->gT("Please submit by %s"), $surveyexpirydate);
     }
     /**
      * Output arrays:
      *    $survey_output  =       final vaiables for whole survey
      *        $survey_output['SITENAME'] =
      *        $survey_output['SURVEYNAME'] =
      *        $survey_output['SURVEY_DESCRIPTION'] =
      *        $survey_output['WELCOME'] =
      *        $survey_output['THEREAREXQUESTIONS'] =
      *        $survey_output['PDF_FORM'] =
      *        $survey_output['HEADELEMENTS'] =
      *        $survey_output['TEMPLATEURL'] =
      *        $survey_output['SUBMIT_TEXT'] =
      *        $survey_output['SUBMIT_BY'] =
      *        $survey_output['THANKS'] =
      *        $survey_output['FAX_TO'] =
      *        $survey_output['SURVEY'] =     contains an array of all the group arrays
      *
      *    $groups[]       =       an array of all the groups output
      *        $group['GROUPNAME'] =
      *        $group['GROUPDESCRIPTION'] =
      *        $group['QUESTIONS'] =     templated formatted content if $question is appended to this at the end of processing each question.
      *        $group['ODD_EVEN'] =     class to differentiate alternate groups
      *        $group['SCENARIO'] =
      *
      *    $questions[]    =       contains an array of all the questions within a group
      *        $question['QUESTION_CODE'] =         content of the question code field
      *        $question['QUESTION_TEXT'] =         content of the question field
      *        $question['QUESTION_SCENARIO'] =         if there are conditions on a question, list the conditions.
      *        $question['QUESTION_MANDATORY'] =     translated 'mandatory' identifier
      *        $question['QUESTION_CLASS'] =         classes to be added to wrapping question div
      *        $question['QUESTION_TYPE_HELP'] =         instructions on how to complete the question
      *        $question['QUESTION_MAN_MESSAGE'] =     (not sure if this is used) mandatory error
      *        $question['QUESTION_VALID_MESSAGE'] =     (not sure if this is used) validation error
      *        $question['ANSWER'] =                contains formatted HTML answer
      *        $question['QUESTIONHELP'] =         content of the question help field.
      *
      */
     $total_questions = 0;
     $mapquestionsNumbers = array();
     $answertext = '';
     // otherwise can throw an error on line 1617
     // =========================================================
     // START doin the business:
     $pdfoutput = '';
     foreach ($degresult->readAll() as $degrow) {
         // ---------------------------------------------------
         // START doing groups
         $deqresult = Questions::model()->getQuestions($surveyid, $degrow['gid'], $surveyprintlang, 0, '"I"');
         $deqrows = array();
         //Create an empty array in case FetchRow does not return any rows
         foreach ($deqresult->readAll() as $deqrow) {
             $deqrows[] = $deqrow;
         }
         // Get table output into array
         // Perform a case insensitive natural sort on group name then question title of a multidimensional array
         usort($deqrows, 'groupOrderThenQuestionOrder');
         if ($degrow['description']) {
             $group_desc = $degrow['description'];
         } else {
             $group_desc = '';
         }
         $group = array('GROUPNAME' => $degrow['group_name'], 'GROUPDESCRIPTION' => $group_desc, 'QUESTIONS' => '');
         // A group can have only hidden questions. In that case you don't want to see the group's header/description either.
         $bGroupHasVisibleQuestions = false;
         if (isset($_POST['printableexport'])) {
             $pdf->titleintopdf($degrow['group_name'], $degrow['description']);
         }
         $gid = $degrow['gid'];
         //Alternate bgcolor for different groups
         if (!isset($group['ODD_EVEN']) || $group['ODD_EVEN'] == ' g-row-even') {
             $group['ODD_EVEN'] = ' g-row-odd';
         } else {
             $group['ODD_EVEN'] = ' g-row-even';
         }
         //Loop through questions
         foreach ($deqrows as $deqrow) {
             // - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
             // START doing questions
             $qidattributes = getQuestionAttributeValues($deqrow['qid'], $deqrow['type']);
             if ($qidattributes['hidden'] == 1 && $deqrow['type'] != '*') {
                 continue;
             }
             $bGroupHasVisibleQuestions = true;
             //GET ANY CONDITIONS THAT APPLY TO THIS QUESTION
             $printablesurveyoutput = '';
             $explanation = '';
             //reset conditions explanation
             $s = 0;
             //                    // TMSW Conditions->Relevance:  show relevance instead of this whole section to create $explanation
             //
             //
             //                            $scenarioresult=Conditions::model()->getScenarios($deqrow['qid']);
             //                            $scenarioresult = $scenarioresult->readAll();
             //                    //Loop through distinct scenarios, thus grouping them together.
             //                    foreach ($scenarioresult as $scenariorow)
             //                    {
             //                        if( $s == 0 && count($scenarioresult) > 1)
             //                        {
             //                            $explanation .= '<p class="scenario">'.self::_try_debug(__LINE__)." -------- Scenario {$scenariorow['scenario']} --------</p>\n\n";
             //                        }
             //                        if($s > 0)
             //                        {
             //                            $explanation .= '<p class="scenario">'.self::_try_debug(__LINE__).' -------- '.$clang->gT("or")." Scenario {$scenariorow['scenario']} --------</p>\n\n";
             //                        }
             //
             //                        $x=0;
             //
             //                        $conditions1="qid={$deqrow['qid']} AND scenario={$scenariorow['scenario']}";
             //                        $distinctresult=Conditions::model()->getSomeConditions(array('cqid','method', 'cfieldname', 'value'), $conditions1, array('cqid'),array('cqid', 'method'));
             //
             //                        //Loop through each condition for a particular scenario.
             //                        foreach ($distinctresult->readAll() as $distinctrow)
             //                        {
             //                              $condition = "qid = '{$distinctrow['cqid']}' AND parent_qid = 0 AND language = '{$surveyprintlang}'";
             //                              $subresult=Questions::model()->find($condition);
             //
             //                            if($x > 0)
             //                            {
             //                                $explanation .= ' <em class="scenario-and-seperator">'.$clang->gT('and').'</em> ';
             //                            }
             //                            if(trim($distinctrow['method'])=='') //If there is no method chosen assume "equals"
             //                            {
             //                                $distinctrow['method']='==';
             //                            }
             //
             //                            if($distinctrow['cqid']){ // cqid != 0  ==> previous answer match
             //                                if($distinctrow['method']=='==')
             //                                {
             //                                    $explanation .= $clang->gT("Answer was")." ";
             //                                }
             //                                elseif($distinctrow['method']=='!=')
             //                                {
             //                                    $explanation .= $clang->gT("Answer was NOT")." ";
             //                                }
             //                                elseif($distinctrow['method']=='<')
             //                                {
             //                                    $explanation .= $clang->gT("Answer was less than")." ";
             //                                }
             //                                elseif($distinctrow['method']=='<=')
             //                                {
             //                                    $explanation .= $clang->gT("Answer was less than or equal to")." ";
             //                                }
             //                                elseif($distinctrow['method']=='>=')
             //                                {
             //                                    $explanation .= $clang->gT("Answer was greater than or equal to")." ";
             //                                }
             //                                elseif($distinctrow['method']=='>')
             //                                {
             //                                    $explanation .= $clang->gT("Answer was greater than")." ";
             //                                }
             //                                elseif($distinctrow['method']=='RX')
             //                                {
             //                                    $explanation .= $clang->gT("Answer matched (regexp)")." ";
             //                                }
             //                                else
             //                                {
             //                                    $explanation .= $clang->gT("Answer was")." ";
             //                                }
             //                                if($distinctrow['value'] == '') {
             //                                    $explanation .= ' '.$clang->gT("Not selected").' ';
             //                                }
             //                                //If question type is numerical or multi-numerical, show the actual value - otherwise, don't.
             //                                if($subresult['type'] == 'N' || $subresult['type'] == 'K') {
             //                                    $explanation .= ' '.$distinctrow['value']. ' ';
             //                                }
             //                            }
             //                            if(!$distinctrow['cqid']) { // cqid == 0  ==> token attribute match
             //                                $tokenData = getTokenFieldsAndNames($surveyid);
             //                                preg_match('/^{TOKEN:([^}]*)}$/',$distinctrow['cfieldname'],$extractedTokenAttr);
             //                                $explanation .= "Your ".$tokenData[strtolower($extractedTokenAttr[1])]." ";
             //                                if($distinctrow['method']=='==')
             //                                {
             //                                    $explanation .= $clang->gT("is")." ";
             //                                }
             //                                elseif($distinctrow['method']=='!=')
             //                                {
             //                                    $explanation .= $clang->gT("is NOT")." ";
             //                                }
             //                                elseif($distinctrow['method']=='<')
             //                                {
             //                                    $explanation .= $clang->gT("is less than")." ";
             //                                }
             //                                elseif($distinctrow['method']=='<=')
             //                                {
             //                                    $explanation .= $clang->gT("is less than or equal to")." ";
             //                                }
             //                                elseif($distinctrow['method']=='>=')
             //                                {
             //                                    $explanation .= $clang->gT("is greater than or equal to")." ";
             //                                }
             //                                elseif($distinctrow['method']=='>')
             //                                {
             //                                    $explanation .= $clang->gT("is greater than")." ";
             //                                }
             //                                elseif($distinctrow['method']=='RX')
             //                                {
             //                                    $explanation .= $clang->gT("is matched (regexp)")." ";
             //                                }
             //                                else
             //                                {
             //                                    $explanation .= $clang->gT("is")." ";
             //                                }
             //                                $answer_section = ' '.$distinctrow['value'].' ';
             //                            }
             //
             //                            $conresult=Conditions::model()->getConditionsQuestions($distinctrow['cqid'],$deqrow['qid'],$scenariorow['scenario'],$surveyprintlang);
             //
             //                            $conditions=array();
             //                            foreach ($conresult->readAll() as $conrow)
             //                            {
             //
             //                                $postans="";
             //                                $value=$conrow['value'];
             //                                switch($conrow['type'])
             //                                {
             //                                    case "Y":
             //                                        switch ($conrow['value'])
             //                                        {
             //                                            case "Y": $conditions[]=$clang->gT("Yes"); break;
             //                                            case "N": $conditions[]=$clang->gT("No"); break;
             //                                        }
             //                                        break;
             //                                    case "G":
             //                                        switch($conrow['value'])
             //                                        {
             //                                            case "M": $conditions[]=$clang->gT("Male"); break;
             //                                            case "F": $conditions[]=$clang->gT("Female"); break;
             //                                        } // switch
             //                                        break;
             //                                    case "A":
             //                                    case "B":
             //                                    case ":":
             //                                    case ";":
             //                                        $conditions[]=$conrow['value'];
             //                                        break;
             //                                    case "C":
             //                                        switch($conrow['value'])
             //                                        {
             //                                            case "Y": $conditions[]=$clang->gT("Yes"); break;
             //                                            case "U": $conditions[]=$clang->gT("Uncertain"); break;
             //                                            case "N": $conditions[]=$clang->gT("No"); break;
             //                                        } // switch
             //                                        break;
             //                                    case "E":
             //                                        switch($conrow['value'])
             //                                        {
             //                                            case "I": $conditions[]=$clang->gT("Increase"); break;
             //                                            case "D": $conditions[]=$clang->gT("Decrease"); break;
             //                                            case "S": $conditions[]=$clang->gT("Same"); break;
             //                                        }
             //                                    case "1":
             //                                        $labelIndex=preg_match("/^[^#]+#([01]{1})$/",$conrow['cfieldname']);
             //                                        if ($labelIndex == 0)
             //                                        { // TIBO
             //
             //                                        $condition="qid='{$conrow['cqid']}' AND code='{$conrow['value']}' AND scale_id=0 AND language='{$surveyprintlang}'";
             //                                        $fresult=Answers::model()->getAllRecords($condition);
             //
             //                                            foreach($fresult->readAll() as $frow)
             //                                            {
             //                                                $postans=$frow['answer'];
             //                                                $conditions[]=$frow['answer'];
             //                                            } // while
             //                                        }
             //                                        elseif ($labelIndex == 1)
             //                                        {
             //
             //                                        $condition="qid='{$conrow['cqid']}' AND code='{$conrow['value']}' AND scale_id=1 AND language='{$surveyprintlang}'";
             //                                        $fresult=Answers::model()->getAllRecords($condition);
             //                                            foreach($fresult->readAll() as $frow)
             //                                            {
             //                                                $postans=$frow['answer'];
             //                                                $conditions[]=$frow['answer'];
             //                                            } // while
             //                                        }
             //                                        break;
             //                                    case "L":
             //                                    case "!":
             //                                    case "O":
             //                                    case "R":
             //                                        $condition="qid='{$conrow['cqid']}' AND code='{$conrow['value']}' AND language='{$surveyprintlang}'";
             //                                        $ansresult=Answers::model()->findAll($condition);
             //
             //                                        foreach ($ansresult as $ansrow)
             //                                        {
             //                                            $conditions[]=$ansrow['answer'];
             //                                        }
             //                                        if($conrow['value'] == "-oth-") {
             //                                            $conditions[]=$clang->gT("Other");
             //                                        }
             //                                        $conditions = array_unique($conditions);
             //                                        break;
             //                                    case "M":
             //                                    case "P":
             //                                        $condition=" parent_qid='{$conrow['cqid']}' AND title='{$conrow['value']}' AND language='{$surveyprintlang}'";
             //                                        $ansresult=Questions::model()->findAll($condition);
             //                                        foreach ($ansresult as $ansrow)
             //                                        {
             //                                            $conditions[]=$ansrow['question'];
             //                                        }
             //                                        $conditions = array_unique($conditions);
             //                                        break;
             //                                    case "N":
             //                                        $conditions[]=$value;
             //                                        break;
             //                                    case "F":
             //                                    case "H":
             //                                    default:
             //                                        $value=substr($conrow['cfieldname'], strpos($conrow['cfieldname'], "X".$conrow['cqid'])+strlen("X".$conrow['cqid']), strlen($conrow['cfieldname']));
             //
             //                                        $condition=" qid='{$conrow['cqid']}' AND code='{$conrow['value']}' AND language='{$surveyprintlang}'";
             //
             //                                        $fresult=Answers::model()->getAllRecords($condition);
             //                                        foreach ($fresult->readAll() as $frow)
             //                                        {
             //                                            $postans=$frow['answer'];
             //                                            $conditions[]=$frow['answer'];
             //                                        } // while
             //                                        break;
             //                                } // switch
             //
             //                                // Now let's complete the answer text with the answer_section
             //                                $answer_section="";
             //                                switch($conrow['type'])
             //                                {
             //                                    case "A":
             //                                    case "B":
             //                                    case "C":
             //                                    case "E":
             //                                    case "F":
             //                                    case "H":
             //                                    case "K":
             //                                        $thiscquestion=$fieldmap[$conrow['cfieldname']];
             //                                        $condition="parent_qid='{$conrow['cqid']}' AND title='{$thiscquestion['aid']}' AND language='{$surveyprintlang}'";
             //                                          $ansresult= Questions::model()->findAll($condition);
             //
             //                                        foreach ($ansresult as $ansrow)
             //                                        {
             //                                            $answer_section=" (".$ansrow['question'].")";
             //                                        }
             //                                        break;
             //
             //                                    case "1": // dual: (Label 1), (Label 2)
             //                                        $labelIndex=substr($conrow['cfieldname'],-1);
             //                                        $thiscquestion=$fieldmap[$conrow['cfieldname']];
             //                                         $condition="parent_qid='{$conrow['cqid']}' AND title='{$thiscquestion['aid']}' AND language='{$surveyprintlang}'";
             //                                         $ansresult= Questions::model()->findAll($condition);
             //                                        $cqidattributes = getQuestionAttributeValues($conrow['cqid'], $conrow['type']);
             //                                        if ($labelIndex == 0)
             //                                        {
             //                                            if (trim($cqidattributes['dualscale_headerA']) != '') {
             //                                                $header = $clang->gT($cqidattributes['dualscale_headerA']);
             //                                            } else {
             //                                                $header = '1';
             //                                            }
             //                                        }
             //                                        elseif ($labelIndex == 1)
             //                                        {
             //                                            if (trim($cqidattributes['dualscale_headerB']) != '') {
             //                                                $header = $clang->gT($cqidattributes['dualscale_headerB']);
             //                                            } else {
             //                                                $header = '2';
             //                                            }
             //                                        }
             //                                        foreach ($ansresult->readAll() as $ansrow)
             //                                        {
             //                                            $answer_section=" (".$ansrow['question']." ".sprintf($clang->gT("Label %s"),$header).")";
             //                                        }
             //                                        break;
             //                                    case ":":
             //                                    case ";": //multi flexi: ( answer [label] )
             //                                        $thiscquestion=$fieldmap[$conrow['cfieldname']];
             //                                        $condition="parent_qid='{$conrow['cqid']}' AND title='{$thiscquestion['aid']}' AND language='{$surveyprintlang}'";
             //                                         $ansresult= Questions::model()->findAll($condition);
             //                                        foreach ($ansresult as $ansrow)
             //                                        {
             //
             //                                        $condition = "qid = '{$conrow['cqid']}' AND code = '{$conrow['value']}' AND language= '{$surveyprintlang}'";
             //                                        $fresult= Answers::model()->findAll($condition);
             //                                            foreach ($fresult as $frow)
             //                                            {
             //                                                //$conditions[]=$frow['title'];
             //                                                $answer_section=" (".$ansrow['question']."[".$frow['answer']."])";
             //                                            } // while
             //                                        }
             //                                        break;
             //                                    case "R": // (Rank 1), (Rank 2)... TIBO
             //                                        $thiscquestion=$fieldmap[$conrow['cfieldname']];
             //                                        $rankid=$thiscquestion['aid'];
             //                                        $answer_section=" (".$clang->gT("RANK")." $rankid)";
             //                                        break;
             //                                    default: // nothing to add
             //                                        break;
             //                                }
             //                            }
             //
             //                            if (count($conditions) > 1)
             //                            {
             //                                $explanation .=  "'".implode("' <em class='scenario-or-seperator'>".$clang->gT("or")."</em> '", $conditions)."'";
             //                            }
             //                            elseif (count($conditions) == 1)
             //                            {
             //                                $explanation .= "'".$conditions[0]."'";
             //                            }
             //                            unset($conditions);
             //                            // Following line commented out because answer_section  was lost, but is required for some question types
             //                            //$explanation .= " ".$clang->gT("to question")." '".$mapquestionsNumbers[$distinctrow['cqid']]."' $answer_section ";
             //                            if($distinctrow['cqid']){
             //                                $explanation .= " <span class='scenario-at-seperator'>".$clang->gT("at question")."</span> '".$mapquestionsNumbers[$distinctrow['cqid']]." [".$subresult['title']."]' (".strip_tags($subresult['question'])."$answer_section)" ;
             //                            }
             //                            else{
             //                                $explanation .= " ".$distinctrow['value'] ;
             //                            }
             //                            //$distinctrow
             //                            $x++;
             //                        }
             //                        $s++;
             //                    }
             $qinfo = LimeExpressionManager::GetQuestionStatus($deqrow['qid']);
             $relevance = trim($qinfo['info']['relevance']);
             $explanation = $qinfo['relEqn'];
             if (trim($relevance) != '' && trim($relevance) != '1') {
                 $explanation = "<b>" . $clang->gT('Only answer this question if the following conditions are met:') . "</b>" . "<br/> ° " . $explanation;
             } else {
                 $explanation = '';
             }
             ++$total_questions;
             //TIBO map question qid to their q number
             $mapquestionsNumbers[$deqrow['qid']] = $total_questions;
             //END OF GETTING CONDITIONS
             $qid = $deqrow['qid'];
             $fieldname = "{$surveyid}" . "X" . "{$gid}" . "X" . "{$qid}";
             if (isset($showsgqacode) && $showsgqacode == true) {
                 $deqrow['question'] = $deqrow['question'] . "<br />" . $clang->gT("ID:") . " {$fieldname} <br />" . $clang->gT("Question code:") . " " . $deqrow['title'];
             }
             $question = array('QUESTION_NUMBER' => $total_questions, 'QUESTION_CODE' => $deqrow['title'], 'QUESTION_TEXT' => preg_replace('/(?:<br ?\\/?>|<\\/(?:p|h[1-6])>)$/is', '', $deqrow['question']), 'QUESTION_SCENARIO' => $explanation, 'QUESTION_MANDATORY' => '', 'QUESTION_ID' => $deqrow['qid'], 'QUESTION_CLASS' => getQuestionClass($deqrow['type']), 'QUESTION_TYPE_HELP' => $qinfo['validTip'], 'QUESTION_MAN_MESSAGE' => '', 'QUESTION_VALID_MESSAGE' => '', 'QUESTION_FILE_VALID_MESSAGE' => '', 'QUESTIONHELP' => '', 'ANSWER' => '');
             if ($question['QUESTION_TYPE_HELP'] != "") {
                 $question['QUESTION_TYPE_HELP'] .= "<br />\n";
             }
             if ($deqrow['mandatory'] == 'Y') {
                 $question['QUESTION_MANDATORY'] = $clang->gT('*');
                 $question['QUESTION_CLASS'] .= ' mandatory';
                 $pdfoutput .= $clang->gT("*");
             }
             $pdfoutput = '';
             //DIFFERENT TYPES OF DATA FIELD HERE
             if (isset($_POST['printableexport'])) {
                 $pdf->intopdf($deqrow['title'] . " " . $deqrow['question']);
             }
             if ($deqrow['help']) {
                 $hh = $deqrow['help'];
                 $question['QUESTIONHELP'] = $hh;
                 if (isset($_POST['printableexport'])) {
                     $pdf->helptextintopdf($hh);
                 }
             }
             if (!empty($qidattributes['page_break'])) {
                 $question['QUESTION_CLASS'] .= ' breakbefore ';
             }
             if (isset($qidattributes['maximum_chars']) && $qidattributes['maximum_chars'] != '') {
                 $question['QUESTION_CLASS'] = "max-chars-{$qidattributes['maximum_chars']} " . $question['QUESTION_CLASS'];
             }
             switch ($deqrow['type']) {
                 // ==================================================================
                 case "5":
                     //5 POINT CHOICE
                     $question['QUESTION_TYPE_HELP'] .= $clang->gT('Please choose *only one* of the following:');
                     if (isset($_POST['printableexport'])) {
                         $pdf->intopdf($clang->gT("Please choose *only one* of the following:"), "U");
                     }
                     $pdfoutput = '';
                     $question['ANSWER'] .= "\n\t<ul>\n";
                     for ($i = 1; $i <= 5; $i++) {
                         $pdfoutput .= " o " . $i . " ";
                         //                        $printablesurveyoutput .="\t\t\t<input type='checkbox' name='$fieldname' value='$i' readonly='readonly' />$i \n";
                         $question['ANSWER'] .= "\t\t<li>\n\t\t\t" . self::_input_type_image('radio', $i) . "\n\t\t\t{$i} " . self::_addsgqacode("({$i})") . "\n\t\t</li>\n";
                     }
                     if (isset($_POST['printableexport'])) {
                         $pdf->intopdf($pdfoutput);
                     }
                     $question['ANSWER'] .= "\t</ul>\n";
                     break;
                     // ==================================================================
                 // ==================================================================
                 case "D":
                     //DATE
                     $question['QUESTION_TYPE_HELP'] .= $clang->gT('Please enter a date:');
                     $question['ANSWER'] .= "\t" . self::_input_type_image('text', $question['QUESTION_TYPE_HELP'], 30, 1);
                     if (isset($_POST['printableexport'])) {
                         $pdf->intopdf($clang->gT("Please enter a date:") . " ___________");
                     }
                     break;
                     // ==================================================================
                 // ==================================================================
                 case "G":
                     //GENDER
                     $question['QUESTION_TYPE_HELP'] .= $clang->gT("Please choose *only one* of the following:");
                     $question['ANSWER'] .= "\n\t<ul>\n";
                     $question['ANSWER'] .= "\t\t<li>\n\t\t\t" . self::_input_type_image('radio', $clang->gT("Female")) . "\n\t\t\t" . $clang->gT("Female") . " " . self::_addsgqacode("(F)") . "\n\t\t</li>\n";
                     $question['ANSWER'] .= "\t\t<li>\n\t\t\t" . self::_input_type_image('radio', $clang->gT("Male")) . "\n\t\t\t" . $clang->gT("Male") . " " . self::_addsgqacode("(M)") . "\n\t\t</li>\n";
                     $question['ANSWER'] .= "\t</ul>\n";
                     if (isset($_POST['printableexport'])) {
                         $pdf->intopdf($clang->gT("Please choose *only one* of the following:"));
                     }
                     if (isset($_POST['printableexport'])) {
                         $pdf->intopdf(" o " . $clang->gT("Female") . " | o " . $clang->gT("Male"));
                     }
                     break;
                     // ==================================================================
                 // ==================================================================
                 case "L":
                     //LIST drop-down/radio-button list
                     // ==================================================================
                 //LIST drop-down/radio-button list
                 // ==================================================================
                 case "!":
                     //List - dropdown
                     if (isset($qidattributes['display_columns']) && trim($qidattributes['display_columns']) != '') {
                         $dcols = $qidattributes['display_columns'];
                     } else {
                         $dcols = 0;
                     }
                     if (isset($qidattributes['category_separator']) && trim($qidattributes['category_separator']) != '') {
                         $optCategorySeparator = $qidattributes['category_separator'];
                     } else {
                         unset($optCategorySeparator);
                     }
                     $question['QUESTION_TYPE_HELP'] .= $clang->gT("Please choose *only one* of the following:");
                     $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $surveyprintlang, $surveyid);
                     if (isset($_POST['printableexport'])) {
                         $pdf->intopdf($clang->gT("Please choose *only one* of the following:"));
                     }
                     $dearesult = Answers::model()->getAllRecords(" qid='{$deqrow['qid']}' AND language='{$surveyprintlang}' ", array('sortorder', 'answer'));
                     $dearesult = $dearesult->readAll();
                     $deacount = count($dearesult);
                     if ($deqrow['other'] == "Y") {
                         $deacount++;
                     }
                     $wrapper = setupColumns(0, $deacount);
                     $question['ANSWER'] = $wrapper['whole-start'];
                     $rowcounter = 0;
                     $colcounter = 1;
                     foreach ($dearesult as $dearow) {
                         if (isset($optCategorySeparator)) {
                             list($category, $answer) = explode($optCategorySeparator, $dearow['answer']);
                             if ($category != '') {
                                 $dearow['answer'] = "({$category}) {$answer} " . self::_addsgqacode("(" . $dearow['code'] . ")");
                             } else {
                                 $dearow['answer'] = $answer . self::_addsgqacode(" (" . $dearow['code'] . ")");
                             }
                             $question['ANSWER'] .= "\t" . $wrapper['item-start'] . "\t\t" . self::_input_type_image('radio', $dearow['answer']) . "\n\t\t\t" . $dearow['answer'] . "\n" . $wrapper['item-end'];
                         } else {
                             $question['ANSWER'] .= "\t" . $wrapper['item-start'] . "\t\t" . self::_input_type_image('radio', $dearow['answer']) . "\n\t\t\t" . $dearow['answer'] . self::_addsgqacode(" (" . $dearow['code'] . ")") . "\n" . $wrapper['item-end'];
                         }
                         if (isset($_POST['printableexport'])) {
                             $pdf->intopdf(" o " . $dearow['answer']);
                         }
                         ++$rowcounter;
                         if ($rowcounter == $wrapper['maxrows'] && $colcounter < $wrapper['cols']) {
                             if ($colcounter == $wrapper['cols'] - 1) {
                                 $question['ANSWER'] .= $wrapper['col-devide-last'];
                             } else {
                                 $question['ANSWER'] .= $wrapper['col-devide'];
                             }
                             $rowcounter = 0;
                             ++$colcounter;
                         }
                     }
                     if ($deqrow['other'] == 'Y') {
                         if (trim($qidattributes["other_replace_text"][$surveyprintlang]) == '') {
                             $qidattributes["other_replace_text"][$surveyprintlang] = "Other";
                         }
                         //                    $printablesurveyoutput .="\t".$wrapper['item-start']."\t\t".self::_input_type_image('radio' , $clang->gT("Other"))."\n\t\t\t".$clang->gT("Other")."\n\t\t\t<input type='text' size='30' readonly='readonly' />\n".$wrapper['item-end'];
                         $question['ANSWER'] .= $wrapper['item-start-other'] . self::_input_type_image('radio', $clang->gT($qidattributes["other_replace_text"][$surveyprintlang])) . ' ' . $clang->gT($qidattributes["other_replace_text"][$surveyprintlang]) . self::_addsgqacode(" (-oth-)") . "\n\t\t\t" . self::_input_type_image('other') . self::_addsgqacode(" (" . $deqrow['sid'] . "X" . $deqrow['gid'] . "X" . $deqrow['qid'] . "other)") . "\n" . $wrapper['item-end'];
                         if (isset($_POST['printableexport'])) {
                             $pdf->intopdf(" o " . $clang->gT($qidattributes["other_replace_text"][$surveyprintlang]) . ": ________");
                         }
                     }
                     $question['ANSWER'] .= $wrapper['whole-end'];
                     //Let's break the presentation into columns.
                     break;
                     // ==================================================================
                 // ==================================================================
                 case "O":
                     //LIST WITH COMMENT
                     $question['QUESTION_TYPE_HELP'] .= $clang->gT("Please choose *only one* of the following:");
                     if (isset($_POST['printableexport'])) {
                         $pdf->intopdf($clang->gT("Please choose *only one* of the following:"), "U");
                     }
                     $dearesult = Answers::model()->getAllRecords(" qid='{$deqrow['qid']}' AND language='{$surveyprintlang}'", array('sortorder', 'answer'));
                     $question['ANSWER'] = "\t<ul>\n";
                     foreach ($dearesult->readAll() as $dearow) {
                         $question['ANSWER'] .= "\t\t<li>\n\t\t\t" . self::_input_type_image('radio', $dearow['answer']) . "\n\t\t\t" . $dearow['answer'] . self::_addsgqacode(" (" . $dearow['code'] . ")") . "\n\t\t</li>\n";
                         if (isset($_POST['printableexport'])) {
                             $pdf->intopdf($dearow['answer']);
                         }
                     }
                     $question['ANSWER'] .= "\t</ul>\n";
                     $question['ANSWER'] .= "\t<p class=\"comment\">\n\t\t" . $clang->gT("Make a comment on your choice here:") . "\n";
                     if (isset($_POST['printableexport'])) {
                         $pdf->intopdf("Make a comment on your choice here:");
                     }
                     $question['ANSWER'] .= "\t\t" . self::_input_type_image('textarea', $clang->gT("Make a comment on your choice here:"), 50, 8) . self::_addsgqacode(" (" . $deqrow['sid'] . "X" . $deqrow['gid'] . "X" . $deqrow['qid'] . "comment)") . "\n\t</p>\n";
                     for ($i = 0; $i < 9; $i++) {
                         if (isset($_POST['printableexport'])) {
                             $pdf->intopdf("____________________");
                         }
                     }
                     break;
                     // ==================================================================
                 // ==================================================================
                 case "R":
                     //RANKING Type Question
                     $rearesult = Answers::model()->getAllRecords(" qid='{$deqrow['qid']}' AND language='{$surveyprintlang}'", array('sortorder', 'answer'));
                     $rearesult = $rearesult->readAll();
                     $reacount = count($rearesult);
                     $question['QUESTION_TYPE_HELP'] .= $clang->gT("Please number each box in order of preference from 1 to") . " {$reacount}";
                     $question['QUESTION_TYPE_HELP'] .= self::_min_max_answers_help($qidattributes, $surveyprintlang, $surveyid);
                     if (isset($_POST['printableexport'])) {
                         $pdf->intopdf($clang->gT("Please number each box in order of preference from 1 to ") . $reacount, "U");
                     }
                     $question['ANSWER'] = "\n<ul>\n";
                     foreach ($rearesult as $rearow) {
                         $question['ANSWER'] .= "\t<li>\n\t" . self::_input_type_image('rank', '', 4, 1) . "\n\t\t&nbsp;" . $rearow['answer'] . self::_addsgqacode(" (" . $fieldname . $rearow['code'] . ")") . "\n\t</li>\n";
                         if (isset($_POST['printableexport'])) {
                             $pdf->intopdf("__ " . $rearow['answer']);
                         }
                     }
                     $question['ANSWER'] .= "\n</ul>\n";
                     break;
                     // ==================================================================
                 // ==================================================================
                 case "M":
                     //Multiple choice (Quite tricky really!)
                     if (trim($qidattributes['display_columns']) != '') {
                         $dcols = $qidattributes['display_columns'];
                     } else {
                         $dcols = 0;
                     }
                     $question['QUESTION_TYPE_HELP'] .= $clang->gT("Please choose *all* that apply:");
                     if (isset($_POST['printableexport'])) {
                         $pdf->intopdf($clang->gT("Please choose *all* that apply:"), "U");
                     }
                     $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $surveyprintlang, $surveyid);
                     $mearesult = Questions::model()->getAllRecords(" parent_qid='{$deqrow['qid']}' AND language='{$surveyprintlang}' ", array('question_order'));
                     $mearesult = $mearesult->readAll();
                     $meacount = count($mearesult);
                     if ($deqrow['other'] == 'Y') {
                         $meacount++;
                     }
                     $wrapper = setupColumns($dcols, $meacount);
                     $question['ANSWER'] = $wrapper['whole-start'];
                     $rowcounter = 0;
                     $colcounter = 1;
                     foreach ($mearesult as $mearow) {
                         $question['ANSWER'] .= $wrapper['item-start'] . self::_input_type_image('checkbox', $mearow['question']) . "\n\t\t" . $mearow['question'] . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . ") ") . $wrapper['item-end'];
                         if (isset($_POST['printableexport'])) {
                             $pdf->intopdf(" o " . $mearow['answer']);
                         }
                         //                        $upto++;
                         ++$rowcounter;
                         if ($rowcounter == $wrapper['maxrows'] && $colcounter < $wrapper['cols']) {
                             if ($colcounter == $wrapper['cols'] - 1) {
                                 $question['ANSWER'] .= $wrapper['col-devide-last'];
                             } else {
                                 $question['ANSWER'] .= $wrapper['col-devide'];
                             }
                             $rowcounter = 0;
                             ++$colcounter;
                         }
                     }
                     if ($deqrow['other'] == "Y") {
                         if (trim($qidattributes['other_replace_text'][$surveyprintlang]) == '') {
                             $qidattributes["other_replace_text"][$surveyprintlang] = "Other";
                         }
                         if (!isset($mearow['answer'])) {
                             $mearow['answer'] = "";
                         }
                         $question['ANSWER'] .= $wrapper['item-start-other'] . self::_input_type_image('checkbox', $mearow['answer']) . $clang->gT($qidattributes["other_replace_text"][$surveyprintlang]) . ":\n\t\t" . self::_input_type_image('other') . self::_addsgqacode(" (" . $fieldname . "other) ") . $wrapper['item-end'];
                         if (isset($_POST['printableexport'])) {
                             $pdf->intopdf(" o " . $clang->gT($qidattributes["other_replace_text"][$surveyprintlang]) . ": ________");
                         }
                     }
                     $question['ANSWER'] .= $wrapper['whole-end'];
                     //                }
                     break;
                     // ==================================================================
                 // ==================================================================
                 case "P":
                     //Multiple choice with comments
                     $question['QUESTION_TYPE_HELP'] .= $clang->gT("Please choose all that apply and provide a comment:");
                     if (isset($_POST['printableexport'])) {
                         $pdf->intopdf($clang->gT("Please choose all that apply and provide a comment:"), "U");
                     }
                     $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $surveyprintlang, $surveyid);
                     $mearesult = Questions::model()->getAllRecords("parent_qid='{$deqrow['qid']}'  AND language='{$surveyprintlang}'", array('question_order'));
                     //                $printablesurveyoutput .="\t\t\t<u>".$clang->gT("Please choose all that apply and provide a comment:")."</u><br />\n";
                     $pdfoutput = array();
                     $j = 0;
                     $longest_string = 0;
                     foreach ($mearesult->readAll() as $mearow) {
                         $longest_string = longestString($mearow['question'], $longest_string);
                         $question['ANSWER'] .= "\t<li><span>\n\t\t" . self::_input_type_image('checkbox', $mearow['question']) . $mearow['question'] . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . ") ") . "</span>\n\t\t" . self::_input_type_image('text', 'comment box', 60) . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . "comment) ") . "\n\t</li>\n";
                         $pdfoutput[$j] = array(" o " . $mearow['title'], " __________");
                         $j++;
                     }
                     if ($deqrow['other'] == "Y") {
                         $question['ANSWER'] .= "\t<li class=\"other\">\n\t\t<div class=\"other-replacetext\">" . $clang->gT('Other:') . self::_input_type_image('other', '', 1) . "</div>" . self::_input_type_image('othercomment', 'comment box', 50) . self::_addsgqacode(" (" . $fieldname . "other) ") . "\n\t</li>\n";
                         // lemeur: PDFOUTPUT HAS NOT BEEN IMPLEMENTED for these fields
                         // not sure who did implement this.
                         $pdfoutput[$j][0] = array(" o " . "Other", " __________");
                         $pdfoutput[$j][1] = array(" o " . "OtherComment", " __________");
                         $j++;
                     }
                     $question['ANSWER'] = "\n<ul>\n" . $question['ANSWER'] . "</ul>\n";
                     if (isset($_POST['printableexport'])) {
                         $pdf->tableintopdf($pdfoutput);
                     }
                     break;
                     // ==================================================================
                 // ==================================================================
                 case "Q":
                     //MULTIPLE SHORT TEXT
                     $width = 60;
                     // ==================================================================
                 // ==================================================================
                 case "K":
                     //MULTIPLE NUMERICAL
                     $question['QUESTION_TYPE_HELP'] = "";
                     $width = isset($width) ? $width : 16;
                     if (isset($_POST['printableexport'])) {
                         $pdf->intopdf($clang->gT("Please write your answer(s) here:"), "U");
                     }
                     //                            if (!empty($qidattributes['equals_num_value']))
                     //                            {
                     //                                $question['QUESTION_TYPE_HELP'] .= "* ".sprintf($clang->gT('Total of all entries must equal %d'),$qidattributes['equals_num_value'])."<br />\n";
                     //                            }
                     //                            if (!empty($qidattributes['max_num_value']))
                     //                            {
                     //                                $question['QUESTION_TYPE_HELP'] .= sprintf($clang->gT('Total of all entries must not exceed %d'), $qidattributes['max_num_value'])."<br />\n";
                     //                            }
                     //                            if (!empty($qidattributes['min_num_value']))
                     //                            {
                     //                                $question['QUESTION_TYPE_HELP'] .= sprintf($clang->gT('Total of all entries must be at least %s'),$qidattributes['min_num_value'])."<br />\n";
                     //                            }
                     $question['QUESTION_TYPE_HELP'] .= $clang->gT("Please write your answer(s) here:");
                     $mearesult = Questions::model()->getAllRecords("parent_qid='{$deqrow['qid']}' AND language='{$surveyprintlang}'", array('question_order'));
                     $longest_string = 0;
                     foreach ($mearesult->readAll() as $mearow) {
                         $longest_string = longestString($mearow['question'], $longest_string);
                         if (isset($qidattributes['slider_layout']) && $qidattributes['slider_layout'] == 1) {
                             $mearow['question'] = explode(':', $mearow['question']);
                             $mearow['question'] = $mearow['question'][0];
                         }
                         $question['ANSWER'] .= "\t<li>\n\t\t<span>" . $mearow['question'] . "</span>\n\t\t" . self::_input_type_image('text', $mearow['question'], $width) . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . ") ") . "\n\t</li>\n";
                         if (isset($_POST['printableexport'])) {
                             $pdf->intopdf($mearow['question'] . ": ____________________");
                         }
                     }
                     $question['ANSWER'] = "\n<ul>\n" . $question['ANSWER'] . "</ul>\n";
                     break;
                     // ==================================================================
                 // ==================================================================
                 case "S":
                     //SHORT TEXT
                     $question['QUESTION_TYPE_HELP'] .= $clang->gT("Please write your answer here:");
                     $question['ANSWER'] = self::_input_type_image('text', $question['QUESTION_TYPE_HELP'], 50);
                     if (isset($_POST['printableexport'])) {
                         $pdf->intopdf($clang->gT("Please write your answer here:"), "U");
                     }
                     if (isset($_POST['printableexport'])) {
                         $pdf->intopdf("____________________");
                     }
                     break;
                     // ==================================================================
                 // ==================================================================
                 case "T":
                     //LONG TEXT
                     $question['QUESTION_TYPE_HELP'] .= $clang->gT("Please write your answer here:");
                     $question['ANSWER'] = self::_input_type_image('textarea', $question['QUESTION_TYPE_HELP'], '100%', 8);
                     if (isset($_POST['printableexport'])) {
                         $pdf->intopdf($clang->gT("Please write your answer here:"), "U");
                     }
                     for ($i = 0; $i < 9; $i++) {
                         if (isset($_POST['printableexport'])) {
                             $pdf->intopdf("____________________");
                         }
                     }
                     break;
                     // ==================================================================
                 // ==================================================================
                 case "U":
                     //HUGE TEXT
                     $question['QUESTION_TYPE_HELP'] .= $clang->gT("Please write your answer here:");
                     $question['ANSWER'] = self::_input_type_image('textarea', $question['QUESTION_TYPE_HELP'], '100%', 30);
                     if (isset($_POST['printableexport'])) {
                         $pdf->intopdf($clang->gT("Please write your answer here:"), "U");
                     }
                     for ($i = 0; $i < 20; $i++) {
                         if (isset($_POST['printableexport'])) {
                             $pdf->intopdf("____________________");
                         }
                     }
                     break;
                     // ==================================================================
                 // ==================================================================
                 case "N":
                     //NUMERICAL
                     $prefix = "";
                     $suffix = "";
                     if ($qidattributes['prefix'][$surveyprintlang] != "") {
                         $prefix = $qidattributes['prefix'][$surveyprintlang];
                         print_r($prefix);
                     }
                     if ($qidattributes['suffix'][$surveyprintlang] != "") {
                         $suffix = $qidattributes['suffix'][$surveyprintlang];
                     }
                     $question['QUESTION_TYPE_HELP'] .= $clang->gT("Please write your answer here:");
                     $question['ANSWER'] = "<ul>\n\t<li>\n\t\t<span>{$prefix}</span>\n\t\t" . self::_input_type_image('text', $question['QUESTION_TYPE_HELP'], 20) . "\n\t\t<span>{$suffix}</span>\n\t\t</li>\n\t</ul>";
                     if (isset($_POST['printableexport'])) {
                         $pdf->intopdf($clang->gT("Please write your answer here:"), "U");
                     }
                     if (isset($_POST['printableexport'])) {
                         $pdf->intopdf("____________________");
                     }
                     break;
                     // ==================================================================
                 // ==================================================================
                 case "Y":
                     //YES/NO
                     $question['QUESTION_TYPE_HELP'] .= $clang->gT("Please choose *only one* of the following:");
                     $question['ANSWER'] = "\n<ul>\n\t<li>\n\t\t" . self::_input_type_image('radio', $clang->gT('Yes')) . "\n\t\t" . $clang->gT('Yes') . self::_addsgqacode(" (Y)") . "\n\t</li>\n";
                     $question['ANSWER'] .= "\n\t<li>\n\t\t" . self::_input_type_image('radio', $clang->gT('No')) . "\n\t\t" . $clang->gT('No') . self::_addsgqacode(" (N)") . "\n\t</li>\n</ul>\n";
                     if (isset($_POST['printableexport'])) {
                         $pdf->intopdf($clang->gT("Please choose *only one* of the following:"), "U");
                     }
                     if (isset($_POST['printableexport'])) {
                         $pdf->intopdf(" o " . $clang->gT("Yes"));
                     }
                     if (isset($_POST['printableexport'])) {
                         $pdf->intopdf(" o " . $clang->gT("No"));
                     }
                     break;
                     // ==================================================================
                 // ==================================================================
                 case "A":
                     //ARRAY (5 POINT CHOICE)
                     $condition = "parent_qid = '{$deqrow['qid']}'  AND language= '{$surveyprintlang}'";
                     $mearesult = Questions::model()->getAllRecords($condition, array('question_order'));
                     $question['QUESTION_TYPE_HELP'] .= $clang->gT("Please choose the appropriate response for each item:");
                     $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $surveyprintlang, $surveyid);
                     $question['ANSWER'] = "\n        <table>\n            <thead>\n                <tr>\n                    <td>&nbsp;</td>\n                    <th style='font-family:Arial,helvetica,sans-serif;font-weight:normal;'>1&nbsp;&nbsp;&nbsp;&nbsp;" . self::_addsgqacode(" (1)") . "</th>\n                    <th style='font-family:Arial,helvetica,sans-serif;font-weight:normal;'>2&nbsp;&nbsp;&nbsp;&nbsp;" . self::_addsgqacode(" (2)") . "</th>\n                    <th style='font-family:Arial,helvetica,sans-serif;font-weight:normal;'>3&nbsp;&nbsp;&nbsp;&nbsp;" . self::_addsgqacode(" (3)") . "</th>\n                    <th style='font-family:Arial,helvetica,sans-serif;font-weight:normal;'>4&nbsp;&nbsp;&nbsp;&nbsp;" . self::_addsgqacode(" (4)") . "</th>\n                    <th style='font-family:Arial,helvetica,sans-serif;font-weight:normal;'>5" . self::_addsgqacode(" (5)") . "</th>\n                </tr>\n            </thead>\n            <tbody>";
                     if (isset($_POST['printableexport'])) {
                         $pdf->intopdf($clang->gT("Please choose the appropriate response for each item:"), "U");
                     }
                     $pdfoutput = array();
                     $j = 0;
                     $rowclass = 'array1';
                     foreach ($mearesult->readAll() as $mearow) {
                         $question['ANSWER'] .= "\t\t<tr class=\"{$rowclass}\">\n";
                         $rowclass = alternation($rowclass, 'row');
                         //semantic differential question type?
                         if (strpos($mearow['question'], '|')) {
                             $answertext = substr($mearow['question'], 0, strpos($mearow['question'], '|')) . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . ")") . " ";
                         } else {
                             $answertext = $mearow['question'] . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . ")");
                         }
                         $question['ANSWER'] .= "\t\t\t<th class=\"answertext\">{$answertext}</th>\n";
                         $pdfoutput[$j][0] = $answertext;
                         for ($i = 1; $i <= 5; $i++) {
                             $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio', $i) . "</td>\n";
                             $pdfoutput[$j][$i] = " o " . $i;
                         }
                         $answertext .= $mearow['question'];
                         //semantic differential question type?
                         if (strpos($mearow['question'], '|')) {
                             $answertext2 = substr($mearow['question'], strpos($mearow['question'], '|') + 1);
                             $question['ANSWER'] .= "\t\t\t<th class=\"answertextright\">{$answertext2}</td>\n";
                         }
                         $question['ANSWER'] .= "\t\t</tr>\n";
                         $j++;
                     }
                     $question['ANSWER'] .= "\t</tbody>\n</table>\n";
                     if (isset($_POST['printableexport'])) {
                         $pdf->tableintopdf($pdfoutput);
                     }
                     break;
                     // ==================================================================
                 // ==================================================================
                 case "B":
                     //ARRAY (10 POINT CHOICE)
                     $mearesult = Questions::model()->getAllRecords(" parent_qid='{$deqrow['qid']}' AND language='{$surveyprintlang}' ", array('question_order'));
                     $question['QUESTION_TYPE_HELP'] .= $clang->gT("Please choose the appropriate response for each item:");
                     $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $surveyprintlang, $surveyid);
                     $question['ANSWER'] .= "\n<table>\n\t<thead>\n\t\t<tr>\n\t\t\t<td>&nbsp;</td>\n";
                     for ($i = 1; $i <= 10; $i++) {
                         $question['ANSWER'] .= "\t\t\t<th>{$i}" . self::_addsgqacode(" ({$i})") . "</th>\n";
                     }
                     $question['ANSWER'] .= "\t</thead>\n\n\t<tbody>\n";
                     if (isset($_POST['printableexport'])) {
                         $pdf->intopdf($clang->gT("Please choose the appropriate response for each item:"), "U");
                     }
                     $pdfoutput = array();
                     $j = 0;
                     $rowclass = 'array1';
                     foreach ($mearesult->readAll() as $mearow) {
                         $question['ANSWER'] .= "\t\t<tr class=\"{$rowclass}\">\n\t\t\t<th class=\"answertext\">{$mearow['question']}" . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . ")") . "</th>\n";
                         $rowclass = alternation($rowclass, 'row');
                         $pdfoutput[$j][0] = $mearow['question'];
                         for ($i = 1; $i <= 10; $i++) {
                             $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio', $i) . "</td>\n";
                             $pdfoutput[$j][$i] = " o " . $i;
                         }
                         $question['ANSWER'] .= "\t\t</tr>\n";
                         $j++;
                     }
                     $question['ANSWER'] .= "\t</tbody>\n</table>\n";
                     if (isset($_POST['printableexport'])) {
                         $pdf->tableintopdf($pdfoutput);
                     }
                     break;
                     // ==================================================================
                 // ==================================================================
                 case "C":
                     //ARRAY (YES/UNCERTAIN/NO)
                     $mearesult = Questions::model()->getAllRecords(" parent_qid='{$deqrow['qid']}'  AND language='{$surveyprintlang}' ", array('question_order'));
                     $question['QUESTION_TYPE_HELP'] .= $clang->gT("Please choose the appropriate response for each item:");
                     $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $surveyprintlang, $surveyid);
                     $question['ANSWER'] = '
     <table>
         <thead>
             <tr>
                 <td>&nbsp;</td>
                 <th>' . $clang->gT("Yes") . self::_addsgqacode(" (Y)") . '</th>
                 <th>' . $clang->gT("Uncertain") . self::_addsgqacode(" (U)") . '</th>
                 <th>' . $clang->gT("No") . self::_addsgqacode(" (N)") . '</th>
             </tr>
         </thead>
         <tbody>
     ';
                     if (isset($_POST['printableexport'])) {
                         $pdf->intopdf($clang->gT("Please choose the appropriate response for each item:"), "U");
                     }
                     $pdfoutput = array();
                     $j = 0;
                     $rowclass = 'array1';
                     foreach ($mearesult->readAll() as $mearow) {
                         $question['ANSWER'] .= "\t\t<tr class=\"{$rowclass}\">\n";
                         $question['ANSWER'] .= "\t\t\t<th class=\"answertext\">{$mearow['question']}" . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . ")") . "</th>\n";
                         $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio', $clang->gT("Yes")) . "</td>\n";
                         $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio', $clang->gT("Uncertain")) . "</td>\n";
                         $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio', $clang->gT("No")) . "</td>\n";
                         $question['ANSWER'] .= "\t\t</tr>\n";
                         $pdfoutput[$j] = array($mearow['question'], " o " . $clang->gT("Yes"), " o " . $clang->gT("Uncertain"), " o " . $clang->gT("No"));
                         $j++;
                         $rowclass = alternation($rowclass, 'row');
                     }
                     $question['ANSWER'] .= "\t</tbody>\n</table>\n";
                     if (isset($_POST['printableexport'])) {
                         $pdf->tableintopdf($pdfoutput);
                     }
                     break;
                 case "E":
                     //ARRAY (Increase/Same/Decrease)
                     $mearesult = Questions::model()->getAllRecords(" parent_qid='{$deqrow['qid']}'  AND language='{$surveyprintlang}' ", array('question_order'));
                     $question['QUESTION_TYPE_HELP'] .= $clang->gT("Please choose the appropriate response for each item:");
                     $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $surveyprintlang, $surveyid);
                     $question['ANSWER'] = '
     <table>
         <thead>
             <tr>
                 <td>&nbsp;</td>
                 <th>' . $clang->gT("Increase") . self::_addsgqacode(" (I)") . '</th>
                 <th>' . $clang->gT("Same") . self::_addsgqacode(" (S)") . '</th>
                 <th>' . $clang->gT("Decrease") . self::_addsgqacode(" (D)") . '</th>
             </tr>
         </thead>
         <tbody>
     ';
                     if (isset($_POST['printableexport'])) {
                         $pdf->intopdf($clang->gT("Please choose the appropriate response for each item:"), "U");
                     }
                     $pdfoutput = array();
                     $j = 0;
                     $rowclass = 'array1';
                     foreach ($mearesult->readAll() as $mearow) {
                         $question['ANSWER'] .= "\t\t<tr class=\"{$rowclass}\">\n";
                         $question['ANSWER'] .= "\t\t\t<th class=\"answertext\">{$mearow['question']}" . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . ")") . "</th>\n";
                         $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio', $clang->gT("Increase")) . "</td>\n";
                         $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio', $clang->gT("Same")) . "</td>\n";
                         $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio', $clang->gT("Decrease")) . "</td>\n";
                         $question['ANSWER'] .= "\t\t</tr>\n";
                         $pdfoutput[$j] = array($mearow['question'] . ":", " o " . $clang->gT("Increase"), " o " . $clang->gT("Same"), " o " . $clang->gT("Decrease"));
                         $j++;
                         $rowclass = alternation($rowclass, 'row');
                     }
                     $question['ANSWER'] .= "\t</tbody>\n</table>\n";
                     if (isset($_POST['printableexport'])) {
                         $pdf->tableintopdf($pdfoutput);
                     }
                     break;
                     // ==================================================================
                 // ==================================================================
                 case ":":
                     //ARRAY (Multi Flexible) (Numbers)
                     $headstyle = "style='padding-left: 20px; padding-right: 7px'";
                     if (trim($qidattributes['multiflexible_max']) != '' && trim($qidattributes['multiflexible_min']) == '') {
                         $maxvalue = $qidattributes['multiflexible_max'];
                         $minvalue = 1;
                     }
                     if (trim($qidattributes['multiflexible_min']) != '' && trim($qidattributes['multiflexible_max']) == '') {
                         $minvalue = $qidattributes['multiflexible_min'];
                         $maxvalue = $qidattributes['multiflexible_min'] + 10;
                     }
                     if (trim($qidattributes['multiflexible_min']) == '' && trim($qidattributes['multiflexible_max']) == '') {
                         $minvalue = 1;
                         $maxvalue = 10;
                     }
                     if (trim($qidattributes['multiflexible_min']) != '' && trim($qidattributes['multiflexible_max']) != '') {
                         if ($qidattributes['multiflexible_min'] < $qidattributes['multiflexible_max']) {
                             $minvalue = $qidattributes['multiflexible_min'];
                             $maxvalue = $qidattributes['multiflexible_max'];
                         }
                     }
                     if (trim($qidattributes['multiflexible_step']) != '') {
                         $stepvalue = $qidattributes['multiflexible_step'];
                     } else {
                         $stepvalue = 1;
                     }
                     if ($qidattributes['multiflexible_checkbox'] != 0) {
                         $checkboxlayout = true;
                     } else {
                         $checkboxlayout = false;
                     }
                     $mearesult = Questions::model()->getAllRecords(" parent_qid='{$deqrow['qid']}' and scale_id=0 AND language='{$surveyprintlang}' ", array('question_order'));
                     //                            if ($checkboxlayout === false)
                     //                            {
                     //                                if ($stepvalue > 1)
                     //                                {
                     //                                    $question['QUESTION_TYPE_HELP'] = sprintf($clang->gT("Please write a multiple of %d between (%s) and (%s) for each item:"),$stepvalue,$minvalue,$maxvalue);
                     //                                    if(isset($_POST['printableexport'])){$pdf->intopdf(sprintf($clang->gT("Please write a multiple of %d between (%s) and (%s) for each item:"),$stepvalue,$minvalue,$maxvalue),"U");}
                     //                                }
                     //                                else {
                     //                                    $question['QUESTION_TYPE_HELP'] = sprintf($clang->gT("Please enter a number between (%s) and (%s) for each item:"),$minvalue,$maxvalue);
                     //                                    if(isset($_POST['printableexport'])){$pdf->intopdf(sprintf($clang->gT("Please enter a number between (%s) and (%s) for each item:"),$minvalue,$maxvalue),"U");}
                     //                                }
                     //                            }
                     //                            else
                     //                            {
                     //                                $question['QUESTION_TYPE_HELP'] .= $clang->gT("Check any that apply").":";
                     //                                if(isset($_POST['printableexport'])){$pdf->intopdf($clang->gT("Check any that apply"),"U");}
                     //                            }
                     $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $surveyprintlang, $surveyid);
                     $question['ANSWER'] .= "\n<table>\n\t<thead>\n\t\t<tr>\n\t\t\t<td>&nbsp;</td>\n";
                     $fresult = Questions::model()->getAllRecords(" parent_qid='{$deqrow['qid']}' and scale_id=1 AND language='{$surveyprintlang}' ", array('question_order'));
                     $fresult = $fresult->readAll();
                     $fcount = count($fresult);
                     $fwidth = "120";
                     $i = 0;
                     $pdfoutput = array();
                     $pdfoutput[0][0] = ' ';
                     //array to temporary store X axis question codes
                     $xaxisarray = array();
                     foreach ($fresult as $frow) {
                         $question['ANSWER'] .= "\t\t\t<th>{$frow['question']}</th>\n";
                         $i++;
                         $pdfoutput[0][$i] = $frow['question'];
                         //add current question code
                         $xaxisarray[$i] = $frow['title'];
                     }
                     $question['ANSWER'] .= "\t\t</tr>\n\t</thead>\n\n\t<tbody>\n";
                     $a = 1;
                     //Counter for pdfoutput
                     $rowclass = 'array1';
                     $result = $mearesult->readAll();
                     foreach ($result as $frow) {
                         $question['ANSWER'] .= "\t<tr class=\"{$rowclass}\">\n";
                         $rowclass = alternation($rowclass, 'row');
                         $answertext = $frow['question'];
                         if (strpos($answertext, '|')) {
                             $answertext = substr($answertext, 0, strpos($answertext, '|'));
                         }
                         $question['ANSWER'] .= "\t\t\t\t\t<th class=\"answertext\">{$answertext}</th>\n";
                         //$printablesurveyoutput .="\t\t\t\t\t<td>";
                         $pdfoutput[$a][0] = $answertext;
                         for ($i = 1; $i <= $fcount; $i++) {
                             $question['ANSWER'] .= "\t\t\t<td>\n";
                             if ($checkboxlayout === false) {
                                 $question['ANSWER'] .= "\t\t\t\t" . self::_input_type_image('text', '', 4) . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . "_" . $xaxisarray[$i] . ") ") . "\n";
                                 $pdfoutput[$a][$i] = "__";
                             } else {
                                 $question['ANSWER'] .= "\t\t\t\t" . self::_input_type_image('checkbox') . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . "_" . $xaxisarray[$i] . ") ") . "\n";
                                 $pdfoutput[$a][$i] = "o";
                             }
                             $question['ANSWER'] .= "\t\t\t</td>\n";
                         }
                         $answertext = $mearow['question'];
                         if (strpos($answertext, '|')) {
                             $answertext = substr($answertext, strpos($answertext, '|') + 1);
                             $question['ANSWER'] .= "\t\t\t<th class=\"answertextright\">{$answertext}</th>\n";
                             //$pdfoutput[$a][$i]=$answertext;
                         }
                         $question['ANSWER'] .= "\t\t</tr>\n";
                         $a++;
                     }
                     $question['ANSWER'] .= "\t</tbody>\n</table>\n";
                     if (isset($_POST['printableexport'])) {
                         $pdf->tableintopdf($pdfoutput);
                     }
                     break;
                     // ==================================================================
                 // ==================================================================
                 case ";":
                     //ARRAY (Multi Flexible) (text)
                     $headstyle = "style='padding-left: 20px; padding-right: 7px'";
                     $mearesult = Questions::model()->getAllRecords(" parent_qid='{$deqrow['qid']}' AND scale_id=0 AND language='{$surveyprintlang}' ", array('question_order'));
                     $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $surveyprintlang, $surveyid);
                     $question['ANSWER'] .= "\n<table>\n\t<thead>\n\t\t<tr>\n\t\t\t<td>&nbsp;</td>\n";
                     $fresult = Questions::model()->getAllRecords(" parent_qid='{$deqrow['qid']}'  AND scale_id=1 AND language='{$surveyprintlang}' ", array('question_order'));
                     $fresult = $fresult->readAll();
                     $fcount = count($fresult);
                     $fwidth = "120";
                     $i = 0;
                     $pdfoutput = array();
                     $pdfoutput[0][0] = '';
                     //array to temporary store X axis question codes
                     $xaxisarray = array();
                     foreach ($fresult as $frow) {
                         $question['ANSWER'] .= "\t\t\t<th>{$frow['question']}</th>\n";
                         $i++;
                         $pdfoutput[0][$i] = $frow['question'];
                         //add current question code
                         $xaxisarray[$i] = $frow['title'];
                     }
                     $question['ANSWER'] .= "\t\t</tr>\n\t</thead>\n\n<tbody>\n";
                     $a = 1;
                     $rowclass = 'array1';
                     foreach ($mearesult->readAll() as $mearow) {
                         $question['ANSWER'] .= "\t\t<tr class=\"{$rowclass}\">\n";
                         $rowclass = alternation($rowclass, 'row');
                         $answertext = $mearow['question'];
                         if (strpos($answertext, '|')) {
                             $answertext = substr($answertext, 0, strpos($answertext, '|'));
                         }
                         $question['ANSWER'] .= "\t\t\t<th class=\"answertext\">{$answertext}</th>\n";
                         $pdfoutput[$a][0] = $answertext;
                         //$printablesurveyoutput .="\t\t\t\t\t<td>";
                         for ($i = 1; $i <= $fcount; $i++) {
                             $question['ANSWER'] .= "\t\t\t<td>\n";
                             $question['ANSWER'] .= "\t\t\t\t" . self::_input_type_image('text', '', 23) . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . "_" . $xaxisarray[$i] . ") ") . "\n";
                             $question['ANSWER'] .= "\t\t\t</td>\n";
                             $pdfoutput[$a][$i] = "_____________";
                         }
                         $answertext = $mearow['question'];
                         if (strpos($answertext, '|')) {
                             $answertext = substr($answertext, strpos($answertext, '|') + 1);
                             $question['ANSWER'] .= "\t\t\t\t<th class=\"answertextright\">{$answertext}</th>\n";
                         }
                         $question['ANSWER'] .= "\t\t</tr>\n";
                         $a++;
                     }
                     $question['ANSWER'] .= "\t</tbody>\n</table>\n";
                     if (isset($_POST['printableexport'])) {
                         $pdf->tableintopdf($pdfoutput);
                     }
                     break;
                     // ==================================================================
                 // ==================================================================
                 case "F":
                     //ARRAY (Flexible Labels)
                     $mearesult = Questions::model()->getAllRecords(" parent_qid='{$deqrow['qid']}'  AND language='{$surveyprintlang}' ", array('question_order'));
                     $question['QUESTION_TYPE_HELP'] .= $clang->gT("Please choose the appropriate response for each item:");
                     $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $surveyprintlang, $surveyid);
                     $fresult = Answers::model()->getAllRecords(" scale_id=0 AND qid='{$deqrow['qid']}'  AND language='{$surveyprintlang}'", array('sortorder', 'code'));
                     $fresult = $fresult->readAll();
                     $fcount = count($fresult);
                     $fwidth = "120";
                     $i = 1;
                     $pdfoutput = array();
                     $pdfoutput[0][0] = '';
                     if (isset($_POST['printableexport'])) {
                         $pdf->intopdf($clang->gT("Please choose the appropriate response for each item:"), "U");
                     }
                     $column_headings = array();
                     foreach ($fresult as $frow) {
                         $column_headings[] = $frow['answer'] . self::_addsgqacode(" (" . $frow['code'] . ")");
                     }
                     if (trim($qidattributes['answer_width']) != '') {
                         $iAnswerWidth = 100 - $qidattributes['answer_width'];
                     } else {
                         $iAnswerWidth = 80;
                     }
                     if (count($column_headings) > 0) {
                         $col_width = round($iAnswerWidth / count($column_headings));
                     } else {
                         $heading = '';
                     }
                     $question['ANSWER'] .= "\n<table>\n\t<thead>\n\t\t<tr>\n";
                     $question['ANSWER'] .= "\t\t\t<td>&nbsp;</td>\n";
                     foreach ($column_headings as $heading) {
                         $question['ANSWER'] .= "\t\t\t<th style=\"width:{$col_width}%;\">{$heading}</th>\n";
                     }
                     $pdfoutput[0][$i] = $heading;
                     $i++;
                     $question['ANSWER'] .= "\t\t</tr>\n\t</thead>\n\n\t<tbody>\n";
                     $counter = 1;
                     $rowclass = 'array1';
                     foreach ($mearesult->readAll() as $mearow) {
                         $question['ANSWER'] .= "\t\t<tr class=\"{$rowclass}\">\n";
                         $rowclass = alternation($rowclass, 'row');
                         if (trim($answertext) == '') {
                             $answertext = '&nbsp;';
                         }
                         //semantic differential question type?
                         if (strpos($mearow['question'], '|')) {
                             $answertext = substr($mearow['question'], 0, strpos($mearow['question'], '|')) . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . ")") . " ";
                         } else {
                             $answertext = $mearow['question'] . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . ")");
                         }
                         if (trim($qidattributes['answer_width']) != '') {
                             $sInsertStyle = ' style="width:' . $qidattributes['answer_width'] . '%" ';
                         } else {
                             $sInsertStyle = '';
                         }
                         $question['ANSWER'] .= "\t\t\t<th {$sInsertStyle} class=\"answertext\">{$answertext}</th>\n";
                         $pdfoutput[$counter][0] = $answertext;
                         for ($i = 1; $i <= $fcount; $i++) {
                             $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio') . "</td>\n";
                             $pdfoutput[$counter][$i] = "o";
                         }
                         $counter++;
                         $answertext = $mearow['question'];
                         //semantic differential question type?
                         if (strpos($mearow['question'], '|')) {
                             $answertext2 = substr($mearow['question'], strpos($mearow['question'], '|') + 1);
                             $question['ANSWER'] .= "\t\t\t<th class=\"answertextright\">{$answertext2}</th>\n";
                         }
                         $question['ANSWER'] .= "\t\t</tr>\n";
                     }
                     $question['ANSWER'] .= "\t</tbody>\n</table>\n";
                     if (isset($_POST['printableexport'])) {
                         $pdf->tableintopdf($pdfoutput);
                     }
                     break;
                     // ==================================================================
                 // ==================================================================
                 case "1":
                     //ARRAY (Flexible Labels) multi scale
                     $leftheader = $qidattributes['dualscale_headerA'][$surveyprintlang];
                     $rightheader = $qidattributes['dualscale_headerB'][$surveyprintlang];
                     $headstyle = 'style="padding-left: 20px; padding-right: 7px"';
                     //$meaquery = "SELECT * FROM {{questions}} WHERE parent_qid={$deqrow['qid']}  AND language='{$surveyprintlang}' ORDER BY question_order";
                     //$mearesult = Yii::app()->db->createCommand($meaquery)->query();
                     $mearesult = Questions::model()->getAllRecords(" parent_qid={$deqrow['qid']}  AND language='{$surveyprintlang}' ", array('question_order'));
                     $question['QUESTION_TYPE_HELP'] .= $clang->gT("Please choose the appropriate response for each item:");
                     $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $surveyprintlang, $surveyid);
                     if (isset($_POST['printableexport'])) {
                         $pdf->intopdf($clang->gT("Please choose the appropriate response for each item:"), "U");
                     }
                     $question['ANSWER'] .= "\n<table>\n\t<thead>\n";
                     $condition = "qid= '{$deqrow['qid']}'  AND language= '{$surveyprintlang}' AND scale_id=0";
                     $fresult = Answers::model()->getAllRecords($condition, array('sortorder', 'code'));
                     $fresult = $fresult->readAll();
                     $fcount = count($fresult);
                     $fwidth = "120";
                     $l1 = 0;
                     $printablesurveyoutput2 = "\t\t\t<td>&nbsp;</td>\n";
                     $myheader2 = '';
                     $pdfoutput = array();
                     $pdfoutput[0][0] = '';
                     foreach ($fresult as $frow) {
                         $printablesurveyoutput2 .= "\t\t\t<th>{$frow['answer']}" . self::_addsgqacode(" (" . $frow['code'] . ")") . "</th>\n";
                         $myheader2 .= "<td></td>";
                         $pdfoutput[0][$l1 + 1] = $frow['answer'];
                         $l1++;
                     }
                     // second scale
                     $printablesurveyoutput2 .= "\t\t\t<td>&nbsp;</td>\n";
                     //$fquery1 = "SELECT * FROM {{answers}} WHERE qid='{$deqrow['qid']}'  AND language='{$surveyprintlang}' AND scale_id=1 ORDER BY sortorder, code";
                     // $fresult1 = Yii::app()->db->createCommand($fquery1)->query();
                     $fresult1 = Answers::model()->getAllRecords(" qid='{$deqrow['qid']}'  AND language='{$surveyprintlang}' AND scale_id=1 ", array('sortorder', 'code'));
                     $fresult1 = $fresult1->readAll();
                     $fcount1 = count($fresult1);
                     $fwidth = "120";
                     $l2 = 0;
                     //array to temporary store second scale question codes
                     $scale2array = array();
                     foreach ($fresult1 as $frow1) {
                         $printablesurveyoutput2 .= "\t\t\t<th>{$frow1['answer']}" . self::_addsgqacode(" (" . $frow1['code'] . ")") . "</th>\n";
                         $pdfoutput[1][$l2] = $frow['answer'];
                         //add current question code
                         $scale2array[$l2] = $frow1['code'];
                         $l2++;
                     }
                     // build header if needed
                     if ($leftheader != '' || $rightheader != '') {
                         $myheader = "\t\t\t<td>&nbsp;</td>";
                         $myheader .= "\t\t\t<th colspan=\"" . $l1 . "\">{$leftheader}</th>\n";
                         if ($rightheader != '') {
                             // $myheader .= "\t\t\t\t\t" .$myheader2;
                             $myheader .= "\t\t\t<td>&nbsp;</td>";
                             $myheader .= "\t\t\t<th colspan=\"" . $l2 . "\">{$rightheader}</td>\n";
                         }
                         $myheader .= "\t\t\t\t</tr>\n";
                     } else {
                         $myheader = '';
                     }
                     $question['ANSWER'] .= $myheader . "\t\t</tr>\n\n\t\t<tr>\n";
                     $question['ANSWER'] .= $printablesurveyoutput2;
                     $question['ANSWER'] .= "\t\t</tr>\n\t</thead>\n\n\t<tbody>\n";
                     $rowclass = 'array1';
                     //counter for each subquestion
                     $sqcounter = 0;
                     foreach ($mearesult->readAll() as $mearow) {
                         $question['ANSWER'] .= "\t\t<tr class=\"{$rowclass}\">\n";
                         $rowclass = alternation($rowclass, 'row');
                         $answertext = $mearow['question'] . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . "#0) / (" . $fieldname . $mearow['title'] . "#1)");
                         if (strpos($answertext, '|')) {
                             $answertext = substr($answertext, 0, strpos($answertext, '|'));
                         }
                         $question['ANSWER'] .= "\t\t\t<th class=\"answertext\">{$answertext}</th>\n";
                         for ($i = 1; $i <= $fcount; $i++) {
                             $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio') . "</td>\n";
                         }
                         $question['ANSWER'] .= "\t\t\t<td>&nbsp;</td>\n";
                         for ($i = 1; $i <= $fcount1; $i++) {
                             $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio') . "</td>\n";
                         }
                         $answertext = $mearow['question'];
                         if (strpos($answertext, '|')) {
                             $answertext = substr($answertext, strpos($answertext, '|') + 1);
                             $question['ANSWER'] .= "\t\t\t<th class=\"answertextright\">{$answertext}</th>\n";
                         }
                         $question['ANSWER'] .= "\t\t</tr>\n";
                         //increase subquestion counter
                         $sqcounter++;
                     }
                     $question['ANSWER'] .= "\t</tbody>\n</table>\n";
                     if (isset($_POST['printableexport'])) {
                         $pdf->tableintopdf($pdfoutput);
                     }
                     break;
                     // ==================================================================
                 // ==================================================================
                 case "H":
                     //ARRAY (Flexible Labels) by Column
                     //$headstyle="style='border-left-style: solid; border-left-width: 1px; border-left-color: #AAAAAA'";
                     $headstyle = "style='padding-left: 20px; padding-right: 7px'";
                     $condition = "parent_qid= '{$deqrow['qid']}'  AND language= '{$surveyprintlang}'";
                     $fresult = Questions::model()->getAllRecords($condition, array('question_order', 'title'));
                     $fresult = $fresult->readAll();
                     $question['QUESTION_TYPE_HELP'] .= $clang->gT("Please choose the appropriate response for each item:");
                     if (isset($_POST['printableexport'])) {
                         $pdf->intopdf($clang->gT("Please choose the appropriate response for each item:"), "U");
                     }
                     $question['ANSWER'] .= "\n<table>\n\t<thead>\n\t\t<tr>\n\t\t\t<td>&nbsp;</td>\n";
                     $mearesult = Answers::model()->getAllRecords(" qid='{$deqrow['qid']}' AND scale_id=0 AND language='{$surveyprintlang}' ", array('sortorder', 'code'));
                     $fcount = count($fresult);
                     $fwidth = "120";
                     $i = 0;
                     $pdfoutput = array();
                     $pdfoutput[0][0] = '';
                     foreach ($fresult as $frow) {
                         $question['ANSWER'] .= "\t\t\t<th>{$frow['question']}" . self::_addsgqacode(" (" . $fieldname . $frow['title'] . ")") . "</th>\n";
                         $i++;
                         $pdfoutput[0][$i] = $frow['question'];
                     }
                     $question['ANSWER'] .= "\t\t</tr>\n\t</thead>\n\n\t<tbody>\n";
                     $a = 1;
                     $rowclass = 'array1';
                     foreach ($mearesult->readAll() as $mearow) {
                         //$_POST['type']=$type;
                         $question['ANSWER'] .= "\t\t<tr class=\"{$rowclass}\">\n";
                         $rowclass = alternation($rowclass, 'row');
                         $question['ANSWER'] .= "\t\t\t<th class=\"answertext\">{$mearow['answer']}" . self::_addsgqacode(" (" . $mearow['code'] . ")") . "</th>\n";
                         //$printablesurveyoutput .="\t\t\t\t\t<td>";
                         $pdfoutput[$a][0] = $mearow['answer'];
                         for ($i = 1; $i <= $fcount; $i++) {
                             $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio') . "</td>\n";
                             $pdfoutput[$a][$i] = "o";
                         }
                         //$printablesurveyoutput .="\t\t\t\t\t</tr></table></td>\n";
                         $question['ANSWER'] .= "\t\t</tr>\n";
                         $a++;
                     }
                     $question['ANSWER'] .= "\t</tbody>\n</table>\n";
                     if (isset($_POST['printableexport'])) {
                         $pdf->tableintopdf($pdfoutput);
                     }
                     break;
                 case "|":
                     // File Upload
                     $question['QUESTION_TYPE_HELP'] .= "Kindly attach the aforementioned documents along with the survey";
                     break;
                     // === END SWITCH ===================================================
             }
             if (isset($_POST['printableexport'])) {
                 $pdf->ln(5);
             }
             $question['QUESTION_TYPE_HELP'] = self::_star_replace($question['QUESTION_TYPE_HELP']);
             $group['QUESTIONS'] .= self::_populate_template('question', $question);
         }
         if ($bGroupHasVisibleQuestions) {
             $survey_output['GROUPS'] .= self::_populate_template('group', $group);
         }
     }
     $survey_output['THEREAREXQUESTIONS'] = str_replace('{NUMBEROFQUESTIONS}', $total_questions, $clang->gT('There are {NUMBEROFQUESTIONS} questions in this survey'));
     // START recursive tag stripping.
     // PHP 5.1.0 introduced the count parameter for preg_replace() and thus allows this procedure to run with only one regular expression.
     // Previous version of PHP needs two regular expressions to do the same thing and thus will run a bit slower.
     $server_is_newer = version_compare(PHP_VERSION, '5.1.0', '>');
     $rounds = 0;
     while ($rounds < 1) {
         $replace_count = 0;
         if ($server_is_newer) {
             $survey_output['GROUPS'] = preg_replace(array('/<td>(?:&nbsp;|&#160;| )?<\\/td>/isU', '/<th[^>]*>(?:&nbsp;|&#160;| )?<\\/th>/isU', '/<([^ >]+)[^>]*>(?:&nbsp;|&#160;|\\r\\n|\\n\\r|\\n|\\r|\\t| )*<\\/\\1>/isU'), array('[[EMPTY-TABLE-CELL]]', '[[EMPTY-TABLE-CELL-HEADER]]', ''), $survey_output['GROUPS'], -1, $replace_count);
         } else {
             $survey_output['GROUPS'] = preg_replace(array('/<td>(?:&nbsp;|&#160;| )?<\\/td>/isU', '/<th[^>]*>(?:&nbsp;|&#160;| )?<\\/th>/isU', '/<([^ >]+)[^>]*>(?:&nbsp;|&#160;|\\r\\n|\\n\\r|\\n|\\r|\\t| )*<\\/\\1>/isU'), array('[[EMPTY-TABLE-CELL]]', '[[EMPTY-TABLE-CELL-HEADER]]', ''), $survey_output['GROUPS']);
             $replace_count = preg_match('/<([^ >]+)[^>]*>(?:&nbsp;|&#160;|\\r\\n|\\n\\r|\\n|\\r|\\t| )*<\\/\\1>/isU', $survey_output['GROUPS']);
         }
         if ($replace_count == 0) {
             ++$rounds;
             $survey_output['GROUPS'] = preg_replace(array('/\\[\\[EMPTY-TABLE-CELL\\]\\]/', '/\\[\\[EMPTY-TABLE-CELL-HEADER\\]\\]/', '/\\n(?:\\t*\\n)+/'), array('<td>&nbsp;</td>', '<th>&nbsp;</th>', "\n"), $survey_output['GROUPS']);
         }
     }
     $survey_output['GROUPS'] = preg_replace('/(<div[^>]*>){NOTEMPTY}(<\\/div>)/', '\\1&nbsp;\\2', $survey_output['GROUPS']);
     // END recursive empty tag stripping.
     if (isset($_POST['printableexport'])) {
         if ($surveystartdate != '') {
             if (isset($_POST['printableexport'])) {
                 $pdf->intopdf(sprintf($clang->gT("Please submit by %s"), $surveyexpirydate));
             }
         }
         if (!empty($surveyfaxto) && $surveyfaxto != '000-00000000') {
             if (isset($_POST['printableexport'])) {
                 $pdf->intopdf(sprintf($clang->gT("Please fax your completed survey to: %s"), $surveyfaxto), 'B');
             }
         }
         $pdf->titleintopdf($clang->gT("Submit Your Survey."), $clang->gT("Thank you for completing this survey."));
         $pdf->write_out($clang->gT($surveyname) . " " . $surveyid . ".pdf");
     } else {
         echo self::_populate_template('survey', $survey_output);
     }
 }
Exemple #14
0
function do_array($ia)
{
    global $thissurvey;
    global $notanswered;
    $repeatheadings = Yii::app()->getConfig("repeatheadings");
    $minrepeatheadings = Yii::app()->getConfig("minrepeatheadings");
    $extraclass = "";
    $clang = Yii::app()->lang;
    $checkconditionFunction = "checkconditions";
    $qquery = "SELECT other FROM {{questions}} WHERE qid={$ia[0]} AND language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "'";
    $qresult = dbExecuteAssoc($qquery);
    //Checked
    $qrow = $qresult->read();
    $other = $qrow['other'];
    $aQuestionAttributes = getQuestionAttributeValues($ia[0], $ia[4]);
    if (trim($aQuestionAttributes['answer_width']) != '') {
        $answerwidth = $aQuestionAttributes['answer_width'];
    } else {
        $answerwidth = 20;
    }
    $columnswidth = 100 - $answerwidth;
    if ($aQuestionAttributes['use_dropdown'] == 1) {
        $useDropdownLayout = true;
        $extraclass .= " dropdown-list";
    } else {
        $useDropdownLayout = false;
    }
    if (ctype_digit(trim($aQuestionAttributes['repeat_headings'])) && trim($aQuestionAttributes['repeat_headings'] != "")) {
        $repeatheadings = intval($aQuestionAttributes['repeat_headings']);
        $minrepeatheadings = 0;
    }
    $lresult = Answers::model()->findAll(array('order' => 'sortorder, code', 'condition' => 'qid=:qid AND language=:language AND scale_id=0', 'params' => array(':qid' => $ia[0], ':language' => $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'])));
    if ($useDropdownLayout === false && count($lresult) > 0) {
        foreach ($lresult as $lrow) {
            $labelans[] = $lrow->answer;
            $labelcode[] = $lrow->code;
        }
        $sQuery = "SELECT question FROM {{questions}} WHERE parent_qid={$ia[0]} AND question like '%|%' ";
        $iCount = Yii::app()->db->createCommand($sQuery)->queryScalar();
        if ($iCount > 0) {
            $right_exists = true;
            $answerwidth = $answerwidth / 2;
        } else {
            $right_exists = false;
        }
        // $right_exists is a flag to find out if there are any right hand answer parts. If there arent we can leave out the right td column
        if ($aQuestionAttributes['random_order'] == 1) {
            $ansquery = "SELECT * FROM {{questions}} WHERE parent_qid={$ia[0]} AND language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "' ORDER BY " . dbRandom();
        } else {
            $ansquery = "SELECT * FROM {{questions}} WHERE parent_qid={$ia[0]} AND language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "' ORDER BY question_order";
        }
        $ansresult = dbExecuteAssoc($ansquery);
        //Checked
        $aQuestions = $ansresult->readAll();
        $anscount = count($aQuestions);
        $fn = 1;
        $numrows = count($labelans);
        if ($ia[6] != 'Y' && SHOW_NO_ANSWER == 1) {
            ++$numrows;
        }
        if ($right_exists) {
            ++$numrows;
        }
        $cellwidth = round($columnswidth / $numrows, 1);
        $answer_start = "\n<table class=\"question subquestions-list questions-list {$extraclass}\" summary=\"" . str_replace('"', '', strip_tags($ia[3])) . " - an array type question\" >\n";
        $answer_head_line = "\t<td>&nbsp;</td>\n";
        foreach ($labelans as $ld) {
            $answer_head_line .= "\t<th>" . $ld . "</th>\n";
        }
        if ($right_exists) {
            $answer_head_line .= "\t<td>&nbsp;</td>\n";
        }
        if ($ia[6] != 'Y' && SHOW_NO_ANSWER == 1) {
            $answer_head_line .= "\t<th>" . $clang->gT('No answer') . "</th>\n";
        }
        $answer_head = "\t<thead><tr>\n" . $answer_head_line . "</thead></tr>\n\t\n";
        $answer = '<tbody>';
        $trbc = '';
        $inputnames = array();
        foreach ($aQuestions as $ansrow) {
            if (isset($repeatheadings) && $repeatheadings > 0 && $fn - 1 > 0 && ($fn - 1) % $repeatheadings == 0) {
                if ($anscount - $fn + 1 >= $minrepeatheadings) {
                    $answer .= "</tbody>\n<tbody>";
                    // Close actual body and open another one
                    $answer .= "<tr class=\"repeat headings\">{$answer_head_line}</tr>";
                }
            }
            $myfname = $ia[1] . $ansrow['title'];
            $answertext = dTexts__run($ansrow['question']);
            $answertextsave = $answertext;
            if (strpos($answertext, '|')) {
                $answertext = substr($answertext, 0, strpos($answertext, '|'));
            }
            /* Check if this item has not been answered: the 'notanswered' variable must be an array,
               containing a list of unanswered questions, the current question must be in the array,
               and there must be no answer available for the item in this session. */
            if (strpos($answertext, '|')) {
                $answerwidth = $answerwidth / 2;
            }
            if ($ia[6] == 'Y' && is_array($notanswered) && array_search($myfname, $notanswered) !== FALSE && $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname] == '') {
                $answertext = '<span class="errormandatory">' . $answertext . '</span>';
            }
            // Get array_filter stuff
            //
            // TMSW - is this correct?
            $trbc = alternation($trbc, 'row');
            list($htmltbody2, $hiddenfield) = return_array_filter_strings($ia, $aQuestionAttributes, $thissurvey, $ansrow, $myfname, $trbc, $myfname, "tr", "{$trbc} answers-list radio-list");
            $fn++;
            $answer .= $htmltbody2;
            $answer .= "\t<th class=\"answertext\">\n{$answertext}" . $hiddenfield . "<input type=\"hidden\" name=\"java{$myfname}\" id=\"java{$myfname}\" value=\"";
            if (isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname])) {
                $answer .= $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname];
            }
            $answer .= "\" />\n\t</th>\n";
            $thiskey = 0;
            foreach ($labelcode as $ld) {
                $answer .= "\t\t\t<td class=\"answer_cell_00{$ld} answer-item radio-item\">\n" . "<label for=\"answer{$myfname}-{$ld}\">\n" . "\t<input class=\"radio\" type=\"radio\" name=\"{$myfname}\" value=\"{$ld}\" id=\"answer{$myfname}-{$ld}\" title=\"" . HTMLEscape(strip_tags($labelans[$thiskey])) . '"';
                if (isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname]) && $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname] == $ld) {
                    $answer .= CHECKED;
                }
                // --> START NEW FEATURE - SAVE
                $answer .= " onclick=\"{$checkconditionFunction}(this.value, this.name, this.type)\" />\n" . "</label>\n" . "\t</td>\n";
                // --> END NEW FEATURE - SAVE
                $thiskey++;
            }
            if (strpos($answertextsave, '|')) {
                $answertext = substr($answertextsave, strpos($answertextsave, '|') + 1);
                $answer .= "\t<th class=\"answertextright\">{$answertext}</th>\n";
            } elseif ($right_exists) {
                $answer .= "\t<td class=\"answertextright\">&nbsp;</td>\n";
            }
            if ($ia[6] != 'Y' && SHOW_NO_ANSWER == 1) {
                $answer .= "\t<td class=\"answer-item radio-item noanswer-item\">\n<label for=\"answer{$myfname}-\">\n" . "\t<input class=\"radio\" type=\"radio\" name=\"{$myfname}\" value=\"\" id=\"answer{$myfname}-\" title=\"" . $clang->gT('No answer') . '"';
                if (!isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname]) || $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname] == '') {
                    $answer .= CHECKED;
                }
                // --> START NEW FEATURE - SAVE
                $answer .= " onclick=\"{$checkconditionFunction}(this.value, this.name, this.type)\"  />\n</label>\n\t</td>\n";
                // --> END NEW FEATURE - SAVE
            }
            $answer .= "</tr>\n";
            $inputnames[] = $myfname;
            //IF a MULTIPLE of flexi-redisplay figure, repeat the headings
        }
        $answer .= "</tbody>\n";
        $answer_cols = "\t<colgroup class=\"col-responses\">\n" . "\t<col class=\"col-answers\" width=\"{$answerwidth}%\" />\n";
        $odd_even = '';
        foreach ($labelans as $c) {
            $odd_even = alternation($odd_even);
            $answer_cols .= "<col class=\"{$odd_even}\" width=\"{$cellwidth}%\" />\n";
        }
        if ($right_exists) {
            $odd_even = alternation($odd_even);
            $answer_cols .= "<col class=\"answertextright {$odd_even}\" width=\"{$answerwidth}%\" />\n";
        }
        if ($ia[6] != 'Y' && SHOW_NO_ANSWER == 1) {
            $odd_even = alternation($odd_even);
            $answer_cols .= "<col class=\"col-no-answer {$odd_even}\" width=\"{$cellwidth}%\" />\n";
        }
        $answer_cols .= "\t</colgroup>\n";
        $answer = $answer_start . $answer_cols . $answer_head . $answer . "</table>\n";
    } elseif ($useDropdownLayout === true && count($lresult) > 0) {
        foreach ($lresult as $lrow) {
            $labels[] = array('code' => $lrow->code, 'answer' => $lrow->answer);
        }
        $sQuery = "SELECT count(question) FROM {{questions}} WHERE parent_qid={$ia[0]} AND question like '%|%' ";
        $iCount = Yii::app()->db->createCommand($sQuery)->queryScalar();
        if ($iCount > 0) {
            $right_exists = true;
            $answerwidth = $answerwidth / 2;
        } else {
            $right_exists = false;
        }
        // $right_exists is a flag to find out if there are any right hand answer parts. If there arent we can leave out the right td column
        if ($aQuestionAttributes['random_order'] == 1) {
            $ansquery = "SELECT * FROM {{questions}} WHERE parent_qid={$ia[0]} AND language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "' ORDER BY " . dbRandom();
        } else {
            $ansquery = "SELECT * FROM {{questions}} WHERE parent_qid={$ia[0]} AND language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "' ORDER BY question_order";
        }
        $ansresult = dbExecuteAssoc($ansquery);
        //Checked
        $aQuestions = $ansresult->readAll();
        $anscount = count($aQuestions);
        $fn = 1;
        $numrows = count($labels);
        if ($ia[6] != 'Y' && SHOW_NO_ANSWER == 1) {
            ++$numrows;
        }
        if ($right_exists) {
            ++$numrows;
        }
        $cellwidth = round($columnswidth / $numrows, 1);
        $answer_start = "\n<table class=\"question subquestions-list questions-list {$extraclass}\" summary=\"" . str_replace('"', '', strip_tags($ia[3])) . " - an array type question\" >\n";
        $answer = "\t<tbody>\n";
        $trbc = '';
        $inputnames = array();
        foreach ($aQuestions as $ansrow) {
            $myfname = $ia[1] . $ansrow['title'];
            $trbc = alternation($trbc, 'row');
            $answertext = $ansrow['question'];
            $answertextsave = $answertext;
            if (strpos($answertext, '|')) {
                $answertext = substr($answertext, 0, strpos($answertext, '|'));
            }
            /* Check if this item has not been answered: the 'notanswered' variable must be an array,
               containing a list of unanswered questions, the current question must be in the array,
               and there must be no answer available for the item in this session. */
            if (strpos($answertext, '|')) {
                $answerwidth = $answerwidth / 2;
            }
            if ($ia[6] == 'Y' && is_array($notanswered) && array_search($myfname, $notanswered) !== FALSE && $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname] == '') {
                $answertext = '<span class="errormandatory">' . $answertext . '</span>';
            }
            // Get array_filter stuff
            list($htmltbody2, $hiddenfield) = return_array_filter_strings($ia, $aQuestionAttributes, $thissurvey, $ansrow, $myfname, $trbc, $myfname, "tr", "{$trbc} question-item answer-item dropdown-item");
            $answer .= $htmltbody2;
            $answer .= "\t<th class=\"answertext\">\n{$answertext}" . $hiddenfield . "<input type=\"hidden\" name=\"java{$myfname}\" id=\"java{$myfname}\" value=\"";
            if (isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname])) {
                $answer .= $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname];
            }
            $answer .= "\" />\n\t</th>\n";
            $answer .= "\t<td >\n" . "<select name=\"{$myfname}\" id=\"answer{$myfname}\" onchange=\"{$checkconditionFunction}(this.value, this.name, this.type);\">\n";
            if (!isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname]) || $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname] == '') {
                $answer .= "\t<option value=\"\" " . SELECTED . '>' . $clang->gT('Please choose') . "...</option>\n";
            }
            foreach ($labels as $lrow) {
                $answer .= "\t<option value=\"" . $lrow['code'] . '" ';
                if (isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname]) && $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname] == $lrow['code']) {
                    $answer .= SELECTED;
                }
                $answer .= '>' . flattenText($lrow['answer']) . "</option>\n";
            }
            // If not mandatory and showanswer, show no ans
            if ($ia[6] != 'Y' && SHOW_NO_ANSWER == 1) {
                $answer .= "\t<option value=\"\" ";
                if (!isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname]) || $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname] == '') {
                    $answer .= SELECTED;
                }
                $answer .= '>' . $clang->gT('No answer') . "</option>\n";
            }
            $answer .= "</select>\n";
            if (strpos($answertextsave, '|')) {
                $answertext = substr($answertextsave, strpos($answertextsave, '|') + 1);
                $answer .= "\t<th class=\"answertextright\">{$answertext}</th>\n";
            } elseif ($right_exists) {
                $answer .= "\t<td class=\"answertextright\">&nbsp;</td>\n";
            }
            $answer .= "</tr>\n";
            $inputnames[] = $myfname;
            //IF a MULTIPLE of flexi-redisplay figure, repeat the headings
            $fn++;
        }
        $answer .= "\t</tbody>";
        $answer = $answer_start . $answer . "\n</table>\n";
    } else {
        $answer = "\n<p class=\"error\">" . $clang->gT("Error: There are no answer options for this question and/or they don't exist in this language.") . "</p>\n";
        $inputnames = '';
    }
    return array($answer, $inputnames);
}
 /**
  * Database::index()
  *
  * @param mixed $action
  * @return
  */
 function index($sa = null)
 {
     $action = Yii::app()->request->getPost('action');
     $clang = $this->getController()->lang;
     $postsid = returnGlobal('sid');
     $postgid = returnGlobal('gid');
     $postqid = returnGlobal('qid');
     $postqaid = returnGlobal('qaid');
     $databaseoutput = '';
     $surveyid = returnGlobal('sid');
     $gid = returnGlobal('gid');
     $qid = returnGlobal('qid');
     // if $action is not passed, check post data.
     if (Yii::app()->getConfig('filterxsshtml') && Yii::app()->session['USER_RIGHT_SUPERADMIN'] != 1) {
         $filter = new CHtmlPurifier();
         $filter->options = array('URI.AllowedSchemes' => array('http' => true, 'https' => true));
         $xssfilter = true;
     } else {
         $xssfilter = false;
     }
     if ($action == "updatedefaultvalues" && hasSurveyPermission($surveyid, 'surveycontent', 'update')) {
         $questlangs = Survey::model()->findByPk($surveyid)->additionalLanguages;
         $baselang = Survey::model()->findByPk($surveyid)->language;
         array_unshift($questlangs, $baselang);
         Questions::model()->updateAll(array('same_default' => Yii::app()->request->getPost('samedefault') ? 1 : 0), 'sid=:sid ANd qid=:qid', array(':sid' => $surveyid, ':qid' => $qid));
         $resrow = Questions::model()->findByAttributes(array('qid' => $qid));
         $questiontype = $resrow['type'];
         $qtproperties = getQuestionTypeList('', 'array');
         if ($qtproperties[$questiontype]['answerscales'] > 0 && $qtproperties[$questiontype]['subquestions'] == 0) {
             for ($scale_id = 0; $scale_id < $qtproperties[$questiontype]['answerscales']; $scale_id++) {
                 foreach ($questlangs as $language) {
                     if (!is_null(Yii::app()->request->getPost('defaultanswerscale_' . $scale_id . '_' . $language))) {
                         $this->_updateDefaultValues($qid, 0, $scale_id, '', $language, Yii::app()->request->getPost('defaultanswerscale_' . $scale_id . '_' . $language), true);
                     }
                     if (!is_null(Yii::app()->request->getPost('other_' . $scale_id . '_' . $language))) {
                         $this->_updateDefaultValues($qid, 0, $scale_id, 'other', $language, Yii::app()->request->getPost('other_' . $scale_id . '_' . $language), true);
                     }
                 }
             }
         }
         if ($qtproperties[$questiontype]['subquestions'] > 0) {
             foreach ($questlangs as $language) {
                 $sqresult = Questions::model()->findAllByAttributes(array('sid' => $surveyid, 'gid' => $gid, 'parent_qid' => $qid, 'language' => $language, 'scale_id' => 0));
                 for ($scale_id = 0; $scale_id < $qtproperties[$questiontype]['subquestions']; $scale_id++) {
                     foreach ($sqresult as $aSubquestionrow) {
                         if (!is_null(Yii::app()->request->getPost('defaultanswerscale_' . $scale_id . '_' . $language . '_' . $aSubquestionrow['qid']))) {
                             $this->_updateDefaultValues($qid, $aSubquestionrow['qid'], $scale_id, '', $language, Yii::app()->request->getPost('defaultanswerscale_' . $scale_id . '_' . $language . '_' . $aSubquestionrow['qid']), true);
                         }
                     }
                 }
             }
         }
         if ($qtproperties[$questiontype]['answerscales'] == 0 && $qtproperties[$questiontype]['subquestions'] == 0) {
             foreach ($questlangs as $language) {
                 if (!is_null(Yii::app()->request->getPost('defaultanswerscale_0_' . $language . '_0'))) {
                     $this->_updateDefaultValues($postqid, 0, 0, '', $language, Yii::app()->request->getPost('defaultanswerscale_0_' . $language . '_0'), true);
                 }
             }
         }
         Yii::app()->session['flashmessage'] = $clang->gT("Default value settings were successfully saved.");
         LimeExpressionManager::SetDirtyFlag();
         if ($databaseoutput != '') {
             echo $databaseoutput;
         } else {
             $this->getController()->redirect($this->getController()->createUrl('admin/survey/sa/view/surveyid/' . $surveyid . '/gid/' . $gid . '/qid/' . $qid));
         }
     }
     if ($action == "updateansweroptions" && hasSurveyPermission($surveyid, 'surveycontent', 'update')) {
         Yii::app()->loadHelper('database');
         $anslangs = Survey::model()->findByPk($surveyid)->additionalLanguages;
         $baselang = Survey::model()->findByPk($surveyid)->language;
         $alllanguages = $anslangs;
         array_unshift($alllanguages, $baselang);
         $resrow = Questions::model()->findByAttributes(array('qid' => $qid));
         $questiontype = $resrow['type'];
         // Checked)
         $qtypes = getQuestionTypeList('', 'array');
         $scalecount = $qtypes[$questiontype]['answerscales'];
         $count = 0;
         $invalidCode = 0;
         $duplicateCode = 0;
         //require_once("../classes/inputfilter/class.inputfilter_clean.php");
         //$myFilter = new InputFilter('','',1,1,1);
         //First delete all answers
         Answers::model()->deleteAllByAttributes(array('qid' => $qid));
         LimeExpressionManager::RevertUpgradeConditionsToRelevance($surveyid);
         for ($scale_id = 0; $scale_id < $scalecount; $scale_id++) {
             $maxcount = (int) Yii::app()->request->getPost('answercount_' . $scale_id);
             for ($sortorderid = 1; $sortorderid < $maxcount; $sortorderid++) {
                 $code = sanitize_paranoid_string(Yii::app()->request->getPost('code_' . $sortorderid . '_' . $scale_id));
                 if (Yii::app()->request->getPost('oldcode_' . $sortorderid . '_' . $scale_id)) {
                     $oldcode = sanitize_paranoid_string(Yii::app()->request->getPost('oldcode_' . $sortorderid . '_' . $scale_id));
                     if ($code !== $oldcode) {
                         Conditions::model()->updateAll(array('value' => $code), 'cqid=:cqid AND value=:value', array(':cqid' => $qid, ':value' => $oldcode));
                     }
                 }
                 $assessmentvalue = (int) Yii::app()->request->getPost('assessment_' . $sortorderid . '_' . $scale_id);
                 foreach ($alllanguages as $language) {
                     $answer = Yii::app()->request->getPost('answer_' . $language . '_' . $sortorderid . '_' . $scale_id);
                     if ($xssfilter) {
                         $answer = $filter->purify($answer);
                     } else {
                         $answer = html_entity_decode($answer, ENT_QUOTES, "UTF-8");
                     }
                     // Fix bug with FCKEditor saving strange BR types
                     $answer = fixCKeditorText($answer);
                     // Now we insert the answers
                     $result = Answers::model()->insertRecords(array('code' => $code, 'answer' => $answer, 'qid' => $qid, 'sortorder' => $sortorderid, 'language' => $language, 'assessment_value' => $assessmentvalue, 'scale_id' => $scale_id));
                     if (!$result) {
                         $databaseoutput .= "<script type=\"text/javascript\">\n<!--\n alert(\"" . $clang->gT("Failed to update answers", "js") . "\")\n //-->\n</script>\n";
                     }
                 }
                 // foreach ($alllanguages as $language)
                 if (isset($oldcode) && $code !== $oldcode) {
                     Conditions::model()->updateAll(array('value' => $code), 'cqid=:cqid AND value=:value', array(':cqid' => $qid, ':value' => $oldcode));
                 }
             }
             // for ($sortorderid=0;$sortorderid<$maxcount;$sortorderid++)
         }
         //  for ($scale_id=0;
         LimeExpressionManager::UpgradeConditionsToRelevance($surveyid);
         if ($invalidCode == 1) {
             $databaseoutput .= "<script type=\"text/javascript\">\n<!--\n alert(\"" . $clang->gT("Answers with a code of 0 (zero) or blank code are not allowed, and will not be saved", "js") . "\")\n //-->\n</script>\n";
         }
         if ($duplicateCode == 1) {
             $databaseoutput .= "<script type=\"text/javascript\">\n<!--\n alert(\"" . $clang->gT("Duplicate codes found, these entries won't be updated", "js") . "\")\n //-->\n</script>\n";
         }
         Yii::app()->session['flashmessage'] = $clang->gT("Answer options were successfully saved.");
         LimeExpressionManager::SetDirtyFlag();
         if ($databaseoutput != '') {
             echo $databaseoutput;
         } else {
             $this->getController()->redirect($this->getController()->createUrl('/admin/question/sa/answeroptions/surveyid/' . $surveyid . '/gid/' . $gid . '/qid/' . $qid));
         }
         //$action='editansweroptions';
     }
     if ($action == "updatesubquestions" && hasSurveyPermission($surveyid, 'surveycontent', 'update')) {
         Yii::app()->loadHelper('database');
         $anslangs = Survey::model()->findByPk($surveyid)->additionalLanguages;
         $baselang = Survey::model()->findByPk($surveyid)->language;
         array_unshift($anslangs, $baselang);
         $row = Questions::model()->findByAttributes(array('qid' => $qid));
         $questiontype = $row['type'];
         // Checked
         $qtypes = getQuestionTypeList('', 'array');
         $scalecount = $qtypes[$questiontype]['subquestions'];
         $clang = $this->getController()->lang;
         // First delete any deleted ids
         $deletedqids = explode(' ', trim(Yii::app()->request->getPost('deletedqids')));
         LimeExpressionManager::RevertUpgradeConditionsToRelevance($surveyid);
         foreach ($deletedqids as $deletedqid) {
             $deletedqid = (int) $deletedqid;
             if ($deletedqid > 0) {
                 // don't remove undefined
                 $result = Questions::model()->deleteAllByAttributes(array('qid' => $deletedqid));
                 if (!$result) {
                     $databaseoutput .= "<script type=\"text/javascript\">\n<!--\n alert(\"" . $clang->gT("Failed to delete answer", "js") . " \")\n //-->\n</script>\n";
                 }
             }
         }
         //Determine ids by evaluating the hidden field
         $rows = array();
         $codes = array();
         $oldcodes = array();
         foreach ($_POST as $postkey => $postvalue) {
             $postkey = explode('_', $postkey);
             if ($postkey[0] == 'answer') {
                 $rows[$postkey[3]][$postkey[1]][$postkey[2]] = $postvalue;
             }
             if ($postkey[0] == 'code') {
                 $codes[$postkey[2]][] = $postvalue;
             }
             if ($postkey[0] == 'oldcode') {
                 $oldcodes[$postkey[2]][] = $postvalue;
             }
         }
         $count = 0;
         $invalidCode = 0;
         $duplicateCode = 0;
         $dupanswers = array();
         /*
         for ($scale_id=0;$scale_id<$scalecount;$scale_id++)
         {
         
         // Find duplicate codes and add these to dupanswers array
         $foundCat=array_count_values($codes);
         foreach($foundCat as $key=>$value){
         if($value>=2){
         $dupanswers[]=$key;
         }
         }
         }
         */
         //require_once("../classes/inputfilter/class.inputfilter_clean.php");
         //$myFilter = new InputFilter('','',1,1,1);
         //$insertqids=array(); //?
         $insertqid = array();
         for ($scale_id = 0; $scale_id < $scalecount; $scale_id++) {
             foreach ($anslangs as $language) {
                 $position = 0;
                 foreach ($rows[$scale_id][$language] as $subquestionkey => $subquestionvalue) {
                     if (substr($subquestionkey, 0, 3) != 'new') {
                         Questions::model()->updateByPk(array('qid' => $subquestionkey, 'language' => $language), array('question_order' => $position + 1, 'title' => $codes[$scale_id][$position], 'question' => $subquestionvalue, 'scale_id' => $scale_id));
                         if (isset($oldcodes[$scale_id][$position]) && $codes[$scale_id][$position] !== $oldcodes[$scale_id][$position]) {
                             Conditions::model()->updateAll(array('cfieldname' => '+' . $surveyid . 'X' . $gid . 'X' . $qid . $codes[$scale_id][$position], 'value' => $codes[$scale_id][$position]), 'cqid=:cqid AND cfieldname=:cfieldname AND value=:value', array(':cqid' => $qid, ':cfieldname' => $surveyid . 'X' . $gid . 'X' . $qid, ':value' => $oldcodes[$scale_id][$position]));
                         }
                     } else {
                         if (!isset($insertqid[$scale_id][$position])) {
                             $insertqid[$scale_id][$position] = Questions::model()->insertRecords(array('sid' => $surveyid, 'gid' => $gid, 'question_order' => $position + 1, 'title' => $codes[$scale_id][$position], 'question' => $subquestionvalue, 'parent_qid' => $qid, 'language' => $language, 'scale_id' => $scale_id));
                         } else {
                             switchMSSQLIdentityInsert('questions', true);
                             Questions::model()->insertRecords(array('qid' => $insertqid[$scale_id][$position], 'sid' => $surveyid, 'gid' => $gid, 'question_order' => $position + 1, 'title' => $codes[$scale_id][$position], 'question' => $subquestionvalue, 'parent_qid' => $qid, 'language' => $language, 'scale_id' => $scale_id));
                             switchMSSQLIdentityInsert('questions', true);
                         }
                     }
                     $position++;
                 }
             }
         }
         LimeExpressionManager::UpgradeConditionsToRelevance($surveyid);
         //include("surveytable_functions.php");
         //surveyFixColumns($surveyid);
         Yii::app()->session['flashmessage'] = $clang->gT("Subquestions were successfully saved.");
         //$action='editsubquestions';
         LimeExpressionManager::SetDirtyFlag();
         if ($databaseoutput != '') {
             echo $databaseoutput;
         } else {
             $this->getController()->redirect($this->getController()->createUrl('/admin/question/sa/subquestions/surveyid/' . $surveyid . '/gid/' . $gid . '/qid/' . $qid));
         }
     }
     if (in_array($action, array('insertquestion', 'copyquestion')) && hasSurveyPermission($surveyid, 'surveycontent', 'create')) {
         $baselang = Survey::model()->findByPk($surveyid)->language;
         if (strlen(Yii::app()->request->getPost('title')) < 1) {
             $databaseoutput .= "<script type=\"text/javascript\">\n<!--\n " . "alert(\"" . $clang->gT("The question could not be added. You must enter at least a question code.", "js") . "\")\n " . "//-->\n</script>\n";
         } else {
             if (Yii::app()->request->getPost('questionposition', "") != "") {
                 $question_order = intval(Yii::app()->request->getPost('questionposition'));
                 //Need to renumber all questions on or after this
                 $cdquery = "UPDATE {{questions}} SET question_order=question_order+1 WHERE gid=:gid AND question_order >= :order";
                 $cdresult = Yii::app()->db->createCommand($cdquery)->bindValues(array(':gid' => $gid, ':order' => $question_order))->query();
             } else {
                 $question_order = getMaxQuestionOrder($gid, $surveyid);
                 $question_order++;
             }
             $_POST['title'] = html_entity_decode(Yii::app()->request->getPost('title'), ENT_QUOTES, "UTF-8");
             $_POST['question_' . $baselang] = html_entity_decode(Yii::app()->request->getPost('question_' . $baselang), ENT_QUOTES, "UTF-8");
             $_POST['help_' . $baselang] = html_entity_decode(Yii::app()->request->getPost('help_' . $baselang), ENT_QUOTES, "UTF-8");
             // Fix bug with FCKEditor saving strange BR types
             if ($xssfilter) {
                 $_POST['title'] = $filter->purify($_POST['title']);
                 $_POST['question_' . $baselang] = $filter->purify($_POST['question_' . $baselang]);
                 $_POST['help_' . $baselang] = $filter->purify($_POST['help_' . $baselang]);
             } else {
                 $_POST['title'] = fixCKeditorText(Yii::app()->request->getPost('title'));
                 $_POST['question_' . $baselang] = fixCKeditorText(Yii::app()->request->getPost('question_' . $baselang));
                 $_POST['help_' . $baselang] = fixCKeditorText(Yii::app()->request->getPost('help_' . $baselang));
             }
             $data = array('sid' => $surveyid, 'gid' => $gid, 'type' => Yii::app()->request->getPost('type'), 'title' => Yii::app()->request->getPost('title'), 'question' => Yii::app()->request->getPost('question_' . $baselang), 'preg' => Yii::app()->request->getPost('preg'), 'help' => Yii::app()->request->getPost('help_' . $baselang), 'other' => Yii::app()->request->getPost('other'), 'mandatory' => Yii::app()->request->getPost('mandatory'), 'relevance' => Yii::app()->request->getPost('relevance'), 'question_order' => $question_order, 'language' => $baselang);
             $qid = Questions::model()->insertRecords($data);
             // Add other languages
             if ($qid) {
                 $addlangs = Survey::model()->findByPk($surveyid)->additionalLanguages;
                 foreach ($addlangs as $alang) {
                     if ($alang != "") {
                         $data = array('qid' => $qid, 'sid' => $surveyid, 'gid' => $gid, 'type' => Yii::app()->request->getPost('type'), 'title' => Yii::app()->request->getPost('title'), 'question' => Yii::app()->request->getPost('question_' . $alang), 'preg' => Yii::app()->request->getPost('preg'), 'help' => Yii::app()->request->getPost('help_' . $alang), 'other' => Yii::app()->request->getPost('other'), 'mandatory' => Yii::app()->request->getPost('mandatory'), 'question_order' => $question_order, 'language' => $alang);
                         $langqid = Questions::model()->insertRecords($data);
                         // Checked */
                         if (!$langqid) {
                             $databaseoutput .= "<script type=\"text/javascript\">\n<!--\n alert(\"" . sprintf($clang->gT("Question in language %s could not be created.", "js"), $alang) . "\\n\")\n //-->\n</script>\n";
                         }
                     }
                 }
             }
             if (!$qid) {
                 $databaseoutput .= "<script type=\"text/javascript\">\n<!--\n alert(\"" . $clang->gT("Question could not be created.", "js") . "\\n\")\n //-->\n</script>\n";
             } else {
                 if ($action == 'copyquestion') {
                     if (returnGlobal('copysubquestions') == "Y") {
                         $aSQIDMappings = array();
                         $r1 = Questions::model()->getSubQuestions(returnGlobal('oldqid'));
                         while ($qr1 = $r1->read()) {
                             $qr1['parent_qid'] = $qid;
                             if (isset($aSQIDMappings[$qr1['qid']])) {
                                 $qr1['qid'] = $aSQIDMappings[$qr1['qid']];
                             } else {
                                 $oldqid = $qr1['qid'];
                                 unset($qr1['qid']);
                             }
                             $qr1['gid'] = $postgid;
                             $iInsertID = Questions::model()->insertRecords($qr1);
                             if (!isset($qr1['qid'])) {
                                 $aSQIDMappings[$oldqid] = $iInsertID;
                             }
                         }
                     }
                     if (returnGlobal('copyanswers') == "Y") {
                         $r1 = Answers::model()->getAnswers(returnGlobal('oldqid'));
                         while ($qr1 = $r1->read()) {
                             Answers::model()->insertRecords(array('qid' => $qid, 'code' => $qr1['code'], 'answer' => $qr1['answer'], 'sortorder' => $qr1['sortorder'], 'language' => $qr1['language'], 'scale_id' => $qr1['scale_id']));
                         }
                     }
                     if (returnGlobal('copyattributes') == "Y") {
                         $r1 = Question_attributes::model()->getQuestionAttributes(returnGlobal('oldqid'));
                         while ($qr1 = $r1->read()) {
                             $qr1['qid'] = $qid;
                             unset($qr1['qaid']);
                             Question_attributes::model()->insertRecords($qr1);
                         }
                     }
                 } else {
                     $qattributes = questionAttributes();
                     $validAttributes = $qattributes[Yii::app()->request->getPost('type')];
                     $aLanguages = array_merge(array(Survey::model()->findByPk($surveyid)->language), Survey::model()->findByPk($surveyid)->additionalLanguages);
                     foreach ($validAttributes as $validAttribute) {
                         if ($validAttribute['i18n']) {
                             foreach ($aLanguages as $sLanguage) {
                                 // TODO sanitise XSS
                                 $value = Yii::app()->request->getPost($validAttribute['name'] . '_' . $sLanguage);
                                 $result = Question_attributes::model()->findAllByAttributes(array('attribute' => $validAttribute['name'], 'qid' => $qid, 'language' => $sLanguage));
                                 if (count($result) > 0) {
                                     if ($value != '') {
                                         Question_attributes::model()->updateAll(array('value' => $value), 'attribute=:attribute AND qid=:qid AND language=:language', array(':attribute' => $validAttribute['name'], ':qid' => $qid, ':language' => $sLanguage));
                                     } else {
                                         Question_attributes::model()->deleteAll('attribute=:attribute AND qid=:qid AND language=:language', array(':attribute' => $validAttribute['name'], ':qid' => $qid, ':language' => $sLanguage));
                                     }
                                 } elseif ($value != '') {
                                     $attribute = new Question_attributes();
                                     $attribute->qid = $qid;
                                     $attribute->value = $value;
                                     $attribute->attribute = $validAttribute['name'];
                                     $attribute->language = $sLanguage;
                                     $attribute->save();
                                 }
                             }
                         } else {
                             $value = Yii::app()->request->getPost($validAttribute['name']);
                             if ($validAttribute['name'] == 'multiflexible_step' && trim($value) != '') {
                                 $value = floatval($value);
                                 if ($value == 0) {
                                     $value = 1;
                                 }
                             }
                             $result = Question_attributes::model()->findAllByAttributes(array('attribute' => $validAttribute['name'], 'qid' => $qid));
                             if (count($result) > 0) {
                                 if ($value != $validAttribute['default'] && trim($value) != "") {
                                     Question_attributes::model()->updateAll(array('value' => $value), 'attribute=:attribute AND qid=:qid', array(':attribute' => $validAttribute['name'], ':qid' => $qid));
                                 } else {
                                     Question_attributes::model()->deleteAll('attribute=:attribute AND qid=:qid', array(':attribute' => $validAttribute['name'], ':qid' => $qid));
                                 }
                             } elseif ($value != $validAttribute['default'] && trim($value) != "") {
                                 $attribute = new Question_attributes();
                                 $attribute->qid = $qid;
                                 $attribute->value = $value;
                                 $attribute->attribute = $validAttribute['name'];
                                 $attribute->save();
                             }
                         }
                     }
                 }
                 Questions::model()->updateQuestionOrder($gid, $surveyid);
                 Yii::app()->session['flashmessage'] = $clang->gT("Question was successfully added.");
             }
         }
         LimeExpressionManager::SetDirtyFlag();
         // so refreshes syntax highlighting
         if ($databaseoutput != '') {
             echo $databaseoutput;
         } else {
             $this->getController()->redirect($this->getController()->createUrl('admin/survey/sa/view/surveyid/' . $surveyid . '/gid/' . $gid . '/qid/' . $qid));
         }
     }
     if ($action == "updatequestion" && hasSurveyPermission($surveyid, 'surveycontent', 'update')) {
         LimeExpressionManager::RevertUpgradeConditionsToRelevance($surveyid);
         $cqr = Questions::model()->findByAttributes(array('qid' => $qid));
         $oldtype = $cqr['type'];
         $oldgid = $cqr['gid'];
         // Remove invalid question attributes on saving
         $qattributes = questionAttributes();
         $criteria = new CDbCriteria();
         $criteria->compare('qid', $qid);
         if (isset($qattributes[Yii::app()->request->getPost('type')])) {
             $validAttributes = $qattributes[Yii::app()->request->getPost('type')];
             foreach ($validAttributes as $validAttribute) {
                 $criteria->compare('attribute', '<>' . $validAttribute['name']);
             }
         }
         Question_attributes::model()->deleteAll($criteria);
         $aLanguages = array_merge(array(Survey::model()->findByPk($surveyid)->language), Survey::model()->findByPk($surveyid)->additionalLanguages);
         //now save all valid attributes
         $validAttributes = $qattributes[Yii::app()->request->getPost('type')];
         foreach ($validAttributes as $validAttribute) {
             if ($validAttribute['i18n']) {
                 foreach ($aLanguages as $sLanguage) {
                     // TODO sanitise XSS
                     $value = Yii::app()->request->getPost($validAttribute['name'] . '_' . $sLanguage);
                     $result = Question_attributes::model()->findAllByAttributes(array('attribute' => $validAttribute['name'], 'qid' => $qid, 'language' => $sLanguage));
                     if (count($result) > 0) {
                         if ($value != '') {
                             Question_attributes::model()->updateAll(array('value' => $value), 'attribute=:attribute AND qid=:qid AND language=:language', array(':attribute' => $validAttribute['name'], ':qid' => $qid, ':language' => $sLanguage));
                         } else {
                             Question_attributes::model()->deleteAll('attribute=:attribute AND qid=:qid AND language=:language', array(':attribute' => $validAttribute['name'], ':qid' => $qid, ':language' => $sLanguage));
                         }
                     } elseif ($value != '') {
                         $attribute = new Question_attributes();
                         $attribute->qid = $qid;
                         $attribute->value = $value;
                         $attribute->attribute = $validAttribute['name'];
                         $attribute->language = $sLanguage;
                         $attribute->save();
                     }
                 }
             } else {
                 $value = Yii::app()->request->getPost($validAttribute['name']);
                 if ($validAttribute['name'] == 'multiflexible_step' && trim($value) != '') {
                     $value = floatval($value);
                     if ($value == 0) {
                         $value = 1;
                     }
                 }
                 $result = Question_attributes::model()->findAllByAttributes(array('attribute' => $validAttribute['name'], 'qid' => $qid));
                 if (count($result) > 0) {
                     if ($value != $validAttribute['default'] && trim($value) != "") {
                         Question_attributes::model()->updateAll(array('value' => $value), 'attribute=:attribute AND qid=:qid', array(':attribute' => $validAttribute['name'], ':qid' => $qid));
                     } else {
                         Question_attributes::model()->deleteAll('attribute=:attribute AND qid=:qid', array(':attribute' => $validAttribute['name'], ':qid' => $qid));
                     }
                 } elseif ($value != $validAttribute['default'] && trim($value) != "") {
                     $attribute = new Question_attributes();
                     $attribute->qid = $qid;
                     $attribute->value = $value;
                     $attribute->attribute = $validAttribute['name'];
                     $attribute->save();
                 }
             }
         }
         $qtypes = getQuestionTypeList('', 'array');
         // These are the questions types that have no answers and therefore we delete the answer in that case
         $iAnswerScales = $qtypes[Yii::app()->request->getPost('type')]['answerscales'];
         $iSubquestionScales = $qtypes[Yii::app()->request->getPost('type')]['subquestions'];
         // These are the questions types that have the other option therefore we set everything else to 'No Other'
         if (Yii::app()->request->getPost('type') != "L" && Yii::app()->request->getPost('type') != "!" && Yii::app()->request->getPost('type') != "P" && Yii::app()->request->getPost('type') != "M") {
             $_POST['other'] = 'N';
         }
         // These are the questions types that have no validation - so zap it accordingly
         if (Yii::app()->request->getPost('type') == "!" || Yii::app()->request->getPost('type') == "L" || Yii::app()->request->getPost('type') == "M" || Yii::app()->request->getPost('type') == "P" || Yii::app()->request->getPost('type') == "F" || Yii::app()->request->getPost('type') == "H" || Yii::app()->request->getPost('type') == "X" || Yii::app()->request->getPost('type') == "") {
             $_POST['preg'] = '';
         }
         // These are the questions types that have no mandatory property - so zap it accordingly
         if (Yii::app()->request->getPost('type') == "X" || Yii::app()->request->getPost('type') == "|") {
             $_POST['mandatory'] = 'N';
         }
         if ($oldtype != Yii::app()->request->getPost('type')) {
             // TMSW Conditions->Relevance:  Do similar check via EM, but do allow such a change since will be easier to modify relevance
             //Make sure there are no conditions based on this question, since we are changing the type
             $ccresult = Conditions::model()->findAllByAttributes(array('cqid' => $qid));
             $cccount = count($ccresult);
             foreach ($ccresult as $ccr) {
                 $qidarray[] = $ccr['qid'];
             }
             if (isset($qidarray) && $qidarray) {
                 $qidlist = implode(", ", $qidarray);
             }
         }
         if (isset($cccount) && $cccount) {
             $databaseoutput .= "<script type=\"text/javascript\">\n<!--\n alert(\"" . $clang->gT("Question could not be updated. There are conditions for other questions that rely on the answers to this question and changing the type will cause problems. You must delete these conditions before you can change the type of this question.", "js") . " ({$qidlist})\")\n //-->\n</script>\n";
         } else {
             if (isset($gid) && $gid != "") {
                 //                    $array_result=checkMoveQuestionConstraintsForConditions(sanitize_int($surveyid),sanitize_int($qid), sanitize_int($gid));
                 //                    // If there is no blocking conditions that could prevent this move
                 //
                 //                    if (is_null($array_result['notAbove']) && is_null($array_result['notBelow']))
                 //                    {
                 $questlangs = Survey::model()->findByPk($surveyid)->additionalLanguages;
                 $baselang = Survey::model()->findByPk($surveyid)->language;
                 array_push($questlangs, $baselang);
                 if ($xssfilter) {
                     $_POST['title'] = $filter->purify($_POST['title']);
                 } else {
                     $_POST['title'] = html_entity_decode(Yii::app()->request->getPost('title'), ENT_QUOTES, "UTF-8");
                 }
                 // Fix bug with FCKEditor saving strange BR types
                 $_POST['title'] = fixCKeditorText(Yii::app()->request->getPost('title'));
                 foreach ($questlangs as $qlang) {
                     if ($xssfilter) {
                         $_POST['question_' . $qlang] = $filter->purify($_POST['question_' . $qlang]);
                         $_POST['help_' . $qlang] = $filter->purify($_POST['help_' . $qlang]);
                     } else {
                         $_POST['question_' . $qlang] = html_entity_decode(Yii::app()->request->getPost('question_' . $qlang), ENT_QUOTES, "UTF-8");
                         $_POST['help_' . $qlang] = html_entity_decode(Yii::app()->request->getPost('help_' . $qlang), ENT_QUOTES, "UTF-8");
                     }
                     // Fix bug with FCKEditor saving strange BR types
                     $_POST['question_' . $qlang] = fixCKeditorText(Yii::app()->request->getPost('question_' . $qlang));
                     $_POST['help_' . $qlang] = fixCKeditorText(Yii::app()->request->getPost('help_' . $qlang));
                     if (isset($qlang) && $qlang != "") {
                         // ToDo: Sanitize the POST variables !
                         $udata = array('type' => Yii::app()->request->getPost('type'), 'title' => Yii::app()->request->getPost('title'), 'question' => Yii::app()->request->getPost('question_' . $qlang), 'preg' => Yii::app()->request->getPost('preg'), 'help' => Yii::app()->request->getPost('help_' . $qlang), 'gid' => $gid, 'other' => Yii::app()->request->getPost('other'), 'mandatory' => Yii::app()->request->getPost('mandatory'), 'relevance' => Yii::app()->request->getPost('relevance'));
                         if ($oldgid != $gid) {
                             if (getGroupOrder($surveyid, $oldgid) > getGroupOrder($surveyid, $gid)) {
                                 // TMSW Conditions->Relevance:  What is needed here?
                                 // Moving question to a 'upper' group
                                 // insert question at the end of the destination group
                                 // this prevent breaking conditions if the target qid is in the dest group
                                 $insertorder = getMaxQuestionOrder($gid, $surveyid) + 1;
                                 $udata = array_merge($udata, array('question_order' => $insertorder));
                             } else {
                                 // Moving question to a 'lower' group
                                 // insert question at the beginning of the destination group
                                 shiftOrderQuestions($surveyid, $gid, 1);
                                 // makes 1 spare room for new question at top of dest group
                                 $udata = array_merge($udata, array('question_order' => 0));
                             }
                         }
                         $condn = array('sid' => $surveyid, 'qid' => $qid, 'language' => $qlang);
                         $question = Questions::model()->findByAttributes($condn);
                         foreach ($udata as $k => $v) {
                             $question->{$k} = $v;
                         }
                         $uqresult = $question->save();
                         //($uqquery); // or safeDie ("Error Update Question: ".$uqquery."<br />");  // Checked)
                         if (!$uqresult) {
                             $databaseoutput .= "<script type=\"text/javascript\">\n<!--\n alert(\"" . $clang->gT("Question could not be updated", "js") . "\n\")\n //-->\n</script>\n";
                         }
                     }
                 }
                 // Update the group ID on subquestions, too
                 if ($oldgid != $gid) {
                     Questions::model()->updateAll(array('gid' => $gid), 'qid=:qid and parent_qid>0', array(':qid' => $qid));
                     // if the group has changed then fix the sortorder of old and new group
                     Questions::model()->updateQuestionOrder($oldgid, $surveyid);
                     Questions::model()->updateQuestionOrder($gid, $surveyid);
                     // If some questions have conditions set on this question's answers
                     // then change the cfieldname accordingly
                     fixMovedQuestionConditions($qid, $oldgid, $gid);
                 }
                 if ($oldtype != Yii::app()->request->getPost('type')) {
                     Questions::model()->updateAll(array('type' => Yii::app()->request->getPost('type')), 'parent_qid=:qid', array(':qid' => $qid));
                 }
                 Answers::model()->deleteAllByAttributes(array('qid' => $qid), 'scale_id >= :scale_id', array(':scale_id' => $iAnswerScales));
                 // Remove old subquestion scales
                 Questions::model()->deleteAllByAttributes(array('parent_qid' => $qid), 'scale_id >= :scale_id', array(':scale_id' => $iSubquestionScales));
                 Yii::app()->session['flashmessage'] = $clang->gT("Question was successfully saved.");
                 //                    }
                 //                    else
                 //                    {
                 //
                 //                        // There are conditions constraints: alert the user
                 //                        $errormsg="";
                 //                        if (!is_null($array_result['notAbove']))
                 //                        {
                 //                            $errormsg.=$clang->gT("This question relies on other question's answers and can't be moved above groupId:","js")
                 //                            . " " . $array_result['notAbove'][0][0] . " " . $clang->gT("in position","js")." ".$array_result['notAbove'][0][1]."\\n"
                 //                            . $clang->gT("See conditions:")."\\n";
                 //
                 //                            foreach ($array_result['notAbove'] as $notAboveCond)
                 //                            {
                 //                                $errormsg.="- cid:". $notAboveCond[3]."\\n";
                 //                            }
                 //
                 //                        }
                 //                        if (!is_null($array_result['notBelow']))
                 //                        {
                 //                            $errormsg.=$clang->gT("Some questions rely on this question's answers. You can't move this question below groupId:","js")
                 //                            . " " . $array_result['notBelow'][0][0] . " " . $clang->gT("in position","js")." ".$array_result['notBelow'][0][1]."\\n"
                 //                            . $clang->gT("See conditions:")."\\n";
                 //
                 //                            foreach ($array_result['notBelow'] as $notBelowCond)
                 //                            {
                 //                                $errormsg.="- cid:". $notBelowCond[3]."\\n";
                 //                            }
                 //                        }
                 //
                 //                        $databaseoutput .= "<script type=\"text/javascript\">\n<!--\n alert(\"$errormsg\")\n //-->\n</script>\n";
                 //                        $gid= $oldgid; // group move impossible ==> keep display on oldgid
                 //                    }
             } else {
                 $databaseoutput .= "<script type=\"text/javascript\">\n<!--\n alert(\"" . $clang->gT("Question could not be updated", "js") . "\")\n //-->\n</script>\n";
             }
         }
         LimeExpressionManager::UpgradeConditionsToRelevance($surveyid);
         if ($databaseoutput != '') {
             echo $databaseoutput;
         } else {
             if (Yii::app()->request->getPost('newpage') == "return") {
                 $this->getController()->redirect($this->getController()->createUrl('admin/question/sa/editquestion/surveyid/' . $surveyid . '/gid/' . $gid . '/qid/' . $qid));
             } else {
                 $this->getController()->redirect($this->getController()->createUrl('admin/survey/sa/view/surveyid/' . $surveyid . '/gid/' . $gid . '/qid/' . $qid));
             }
         }
     }
     if ($action == "updatesurveylocalesettings" && hasSurveyPermission($surveyid, 'surveylocale', 'update')) {
         $languagelist = Survey::model()->findByPk($surveyid)->additionalLanguages;
         $languagelist[] = Survey::model()->findByPk($surveyid)->language;
         Yii::app()->loadHelper('database');
         foreach ($languagelist as $langname) {
             if ($langname) {
                 $url = Yii::app()->request->getPost('url_' . $langname);
                 if ($url == 'http://') {
                     $url = "";
                 }
                 // Clean XSS attacks
                 if ($xssfilter) {
                     $purifier = new CHtmlPurifier();
                     $purifier->options = array('HTML.Allowed' => 'p,a[href],b,i');
                     $short_title = $purifier->purify(Yii::app()->request->getPost('short_title_' . $langname));
                     $description = $purifier->purify(Yii::app()->request->getPost('description_' . $langname));
                     $welcome = $purifier->purify(Yii::app()->request->getPost('welcome_' . $langname));
                     $endtext = $purifier->purify(Yii::app()->request->getPost('endtext_' . $langname));
                     $sURLDescription = $purifier->purify(Yii::app()->request->getPost('urldescrip_' . $langname));
                     $sURL = $purifier->purify(Yii::app()->request->getPost('url_' . $langname));
                 } else {
                     $short_title = html_entity_decode(Yii::app()->request->getPost('short_title_' . $langname), ENT_QUOTES, "UTF-8");
                     $description = html_entity_decode(Yii::app()->request->getPost('description_' . $langname), ENT_QUOTES, "UTF-8");
                     $welcome = html_entity_decode(Yii::app()->request->getPost('welcome_' . $langname), ENT_QUOTES, "UTF-8");
                     $endtext = html_entity_decode(Yii::app()->request->getPost('endtext_' . $langname), ENT_QUOTES, "UTF-8");
                     $sURLDescription = html_entity_decode(Yii::app()->request->getPost('urldescrip_' . $langname), ENT_QUOTES, "UTF-8");
                     $sURL = html_entity_decode(Yii::app()->request->getPost('url_' . $langname), ENT_QUOTES, "UTF-8");
                 }
                 // Fix bug with FCKEditor saving strange BR types
                 $short_title = Yii::app()->request->getPost('short_title_' . $langname);
                 $description = Yii::app()->request->getPost('description_' . $langname);
                 $welcome = Yii::app()->request->getPost('welcome_' . $langname);
                 $endtext = Yii::app()->request->getPost('endtext_' . $langname);
                 $short_title = fixCKeditorText($short_title);
                 $description = fixCKeditorText($description);
                 $welcome = fixCKeditorText($welcome);
                 $endtext = fixCKeditorText($endtext);
                 $data = array('surveyls_title' => $short_title, 'surveyls_description' => $description, 'surveyls_welcometext' => $welcome, 'surveyls_endtext' => $endtext, 'surveyls_url' => $sURL, 'surveyls_urldescription' => $sURLDescription, 'surveyls_dateformat' => Yii::app()->request->getPost('dateformat_' . $langname), 'surveyls_numberformat' => Yii::app()->request->getPost('numberformat_' . $langname));
                 $Surveys_languagesettings = Surveys_languagesettings::model()->findByPk(array('surveyls_survey_id' => $postsid, 'surveyls_language' => $langname));
                 $Surveys_languagesettings->attributes = $data;
                 $Surveys_languagesettings->save();
                 // save the change to database
             }
         }
         Yii::app()->session['flashmessage'] = $clang->gT("Survey text elements successfully saved.");
         if ($databaseoutput != '') {
             echo $databaseoutput;
         } else {
             $this->getController()->redirect($this->getController()->createUrl('admin/survey/sa/view/surveyid/' . $surveyid));
         }
     }
     if (($action == "updatesurveysettingsandeditlocalesettings" || $action == "updatesurveysettings") && hasSurveyPermission($surveyid, 'surveysettings', 'update')) {
         Yii::app()->loadHelper('surveytranslator');
         Yii::app()->loadHelper('database');
         $formatdata = getDateFormatData(Yii::app()->session['dateformat']);
         $expires = $_POST['expires'];
         if (trim($expires) == "") {
             $expires = null;
         } else {
             Yii::app()->loadLibrary('Date_Time_Converter');
             $datetimeobj = new date_time_converter($expires, $formatdata['phpdate'] . ' H:i');
             //new Date_Time_Converter($expires, $formatdata['phpdate'].' H:i');
             $expires = $datetimeobj->convert("Y-m-d H:i:s");
         }
         $startdate = $_POST['startdate'];
         if (trim($startdate) == "") {
             $startdate = null;
         } else {
             Yii::app()->loadLibrary('Date_Time_Converter');
             $datetimeobj = new date_time_converter($startdate, $formatdata['phpdate'] . ' H:i');
             //new Date_Time_Converter($startdate,$formatdata['phpdate'].' H:i');
             $startdate = $datetimeobj->convert("Y-m-d H:i:s");
         }
         //make sure only numbers are passed within the $_POST variable
         $tokenlength = (int) $_POST['tokenlength'];
         //token length has to be at least 5, otherwise set it to default (15)
         if ($tokenlength < 5) {
             $tokenlength = 15;
         }
         cleanLanguagesFromSurvey($surveyid, Yii::app()->request->getPost('languageids'));
         fixLanguageConsistency($surveyid, Yii::app()->request->getPost('languageids'));
         $template = Yii::app()->request->getPost('template');
         if (Yii::app()->session['USER_RIGHT_SUPERADMIN'] != 1 && Yii::app()->session['USER_RIGHT_MANAGE_TEMPLATE'] != 1 && !hasTemplateManageRights(Yii::app()->session['loginID'], $template)) {
             $template = "default";
         }
         $aURLParams = json_decode(Yii::app()->request->getPost('allurlparams'), true);
         Survey_url_parameters::model()->deleteAllByAttributes(array('sid' => $surveyid));
         foreach ($aURLParams as $aURLParam) {
             $aURLParam['parameter'] = trim($aURLParam['parameter']);
             if ($aURLParam['parameter'] == '' || !preg_match('/^[a-zA-Z_][a-zA-Z0-9_]*$/', $aURLParam['parameter']) || $aURLParam['parameter'] == 'sid' || $aURLParam['parameter'] == 'newtest' || $aURLParam['parameter'] == 'token' || $aURLParam['parameter'] == 'lang') {
                 continue;
                 // this parameter name seems to be invalid - just ignore it
             }
             unset($aURLParam['act']);
             unset($aURLParam['title']);
             unset($aURLParam['id']);
             if ($aURLParam['targetqid'] == '') {
                 $aURLParam['targetqid'] = NULL;
             }
             if ($aURLParam['targetsqid'] == '') {
                 $aURLParam['targetsqid'] = NULL;
             }
             $aURLParam['sid'] = $surveyid;
             $param = new Survey_url_parameters();
             foreach ($aURLParam as $k => $v) {
                 $param->{$k} = $v;
             }
             $param->save();
         }
         $updatearray = array('admin' => Yii::app()->request->getPost('admin'), 'expires' => $expires, 'adminemail' => Yii::app()->request->getPost('adminemail'), 'startdate' => $startdate, 'bounce_email' => Yii::app()->request->getPost('bounce_email'), 'anonymized' => Yii::app()->request->getPost('anonymized'), 'faxto' => Yii::app()->request->getPost('faxto'), 'format' => Yii::app()->request->getPost('format'), 'savetimings' => Yii::app()->request->getPost('savetimings'), 'template' => $template, 'assessments' => Yii::app()->request->getPost('assessments'), 'language' => Yii::app()->request->getPost('language'), 'additional_languages' => Yii::app()->request->getPost('languageids'), 'datestamp' => Yii::app()->request->getPost('datestamp'), 'ipaddr' => Yii::app()->request->getPost('ipaddr'), 'refurl' => Yii::app()->request->getPost('refurl'), 'publicgraphs' => Yii::app()->request->getPost('publicgraphs'), 'usecookie' => Yii::app()->request->getPost('usecookie'), 'allowregister' => Yii::app()->request->getPost('allowregister'), 'allowsave' => Yii::app()->request->getPost('allowsave'), 'navigationdelay' => Yii::app()->request->getPost('navigationdelay'), 'printanswers' => Yii::app()->request->getPost('printanswers'), 'publicstatistics' => Yii::app()->request->getPost('publicstatistics'), 'autoredirect' => Yii::app()->request->getPost('autoredirect'), 'showxquestions' => Yii::app()->request->getPost('showxquestions'), 'showgroupinfo' => Yii::app()->request->getPost('showgroupinfo'), 'showqnumcode' => Yii::app()->request->getPost('showqnumcode'), 'shownoanswer' => Yii::app()->request->getPost('shownoanswer'), 'showwelcome' => Yii::app()->request->getPost('showwelcome'), 'allowprev' => Yii::app()->request->getPost('allowprev'), 'allowjumps' => Yii::app()->request->getPost('allowjumps'), 'nokeyboard' => Yii::app()->request->getPost('nokeyboard'), 'showprogress' => Yii::app()->request->getPost('showprogress'), 'listpublic' => Yii::app()->request->getPost('public'), 'htmlemail' => Yii::app()->request->getPost('htmlemail'), 'sendconfirmation' => Yii::app()->request->getPost('sendconfirmation'), 'tokenanswerspersistence' => Yii::app()->request->getPost('tokenanswerspersistence'), 'alloweditaftercompletion' => Yii::app()->request->getPost('alloweditaftercompletion'), 'usecaptcha' => Yii::app()->request->getPost('usecaptcha'), 'emailresponseto' => trim(Yii::app()->request->getPost('emailresponseto')), 'emailnotificationto' => trim(Yii::app()->request->getPost('emailnotificationto')), 'googleanalyticsapikey' => trim(Yii::app()->request->getPost('googleanalyticsapikey')), 'googleanalyticsstyle' => trim(Yii::app()->request->getPost('googleanalyticsstyle')), 'tokenlength' => $tokenlength);
         // use model
         $Survey = Survey::model()->findByPk($surveyid);
         foreach ($updatearray as $k => $v) {
             $Survey->{$k} = $v;
         }
         $Survey->save();
         #            Survey::model()->updateByPk($surveyid, $updatearray);
         $sqlstring = "surveyls_survey_id=:sid AND surveyls_language <> :base ";
         $params = array(':sid' => $surveyid, ':base' => Survey::model()->findByPk($surveyid)->language);
         $i = 100000;
         foreach (Survey::model()->findByPk($surveyid)->additionalLanguages as $langname) {
             if ($langname) {
                 $sqlstring .= "AND surveyls_language <> :{$i} ";
                 $params[':' . $i] = $langname;
             }
             $i++;
         }
         Surveys_languagesettings::model()->deleteAll($sqlstring, $params);
         $usresult = true;
         foreach (Survey::model()->findByPk($surveyid)->additionalLanguages as $langname) {
             if ($langname) {
                 $oLanguageSettings = Surveys_languagesettings::model()->find('surveyls_survey_id=:surveyid AND surveyls_language=:langname', array(':surveyid' => $surveyid, ':langname' => $langname));
                 if (!$oLanguageSettings) {
                     $oLanguageSettings = new Surveys_languagesettings();
                     $languagedetails = getLanguageDetails($langname);
                     $insertdata = array('surveyls_survey_id' => $surveyid, 'surveyls_language' => $langname, 'surveyls_title' => '', 'surveyls_dateformat' => $languagedetails['dateformat']);
                     foreach ($insertdata as $k => $v) {
                         $oLanguageSettings->{$k} = $v;
                     }
                     $usresult = $oLanguageSettings->save();
                 }
             }
         }
         if ($usresult) {
             Yii::app()->session['flashmessage'] = $clang->gT("Survey settings were successfully saved.");
         } else {
             Yii::app()->session['flashmessage'] = $clang->gT("Error:") . '<br>' . $clang->gT("Survey could not be updated.");
         }
         if (Yii::app()->request->getPost('action') == "updatesurveysettingsandeditlocalesettings") {
             $this->getController()->redirect($this->getController()->createUrl('admin/survey/sa/editlocalsettings/surveyid/' . $surveyid));
         } else {
             $this->getController()->redirect($this->getController()->createUrl('admin/survey/sa/view/surveyid/' . $surveyid));
         }
     }
     if (!$action) {
         $this->getController()->redirect("/admin", "refresh");
     }
 }
/**
* Import survey from an TSV file template that does not require or allow assigning of GID or QID values.
* NOTE:  This currently only supports import of one language
* @global type $connect
* @global type $dbprefix
* @global type $clang
* @global type $timeadjust
* @param type $sFullFilepath
* @return type
*
* @author TMSWhite
*/
function TSVImportSurvey($sFullFilepath)
{
    $clang = Yii::app()->lang;
    $insertdata = array();
    $results = array();
    $results['error'] = false;
    $baselang = 'en';
    // TODO set proper default
    $encoding = '';
    $handle = fopen($sFullFilepath, 'r');
    $bom = fread($handle, 2);
    rewind($handle);
    // Excel tends to save CSV as UTF-16, which PHP does not properly detect
    if ($bom === chr(0xff) . chr(0xfe) || $bom === chr(0xfe) . chr(0xff)) {
        // UTF16 Byte Order Mark present
        $encoding = 'UTF-16';
    } else {
        $file_sample = fread($handle, 1000) + 'e';
        //read first 1000 bytes
        // + e is a workaround for mb_string bug
        rewind($handle);
        $encoding = mb_detect_encoding($file_sample, 'UTF-8, UTF-7, ASCII, EUC-JP,SJIS, eucJP-win, SJIS-win, JIS, ISO-2022-JP');
    }
    if ($encoding && $encoding != 'UTF-8') {
        stream_filter_append($handle, 'convert.iconv.' . $encoding . '/UTF-8');
    }
    $file = stream_get_contents($handle);
    fclose($handle);
    // fix Excel non-breaking space
    $file = str_replace("0xC20xA0", ' ', $file);
    $filelines = explode("\n", $file);
    $row = array_shift($filelines);
    $headers = explode("\t", $row);
    $rowheaders = array();
    foreach ($headers as $header) {
        $rowheaders[] = trim($header);
    }
    // remove BOM from the first header cell, if needed
    $rowheaders[0] = preg_replace("/^\\W+/", "", $rowheaders[0]);
    if (preg_match('/class$/', $rowheaders[0])) {
        $rowheaders[0] = 'class';
        // second attempt to remove BOM
    }
    $adata = array();
    foreach ($filelines as $rowline) {
        $rowarray = array();
        $row = explode("\t", $rowline);
        for ($i = 0; $i < count($rowheaders); ++$i) {
            $val = isset($row[$i]) ? $row[$i] : '';
            // if Excel was used, it surrounds strings with quotes and doubles internal double quotes.  Fix that.
            if (preg_match('/^".*"$/', $val)) {
                $val = str_replace('""', '"', substr($val, 1, -1));
            }
            $rowarray[$rowheaders[$i]] = $val;
        }
        $adata[] = $rowarray;
    }
    $results['defaultvalues'] = 0;
    $results['answers'] = 0;
    $results['surveys'] = 0;
    $results['languages'] = 0;
    $results['questions'] = 0;
    $results['subquestions'] = 0;
    $results['question_attributes'] = 0;
    $results['groups'] = 0;
    $results['importwarnings'] = array();
    // these aren't used here, but are needed to avoid errors in post-import display
    $results['assessments'] = 0;
    $results['quota'] = 0;
    $results['quotamembers'] = 0;
    $results['quotals'] = 0;
    // collect information about survey and its language settings
    $surveyinfo = array();
    $surveyls = array();
    foreach ($adata as $row) {
        switch ($row['class']) {
            case 'S':
                if (isset($row['text']) && $row['name'] != 'datecreated') {
                    $surveyinfo[$row['name']] = $row['text'];
                }
                break;
            case 'SL':
                if (!isset($surveyls[$row['language']])) {
                    $surveyls[$row['language']] = array();
                }
                if (isset($row['text'])) {
                    $surveyls[$row['language']][$row['name']] = $row['text'];
                }
                break;
        }
    }
    $iOldSID = 1;
    if (isset($surveyinfo['sid'])) {
        $iOldSID = (int) $surveyinfo['sid'];
    }
    // Create the survey entry
    $surveyinfo['startdate'] = NULL;
    $surveyinfo['active'] = 'N';
    // unset($surveyinfo['datecreated']);
    switchMSSQLIdentityInsert('surveys', true);
    $iNewSID = Survey::model()->insertNewSurvey($surveyinfo);
    //or safeDie($clang->gT("Error").": Failed to insert survey<br />");
    if ($iNewSID == false) {
        $results['error'] = Survey::model()->getErrors();
        $results['bFailed'] = true;
        return $results;
    }
    $surveyinfo['sid'] = $iNewSID;
    $results['surveys']++;
    switchMSSQLIdentityInsert('surveys', false);
    $results['newsid'] = $iNewSID;
    $gid = 0;
    $gseq = 0;
    // group_order
    $qid = 0;
    $qseq = 0;
    // question_order
    $qtype = 'T';
    $aseq = 0;
    // answer sortorder
    // set the language for the survey
    $_title = 'Missing Title';
    foreach ($surveyls as $_lang => $insertdata) {
        $insertdata['surveyls_survey_id'] = $iNewSID;
        $insertdata['surveyls_language'] = $_lang;
        if (isset($insertdata['surveyls_title'])) {
            $_title = $insertdata['surveyls_title'];
        } else {
            $insertdata['surveyls_title'] = $_title;
        }
        $result = Surveys_languagesettings::model()->insertNewSurvey($insertdata);
        //
        if (!$result) {
            $results['error'][] = $clang->gT("Error") . " : " . $clang->gT("Failed to insert survey language");
            break;
        }
        $results['languages']++;
    }
    $ginfo = array();
    $qinfo = array();
    $sqinfo = array();
    if (isset($surveyinfo['language'])) {
        $baselang = $surveyinfo['language'];
        // the base language
    }
    $rownumber = 1;
    foreach ($adata as $row) {
        $rownumber += 1;
        switch ($row['class']) {
            case 'G':
                // insert group
                $insertdata = array();
                $insertdata['sid'] = $iNewSID;
                $gname = isset($row['name']) ? $row['name'] : 'G' . $gseq;
                $insertdata['group_name'] = $gname;
                $insertdata['grelevance'] = isset($row['relevance']) ? $row['relevance'] : '';
                $insertdata['description'] = isset($row['text']) ? $row['text'] : '';
                $insertdata['language'] = isset($row['language']) ? $row['language'] : $baselang;
                // For multi numeric survey : same title
                if (isset($ginfo[$gname])) {
                    $gseq = $ginfo[$gname]['group_order'];
                    $gid = $ginfo[$gname]['gid'];
                    $insertdata['gid'] = $gid;
                    $insertdata['group_order'] = $gseq;
                } else {
                    $insertdata['group_order'] = $gseq;
                }
                $newgid = Groups::model()->insertRecords($insertdata);
                if (!$newgid) {
                    $results['error'][] = $clang->gT("Error") . " : " . $clang->gT("Failed to insert group") . ". " . $clang->gT("Text file row number ") . $rownumber . " (" . $gname . ")";
                    break;
                }
                if (!isset($ginfo[$gname])) {
                    $results['groups']++;
                    $gid = $newgid;
                    // save this for later
                    $ginfo[$gname]['gid'] = $gid;
                    $ginfo[$gname]['group_order'] = $gseq++;
                }
                $qseq = 0;
                // reset the question_order
                break;
            case 'Q':
                // insert question
                $insertdata = array();
                $insertdata['sid'] = $iNewSID;
                $qtype = isset($row['type/scale']) ? $row['type/scale'] : 'T';
                $qname = isset($row['name']) ? $row['name'] : 'Q' . $qseq;
                $insertdata['gid'] = $gid;
                $insertdata['type'] = $qtype;
                $insertdata['title'] = $qname;
                $insertdata['question'] = isset($row['text']) ? $row['text'] : '';
                $insertdata['relevance'] = isset($row['relevance']) ? $row['relevance'] : '';
                $insertdata['preg'] = isset($row['validation']) ? $row['validation'] : '';
                $insertdata['help'] = isset($row['help']) ? $row['help'] : '';
                $insertdata['language'] = isset($row['language']) ? $row['language'] : $baselang;
                $insertdata['mandatory'] = isset($row['mandatory']) ? $row['mandatory'] : '';
                $insertdata['other'] = isset($row['other']) ? $row['other'] : 'N';
                $insertdata['same_default'] = isset($row['same_default']) ? $row['same_default'] : 0;
                $insertdata['parent_qid'] = 0;
                // For multi numeric survey : same name, add the gid to have same name on different gid. Bad for EM.
                $fullqname = "G{$gid}_" . $qname;
                if (isset($qinfo[$fullqname])) {
                    $qseq = $qinfo[$fullqname]['question_order'];
                    $qid = $qinfo[$fullqname]['qid'];
                    $insertdata['qid'] = $qid;
                    $insertdata['question_order'] = $qseq;
                } else {
                    $insertdata['question_order'] = $qseq;
                }
                // Insert question and keep the qid for multi language survey
                $result = Questions::model()->insertRecords($insertdata);
                if (!$result) {
                    $results['error'][] = $clang->gT("Error") . " : " . $clang->gT("Could not insert question") . ". " . $clang->gT("Text file row number ") . $rownumber . " (" . $qname . ")";
                    break;
                }
                $newqid = $result;
                if (!isset($qinfo[$fullqname])) {
                    $results['questions']++;
                    $qid = $newqid;
                    // save this for later
                    $qinfo[$fullqname]['qid'] = $qid;
                    $qinfo[$fullqname]['question_order'] = $qseq++;
                }
                $aseq = 0;
                //reset the answer sortorder
                $sqseq = 0;
                //reset the sub question sortorder
                // insert question attributes
                foreach ($row as $key => $val) {
                    switch ($key) {
                        case 'class':
                        case 'type/scale':
                        case 'name':
                        case 'text':
                        case 'validation':
                        case 'relevance':
                        case 'help':
                        case 'language':
                        case 'mandatory':
                        case 'other':
                        case 'same_default':
                        case 'default':
                            break;
                        default:
                            if ($key != '' && $val != '') {
                                $insertdata = array();
                                $insertdata['qid'] = $qid;
                                $insertdata['language'] = isset($row['language']) ? $row['language'] : $baselang;
                                $insertdata['attribute'] = $key;
                                $insertdata['value'] = $val;
                                $result = Question_attributes::model()->insertRecords($insertdata);
                                //
                                if (!$result) {
                                    $results['importwarnings'][] = $clang->gT("Warning") . " : " . $clang->gT("Failed to insert question attribute") . ". " . $clang->gT("Text file row number ") . $rownumber . " ({$key})";
                                    break;
                                }
                                $results['question_attributes']++;
                            }
                            break;
                    }
                }
                // insert default value
                if (isset($row['default'])) {
                    $insertdata = array();
                    $insertdata['qid'] = $qid;
                    $insertdata['language'] = isset($row['language']) ? $row['language'] : $baselang;
                    $insertdata['defaultvalue'] = $row['default'];
                    $result = Defaultvalues::model()->insertRecords($insertdata);
                    if (!$result) {
                        $results['importwarnings'][] = $clang->gT("Warning") . " : " . $clang->gT("Failed to insert default value") . ". " . $clang->gT("Text file row number ") . $rownumber;
                        break;
                    }
                    $results['defaultvalues']++;
                }
                break;
            case 'SQ':
                $sqname = isset($row['name']) ? $row['name'] : 'SQ' . $sqseq;
                if ($qtype == 'O' || $qtype == '|') {
                    // these are fake rows to show naming of comment and filecount fields
                } elseif ($sqname == 'other' && ($qtype == '!' || $qtype == 'L')) {
                    // only want to set default value for 'other' in these cases - not a real SQ row
                    // TODO - this isn't working
                    if (isset($row['default'])) {
                        $insertdata = array();
                        $insertdata['qid'] = $qid;
                        $insertdata['specialtype'] = 'other';
                        $insertdata['language'] = isset($row['language']) ? $row['language'] : $baselang;
                        $insertdata['defaultvalue'] = $row['default'];
                        $result = Defaultvalues::model()->insertRecords($insertdata);
                        if (!$result) {
                            $results['importwarnings'][] = $clang->gT("Warning") . " : " . $clang->gT("Failed to insert default value") . ". " . $clang->gT("Text file row number ") . $rownumber;
                            break;
                        }
                        $results['defaultvalues']++;
                    }
                } else {
                    $insertdata = array();
                    $scale_id = isset($row['type/scale']) ? $row['type/scale'] : 0;
                    $insertdata['sid'] = $iNewSID;
                    $insertdata['gid'] = $gid;
                    $insertdata['parent_qid'] = $qid;
                    $insertdata['type'] = $qtype;
                    $insertdata['title'] = $sqname;
                    $insertdata['question'] = isset($row['text']) ? $row['text'] : '';
                    $insertdata['relevance'] = isset($row['relevance']) ? $row['relevance'] : '';
                    $insertdata['preg'] = isset($row['validation']) ? $row['validation'] : '';
                    $insertdata['help'] = isset($row['help']) ? $row['help'] : '';
                    $insertdata['language'] = isset($row['language']) ? $row['language'] : $baselang;
                    $insertdata['mandatory'] = isset($row['mandatory']) ? $row['mandatory'] : '';
                    $insertdata['scale_id'] = $scale_id;
                    // For multi nueric language, qid is needed, why not gid. name is not unique.
                    $fullsqname = "G{$gid}Q{$qid}_{$sqname}";
                    if (isset($sqinfo[$fullsqname])) {
                        $qseq = $sqinfo[$fullsqname]['question_order'];
                        $sqid = $sqinfo[$fullsqname]['sqid'];
                        $insertdata['question_order'] = $qseq;
                        $insertdata['qid'] = $sqid;
                    } else {
                        $insertdata['question_order'] = $qseq;
                    }
                    // Insert sub question and keep the sqid for multi language survey
                    $newsqid = Questions::model()->insertRecords($insertdata);
                    if (!$newsqid) {
                        $results['error'][] = $clang->gT("Error") . " : " . $clang->gT("Could not insert sub question") . ". " . $clang->gT("Text file row number ") . $rownumber . " (" . $qname . ")";
                        break;
                    }
                    if (!isset($sqinfo[$fullsqname])) {
                        $sqinfo[$fullsqname]['question_order'] = $qseq++;
                        $sqid = $newsqid;
                        // save this for later
                        $sqinfo[$fullsqname]['sqid'] = $sqid;
                        $results['subquestions']++;
                    }
                    // insert default value
                    if (isset($row['default'])) {
                        $insertdata = array();
                        $insertdata['qid'] = $qid;
                        $insertdata['sqid'] = $sqid;
                        $insertdata['scale_id'] = $scale_id;
                        $insertdata['language'] = isset($row['language']) ? $row['language'] : $baselang;
                        $insertdata['defaultvalue'] = $row['default'];
                        $result = Defaultvalues::model()->insertRecords($insertdata);
                        if (!$result) {
                            $results['importwarnings'][] = $clang->gT("Warning") . " : " . $clang->gT("Failed to insert default value") . ". " . $clang->gT("Text file row number ") . $rownumber;
                            break;
                        }
                        $results['defaultvalues']++;
                    }
                }
                break;
            case 'A':
                $insertdata = array();
                $insertdata['qid'] = $qid;
                $insertdata['code'] = isset($row['name']) ? $row['name'] : 'A' . $aseq;
                $insertdata['answer'] = isset($row['text']) ? $row['text'] : '';
                $insertdata['scale_id'] = isset($row['type/scale']) ? $row['type/scale'] : 0;
                $insertdata['language'] = isset($row['language']) ? $row['language'] : $baselang;
                $insertdata['assessment_value'] = isset($row['relevance']) ? $row['relevance'] : '';
                $insertdata['sortorder'] = ++$aseq;
                $result = Answers::model()->insertRecords($insertdata);
                // or safeDie("Error: Failed to insert answer<br />");
                if (!$result) {
                    $results['error'][] = $clang->gT("Error") . " : " . $clang->gT("Could not insert answer") . ". " . $clang->gT("Text file row number ") . $rownumber;
                }
                $results['answers']++;
                break;
        }
    }
    // Delete the survey if error found
    if (is_array($results['error'])) {
        $result = Survey::model()->deleteSurvey($iNewSID);
    }
    return $results;
}
Exemple #17
0
 /**
  * Deletes a survey and all its data
  *
  * @access public
  * @param int $iSurveyID
  * @param bool @recursive
  * @return void
  */
 public function deleteSurvey($iSurveyID, $recursive = true)
 {
     Survey::model()->deleteByPk($iSurveyID);
     if ($recursive == true) {
         if (tableExists("{{survey_" . intval($iSurveyID) . "}}")) {
             Yii::app()->db->createCommand()->dropTable("{{survey_" . intval($iSurveyID) . "}}");
         }
         if (tableExists("{{survey_" . intval($iSurveyID) . "_timings}}")) {
             Yii::app()->db->createCommand()->dropTable("{{survey_" . intval($iSurveyID) . "_timings}}");
         }
         if (tableExists("{{tokens_" . intval($iSurveyID) . "}}")) {
             Yii::app()->db->createCommand()->dropTable("{{tokens_" . intval($iSurveyID) . "}}");
         }
         $oResult = Questions::model()->findAllByAttributes(array('sid' => $iSurveyID));
         foreach ($oResult as $aRow) {
             Answers::model()->deleteAllByAttributes(array('qid' => $aRow['qid']));
             Conditions::model()->deleteAllByAttributes(array('qid' => $aRow['qid']));
             Question_attributes::model()->deleteAllByAttributes(array('qid' => $aRow['qid']));
             Defaultvalues::model()->deleteAllByAttributes(array('qid' => $aRow['qid']));
         }
         Questions::model()->deleteAllByAttributes(array('sid' => $iSurveyID));
         Assessment::model()->deleteAllByAttributes(array('sid' => $iSurveyID));
         Groups::model()->deleteAllByAttributes(array('sid' => $iSurveyID));
         Surveys_languagesettings::model()->deleteAllByAttributes(array('surveyls_survey_id' => $iSurveyID));
         Survey_permissions::model()->deleteAllByAttributes(array('sid' => $iSurveyID));
         Saved_control::model()->deleteAllByAttributes(array('sid' => $iSurveyID));
         Survey_url_parameters::model()->deleteAllByAttributes(array('sid' => $iSurveyID));
         Quota::model()->deleteQuota(array('sid' => $iSurveyID), true);
     }
 }
 /**
  * RPC Routine to delete a question of a survey .
  * Returns the id of the deleted question.
  *
  * @access public
  * @param string $sSessionKey Auth credentials
  * @param int iQuestionID Id of the question to delete 
  * @return array|int Id of the deleted Question or status
  */
 public function delete_question($sSessionKey, $iQuestionID)
 {
     if ($this->_checkSessionKey($sSessionKey)) {
         $oQuestion = Questions::model()->findByAttributes(array('qid' => $iQuestionID));
         if (!isset($oQuestion)) {
             return array('status' => 'Error: Invalid question ID');
         }
         $iSurveyID = $oQuestion['sid'];
         if (hasSurveyPermission($iSurveyID, 'surveycontent', 'delete')) {
             $oSurvey = Survey::model()->findByPk($iSurveyID);
             if ($oSurvey['active'] == 'Y') {
                 return array('status' => 'Survey is active and not editable');
             }
             $iGroupID = $oQuestion['gid'];
             $oCondition = Conditions::model()->findAllByAttributes(array('cqid' => $iQuestionID));
             if (count($oCondition) > 0) {
                 return array('status' => 'Cannot delete Question. Others rely on this question');
             }
             LimeExpressionManager::RevertUpgradeConditionsToRelevance(NULL, $iQuestionID);
             try {
                 Conditions::model()->deleteAllByAttributes(array('qid' => $iQuestionID));
                 Question_attributes::model()->deleteAllByAttributes(array('qid' => $iQuestionID));
                 Answers::model()->deleteAllByAttributes(array('qid' => $iQuestionID));
                 $sCriteria = new CDbCriteria();
                 $sCriteria->addCondition('qid = :qid or parent_qid = :qid');
                 $sCriteria->params[':qid'] = $iQuestionID;
                 Questions::model()->deleteAll($sCriteria);
                 Defaultvalues::model()->deleteAllByAttributes(array('qid' => $iQuestionID));
                 Quota_members::model()->deleteAllByAttributes(array('qid' => $iQuestionID));
                 Questions::updateSortOrder($iGroupID, $iSurveyID);
                 return (int) $iQuestionID;
             } catch (Exception $e) {
                 return array('status' => 'Error');
             }
         } else {
             return array('status' => 'No permission');
         }
     } else {
         return array('status' => 'Invalid session key');
     }
 }
 function index($subaction, $iSurveyID = null, $gid = null, $qid = null)
 {
     $iSurveyID = sanitize_int($iSurveyID);
     $gid = sanitize_int($gid);
     $qid = sanitize_int($qid);
     $clang = $this->getController()->lang;
     $imageurl = Yii::app()->getConfig("adminimageurl");
     Yii::app()->loadHelper("database");
     if (!empty($_POST['subaction'])) {
         $subaction = Yii::app()->request->getPost('subaction');
     }
     //BEGIN Sanitizing POSTed data
     if (!isset($iSurveyID)) {
         $iSurveyID = returnGlobal('sid');
     }
     if (!isset($qid)) {
         $qid = returnGlobal('qid');
     }
     if (!isset($gid)) {
         $gid = returnGlobal('gid');
     }
     if (!isset($p_scenario)) {
         $p_scenario = returnGlobal('scenario');
     }
     if (!isset($p_cqid)) {
         $p_cqid = returnGlobal('cqid');
         if ($p_cqid == '') {
             $p_cqid = 0;
         }
         // we are not using another question as source of condition
     }
     if (!isset($p_cid)) {
         $p_cid = returnGlobal('cid');
     }
     if (!isset($p_subaction)) {
         if (isset($_POST['subaction'])) {
             $p_subaction = $_POST['subaction'];
         } else {
             $p_subaction = $subaction;
         }
     }
     if (!isset($p_cquestions)) {
         $p_cquestions = returnGlobal('cquestions');
     }
     if (!isset($p_csrctoken)) {
         $p_csrctoken = returnGlobal('csrctoken');
     }
     if (!isset($p_prevquestionsgqa)) {
         $p_prevquestionsgqa = returnGlobal('prevQuestionSGQA');
     }
     if (!isset($p_canswers)) {
         if (isset($_POST['canswers']) && is_array($_POST['canswers'])) {
             foreach ($_POST['canswers'] as $key => $val) {
                 $p_canswers[$key] = preg_replace("/[^_.a-zA-Z0-9]@/", "", $val);
             }
         }
     }
     // this array will be used soon,
     // to explain wich conditions is used to evaluate the question
     if (Yii::app()->getConfig('stringcomparizonoperators') == 1) {
         $method = array("<" => $clang->gT("Less than"), "<=" => $clang->gT("Less than or equal to"), "==" => $clang->gT("equals"), "!=" => $clang->gT("Not equal to"), ">=" => $clang->gT("Greater than or equal to"), ">" => $clang->gT("Greater than"), "RX" => $clang->gT("Regular expression"), "a<b" => $clang->gT("Less than (Strings)"), "a<=b" => $clang->gT("Less than or equal to (Strings)"), "a>=b" => $clang->gT("Greater than or equal to (Strings)"), "a>b" => $clang->gT("Greater than (Strings)"));
     } else {
         $method = array("<" => $clang->gT("Less than"), "<=" => $clang->gT("Less than or equal to"), "==" => $clang->gT("equals"), "!=" => $clang->gT("Not equal to"), ">=" => $clang->gT("Greater than or equal to"), ">" => $clang->gT("Greater than"), "RX" => $clang->gT("Regular expression"));
     }
     if (isset($_POST['method'])) {
         if (!in_array($_POST['method'], array_keys($method))) {
             $p_method = "==";
         } else {
             $p_method = trim($_POST['method']);
         }
     }
     if (isset($_POST['newscenarionum'])) {
         $p_newscenarionum = sanitize_int($_POST['newscenarionum']);
     }
     //END Sanitizing POSTed data
     //include_once("login_check.php");
     include_once "database.php";
     // Caution (lemeur): database.php uses autoUnescape on all entries in $_POST
     // Take care to not use autoUnescape on $_POST variables after this
     $br = CHtml::openTag('br /');
     //MAKE SURE THAT THERE IS A SID
     if (!isset($iSurveyID) || !$iSurveyID) {
         $conditionsoutput = $clang->gT("You have not selected a survey") . str_repeat($br, 2);
         $conditionsoutput .= CHtml::submitButton($clang->gT("Main admin screen"), array('onclick' => "window.open('" . $this->getController()->createUrl("admin/") . "', '_top')")) . $br;
         safeDie($conditionsoutput);
         return;
     }
     if (isset($p_subaction) && $p_subaction == "resetsurveylogic") {
         $clang = $this->getController()->lang;
         $resetsurveylogicoutput = $br;
         $resetsurveylogicoutput .= CHtml::openTag('table', array('class' => 'alertbox'));
         $resetsurveylogicoutput .= CHtml::openTag('tr') . CHtml::openTag('td', array('colspan' => '2'));
         $resetsurveylogicoutput .= CHtml::tag('font', array('size' => '1'), CHtml::tag('strong', array(), $clang->gT("Reset Survey Logic")));
         $resetsurveylogicoutput .= CHtml::closeTag('td') . CHtml::closeTag('tr');
         if (!isset($_GET['ok'])) {
             $button_yes = CHtml::submitButton($clang->gT("Yes"), array('onclick' => "window.open('" . $this->getController()->createUrl("admin/conditions/sa/index/subaction/resetsurveylogic/surveyid/{$iSurveyID}") . "?ok=Y" . "', '_top')"));
             $button_cancel = CHtml::submitButton($clang->gT("Cancel"), array('onclick' => "window.open('" . $this->getController()->createUrl("admin/survey/sa/view/surveyid/{$iSurveyID}") . "', '_top')"));
             $messagebox_content = $clang->gT("You are about to delete all conditions on this survey's questions") . "({$iSurveyID})" . $br . $clang->gT("We recommend that before you proceed, you export the entire survey from the main administration screen.") . $br . $clang->gT("Continue?") . $br . $button_yes . $button_cancel;
             $this->_renderWrappedTemplate('conditions', array('message' => array('title' => $clang->gT("Warning"), 'message' => $messagebox_content)));
             exit;
         } else {
             LimeExpressionManager::RevertUpgradeConditionsToRelevance($iSurveyID);
             Conditions::model()->deleteRecords("qid in (select qid from {{questions}} where sid={$iSurveyID})");
             Yii::app()->session['flashmessage'] = $clang->gT("All conditions in this survey have been deleted.");
             $this->getController()->redirect($this->getController()->createUrl('admin/survey/sa/view/surveyid/' . $iSurveyID));
         }
     }
     // MAKE SURE THAT THERE IS A QID
     if (!isset($qid) || !$qid) {
         $conditionsoutput = $clang->gT("You have not selected a question") . str_repeat($br, 2);
         $conditionsoutput .= CHtml::submitButton($clang->gT("Main admin screen"), array('onclick' => "window.open('" . $this->getController()->createUrl("admin/") . "', '_top')")) . $br;
         safeDie($conditionsoutput);
         return;
     }
     // If we made it this far, then lets develop the menu items
     // add the conditions container table
     $extraGetParams = "";
     if (isset($qid) && isset($gid)) {
         $extraGetParams = "/gid/{$gid}/qid/{$qid}";
     }
     $conditionsoutput_action_error = "";
     // defined during the actions
     $markcidarray = array();
     if (isset($_GET['markcid'])) {
         $markcidarray = explode("-", $_GET['markcid']);
     }
     //BEGIN PROCESS ACTIONS
     // ADD NEW ENTRY IF THIS IS AN ADD
     if (isset($p_subaction) && $p_subaction == "insertcondition") {
         if (!isset($p_canswers) && !isset($_POST['ConditionConst']) && !isset($_POST['prevQuestionSGQA']) && !isset($_POST['tokenAttr']) && !isset($_POST['ConditionRegexp']) || !isset($p_cquestions) && !isset($p_csrctoken)) {
             $conditionsoutput_action_error .= CHtml::script("\n<!--\n alert(\"" . $clang->gT("Your condition could not be added! It did not include the question and/or answer upon which the condition was based. Please ensure you have selected a question and an answer.", "js") . "\")\n //-->\n");
         } else {
             if (isset($p_cquestions) && $p_cquestions != '') {
                 $conditionCfieldname = $p_cquestions;
             } elseif (isset($p_csrctoken) && $p_csrctoken != '') {
                 $conditionCfieldname = $p_csrctoken;
             }
             $condition_data = array('qid' => $qid, 'scenario' => $p_scenario, 'cqid' => $p_cqid, 'cfieldname' => $conditionCfieldname, 'method' => $p_method);
             if (isset($p_canswers)) {
                 foreach ($p_canswers as $ca) {
                     //First lets make sure there isn't already an exact replica of this condition
                     $condition_data['value'] = $ca;
                     $result = Conditions::model()->findAllByAttributes($condition_data);
                     $count_caseinsensitivedupes = count($result);
                     if ($count_caseinsensitivedupes == 0) {
                         $result = Conditions::model()->insertRecords($condition_data);
                     }
                 }
             }
             unset($posted_condition_value);
             // Please note that autoUnescape is already applied in database.php included above
             // so we only need to db_quote _POST variables
             if (isset($_POST['ConditionConst']) && isset($_POST['editTargetTab']) && $_POST['editTargetTab'] == "#CONST") {
                 $posted_condition_value = Yii::app()->request->getPost('ConditionConst');
             } elseif (isset($_POST['prevQuestionSGQA']) && isset($_POST['editTargetTab']) && $_POST['editTargetTab'] == "#PREVQUESTIONS") {
                 $posted_condition_value = Yii::app()->request->getPost('prevQuestionSGQA');
             } elseif (isset($_POST['tokenAttr']) && isset($_POST['editTargetTab']) && $_POST['editTargetTab'] == "#TOKENATTRS") {
                 $posted_condition_value = Yii::app()->request->getPost('tokenAttr');
             } elseif (isset($_POST['ConditionRegexp']) && isset($_POST['editTargetTab']) && $_POST['editTargetTab'] == "#REGEXP") {
                 $posted_condition_value = Yii::app()->request->getPost('ConditionRegexp');
             }
             if (isset($posted_condition_value)) {
                 $condition_data['value'] = $posted_condition_value;
                 $result = Conditions::model()->insertRecords($condition_data);
             }
         }
         LimeExpressionManager::UpgradeConditionsToRelevance(NULL, $qid);
     }
     // UPDATE ENTRY IF THIS IS AN EDIT
     if (isset($p_subaction) && $p_subaction == "updatecondition") {
         if (!isset($p_canswers) && !isset($_POST['ConditionConst']) && !isset($_POST['prevQuestionSGQA']) && !isset($_POST['tokenAttr']) && !isset($_POST['ConditionRegexp']) || !isset($p_cquestions) && !isset($p_csrctoken)) {
             $conditionsoutput_action_error .= CHtml::script("\n<!--\n alert(\"" . $clang->gT("Your condition could not be added! It did not include the question and/or answer upon which the condition was based. Please ensure you have selected a question and an answer.", "js") . "\")\n //-->\n");
         } else {
             if (isset($p_cquestions) && $p_cquestions != '') {
                 $conditionCfieldname = $p_cquestions;
             } elseif (isset($p_csrctoken) && $p_csrctoken != '') {
                 $conditionCfieldname = $p_csrctoken;
             }
             if (isset($p_canswers)) {
                 foreach ($p_canswers as $ca) {
                     // This is an Edit, there will only be ONE VALUE
                     $updated_data = array('qid' => $qid, 'scenario' => $p_scenario, 'cqid' => $p_cqid, 'cfieldname' => $conditionCfieldname, 'method' => $p_method, 'value' => $ca);
                     $result = Conditions::model()->insertRecords($updated_data, TRUE, array('cid' => $p_cid));
                 }
             }
             unset($posted_condition_value);
             // Please note that autoUnescape is already applied in database.php included above
             // so we only need to db_quote _POST variables
             if (isset($_POST['ConditionConst']) && isset($_POST['editTargetTab']) && $_POST['editTargetTab'] == "#CONST") {
                 $posted_condition_value = Yii::app()->request->getPost('ConditionConst');
             } elseif (isset($_POST['prevQuestionSGQA']) && isset($_POST['editTargetTab']) && $_POST['editTargetTab'] == "#PREVQUESTIONS") {
                 $posted_condition_value = Yii::app()->request->getPost('prevQuestionSGQA');
             } elseif (isset($_POST['tokenAttr']) && isset($_POST['editTargetTab']) && $_POST['editTargetTab'] == "#TOKENATTRS") {
                 $posted_condition_value = Yii::app()->request->getPost('tokenAttr');
             } elseif (isset($_POST['ConditionRegexp']) && isset($_POST['editTargetTab']) && $_POST['editTargetTab'] == "#REGEXP") {
                 $posted_condition_value = Yii::app()->request->getPost('ConditionRegexp');
             }
             if (isset($posted_condition_value)) {
                 $updated_data = array('qid' => $qid, 'scenario' => $p_scenario, 'cqid' => $p_cqid, 'cfieldname' => $conditionCfieldname, 'method' => $p_method, 'value' => $posted_condition_value);
                 $result = Conditions::model()->insertRecords($updated_data, TRUE, array('cid' => $p_cid));
             }
         }
         LimeExpressionManager::UpgradeConditionsToRelevance(NULL, $qid);
     }
     // DELETE ENTRY IF THIS IS DELETE
     if (isset($p_subaction) && $p_subaction == "delete") {
         LimeExpressionManager::RevertUpgradeConditionsToRelevance(NULL, $qid);
         // in case deleted the last condition
         $result = Conditions::model()->deleteRecords(array('cid' => $p_cid));
         LimeExpressionManager::UpgradeConditionsToRelevance(NULL, $qid);
     }
     // DELETE ALL CONDITIONS IN THIS SCENARIO
     if (isset($p_subaction) && $p_subaction == "deletescenario") {
         LimeExpressionManager::RevertUpgradeConditionsToRelevance(NULL, $qid);
         // in case deleted the last condition
         $result = Conditions::model()->deleteRecords(array('qid' => $qid, 'scenario' => $p_scenario));
         LimeExpressionManager::UpgradeConditionsToRelevance(NULL, $qid);
     }
     // UPDATE SCENARIO
     if (isset($p_subaction) && $p_subaction == "updatescenario" && isset($p_newscenarionum)) {
         $result = Conditions::model()->insertRecords(array('scenario' => $p_newscenarionum), TRUE, array('qid' => $qid, 'scenario' => $p_scenario));
         LimeExpressionManager::UpgradeConditionsToRelevance(NULL, $qid);
     }
     // DELETE ALL CONDITIONS FOR THIS QUESTION
     if (isset($p_subaction) && $p_subaction == "deleteallconditions") {
         LimeExpressionManager::RevertUpgradeConditionsToRelevance(NULL, $qid);
         // in case deleted the last condition
         $result = Conditions::model()->deleteRecords(array('qid' => $qid));
     }
     // RENUMBER SCENARIOS
     if (isset($p_subaction) && $p_subaction == "renumberscenarios") {
         $query = "SELECT DISTINCT scenario FROM {{conditions}} WHERE qid=:qid ORDER BY scenario";
         $result = Yii::app()->db->createCommand($query)->bindParam(":qid", $qid, PDO::PARAM_INT)->query() or safeDie("Couldn't select scenario<br />{$query}<br />");
         $newindex = 1;
         foreach ($result->readAll() as $srow) {
             // new var $update_result == old var $result2
             $update_result = Conditions::model()->insertRecords(array('scenario' => $newindex), TRUE, array('qid' => $qid, 'scenario' => $srow['scenario']));
             $newindex++;
         }
         LimeExpressionManager::UpgradeConditionsToRelevance(NULL, $qid);
         Yii::app()->session['flashmessage'] = $clang->gT("All conditions scenarios were renumbered.");
     }
     // COPY CONDITIONS IF THIS IS COPY
     if (isset($p_subaction) && $p_subaction == "copyconditions") {
         $qid = returnGlobal('qid');
         $copyconditionsfrom = returnGlobal('copyconditionsfrom');
         $copyconditionsto = returnGlobal('copyconditionsto');
         if (isset($copyconditionsto) && is_array($copyconditionsto) && isset($copyconditionsfrom) && is_array($copyconditionsfrom)) {
             //Get the conditions we are going to copy
             foreach ($copyconditionsfrom as &$entry) {
                 $entry = Yii::app()->db->quoteValue($entry);
             }
             $query = "SELECT * FROM {{conditions}}\n" . "WHERE cid in (";
             $query .= implode(", ", $copyconditionsfrom);
             $query .= ")";
             $result = Yii::app()->db->createCommand($query)->query() or safeDie("Couldn't get conditions for copy<br />{$query}<br />");
             foreach ($result->readAll() as $row) {
                 $proformaconditions[] = array("scenario" => $row['scenario'], "cqid" => $row['cqid'], "cfieldname" => $row['cfieldname'], "method" => $row['method'], "value" => $row['value']);
             }
             // while
             foreach ($copyconditionsto as $copyc) {
                 list($newsid, $newgid, $newqid) = explode("X", $copyc);
                 foreach ($proformaconditions as $pfc) {
                     //TIBO
                     //First lets make sure there isn't already an exact replica of this condition
                     $conditions_data = array('qid' => $newqid, 'scenario' => $pfc['scenario'], 'cqid' => $pfc['cqid'], 'cfieldname' => $pfc['cfieldname'], 'method' => $pfc['method'], 'value' => $pfc['value']);
                     $result = Conditions::model()->findAllByAttributes($conditions_data);
                     $count_caseinsensitivedupes = count($result);
                     $countduplicates = 0;
                     if ($count_caseinsensitivedupes != 0) {
                         foreach ($result as $ccrow) {
                             if ($ccrow['value'] == $pfc['value']) {
                                 $countduplicates++;
                             }
                         }
                     }
                     if ($countduplicates == 0) {
                         $result = Conditions::model()->insertRecords($conditions_data);
                         $conditionCopied = true;
                     } else {
                         $conditionDuplicated = true;
                     }
                 }
             }
             if (isset($conditionCopied) && $conditionCopied === true) {
                 if (isset($conditionDuplicated) && $conditionDuplicated == true) {
                     $CopyConditionsMessage = CHtml::tag('div', array('class' => 'partialheader'), '(' . $clang->gT("Conditions successfully copied (some were skipped because they were duplicates)") . ')');
                 } else {
                     $CopyConditionsMessage = CHtml::tag('div', array('class' => 'successheader'), '(' . $clang->gT("Conditions successfully copied") . ')');
                 }
             } else {
                 $CopyConditionsMessage = CHtml::tag('div', array('class' => 'warningheader'), '(' . $clang->gT("No conditions could be copied (due to duplicates)") . ')');
             }
         }
         LimeExpressionManager::UpgradeConditionsToRelevance($iSurveyID);
         // do for whole survey, since don't know which questions affected.
     }
     //END PROCESS ACTIONS
     $cquestions = array();
     $canswers = array();
     //BEGIN: GATHER INFORMATION
     // 1: Get information for this question
     if (!isset($qid)) {
         $qid = returnGlobal('qid');
     }
     if (!isset($iSurveyID)) {
         $iSurveyID = returnGlobal('sid');
     }
     $thissurvey = getSurveyInfo($iSurveyID);
     $qresult = Questions::model()->with('groups')->findByAttributes(array('qid' => $qid, 'parent_qid' => 0, 'language' => Survey::model()->findByPk($iSurveyID)->language));
     $questiongroupname = $qresult->groups->group_name;
     $questiontitle = $qresult['title'];
     $questiontext = $qresult['question'];
     $questiontype = $qresult['type'];
     // 2: Get all other questions that occur before this question that are pre-determined answer types
     // To avoid natural sort order issues,
     // first get all questions in natural sort order
     // , and find out which number in that order this question is
     $qresult = Questions::model()->with(array('groups' => array('condition' => 'groups.language = :lang', 'params' => array(':lang' => Survey::model()->findByPk($iSurveyID)->language))))->findAllByAttributes(array('parent_qid' => 0, 'sid' => $iSurveyID, 'language' => Survey::model()->findByPk($iSurveyID)->language));
     $qrows = array();
     foreach ($qresult as $k => $v) {
         $qrows[$k] = array_merge($v->attributes, $v->groups->attributes);
     }
     // Perform a case insensitive natural sort on group name then question title (known as "code" in the form) of a multidimensional array
     usort($qrows, 'groupOrderThenQuestionOrder');
     $position = "before";
     // Go through each question until we reach the current one
     foreach ($qrows as $qrow) {
         if ($qrow["qid"] != $qid && $position == "before") {
             // remember all previous questions
             // all question types are supported.
             $questionlist[] = $qrow["qid"];
         } elseif ($qrow["qid"] == $qid) {
             break;
         }
     }
     // Now, using the same array which is now properly sorted by group then question
     // Create an array of all the questions that appear AFTER the current one
     $position = "before";
     foreach ($qrows as $qrow) {
         if ($qrow["qid"] == $qid) {
             $position = "after";
             //break;
         } elseif ($qrow["qid"] != $qid && $position == "after") {
             $postquestionlist[] = $qrow['qid'];
         }
     }
     $theserows = array();
     $postrows = array();
     if (isset($questionlist) && is_array($questionlist)) {
         foreach ($questionlist as $ql) {
             $result = Questions::model()->with(array('groups' => array('condition' => 'groups.language = :lang', 'params' => array(':lang' => Survey::model()->findByPk($iSurveyID)->language))))->findAllByAttributes(array('qid' => $ql, 'parent_qid' => 0, 'sid' => $iSurveyID, 'language' => Survey::model()->findByPk($iSurveyID)->language));
             $thiscount = count($result);
             // And store again these questions in this array...
             foreach ($result as $myrows) {
                 //key => value
                 $theserows[] = array("qid" => $myrows['qid'], "sid" => $myrows['sid'], "gid" => $myrows['gid'], "question" => $myrows['question'], "type" => $myrows['type'], "mandatory" => $myrows['mandatory'], "other" => $myrows['other'], "title" => $myrows['title']);
             }
         }
     }
     if (isset($postquestionlist) && is_array($postquestionlist)) {
         foreach ($postquestionlist as $pq) {
             $result = Questions::model()->with(array('groups' => array('condition' => 'groups.language = :lang', 'params' => array(':lang' => Survey::model()->findByPk($iSurveyID)->language))))->findAllByAttributes(array('qid' => $pq, 'parent_qid' => 0, 'sid' => $iSurveyID, 'language' => Survey::model()->findByPk($iSurveyID)->language));
             $postcount = count($result);
             foreach ($result as $myrows) {
                 $postrows[] = array("qid" => $myrows['qid'], "sid" => $myrows['sid'], "gid" => $myrows['gid'], "question" => $myrows['question'], "type" => $myrows['type'], "mandatory" => $myrows['mandatory'], "other" => $myrows['other'], "title" => $myrows['title']);
             }
             // while
         }
         $postquestionscount = count($postrows);
     }
     $questionscount = count($theserows);
     if (isset($postquestionscount) && $postquestionscount > 0) {
         //Build the array used for the questionNav and copyTo select boxes
         foreach ($postrows as $pr) {
             $pquestions[] = array("text" => $pr['title'] . ": " . substr(strip_tags($pr['question']), 0, 80), "fieldname" => $pr['sid'] . "X" . $pr['gid'] . "X" . $pr['qid']);
         }
     }
     // Previous question parsing ==> building cquestions[] and canswers[]
     if ($questionscount > 0) {
         $X = "X";
         foreach ($theserows as $rows) {
             $shortquestion = $rows['title'] . ": " . strip_tags($rows['question']);
             if ($rows['type'] == "A" || $rows['type'] == "B" || $rows['type'] == "C" || $rows['type'] == "E" || $rows['type'] == "F" || $rows['type'] == "H") {
                 $aresult = Questions::model()->findAllByAttributes(array('parent_qid' => $rows['qid'], 'language' => Survey::model()->findByPk($iSurveyID)->language), array('order' => 'question_order ASC'));
                 foreach ($aresult as $arows) {
                     $shortanswer = "{$arows['title']}: [" . flattenText($arows['question']) . "]";
                     $shortquestion = $rows['title'] . ":{$shortanswer} " . flattenText($rows['question']);
                     $cquestions[] = array($shortquestion, $rows['qid'], $rows['type'], $rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title']);
                     switch ($rows['type']) {
                         case "A":
                             //Array 5 buttons
                             for ($i = 1; $i <= 5; $i++) {
                                 $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], $i, $i);
                             }
                             break;
                         case "B":
                             //Array 10 buttons
                             for ($i = 1; $i <= 10; $i++) {
                                 $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], $i, $i);
                             }
                             break;
                         case "C":
                             //Array Y/N/NA
                             $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], "Y", $clang->gT("Yes"));
                             $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], "U", $clang->gT("Uncertain"));
                             $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], "N", $clang->gT("No"));
                             break;
                         case "E":
                             //Array >/=/<
                             $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], "I", $clang->gT("Increase"));
                             $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], "S", $clang->gT("Same"));
                             $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], "D", $clang->gT("Decrease"));
                             break;
                         case "F":
                             //Array Flexible Row
                         //Array Flexible Row
                         case "H":
                             //Array Flexible Column
                             $fresult = Answers::model()->findAllByAttributes(array('qid' => $rows['qid'], "language" => Survey::model()->findByPk($iSurveyID)->language, 'scale_id' => 0), array('order' => 'sortorder, code'));
                             foreach ($fresult as $frow) {
                                 $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], $frow['code'], $frow['answer']);
                             }
                             break;
                     }
                     // Only Show No-Answer if question is not mandatory
                     if ($rows['mandatory'] != 'Y') {
                         $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], "", $clang->gT("No answer"));
                     }
                 }
                 //while
             } elseif ($rows['type'] == ":" || $rows['type'] == ";") {
                 // Multiflexi
                 //Get question attribute for $canswers
                 $qidattributes = getQuestionAttributeValues($rows['qid'], $rows['type']);
                 if (isset($qidattributes['multiflexible_max']) && trim($qidattributes['multiflexible_max']) != '') {
                     $maxvalue = floatval($qidattributes['multiflexible_max']);
                 } else {
                     $maxvalue = 10;
                 }
                 if (isset($qidattributes['multiflexible_min']) && trim($qidattributes['multiflexible_min']) != '') {
                     $minvalue = floatval($qidattributes['multiflexible_min']);
                 } else {
                     $minvalue = 1;
                 }
                 if (isset($qidattributes['multiflexible_step']) && trim($qidattributes['multiflexible_step']) != '') {
                     $stepvalue = floatval($qidattributes['multiflexible_step']);
                     if ($stepvalue == 0) {
                         $stepvalue = 1;
                     }
                 } else {
                     $stepvalue = 1;
                 }
                 if (isset($qidattributes['multiflexible_checkbox']) && $qidattributes['multiflexible_checkbox'] != 0) {
                     $minvalue = 0;
                     $maxvalue = 1;
                     $stepvalue = 1;
                 }
                 // Get the Y-Axis
                 $fquery = "SELECT sq.*, q.other" . " FROM {{questions sq}}, {{questions q}}" . " WHERE sq.sid={$iSurveyID} AND sq.parent_qid=q.qid " . "AND q.language=:lang" . " AND sq.language=:lang" . " AND q.qid=:qid\n                    AND sq.scale_id=0\n                    ORDER BY sq.question_order";
                 $sLanguage = Survey::model()->findByPk($iSurveyID)->language;
                 $y_axis_db = Yii::app()->db->createCommand($fquery)->bindParam(":lang", $sLanguage, PDO::PARAM_STR)->bindParam(":qid", $rows['qid'], PDO::PARAM_INT)->query();
                 // Get the X-Axis
                 $aquery = "SELECT sq.*\n                    FROM {{questions q}}, {{questions sq}}\n                    WHERE q.sid={$iSurveyID}\n                    AND sq.parent_qid=q.qid\n                    AND q.language=:lang\n                    AND sq.language=:lang\n                    AND q.qid=:qid\n                    AND sq.scale_id=1\n                    ORDER BY sq.question_order";
                 $x_axis_db = Yii::app()->db->createCommand($aquery)->bindParam(":lang", $sLanguage, PDO::PARAM_STR)->bindParam(":qid", $rows['qid'], PDO::PARAM_INT)->query() or safeDie("Couldn't get answers to Array questions<br />{$aquery}<br />");
                 foreach ($x_axis_db->readAll() as $frow) {
                     $x_axis[$frow['title']] = $frow['question'];
                 }
                 foreach ($y_axis_db->readAll() as $yrow) {
                     foreach ($x_axis as $key => $val) {
                         $shortquestion = $rows['title'] . ":{$yrow['title']}:{$key}: [" . strip_tags($yrow['question']) . "][" . strip_tags($val) . "] " . flattenText($rows['question']);
                         $cquestions[] = array($shortquestion, $rows['qid'], $rows['type'], $rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $yrow['title'] . "_" . $key);
                         if ($rows['type'] == ":") {
                             for ($ii = $minvalue; $ii <= $maxvalue; $ii += $stepvalue) {
                                 $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $yrow['title'] . "_" . $key, $ii, $ii);
                             }
                         }
                     }
                 }
                 unset($x_axis);
             } elseif ($rows['type'] == "1") {
                 $aresult = Questions::model()->findAllByAttributes(array('parent_qid' => $rows['qid'], 'language' => Survey::model()->findByPk($iSurveyID)->language), array('order' => 'question_order desc'));
                 foreach ($aresult as $arows) {
                     $attr = getQuestionAttributeValues($rows['qid']);
                     $label1 = isset($attr['dualscale_headerA']) ? $attr['dualscale_headerA'] : 'Label1';
                     $label2 = isset($attr['dualscale_headerB']) ? $attr['dualscale_headerB'] : 'Label2';
                     $shortanswer = "{$arows['title']}: [" . strip_tags($arows['question']) . "][{$label1}]";
                     $shortquestion = $rows['title'] . ":{$shortanswer} " . strip_tags($rows['question']);
                     $cquestions[] = array($shortquestion, $rows['qid'], $rows['type'], $rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'] . "#0");
                     $shortanswer = "{$arows['title']}: [" . strip_tags($arows['question']) . "][{$label2}]";
                     $shortquestion = $rows['title'] . ":{$shortanswer} " . strip_tags($rows['question']);
                     $cquestions[] = array($shortquestion, $rows['qid'], $rows['type'], $rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'] . "#1");
                     // first label
                     $lresult = Answers::model()->findAllByAttributes(array('qid' => $rows['qid'], 'scale_id' => 0, 'language' => Survey::model()->findByPk($iSurveyID)->language), array('order' => 'sortorder, answer'));
                     foreach ($lresult as $lrows) {
                         $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'] . "#0", "{$lrows['code']}", "{$lrows['code']}");
                     }
                     // second label
                     $lresult = Answers::model()->findAllByAttributes(array('qid' => $rows['qid'], 'scale_id' => 1, 'language' => Survey::model()->findByPk($iSurveyID)->language), array('order' => 'sortorder, answer'));
                     foreach ($lresult as $lrows) {
                         $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'] . "#1", "{$lrows['code']}", "{$lrows['code']}");
                     }
                     // Only Show No-Answer if question is not mandatory
                     if ($rows['mandatory'] != 'Y') {
                         $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'] . "#0", "", $clang->gT("No answer"));
                         $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'] . "#1", "", $clang->gT("No answer"));
                     }
                 }
                 //while
             } elseif ($rows['type'] == "K" || $rows['type'] == "Q") {
                 $aresult = Questions::model()->findAllByAttributes(array("parent_qid" => $rows['qid'], "language" => Survey::model()->findByPk($iSurveyID)->language), array('order' => 'question_order desc'));
                 foreach ($aresult as $arows) {
                     $shortanswer = "{$arows['title']}: [" . strip_tags($arows['question']) . "]";
                     $shortquestion = $rows['title'] . ":{$shortanswer} " . strip_tags($rows['question']);
                     $cquestions[] = array($shortquestion, $rows['qid'], $rows['type'], $rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title']);
                     // Only Show No-Answer if question is not mandatory
                     if ($rows['mandatory'] != 'Y') {
                         $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], "", $clang->gT("No answer"));
                     }
                 }
                 //while
             } elseif ($rows['type'] == "R") {
                 $aresult = Answers::model()->findAllByAttributes(array("qid" => $rows['qid'], "scale_id" => 0, "language" => Survey::model()->findByPk($iSurveyID)->language), array('order' => 'sortorder, answer'));
                 $acount = count($aresult);
                 foreach ($aresult as $arow) {
                     $theanswer = addcslashes($arow['answer'], "'");
                     $quicky[] = array($arow['code'], $theanswer);
                 }
                 for ($i = 1; $i <= $acount; $i++) {
                     $cquestions[] = array("{$rows['title']}: [RANK {$i}] " . strip_tags($rows['question']), $rows['qid'], $rows['type'], $rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $i);
                     foreach ($quicky as $qck) {
                         $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $i, $qck[0], $qck[1]);
                     }
                     // Only Show No-Answer if question is not mandatory
                     if ($rows['mandatory'] != 'Y') {
                         $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $i, " ", $clang->gT("No answer"));
                     }
                 }
                 unset($quicky);
             } elseif ($rows['type'] == "M" || $rows['type'] == "P") {
                 $shortanswer = " [" . $clang->gT("Group of checkboxes") . "]";
                 $shortquestion = $rows['title'] . ":{$shortanswer} " . strip_tags($rows['question']);
                 $cquestions[] = array($shortquestion, $rows['qid'], $rows['type'], $rows['sid'] . $X . $rows['gid'] . $X . $rows['qid']);
                 $aresult = Questions::model()->findAllByAttributes(array("parent_qid" => $rows['qid'], "language" => Survey::model()->findByPk($iSurveyID)->language), array('order' => 'question_order desc'));
                 foreach ($aresult as $arows) {
                     $theanswer = addcslashes($arows['question'], "'");
                     $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], $arows['title'], $theanswer);
                     $shortanswer = "{$arows['title']}: [" . strip_tags($arows['question']) . "]";
                     $shortanswer .= "[" . $clang->gT("Single checkbox") . "]";
                     $shortquestion = $rows['title'] . ":{$shortanswer} " . strip_tags($rows['question']);
                     $cquestions[] = array($shortquestion, $rows['qid'], $rows['type'], "+" . $rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title']);
                     $canswers[] = array("+" . $rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], 'Y', $clang->gT("checked"));
                     $canswers[] = array("+" . $rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], '', $clang->gT("not checked"));
                 }
             } elseif ($rows['type'] == "X") {
                 //Just ignore this questiontype
             } else {
                 $cquestions[] = array($shortquestion, $rows['qid'], $rows['type'], $rows['sid'] . $X . $rows['gid'] . $X . $rows['qid']);
                 switch ($rows['type']) {
                     case "Y":
                         // Y/N/NA
                         $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], "Y", $clang->gT("Yes"));
                         $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], "N", $clang->gT("No"));
                         // Only Show No-Answer if question is not mandatory
                         if ($rows['mandatory'] != 'Y') {
                             $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], " ", $clang->gT("No answer"));
                         }
                         break;
                     case "G":
                         //Gender
                         $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], "F", $clang->gT("Female"));
                         $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], "M", $clang->gT("Male"));
                         // Only Show No-Answer if question is not mandatory
                         if ($rows['mandatory'] != 'Y') {
                             $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], " ", $clang->gT("No answer"));
                         }
                         break;
                     case "5":
                         // 5 choice
                         for ($i = 1; $i <= 5; $i++) {
                             $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], $i, $i);
                         }
                         // Only Show No-Answer if question is not mandatory
                         if ($rows['mandatory'] != 'Y') {
                             $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], " ", $clang->gT("No answer"));
                         }
                         break;
                     case "N":
                         // Simple Numerical questions
                         // Only Show No-Answer if question is not mandatory
                         if ($rows['mandatory'] != 'Y') {
                             $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], " ", $clang->gT("No answer"));
                         }
                         break;
                     default:
                         $aresult = Answers::model()->findAllByAttributes(array('qid' => $rows['qid'], 'scale_id' => 0, 'language' => Survey::model()->findByPk($iSurveyID)->language), array('order' => 'sortorder, answer'));
                         foreach ($aresult as $arows) {
                             $theanswer = addcslashes($arows['answer'], "'");
                             $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], $arows['code'], $theanswer);
                         }
                         if ($rows['type'] == "D") {
                             // Only Show No-Answer if question is not mandatory
                             if ($rows['mandatory'] != 'Y') {
                                 $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], " ", $clang->gT("No answer"));
                             }
                         } elseif ($rows['type'] != "M" && $rows['type'] != "P" && $rows['type'] != "J" && $rows['type'] != "I") {
                             // For dropdown questions
                             // optinnaly add the 'Other' answer
                             if (($rows['type'] == "L" || $rows['type'] == "!") && $rows['other'] == "Y") {
                                 $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], "-oth-", $clang->gT("Other"));
                             }
                             // Only Show No-Answer if question is not mandatory
                             if ($rows['mandatory'] != 'Y') {
                                 $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], " ", $clang->gT("No answer"));
                             }
                         }
                         break;
                 }
                 //switch row type
             }
             //else
         }
         //foreach theserows
     }
     //if questionscount > 0
     //END Gather Information for this question
     $questionNavOptions = CHtml::openTag('optgroup', array('class' => 'activesurveyselect', 'label' => $clang->gT("Before", "js")));
     foreach ($theserows as $row) {
         $question = $row['question'];
         $question = strip_tags($question);
         if (strlen($question) < 35) {
             $questionselecter = $question;
         } else {
             //$questionselecter = substr($question, 0, 35)."..";
             $questionselecter = htmlspecialchars(mb_strcut(html_entity_decode($question, ENT_QUOTES, 'UTF-8'), 0, 35, 'UTF-8')) . "...";
         }
         $questionNavOptions .= CHtml::tag('option', array('value' => $this->getController()->createUrl("/admin/conditions/sa/index/subaction/editconditionsform/surveyid/{$iSurveyID}/gid/{$row['gid']}/qid/{$row['qid']}")), $questionselecter);
     }
     $questionNavOptions .= CHtml::closeTag('optgroup');
     $questionNavOptions .= CHtml::openTag('optgroup', array('class' => 'activesurveyselect', 'label' => $clang->gT("Current", "js")));
     $question = strip_tags($questiontext);
     if (strlen($question) < 35) {
         $questiontextshort = $question;
     } else {
         //$questiontextshort = substr($question, 0, 35)."..";
         $questiontextshort = htmlspecialchars(mb_strcut(html_entity_decode($question, ENT_QUOTES, 'UTF-8'), 0, 35, 'UTF-8')) . "...";
     }
     $questionNavOptions .= CHtml::tag('option', array('value' => $this->getController()->createUrl("/admin/conditions/sa/index/subaction/editconditionsform/surveyid/{$iSurveyID}/gid/{$gid}/qid/{$qid}"), 'selected' => 'selected'), $questiontitle . ': ' . $questiontextshort);
     $questionNavOptions .= CHtml::closeTag('optgroup');
     $questionNavOptions .= CHtml::openTag('optgroup', array('class' => 'activesurveyselect', 'label' => $clang->gT("After", "js")));
     foreach ($postrows as $row) {
         $question = $row['question'];
         $question = strip_tags($question);
         if (strlen($question) < 35) {
             $questionselecter = $question;
         } else {
             //$questionselecter = substr($question, 0, 35)."..";
             $questionselecter = htmlspecialchars(mb_strcut(html_entity_decode($question, ENT_QUOTES, 'UTF-8'), 0, 35, 'UTF-8')) . "...";
         }
         $questionNavOptions .= CHtml::tag('option', array('value' => $this->getController()->createUrl("/admin/conditions/sa/index/subaction/editconditionsform/surveyid/{$iSurveyID}/gid/{$row['gid']}/qid/{$row['qid']}")), $row['title'] . ':' . $questionselecter);
     }
     $questionNavOptions .= CHtml::closeTag('optgroup');
     //Now display the information and forms
     //BEGIN: PREPARE JAVASCRIPT TO SHOW MATCHING ANSWERS TO SELECTED QUESTION
     $javascriptpre = CHtml::openTag('script', array('type' => 'text/javascript')) . "<!--\n" . "\tvar Fieldnames = new Array();\n" . "\tvar Codes = new Array();\n" . "\tvar Answers = new Array();\n" . "\tvar QFieldnames = new Array();\n" . "\tvar Qcqids = new Array();\n" . "\tvar Qtypes = new Array();\n";
     $jn = 0;
     if (isset($canswers)) {
         foreach ($canswers as $can) {
             $an = ls_json_encode(flattenText($can[2]));
             $javascriptpre .= "Fieldnames[{$jn}]='{$can['0']}';\n" . "Codes[{$jn}]='{$can['1']}';\n" . "Answers[{$jn}]={$an};\n";
             $jn++;
         }
     }
     $jn = 0;
     if (isset($cquestions)) {
         foreach ($cquestions as $cqn) {
             $javascriptpre .= "QFieldnames[{$jn}]='{$cqn['3']}';\n" . "Qcqids[{$jn}]='{$cqn['1']}';\n" . "Qtypes[{$jn}]='{$cqn['2']}';\n";
             $jn++;
         }
     }
     //  record a JS variable to let jQuery know if survey is Anonymous
     if ($thissurvey['anonymized'] == 'Y') {
         $javascriptpre .= "isAnonymousSurvey = true;";
     } else {
         $javascriptpre .= "isAnonymousSurvey = false;";
     }
     $javascriptpre .= "//-->\n" . CHtml::closeTag('script');
     //END: PREPARE JAVASCRIPT TO SHOW MATCHING ANSWERS TO SELECTED QUESTION
     $this->getController()->_css_admin_includes(Yii::app()->getConfig("publicstyleurl") . 'jquery.multiselect.css');
     $aViewUrls = array();
     $aData['clang'] = $clang;
     $aData['surveyid'] = $iSurveyID;
     $aData['qid'] = $qid;
     $aData['gid'] = $gid;
     $aData['imageurl'] = $imageurl;
     $aData['extraGetParams'] = $extraGetParams;
     $aData['quesitonNavOptions'] = $questionNavOptions;
     $aData['conditionsoutput_action_error'] = $conditionsoutput_action_error;
     $aData['javascriptpre'] = $javascriptpre;
     $aViewUrls['conditionshead_view'][] = $aData;
     //BEGIN DISPLAY CONDITIONS FOR THIS QUESTION
     if ($subaction == 'index' || $subaction == 'editconditionsform' || $subaction == 'insertcondition' || $subaction == "editthiscondition" || $subaction == "delete" || $subaction == "updatecondition" || $subaction == "deletescenario" || $subaction == "renumberscenarios" || $subaction == "deleteallconditions" || $subaction == "updatescenario" || $subaction == 'copyconditionsform' || $subaction == 'copyconditions' || $subaction == 'conditions') {
         //3: Get other conditions currently set for this question
         $conditionscount = 0;
         $s = 0;
         $criteria = new CDbCriteria();
         $criteria->select = 'scenario';
         // only select the 'scenario' column
         $criteria->condition = 'qid=:qid';
         $criteria->params = array(':qid' => $qid);
         $criteria->order = 'scenario';
         $criteria->group = 'scenario';
         $scenarioresult = Conditions::model()->findAll($criteria);
         $scenariocount = count($scenarioresult);
         $showreplace = "{$questiontitle}" . $this->_showSpeaker($questiontext);
         $onlyshow = sprintf($clang->gT("Only show question %s IF"), $showreplace);
         $aData['conditionsoutput'] = '';
         $aData['extraGetParams'] = $extraGetParams;
         $aData['quesitonNavOptions'] = $questionNavOptions;
         $aData['conditionsoutput_action_error'] = $conditionsoutput_action_error;
         $aData['javascriptpre'] = $javascriptpre;
         $aData['onlyshow'] = $onlyshow;
         $aData['subaction'] = $subaction;
         $aData['scenariocount'] = $scenariocount;
         $aViewUrls['conditionslist_view'][] = $aData;
         if ($scenariocount > 0) {
             //self::_js_admin_includes($this->config->item("generalscripts").'jquery/jquery.checkgroup.js');
             $this->getController()->_js_admin_includes(Yii::app()->getConfig("generalscripts") . 'jquery/jquery.checkgroup.js');
             foreach ($scenarioresult as $scenarionr) {
                 $scenariotext = "";
                 if ($s == 0 && $scenariocount > 1) {
                     $scenariotext = " -------- <i>Scenario {$scenarionr['scenario']}</i> --------";
                 }
                 if ($s > 0) {
                     $scenariotext = " -------- <i>" . $clang->gT("OR") . " Scenario {$scenarionr['scenario']}</i> --------";
                 }
                 if ($subaction == "copyconditionsform" || $subaction == "copyconditions") {
                     $initialCheckbox = "<td><input type='checkbox' id='scenarioCbx{$scenarionr['scenario']}' checked='checked'/>\n" . "<script type='text/javascript'>\$(document).ready(function () { \$('#scenarioCbx{$scenarionr['scenario']}').checkgroup({ groupName:'aConditionFromScenario{$scenarionr['scenario']}'}); });</script>" . "</td><td>&nbsp;</td>\n";
                 } else {
                     $initialCheckbox = "";
                 }
                 if ($scenariotext != "" && ($subaction == "editconditionsform" || $subaction == "insertcondition" || $subaction == "updatecondition" || $subaction == "editthiscondition" || $subaction == "renumberscenarios" || $subaction == "updatescenario" || $subaction == "deletescenario" || $subaction == "delete")) {
                     $img_tag = CHtml::image($imageurl . '/scenario_delete.png', $clang->gT("Delete this scenario"), array('name' => 'DeleteWholeGroup'));
                     $additional_main_content = CHtml::link($img_tag, '#', array('onclick' => "if ( confirm('" . $clang->gT("Are you sure you want to delete all conditions set in this scenario?", "js") . "')) { document.getElementById('deletescenario{$scenarionr['scenario']}').submit();}"));
                     $img_tag = CHtml::image($imageurl . '/scenario_edit.png', $clang->gT("Edit scenario"), array('name' => 'DeleteWholeGroup'));
                     $additional_main_content .= CHtml::link($img_tag, '#', array('id' => 'editscenariobtn' . $scenarionr['scenario'], 'onclick' => "\$('#editscenario{$scenarionr['scenario']}').toggle('slow');"));
                     $aData['additional_content'] = $additional_main_content;
                 }
                 $aData['initialCheckbox'] = $initialCheckbox;
                 $aData['scenariotext'] = $scenariotext;
                 $aData['scenarionr'] = $scenarionr;
                 if (!isset($aViewUrls['output'])) {
                     $aViewUrls['output'] = '';
                 }
                 $aViewUrls['output'] .= $this->getController()->render('/admin/conditions/includes/conditions_scenario', $aData, TRUE);
                 unset($currentfield);
                 $query = "SELECT count(*) as recordcount\n                    FROM {{conditions}} c, {{questions}} q, {{groups}} g\n                    WHERE c.cqid=q.qid " . "AND q.gid=g.gid " . "AND q.parent_qid=0 " . "AND q.language=:lang1 " . "AND g.language=:lang2 " . "AND c.qid=:qid " . "AND c.scenario=:scenario " . "AND c.cfieldname NOT LIKE '{%' ";
                 // avoid catching SRCtokenAttr conditions
                 $sLanguage = Survey::model()->findByPk($iSurveyID)->language;
                 $result = Yii::app()->db->createCommand($query)->bindValue(":scenario", $scenarionr['scenario'])->bindValue(":qid", $qid, PDO::PARAM_INT)->bindValue(":lang1", $sLanguage, PDO::PARAM_STR)->bindValue(":lang2", $sLanguage, PDO::PARAM_STR)->queryRow();
                 $conditionscount = (int) $result['recordcount'];
                 $query = "SELECT c.cid, c.scenario, c.cqid, c.cfieldname, c.method, c.value, q.type\n                    FROM {{conditions}} c, {{questions}} q, {{groups}} g\n                    WHERE c.cqid=q.qid " . "AND q.gid=g.gid " . "AND q.parent_qid=0 " . "AND q.language=:lang1 " . "AND g.language=:lang2 " . "AND c.qid=:qid " . "AND c.scenario=:scenario " . "AND c.cfieldname NOT LIKE '{%' " . "ORDER BY g.group_order, q.question_order, c.cfieldname";
                 $sLanguage = Survey::model()->findByPk($iSurveyID)->language;
                 $result = Yii::app()->db->createCommand($query)->bindValue(":scenario", $scenarionr['scenario'])->bindValue(":qid", $qid, PDO::PARAM_INT)->bindValue(":lang1", $sLanguage, PDO::PARAM_STR)->bindValue(":lang2", $sLanguage, PDO::PARAM_STR)->query() or safeDie("Couldn't get other conditions for question {$qid}<br />{$query}<br />");
                 $querytoken = "SELECT count(*) as recordcount " . "FROM {{conditions}} " . "WHERE " . " {{conditions}}.qid=:qid " . "AND {{conditions}}.scenario=:scenario " . "AND {{conditions}}.cfieldname LIKE '{%' ";
                 // only catching SRCtokenAttr conditions
                 $resulttoken = Yii::app()->db->createCommand($querytoken)->bindValue(":scenario", $scenarionr['scenario'], PDO::PARAM_INT)->bindValue(":qid", $qid, PDO::PARAM_INT)->queryRow() or safeDie("Couldn't get other conditions for question {$qid}<br />{$query}<br />");
                 $conditionscounttoken = (int) $resulttoken['recordcount'];
                 $querytoken = "SELECT {{conditions}}.cid, " . "{{conditions}}.scenario, " . "{{conditions}}.cqid, " . "{{conditions}}.cfieldname, " . "{{conditions}}.method, " . "{{conditions}}.value, " . "'' AS type " . "FROM {{conditions}} " . "WHERE " . " {{conditions}}.qid=:qid " . "AND {{conditions}}.scenario=:scenario " . "AND {{conditions}}.cfieldname LIKE '{%' " . "ORDER BY {{conditions}}.cfieldname";
                 $resulttoken = Yii::app()->db->createCommand($querytoken)->bindValue(":scenario", $scenarionr['scenario'], PDO::PARAM_INT)->bindValue(":qid", $qid, PDO::PARAM_INT)->query() or safeDie("Couldn't get other conditions for question {$qid}<br />{$query}<br />");
                 $conditionscount = $conditionscount + $conditionscounttoken;
                 if ($conditionscount > 0) {
                     $aConditionsMerged = array();
                     foreach ($resulttoken->readAll() as $arow) {
                         $aConditionsMerged[] = $arow;
                     }
                     foreach ($result->readAll() as $arow) {
                         $aConditionsMerged[] = $arow;
                     }
                     foreach ($aConditionsMerged as $rows) {
                         if ($rows['method'] == "") {
                             $rows['method'] = "==";
                         }
                         //Fill in the empty method from previous versions
                         $markcidstyle = "oddrow";
                         if (array_search($rows['cid'], $markcidarray) !== FALSE) {
                             // This is the style used when the condition editor is called
                             // in order to check which conditions prevent a question deletion
                             $markcidstyle = "markedrow";
                         }
                         if ($subaction == "editthiscondition" && isset($p_cid) && $rows['cid'] === $p_cid) {
                             // Style used when editing a condition
                             $markcidstyle = "editedrow";
                         }
                         if (isset($currentfield) && $currentfield != $rows['cfieldname']) {
                             $aViewUrls['output'] .= "<tr class='evenrow'>\n" . "\t<td colspan='2'>\n" . "<span><strong>" . $clang->gT("and") . "</strong></span></td></tr>";
                         } elseif (isset($currentfield)) {
                             $aViewUrls['output'] .= "<tr class='evenrow'>\n" . "\t<td colspan='2'>\n" . "<span><strong>" . $clang->gT("or") . "</strong></span></td></tr>";
                         }
                         $aViewUrls['output'] .= "\t<tr class='{$markcidstyle}'>\n" . "\t<td colspan='2'>" . CHtml::form(array("/admin/conditions/sa/index/subaction/{$subaction}/surveyid/{$iSurveyID}/gid/{$gid}/qid/{$qid}/"), 'post', array('id' => "conditionaction{$rows['cid']}", 'name' => "conditionaction{$rows['cid']}")) . "<table>\n" . "\t<tr>\n";
                         if ($subaction == "copyconditionsform" || $subaction == "copyconditions") {
                             $aViewUrls['output'] .= "<td>&nbsp;&nbsp;</td>" . "<td>\n" . "\t<input type='checkbox' name='aConditionFromScenario{$scenarionr['scenario']}' id='cbox{$rows['cid']}' value='{$rows['cid']}' checked='checked'/>\n" . "</td>\n";
                         }
                         $aViewUrls['output'] .= "" . "<td>\n" . "\t<span>\n";
                         $leftOperandType = 'unknown';
                         // prevquestion, tokenattr
                         if ($thissurvey['anonymized'] != 'Y' && preg_match('/^{TOKEN:([^}]*)}$/', $rows['cfieldname'], $extractedTokenAttr) > 0) {
                             $leftOperandType = 'tokenattr';
                             $aTokenAttrNames = getTokenFieldsAndNames($iSurveyID);
                             if (count($aTokenAttrNames) != 0) {
                                 $thisAttrName = HTMLEscape($aTokenAttrNames[strtolower($extractedTokenAttr[1])]['description']) . " [" . $clang->gT("From token table") . "]";
                             } else {
                                 $thisAttrName = HTMLEscape($extractedTokenAttr[1]) . " [" . $clang->gT("Inexistant token table") . "]";
                             }
                             $aViewUrls['output'] .= "\t{$thisAttrName}\n";
                             // TIBO not sure this is used anymore !!
                             $conditionsList[] = array("cid" => $rows['cid'], "text" => $thisAttrName);
                         } else {
                             $leftOperandType = 'prevquestion';
                             foreach ($cquestions as $cqn) {
                                 if ($cqn[3] == $rows['cfieldname']) {
                                     $aViewUrls['output'] .= "\t{$cqn['0']} (qid{$rows['cqid']})\n";
                                     $conditionsList[] = array("cid" => $rows['cid'], "text" => $cqn[0] . " ({$rows['value']})");
                                 } else {
                                     //$aViewUrls['output'] .= "\t<font color='red'>ERROR: Delete this condition. It is out of order.</font>\n";
                                 }
                             }
                         }
                         $aViewUrls['output'] .= "\t</span></td>\n" . "\t<td>\n" . "<span>\n" . $method[trim($rows['method'])] . "</span>\n" . "\t</td>\n" . "\n" . "\t<td>\n" . "<span>\n";
                         // let's read the condition's right operand
                         // determine its type and display it
                         $rightOperandType = 'unknown';
                         // predefinedAnsw,constantVal, prevQsgqa, tokenAttr, regexp
                         if ($rows['method'] == 'RX') {
                             $rightOperandType = 'regexp';
                             $aViewUrls['output'] .= "" . HTMLEscape($rows['value']) . "\n";
                         } elseif (preg_match('/^@([0-9]+X[0-9]+X[^@]*)@$/', $rows['value'], $matchedSGQA) > 0) {
                             // SGQA
                             $rightOperandType = 'prevQsgqa';
                             $textfound = false;
                             foreach ($cquestions as $cqn) {
                                 if ($cqn[3] == $matchedSGQA[1]) {
                                     $matchedSGQAText = $cqn[0];
                                     $textfound = true;
                                     break;
                                 }
                             }
                             if ($textfound === false) {
                                 $matchedSGQAText = $rows['value'] . ' (' . $clang->gT("Not found") . ')';
                             }
                             $aViewUrls['output'] .= "" . HTMLEscape($matchedSGQAText) . "\n";
                         } elseif ($thissurvey['anonymized'] != 'Y' && preg_match('/^{TOKEN:([^}]*)}$/', $rows['value'], $extractedTokenAttr) > 0) {
                             $rightOperandType = 'tokenAttr';
                             $aTokenAttrNames = getTokenFieldsAndNames($iSurveyID);
                             if (count($aTokenAttrNames) != 0) {
                                 $thisAttrName = HTMLEscape($aTokenAttrNames[strtolower($extractedTokenAttr[1])]['description']) . " [" . $clang->gT("From token table") . "]";
                             } else {
                                 $thisAttrName = HTMLEscape($extractedTokenAttr[1]) . " [" . $clang->gT("Inexistant token table") . "]";
                             }
                             $aViewUrls['output'] .= "\t{$thisAttrName}\n";
                         } elseif (isset($canswers)) {
                             foreach ($canswers as $can) {
                                 if ($can[0] == $rows['cfieldname'] && $can[1] == $rows['value']) {
                                     $aViewUrls['output'] .= "{$can['2']} ({$can['1']})\n";
                                     $rightOperandType = 'predefinedAnsw';
                                 }
                             }
                         }
                         // if $rightOperandType is still unkown then it is a simple constant
                         if ($rightOperandType == 'unknown') {
                             $rightOperandType = 'constantVal';
                             if ($rows['value'] == ' ' || $rows['value'] == '') {
                                 $aViewUrls['output'] .= "" . $clang->gT("No answer") . "\n";
                             } else {
                                 $aViewUrls['output'] .= "" . HTMLEscape($rows['value']) . "\n";
                             }
                         }
                         $aViewUrls['output'] .= "\t</span></td>\n" . "\t<td>\n";
                         if ($subaction == "editconditionsform" || $subaction == "insertcondition" || $subaction == "updatecondition" || $subaction == "editthiscondition" || $subaction == "renumberscenarios" || $subaction == "deleteallconditions" || $subaction == "updatescenario" || $subaction == "deletescenario" || $subaction == "delete") {
                             // show single condition action buttons in edit mode
                             $aData['rows'] = $rows;
                             $aData['sImageURL'] = Yii::app()->getConfig('adminimageurl');
                             //$aViewUrls['includes/conditions_edit'][] = $aData;
                             $aViewUrls['output'] .= $this->getController()->render('/admin/conditions/includes/conditions_edit', $aData, TRUE);
                             // now sets e corresponding hidden input field
                             // depending on the leftOperandType
                             if ($leftOperandType == 'tokenattr') {
                                 $aViewUrls['output'] .= CHtml::hiddenField('csrctoken', HTMLEscape($rows['cfieldname']), array('id' => 'csrctoken' . $rows['cid']));
                             } else {
                                 $aViewUrls['output'] .= CHtml::hiddenField('cquestions', HTMLEscape($rows['cfieldname']), array('id' => 'cquestions' . $rows['cid']));
                             }
                             // now set the corresponding hidden input field
                             // depending on the rightOperandType
                             // This is used when Editting a condition
                             if ($rightOperandType == 'predefinedAnsw') {
                                 $aViewUrls['output'] .= CHtml::hiddenField('EDITcanswers[]', HTMLEscape($rows['value']), array('id' => 'editModeTargetVal' . $rows['cid']));
                             } elseif ($rightOperandType == 'prevQsgqa') {
                                 $aViewUrls['output'] .= CHtml::hiddenField('EDITprevQuestionSGQA', HTMLEscape($rows['value']), array('id' => 'editModeTargetVal' . $rows['cid']));
                             } elseif ($rightOperandType == 'tokenAttr') {
                                 $aViewUrls['output'] .= CHtml::hiddenField('EDITtokenAttr', HTMLEscape($rows['value']), array('id' => 'editModeTargetVal' . $rows['cid']));
                             } elseif ($rightOperandType == 'regexp') {
                                 $aViewUrls['output'] .= CHtml::hiddenField('EDITConditionRegexp', HTMLEscape($rows['value']), array('id' => 'editModeTargetVal' . $rows['cid']));
                             } else {
                                 $aViewUrls['output'] .= CHtml::hiddenField('EDITConditionConst', HTMLEscape($rows['value']), array('id' => 'editModeTargetVal' . $rows['cid']));
                             }
                         }
                         $aViewUrls['output'] .= CHtml::closeTag('td') . CHtml::closeTag('tr') . CHtml::closeTag('table') . CHtml::closeTag('form') . CHtml::closeTag('td') . CHtml::closeTag('tr');
                         $currentfield = $rows['cfieldname'];
                     }
                 }
                 $s++;
             }
         } else {
             // no condition ==> disable delete all conditions button, and display a simple comment
             $aViewUrls['output'] = CHtml::openTag('tr') . CHtml::tag('td', array(), $clang->gT("This question is always shown.")) . CHtml::tag('td', array(), '&nbsp;') . CHtml::closeTag('tr');
         }
         $aViewUrls['output'] .= CHtml::closeTag('table');
     }
     //END DISPLAY CONDITIONS FOR THIS QUESTION
     // BEGIN: DISPLAY THE COPY CONDITIONS FORM
     if ($subaction == "copyconditionsform" || $subaction == "copyconditions") {
         $aViewUrls['output'] .= "<tr class=''><td colspan='3'>\n" . CHtml::form(array("/admin/conditions/sa/index/subaction/copyconditions/surveyid/{$iSurveyID}/gid/{$gid}/qid/{$qid}/"), 'post', array('id' => "copyconditions", 'name' => "copyconditions")) . "<div class='header ui-widget-header'>" . $clang->gT("Copy conditions") . "</div>\n";
         //CopyConditionsMessage
         if (isset($CopyConditionsMessage)) {
             $aViewUrls['output'] .= "<div class='messagebox ui-corner-all'>\n" . "{$CopyConditionsMessage}\n" . "</div>\n";
         }
         if (isset($conditionsList) && is_array($conditionsList)) {
             //TIBO
             $this->getController()->_js_admin_includes(Yii::app()->getConfig("generalscripts") . 'jquery/jquery.multiselect.min.js');
             // TODO
             $aViewUrls['output'] .= "<script type='text/javascript'>\$(document).ready(function () { \$('#copytomultiselect').multiselect( { autoOpen: true, noneSelectedText: '" . $clang->gT("No questions selected") . "', checkAllText: '" . $clang->gT("Check all") . "', uncheckAllText: '" . $clang->gT("Uncheck all") . "', selectedText: '# " . $clang->gT("selected") . "', beforeclose: function(){ return false;},height: 200 } ); });</script>";
             $aViewUrls['output'] .= "\t<div class='conditioncopy-tbl-row'>\n" . "\t<div class='condition-tbl-left'>" . $clang->gT("Copy the selected conditions to") . ":</div>\n" . "\t<div class='condition-tbl-right'>\n" . "\t\t<select name='copyconditionsto[]' id='copytomultiselect'  multiple='multiple' >\n";
             if (isset($pquestions) && count($pquestions) != 0) {
                 foreach ($pquestions as $pq) {
                     $aViewUrls['output'] .= "\t\t<option value='{$pq['fieldname']}'>" . $pq['text'] . "</option>\n";
                 }
             }
             $aViewUrls['output'] .= "\t\t</select>\n" . "\t</div>\n" . "\t</div>\n";
             if (!isset($pquestions) || count($pquestions) == 0) {
                 $disableCopyCondition = " disabled='disabled'";
             } else {
                 $disableCopyCondition = " ";
             }
             $aViewUrls['output'] .= "\t<div class='condition-tbl-full'>\n" . "\t\t<input type='submit' value='" . $clang->gT("Copy conditions") . "' onclick=\"prepareCopyconditions(); return true;\" {$disableCopyCondition}/>\n" . "<input type='hidden' name='subaction' value='copyconditions' />\n" . "<input type='hidden' name='sid' value='{$iSurveyID}' />\n" . "<input type='hidden' name='gid' value='{$gid}' />\n" . "<input type='hidden' name='qid' value='{$qid}' />\n" . "</div>\n";
             $aViewUrls['output'] .= "<script type=\"text/javascript\">\n" . "function prepareCopyconditions()\n" . "{\n" . "\t\$(\"input:checked[name^='aConditionFromScenario']\").each(function(i,val)\n" . "\t{\n" . "var thecid = val.value;\n" . "var theform = document.getElementById('copyconditions');\n" . "addHiddenElement(theform,'copyconditionsfrom[]',thecid);\n" . "return true;\n" . "\t});\n" . "}\n" . "</script>\n";
         } else {
             $aViewUrls['output'] .= "<div class='messagebox ui-corner-all'>\n" . "<div class='partialheader'>" . $clang->gT("There are no existing conditions in this survey.") . "</div><br />\n" . "</div>\n";
         }
         $aViewUrls['output'] .= "</form></td></tr>\n";
     }
     // END: DISPLAY THE COPY CONDITIONS FORM
     if (isset($cquestions)) {
         if (count($cquestions) > 0 && count($cquestions) <= 10) {
             $qcount = count($cquestions);
         } else {
             $qcount = 9;
         }
     } else {
         $qcount = 0;
     }
     //BEGIN: DISPLAY THE ADD or EDIT CONDITION FORM
     if ($subaction == "editconditionsform" || $subaction == "insertcondition" || $subaction == "updatecondition" || $subaction == "deletescenario" || $subaction == "renumberscenarios" || $subaction == "deleteallconditions" || $subaction == "updatescenario" || $subaction == "editthiscondition" || $subaction == "delete") {
         $aViewUrls['output'] .= CHtml::form(array("/admin/conditions/sa/index/subaction/{$subaction}/surveyid/{$iSurveyID}/gid/{$gid}/qid/{$qid}/"), 'post', array('id' => "editconditions", 'name' => "editconditions"));
         if ($subaction == "editthiscondition" && isset($p_cid)) {
             $mytitle = $clang->gT("Edit condition");
         } else {
             $mytitle = $clang->gT("Add condition");
         }
         $aViewUrls['output'] .= "<div class='header ui-widget-header'>" . $mytitle . "</div>\n";
         ///////////////////////////////////////////////////////////////////////////////////////////
         // Begin "Scenario" row
         if ($subaction != "editthiscondition" && isset($scenariocount) && ($scenariocount == 1 || $scenariocount == 0) || $subaction == "editthiscondition" && isset($scenario) && $scenario == 1) {
             $scenarioAddBtn = "\t<a id='scenarioaddbtn' href='#' onclick=\"\$('#scenarioaddbtn').hide();\$('#defaultscenariotxt').hide('slow');\$('#scenario').show('slow');\">" . "<img src='{$imageurl}/plus.png' alt='" . $clang->gT('Add scenario') . "' /></a>\n";
             $scenarioTxt = "<span id='defaultscenariotxt'>" . $clang->gT("Default scenario") . "</span>";
             $scenarioInputStyle = "style = 'display: none;'";
         } else {
             $scenarioAddBtn = "";
             $scenarioTxt = "";
             $scenarioInputStyle = "style = ''";
         }
         $aViewUrls['output'] .= "<div class='condition-tbl-row'>\n" . "<div class='condition-tbl-left'>{$scenarioAddBtn}&nbsp;" . $clang->gT("Scenario") . "</div>\n" . "<div class='condition-tbl-right'><input type='text' name='scenario' id='scenario' value='1' size='2' {$scenarioInputStyle}/>" . "{$scenarioTxt}\n" . "</div>\n" . "</div>\n";
         // Begin "Question" row
         $aViewUrls['output'] .= "<div class='condition-tbl-row'>\n" . "<div class='condition-tbl-left'>" . $clang->gT("Question") . "</div>\n" . "<div class='condition-tbl-right'>\n" . "\t<div id=\"conditionsource\" class=\"tabs-nav\">\n" . "\t<ul>\n" . "\t<li><a href=\"#SRCPREVQUEST\"><span>" . $clang->gT("Previous questions") . "</span></a></li>\n" . "\t<li><a href=\"#SRCTOKENATTRS\"><span>" . $clang->gT("Token fields") . "</span></a></li>\n" . "\t</ul>\n";
         // Previous question tab
         $aViewUrls['output'] .= "<div id='SRCPREVQUEST'><select name='cquestions' id='cquestions' size='" . ($qcount + 1) . "' >\n";
         if (isset($cquestions)) {
             $js_getAnswers_onload = "";
             foreach ($cquestions as $cqn) {
                 $aViewUrls['output'] .= "<option value='{$cqn['3']}' title=\"" . htmlspecialchars($cqn[0]) . "\"";
                 if (isset($p_cquestions) && $cqn[3] == $p_cquestions) {
                     $aViewUrls['output'] .= " selected";
                     if (isset($p_canswers)) {
                         $canswersToSelect = "";
                         foreach ($p_canswers as $checkval) {
                             $canswersToSelect .= ";{$checkval}";
                         }
                         $canswersToSelect = substr($canswersToSelect, 1);
                         $js_getAnswers_onload .= "\$('#canswersToSelect').val('{$canswersToSelect}');\n";
                     }
                 }
                 $aViewUrls['output'] .= ">{$cqn['0']}</option>\n";
             }
         }
         $aViewUrls['output'] .= "</select>\n" . "</div>\n";
         // Source token Tab
         $aViewUrls['output'] .= "<div id='SRCTOKENATTRS'><select name='csrctoken' id='csrctoken' size='" . ($qcount + 1) . "' >\n";
         foreach (getTokenFieldsAndNames($iSurveyID) as $tokenattr => $tokenattrName) {
             // Check to select
             if (isset($p_csrctoken) && $p_csrctoken == '{TOKEN:' . strtoupper($tokenattr) . '}') {
                 $selectThisSrcTokenAttr = "selected=\"selected\"";
             } else {
                 $selectThisSrcTokenAttr = "";
             }
             $aViewUrls['output'] .= "<option value='{TOKEN:" . strtoupper($tokenattr) . "}' {$selectThisSrcTokenAttr}>" . HTMLEscape($tokenattrName['description']) . "</option>\n";
         }
         $aViewUrls['output'] .= "</select>\n" . "</div>\n\n";
         $aViewUrls['output'] .= "\t</div>\n";
         // end conditionsource div
         $aViewUrls['output'] .= "</div>\n" . "</div>\n";
         // Begin "Comparison operator" row
         $aViewUrls['output'] .= "<div class='condition-tbl-row'>\n" . "<div class='condition-tbl-left'>" . $clang->gT("Comparison operator") . "</div>\n" . "<div class='condition-tbl-right'>\n" . "<select name='method' id='method'>\n";
         foreach ($method as $methodCode => $methodTxt) {
             $selected = $methodCode == "==" ? " selected='selected'" : "";
             $aViewUrls['output'] .= "\t<option value='" . $methodCode . "'{$selected}>" . $methodTxt . "</option>\n";
         }
         $aViewUrls['output'] .= "</select>\n" . "</div>\n" . "</div>\n";
         // Begin "Answer" row
         $aViewUrls['output'] .= "<div class='condition-tbl-row'>\n" . "<div class='condition-tbl-left'>" . $clang->gT("Answer") . "</div>\n";
         if ($subaction == "editthiscondition") {
             $multipletext = "";
             if (isset($_POST['EDITConditionConst']) && $_POST['EDITConditionConst'] != '') {
                 $EDITConditionConst = HTMLEscape($_POST['EDITConditionConst']);
             } else {
                 $EDITConditionConst = "";
             }
             if (isset($_POST['EDITConditionRegexp']) && $_POST['EDITConditionRegexp'] != '') {
                 $EDITConditionRegexp = HTMLEscape($_POST['EDITConditionRegexp']);
             } else {
                 $EDITConditionRegexp = "";
             }
         } else {
             $multipletext = "multiple";
             if (isset($_POST['ConditionConst']) && $_POST['ConditionConst'] != '') {
                 $EDITConditionConst = HTMLEscape($_POST['ConditionConst']);
             } else {
                 $EDITConditionConst = "";
             }
             if (isset($_POST['ConditionRegexp']) && $_POST['ConditionRegexp'] != '') {
                 $EDITConditionRegexp = HTMLEscape($_POST['ConditionRegexp']);
             } else {
                 $EDITConditionRegexp = "";
             }
         }
         $aViewUrls['output'] .= "" . "<div class='condition-tbl-right'>\n" . "<div id=\"conditiontarget\" class=\"tabs-nav\">\n" . "\t<ul>\n" . "\t\t<li><a href=\"#CANSWERSTAB\"><span>" . $clang->gT("Predefined") . "</span></a></li>\n" . "\t\t<li><a href=\"#CONST\"><span>" . $clang->gT("Constant") . "</span></a></li>\n" . "\t\t<li><a href=\"#PREVQUESTIONS\"><span>" . $clang->gT("Questions") . "</span></a></li>\n" . "\t\t<li><a href=\"#TOKENATTRS\"><span>" . $clang->gT("Token fields") . "</span></a></li>\n" . "\t\t<li><a href=\"#REGEXP\"><span>" . $clang->gT("RegExp") . "</span></a></li>\n" . "\t</ul>\n";
         // Predefined answers tab
         $aViewUrls['output'] .= "\t<div id='CANSWERSTAB'>\n" . "\t\t<select  name='canswers[]' {$multipletext} id='canswers' size='7'>\n" . "\t\t</select>\n" . "\t\t<br /><span id='canswersLabel'>" . $clang->gT("Predefined answer options for this question") . "</span>\n" . "\t</div>\n";
         // Constant tab
         $aViewUrls['output'] .= "\t<div id='CONST' style='display:block;' >\n" . "\t\t<textarea name='ConditionConst' id='ConditionConst' rows='5' cols='113'>{$EDITConditionConst}</textarea>\n" . "\t\t<br /><div id='ConditionConstLabel'>" . $clang->gT("Constant value") . "</div>\n" . "\t</div>\n";
         // Previous answers tab @SGQA@ placeholders
         $aViewUrls['output'] .= "\t<div id='PREVQUESTIONS'>\n" . "\t\t<select name='prevQuestionSGQA' id='prevQuestionSGQA' size='7'>\n";
         foreach ($cquestions as $cqn) {
             // building the @SGQA@ placeholders options
             if ($cqn[2] != 'M' && $cqn[2] != 'P') {
                 // Type M or P aren't real fieldnames and thus can't be used in @SGQA@ placehodlers
                 $aViewUrls['output'] .= "\t\t<option value='@{$cqn['3']}@' title=\"" . htmlspecialchars($cqn[0]) . "\"";
                 if (isset($p_prevquestionsgqa) && $p_prevquestionsgqa == "@" . $cqn[3] . "@") {
                     $aViewUrls['output'] .= " selected='selected'";
                 }
                 $aViewUrls['output'] .= ">{$cqn['0']}</option>\n";
             }
         }
         $aViewUrls['output'] .= "\t\t</select>\n" . "\t\t<br /><span id='prevQuestionSGQALabel'>" . $clang->gT("Answers from previous questions") . "</span>\n" . "\t</div>\n";
         // Token tab
         $aViewUrls['output'] .= "\t<div id='TOKENATTRS'>\n" . "\t\t<select name='tokenAttr' id='tokenAttr' size='7'>\n";
         foreach (getTokenFieldsAndNames($iSurveyID) as $tokenattr => $tokenattrName) {
             $aViewUrls['output'] .= "\t\t<option value='{TOKEN:" . strtoupper($tokenattr) . "}'>" . HTMLEscape($tokenattrName['description']) . "</option>\n";
         }
         $aViewUrls['output'] .= "\t\t</select>\n" . "\t\t<br /><span id='tokenAttrLabel'>" . $clang->gT("Attributes values from the participant's token") . "</span>\n" . "\t</div>\n";
         // Regexp Tab
         $aViewUrls['output'] .= "\t<div id='REGEXP' style='display:block;'>\n" . "\t\t<textarea name='ConditionRegexp' id='ConditionRegexp' rows='5' cols='113'>{$EDITConditionRegexp}</textarea>\n" . "\t\t<br /><div id='ConditionRegexpLabel'><a href=\"http://docs.limesurvey.org/tiki-index.php?page=Using+Regular+Expressions\" target=\"_blank\">" . $clang->gT("Regular expression") . "</a></div>\n" . "\t</div>\n";
         $aViewUrls['output'] .= "</div>\n";
         // end conditiontarget div
         $this->getController()->_js_admin_includes(Yii::app()->getConfig("adminscripts") . 'conditions.js');
         $this->getController()->_js_admin_includes(Yii::app()->getConfig("generalscripts") . 'jquery/lime-conditions-tabs.js');
         if ($subaction == "editthiscondition" && isset($p_cid)) {
             $submitLabel = $clang->gT("Update condition");
             $submitSubaction = "updatecondition";
             $submitcid = sanitize_int($p_cid);
         } else {
             $submitLabel = $clang->gT("Add condition");
             $submitSubaction = "insertcondition";
             $submitcid = "";
         }
         $aViewUrls['output'] .= "</div>\n" . "</div>\n";
         // Begin buttons row
         $aViewUrls['output'] .= "<div class='condition-tbl-full'>\n" . "\t<input type='reset' id='resetForm' value='" . $clang->gT("Clear") . "' />\n" . "\t<input type='submit' value='" . $submitLabel . "' />\n" . "<input type='hidden' name='sid' value='{$iSurveyID}' />\n" . "<input type='hidden' name='gid' value='{$gid}' />\n" . "<input type='hidden' name='qid' value='{$qid}' />\n" . "<input type='hidden' name='subaction' value='{$submitSubaction}' />\n" . "<input type='hidden' name='cqid' id='cqid' value='' />\n" . "<input type='hidden' name='cid' id='cid' value='" . $submitcid . "' />\n" . "<input type='hidden' name='editTargetTab' id='editTargetTab' value='' />\n" . "<input type='hidden' name='editSourceTab' id='editSourceTab' value='' />\n" . "<input type='hidden' name='canswersToSelect' id='canswersToSelect' value='' />\n" . "</div>\n" . "</form>\n";
         if (!isset($js_getAnswers_onload)) {
             $js_getAnswers_onload = '';
         }
         $aViewUrls['output'] .= "<script type='text/javascript'>\n" . "<!--\n" . "\t" . $js_getAnswers_onload . "\n";
         if (isset($p_method)) {
             $aViewUrls['output'] .= "\tdocument.getElementById('method').value='" . $p_method . "';\n";
         }
         if ($subaction == "editthiscondition") {
             // in edit mode we read previous values in order to dusplay them in the corresponding inputs
             if (isset($_POST['EDITConditionConst']) && $_POST['EDITConditionConst'] != '') {
                 // In order to avoid issues with backslash escaping, I don't use javascript to set the value
                 // Thus the value is directly set when creating the Textarea element
                 //$aViewUrls['output'] .= "\tdocument.getElementById('ConditionConst').value='".HTMLEscape($_POST['EDITConditionConst'])."';\n";
                 $aViewUrls['output'] .= "\tdocument.getElementById('editTargetTab').value='#CONST';\n";
             } elseif (isset($_POST['EDITprevQuestionSGQA']) && $_POST['EDITprevQuestionSGQA'] != '') {
                 $aViewUrls['output'] .= "\tdocument.getElementById('prevQuestionSGQA').value='" . HTMLEscape($_POST['EDITprevQuestionSGQA']) . "';\n";
                 $aViewUrls['output'] .= "\tdocument.getElementById('editTargetTab').value='#PREVQUESTIONS';\n";
             } elseif (isset($_POST['EDITtokenAttr']) && $_POST['EDITtokenAttr'] != '') {
                 $aViewUrls['output'] .= "\tdocument.getElementById('tokenAttr').value='" . HTMLEscape($_POST['EDITtokenAttr']) . "';\n";
                 $aViewUrls['output'] .= "\tdocument.getElementById('editTargetTab').value='#TOKENATTRS';\n";
             } elseif (isset($_POST['EDITConditionRegexp']) && $_POST['EDITConditionRegexp'] != '') {
                 // In order to avoid issues with backslash escaping, I don't use javascript to set the value
                 // Thus the value is directly set when creating the Textarea element
                 //$aViewUrls['output'] .= "\tdocument.getElementById('ConditionRegexp').value='".HTMLEscape($_POST['EDITConditionRegexp'])."';\n";
                 $aViewUrls['output'] .= "\tdocument.getElementById('editTargetTab').value='#REGEXP';\n";
             } elseif (isset($_POST['EDITcanswers']) && is_array($_POST['EDITcanswers'])) {
                 // was a predefined answers post
                 $aViewUrls['output'] .= "\tdocument.getElementById('editTargetTab').value='#CANSWERSTAB';\n";
                 $aViewUrls['output'] .= "\t\$('#canswersToSelect').val('" . $_POST['EDITcanswers'][0] . "');\n";
             }
             if (isset($_POST['csrctoken']) && $_POST['csrctoken'] != '') {
                 $aViewUrls['output'] .= "\tdocument.getElementById('csrctoken').value='" . HTMLEscape($_POST['csrctoken']) . "';\n";
                 $aViewUrls['output'] .= "\tdocument.getElementById('editSourceTab').value='#SRCTOKENATTRS';\n";
             } else {
                 if (isset($_POST['cquestions']) && $_POST['cquestions'] != '') {
                     $aViewUrls['output'] .= "\tdocument.getElementById('cquestions').value='" . HTMLEscape($_POST['cquestions']) . "';\n";
                     $aViewUrls['output'] .= "\tdocument.getElementById('editSourceTab').value='#SRCPREVQUEST';\n";
                 }
             }
         } else {
             // in other modes, for the moment we do the same as for edit mode
             if (isset($_POST['ConditionConst']) && $_POST['ConditionConst'] != '') {
                 // In order to avoid issues with backslash escaping, I don't use javascript to set the value
                 // Thus the value is directly set when creating the Textarea element
                 //$aViewUrls['output'] .= "\tdocument.getElementById('ConditionConst').value='".HTMLEscape($_POST['ConditionConst'])."';\n";
                 $aViewUrls['output'] .= "\tdocument.getElementById('editTargetTab').value='#CONST';\n";
             } elseif (isset($_POST['prevQuestionSGQA']) && $_POST['prevQuestionSGQA'] != '') {
                 $aViewUrls['output'] .= "\tdocument.getElementById('prevQuestionSGQA').value='" . HTMLEscape($_POST['prevQuestionSGQA']) . "';\n";
                 $aViewUrls['output'] .= "\tdocument.getElementById('editTargetTab').value='#PREVQUESTIONS';\n";
             } elseif (isset($_POST['tokenAttr']) && $_POST['tokenAttr'] != '') {
                 $aViewUrls['output'] .= "\tdocument.getElementById('tokenAttr').value='" . HTMLEscape($_POST['tokenAttr']) . "';\n";
                 $aViewUrls['output'] .= "\tdocument.getElementById('editTargetTab').value='#TOKENATTRS';\n";
             } elseif (isset($_POST['ConditionRegexp']) && $_POST['ConditionRegexp'] != '') {
                 // In order to avoid issues with backslash escaping, I don't use javascript to set the value
                 // Thus the value is directly set when creating the Textarea element
                 //$aViewUrls['output'] .= "\tdocument.getElementById('ConditionRegexp').value='".HTMLEscape($_POST['ConditionRegexp'])."';\n";
                 $aViewUrls['output'] .= "\tdocument.getElementById('editTargetTab').value='#REGEXP';\n";
             } else {
                 // was a predefined answers post
                 if (isset($_POST['cquestions'])) {
                     $aViewUrls['output'] .= "\tdocument.getElementById('cquestions').value='" . HTMLEscape($_POST['cquestions']) . "';\n";
                 }
                 $aViewUrls['output'] .= "\tdocument.getElementById('editTargetTab').value='#CANSWERSTAB';\n";
             }
             if (isset($_POST['csrctoken']) && $_POST['csrctoken'] != '') {
                 $aViewUrls['output'] .= "\tdocument.getElementById('csrctoken').value='" . HTMLEscape($_POST['csrctoken']) . "';\n";
                 $aViewUrls['output'] .= "\tdocument.getElementById('editSourceTab').value='#SRCTOKENATTRS';\n";
             } else {
                 if (isset($_POST['cquestions'])) {
                     $aViewUrls['output'] .= "\tdocument.getElementById('cquestions').value='" . javascriptEscape($_POST['cquestions']) . "';\n";
                 }
                 $aViewUrls['output'] .= "\tdocument.getElementById('editSourceTab').value='#SRCPREVQUEST';\n";
             }
         }
         if (isset($p_scenario)) {
             $aViewUrls['output'] .= "\tdocument.getElementById('scenario').value='" . $p_scenario . "';\n";
         }
         $aViewUrls['output'] .= "-->\n" . "</script>\n";
     }
     //END: DISPLAY THE ADD or EDIT CONDITION FORM
     $conditionsoutput = $aViewUrls['output'];
     $aData['conditionsoutput'] = $conditionsoutput;
     $this->_renderWrappedTemplate('conditions', $aViewUrls, $aData);
     // TMSW Conditions->Relevance:  Must call LEM->ConvertConditionsToRelevance() whenever Condition is added or updated - what is best location for that action?
 }
/**
* This function replaces the old insertans tags with new ones across a survey
*
* @param string $newsid  Old SID
* @param string $oldsid  New SID
* @param mixed $fieldnames Array  array('oldfieldname'=>'newfieldname')
*/
function translateInsertansTags($newsid, $oldsid, $fieldnames)
{
    uksort($fieldnames, create_function('$a,$b', 'return strlen($a) < strlen($b);'));
    Yii::app()->loadHelper('database');
    $newsid = sanitize_int($newsid);
    $oldsid = sanitize_int($oldsid);
    # translate 'surveyls_urldescription' and 'surveyls_url' INSERTANS tags in surveyls
    $sql = "SELECT surveyls_survey_id, surveyls_language, surveyls_urldescription, surveyls_url from {{surveys_languagesettings}}\n    WHERE surveyls_survey_id=" . $newsid . " AND (surveyls_urldescription LIKE '%{$oldsid}X%' OR surveyls_url LIKE '%{$oldsid}X%')";
    $result = dbExecuteAssoc($sql) or show_error("Can't read groups table in transInsertAns ");
    // Checked
    //while ($qentry = $res->FetchRow())
    foreach ($result->readAll() as $qentry) {
        $urldescription = $qentry['surveyls_urldescription'];
        $endurl = $qentry['surveyls_url'];
        $language = $qentry['surveyls_language'];
        foreach ($fieldnames as $sOldFieldname => $sNewFieldname) {
            $pattern = $sOldFieldname;
            $replacement = $sNewFieldname;
            $urldescription = preg_replace('/' . $pattern . '/', $replacement, $urldescription);
            $endurl = preg_replace('/' . $pattern . '/', $replacement, $endurl);
        }
        if (strcmp($urldescription, $qentry['surveyls_urldescription']) != 0 || strcmp($endurl, $qentry['surveyls_url']) != 0) {
            // Update Field
            $data = array('surveyls_urldescription' => $urldescription, 'surveyls_url' => $endurl);
            $where = array('surveyls_survey_id' => $newsid, 'surveyls_language' => $language);
            Surveys_languagesettings::update($data, $where);
        }
        // Enf if modified
    }
    // end while qentry
    # translate 'quotals_urldescrip' and 'quotals_url' INSERTANS tags in quota_languagesettings
    $sql = "SELECT quotals_id, quotals_urldescrip, quotals_url from {{quota_languagesettings}} qls, {{quota}} q\n    WHERE sid=" . $newsid . " AND q.id=qls.quotals_quota_id AND (quotals_urldescrip LIKE '%{$oldsid}X%' OR quotals_url LIKE '%{$oldsid}X%')";
    $result = dbExecuteAssoc($sql) or safeDie("Can't read quota table in transInsertAns");
    // Checked
    foreach ($result->readAll() as $qentry) {
        $urldescription = $qentry['quotals_urldescrip'];
        $endurl = $qentry['quotals_url'];
        foreach ($fieldnames as $sOldFieldname => $sNewFieldname) {
            $pattern = $sOldFieldname;
            $replacement = $sNewFieldname;
            $urldescription = preg_replace('/' . $pattern . '/', $replacement, $urldescription);
            $endurl = preg_replace('/' . $pattern . '/', $replacement, $endurl);
        }
        if (strcmp($urldescription, $qentry['quotals_urldescrip']) != 0 || strcmp($endurl, $qentry['quotals_url']) != 0) {
            // Update Field
            $sqlupdate = "UPDATE {{quota_languagesettings}} SET quotals_urldescrip='" . $urldescription . "', quotals_url='" . $endurl . "' WHERE quotals_id={$qentry['quotals_id']}";
            $updateres = dbExecuteAssoc($sqlupdate) or safeDie("Couldn't update INSERTANS in quota_languagesettings<br />{$sqlupdate}<br />");
            //Checked
        }
        // Enf if modified
    }
    // end while qentry
    # translate 'description' INSERTANS tags in groups
    $sql = "SELECT gid, language, group_name, description from {{groups}}\n    WHERE sid=" . $newsid . " AND description LIKE '%{$oldsid}X%' OR group_name LIKE '%{$oldsid}X%'";
    $res = dbExecuteAssoc($sql) or show_error("Can't read groups table in transInsertAns");
    // Checked
    //while ($qentry = $res->FetchRow())
    foreach ($res->readAll() as $qentry) {
        $gpname = $qentry['group_name'];
        $description = $qentry['description'];
        $gid = $qentry['gid'];
        $language = $qentry['language'];
        foreach ($fieldnames as $sOldFieldname => $sNewFieldname) {
            $pattern = $sOldFieldname;
            $replacement = $sNewFieldname;
            $gpname = preg_replace('/' . $pattern . '/', $replacement, $gpname);
            $description = preg_replace('/' . $pattern . '/', $replacement, $description);
        }
        if (strcmp($description, $qentry['description']) != 0 || strcmp($gpname, $qentry['group_name']) != 0) {
            // Update Fields
            $data = array('description' => $description, 'group_name' => $gpname);
            $where = array('gid' => $gid, 'language' => $language);
            Groups::model()->update($data, $where);
        }
        // Enf if modified
    }
    // end while qentry
    # translate 'question' and 'help' INSERTANS tags in questions
    $sql = "SELECT qid, language, question, help from {{questions}}\n    WHERE sid=" . $newsid . " AND (question LIKE '%{$oldsid}X%' OR help LIKE '%{$oldsid}X%')";
    $result = dbExecuteAssoc($sql) or die("Can't read question table in transInsertAns ");
    // Checked
    //while ($qentry = $res->FetchRow())
    $aResultData = $result->readAll();
    foreach ($aResultData as $qentry) {
        $question = $qentry['question'];
        $help = $qentry['help'];
        $qid = $qentry['qid'];
        $language = $qentry['language'];
        foreach ($fieldnames as $sOldFieldname => $sNewFieldname) {
            $pattern = $sOldFieldname;
            $replacement = $sNewFieldname;
            $question = preg_replace('/' . $pattern . '/', $replacement, $question);
            $help = preg_replace('/' . $pattern . '/', $replacement, $help);
        }
        if (strcmp($question, $qentry['question']) != 0 || strcmp($help, $qentry['help']) != 0) {
            // Update Field
            $data = array('question' => $question, 'help' => $help);
            $where = array('qid' => $qid, 'language' => $language);
            Questions::model()->updateByPk($where, $data);
        }
        // Enf if modified
    }
    // end while qentry
    # translate 'answer' INSERTANS tags in answers
    $result = Answers::model()->oldNewInsertansTags($newsid, $oldsid);
    //while ($qentry = $res->FetchRow())
    foreach ($result as $qentry) {
        $answer = $qentry['answer'];
        $code = $qentry['code'];
        $qid = $qentry['qid'];
        $language = $qentry['language'];
        foreach ($fieldnames as $sOldFieldname => $sNewFieldname) {
            $pattern = $sOldFieldname;
            $replacement = $sNewFieldname;
            $answer = preg_replace('/' . $pattern . '/', $replacement, $answer);
        }
        if (strcmp($answer, $qentry['answer']) != 0) {
            // Update Field
            $data = array('answer' => $answer, 'qid' => $qid);
            $where = array('code' => $code, 'language' => $language);
            Answers::model()->update($data, $where);
        }
        // Enf if modified
    }
    // end while qentry
}
Exemple #21
0
 /**
  * Function responsible for deleting a question.
  *
  * @access public
  * @param string $action
  * @param int $surveyid
  * @param int $gid
  * @param int $qid
  * @return void
  */
 public function delete($surveyid, $gid, $qid)
 {
     $clang = $this->getController()->lang;
     $surveyid = sanitize_int($surveyid);
     $gid = sanitize_int($gid);
     $qid = sanitize_int($qid);
     if (hasSurveyPermission($surveyid, 'surveycontent', 'delete')) {
         if (!isset($qid)) {
             $qid = returnGlobal('qid');
         }
         LimeExpressionManager::RevertUpgradeConditionsToRelevance(NULL, $qid);
         // Check if any other questions have conditions which rely on this question. Don't delete if there are.
         // TMSW Conditions->Relevance:  Allow such deletes - can warn about missing relevance separately.
         $ccresult = Conditions::model()->findAllByAttributes(array('cqid' => $qid));
         $cccount = count($ccresult);
         // There are conditions dependent on this question
         if ($cccount) {
             foreach ($ccresult as $ccr) {
                 $qidarray[] = $ccr->qid;
             }
             if (isset($qidarray)) {
                 $qidlist = implode(", ", $qidarray);
             }
             $message = $clang->gT("Question could not be deleted. There are conditions for other questions that rely on this question. You cannot delete this question until those conditions are removed.");
             $message .= "<br /><a href='" . $this->getController()->createUrl("admin/expressions/sa/survey_logic_file/sid/{$surveyid}") . "' >" . $clang->gT("Look at survey logic files") . "</a>.";
             $this->getController()->error($message, $this->getController()->createUrl("admin/survey/sa/view/surveyid/{$surveyid}/gid/{$gid}/qid/{$qid}"));
         } else {
             $row = Questions::model()->findByAttributes(array('qid' => $qid))->attributes;
             $gid = $row['gid'];
             // See if there are any conditions/attributes/answers/defaultvalues for this question,
             // and delete them now as well
             Conditions::model()->deleteAllByAttributes(array('qid' => $qid));
             Question_attributes::model()->deleteAllByAttributes(array('qid' => $qid));
             Answers::model()->deleteAllByAttributes(array('qid' => $qid));
             $criteria = new CDbCriteria();
             $criteria->addCondition('qid = :qid1 or parent_qid = :qid2');
             $criteria->params[':qid1'] = $qid;
             $criteria->params[':qid2'] = $qid;
             Questions::model()->deleteAll($criteria);
             Defaultvalues::model()->deleteAllByAttributes(array('qid' => $qid));
             Quota_members::model()->deleteAllByAttributes(array('qid' => $qid));
             Questions::model()->updateQuestionOrder($gid, $surveyid);
             $qid = "";
             $postqid = "";
             $_GET['qid'] = "";
         }
         Yii::app()->session['flashmessage'] = $clang->gT("Question was successfully deleted.");
         $this->getController()->redirect($this->getController()->createUrl('admin/survey/sa/view/surveyid/' . $surveyid . '/gid/' . $gid));
     } else {
         Yii::app()->session['flashmessage'] = $clang->gT("You are not authorized to delete questions.");
         $this->getController()->redirect($this->getController()->createUrl('admin/survey/sa/view/surveyid/' . $surveyid . '/gid/' . $gid));
     }
 }
 public function uploadAction($uuid = null)
 {
     $this->view->disable();
     if ($this->request->isPost()) {
         $uuid = $this->request->getPost('uuid', 'string');
         $upload = $this->getDi()->getUpload($options = array('uuid' => $uuid));
         // handle quesiton uploads
         if (isset($upload->response['files'][0]->url)) {
             if ($this->request->getPost('question')) {
                 // handle question uploads
                 $ques = $this->request->getPost('question', 'int');
                 $value = $upload->response['files'][0];
                 $check = Answers::findFirst(array('uuid = ?1 AND question = ?2 AND type = ?3', 'bind' => array(1 => $uuid, 2 => $ques, 3 => 'video')));
                 if ($check) {
                     // save existing
                     $check->value = json_encode($value);
                     $check->save();
                 } else {
                     // save new
                     $answer = new Answers();
                     $answer->assign(array('uuid' => $uuid, 'question' => $ques, 'type' => 'video', 'value' => json_encode($value)));
                     $answer->save();
                 }
             } else {
                 // hadnle resume uploads
                 $response = Response::findFirstByUuid($uuid);
                 $response->resume = json_encode($upload->response['files'][0]);
                 $response->save();
             }
         }
     }
 }
 /**
  * @return bool
  * @param Answers $ans
  */
 public static function submitTest($ans)
 {
     $db = DB::getConn();
     $uid = $ans->getUid();
     $cate = $ans->getCate();
     $res = $ans->getRes();
     $stm = $db->prepare('insert into Answers (uid, cate, ans, time) values (:uid, :cate, :ans, date("now"))');
     $stm->bindParam(':uid', $uid);
     $stm->bindParam(':cate', $cate);
     $stm->bindParam(':ans', $res);
     $stm->execute();
 }
Exemple #24
0
 /**
  * Удаление вопросов, соответсвующих заданному тесту (по $testId )
  *
  * @param int $testId
  * @return void
  */
 public function removeQuestionsByTestId($testId)
 {
     $arrQuestionsId = $this->_getQuestionIdListByTestId($testId);
     if (!empty($arrQuestionsId)) {
         // Удаляем ответы для вопросов теста
         $objAnswers = new Answers();
         $objAnswers->removeAnswersByQuestionIdList($arrQuestionsId);
         // Удаляем вопросы теста
         $where = array('tq_id IN ( ? )' => implode(', ', $arrQuestionsId));
         $this->delete($where);
     }
 }
<?php

/**
 * Created by PhpStorm.
 * User: JayDz
 * Date: 15/07/15
 * Time: 2:54 PM
 */
require_once './controller/QuestionCtrl.php';
$uid = $_COOKIE['uid'];
//echo $uid;
$b = false;
if (isset($_POST['c']) && $_POST['c'] != '') {
    $c = $_POST['c'];
    $answers = new Answers($uid, $c);
    foreach ($_POST as $key => $value) {
        $param_name = 'ans::';
        if (substr($key, 0, strlen($param_name)) == $param_name) {
            $ques = explode('ans::', $key)[1];
            $ans = explode('_', $value)[1];
            $ktext = explode('_', $value)[2];
            $answers->addAns(new Answer($ques, $ans . '_' . $ktext));
            $b = true;
        }
    }
}
if ($b) {
    QuestionCtrl::submitTest($answers);
    echo 'okkkk';
} else {
    echo '<script>window.location.href="index.php"</script>';
 /**
  * RPC Routine to return properties of a question of a survey.
  * Returns string
  *
  * @access public
  * @param string $sSessionKey Auth credentials
  * @param int $iQuestionID Id of the question to get properties
  * @param array $aQuestionSettings The properties to get
  * @param string $sLanguage Optional parameter language for multilingual questions
  * @return array The requested values
  */
 public function get_question_properties($sSessionKey, $iQuestionID, $aQuestionSettings, $sLanguage = NULL)
 {
     if ($this->_checkSessionKey($sSessionKey)) {
         Yii::app()->loadHelper("surveytranslator");
         $oQuestion = Questions::model()->findByAttributes(array('qid' => $iQuestionID));
         if (!isset($oQuestion)) {
             return array('status' => 'Error: Invalid questionid');
         }
         $iSurveyID = $oQuestion->sid;
         if (hasSurveyPermission($iSurveyID, 'survey', 'read')) {
             if (is_null($sLanguage)) {
                 $sLanguage = Survey::model()->findByPk($iSurveyID)->language;
             }
             if (!array_key_exists($sLanguage, getLanguageDataRestricted())) {
                 return array('status' => 'Error: Invalid language');
             }
             $oQuestion = Questions::model()->findByAttributes(array('qid' => $iQuestionID, 'language' => $sLanguage));
             if (!isset($oQuestion)) {
                 return array('status' => 'Error: Invalid questionid');
             }
             $aBasicDestinationFields = Questions::model()->tableSchema->columnNames;
             array_push($aBasicDestinationFields, 'available_answers');
             array_push($aBasicDestinationFields, 'subquestions');
             array_push($aBasicDestinationFields, 'attributes');
             array_push($aBasicDestinationFields, 'attributes_lang');
             array_push($aBasicDestinationFields, 'answeroptions');
             $aQuestionSettings = array_intersect($aQuestionSettings, $aBasicDestinationFields);
             if (empty($aQuestionSettings)) {
                 return array('status' => 'No valid Data');
             }
             $aResult = array();
             foreach ($aQuestionSettings as $sPropertyName) {
                 if ($sPropertyName == 'available_answers' || $sPropertyName == 'subquestions') {
                     $oSubQuestions = Questions::model()->findAllByAttributes(array('parent_qid' => $iQuestionID, 'language' => $sLanguage), array('order' => 'title'));
                     if (count($oSubQuestions) > 0) {
                         $aData = array();
                         foreach ($oSubQuestions as $oSubQuestion) {
                             if ($sPropertyName == 'available_answers') {
                                 $aData[$oSubQuestion['title']] = $oSubQuestion['question'];
                             } else {
                                 $aData[$oSubQuestion['qid']]['title'] = $oSubQuestion['title'];
                                 $aData[$oSubQuestion['qid']]['question'] = $oSubQuestion['question'];
                                 $aData[$oSubQuestion['qid']]['scale_id'] = $oSubQuestion['scale_id'];
                             }
                         }
                         $aResult[$sPropertyName] = $aData;
                     } else {
                         $aResult[$sPropertyName] = 'No available answers';
                     }
                 } else {
                     if ($sPropertyName == 'attributes') {
                         $oAttributes = Question_attributes::model()->findAllByAttributes(array('qid' => $iQuestionID, 'language' => null), array('order' => 'attribute'));
                         if (count($oAttributes) > 0) {
                             $aData = array();
                             foreach ($oAttributes as $oAttribute) {
                                 $aData[$oAttribute['attribute']] = $oAttribute['value'];
                             }
                             $aResult['attributes'] = $aData;
                         } else {
                             $aResult['attributes'] = 'No available attributes';
                         }
                     } else {
                         if ($sPropertyName == 'attributes_lang') {
                             $oAttributes = Question_attributes::model()->findAllByAttributes(array('qid' => $iQuestionID, 'language' => $sLanguage), array('order' => 'attribute'));
                             if (count($oAttributes) > 0) {
                                 $aData = array();
                                 foreach ($oAttributes as $oAttribute) {
                                     $aData[$oAttribute['attribute']] = $oAttribute['value'];
                                 }
                                 $aResult['attributes_lang'] = $aData;
                             } else {
                                 $aResult['attributes_lang'] = 'No available attributes';
                             }
                         } else {
                             if ($sPropertyName == 'answeroptions') {
                                 $oAttributes = Answers::model()->findAllByAttributes(array('qid' => $iQuestionID, 'language' => $sLanguage), array('order' => 'sortorder'));
                                 if (count($oAttributes) > 0) {
                                     $aData = array();
                                     foreach ($oAttributes as $oAttribute) {
                                         $aData[$oAttribute['code']]['answer'] = $oAttribute['answer'];
                                         $aData[$oAttribute['code']]['assessment_value'] = $oAttribute['assessment_value'];
                                         $aData[$oAttribute['code']]['scale_id'] = $oAttribute['scale_id'];
                                     }
                                     $aResult['answeroptions'] = $aData;
                                 } else {
                                     $aResult['answeroptions'] = 'No available answer options';
                                 }
                             } else {
                                 $aResult[$sPropertyName] = $oQuestion->{$sPropertyName};
                             }
                         }
                     }
                 }
             }
             return $aResult;
         } else {
             return array('status' => 'No permission');
         }
     } else {
         return array('status' => 'Invalid session key');
     }
 }
 /**
  * Shows admin menu for question
  * @param int Survey id
  * @param int Group id
  * @param int Question id
  * @param string action
  */
 function _questionbar($iSurveyID, $gid, $qid, $action = null)
 {
     $clang = $this->getController()->lang;
     $baselang = Survey::model()->findByPk($iSurveyID)->language;
     //Show Question Details
     //Count answer-options for this question
     $qrr = Answers::model()->findAllByAttributes(array('qid' => $qid, 'language' => $baselang));
     $aData['qct'] = $qct = count($qrr);
     //Count sub-questions for this question
     $sqrq = Questions::model()->findAllByAttributes(array('parent_qid' => $qid, 'language' => $baselang));
     $aData['sqct'] = $sqct = count($sqrq);
     $qrrow = Questions::model()->findByAttributes(array('qid' => $qid, 'gid' => $gid, 'sid' => $iSurveyID, 'language' => $baselang));
     $questionsummary = "<div class='menubar'>\n";
     // Check if other questions in the Survey are dependent upon this question
     $condarray = getQuestDepsForConditions($iSurveyID, "all", "all", $qid, "by-targqid", "outsidegroup");
     $sumresult1 = Survey::model()->findByPk($iSurveyID);
     if (is_null($sumresult1)) {
         Yii::app()->session['flashmessage'] = $clang->gT("Invalid survey ID");
         $this->getController()->redirect($this->getController()->createUrl("admin/index"));
     }
     //  if surveyid is invalid then die to prevent errors at a later time
     $surveyinfo = $sumresult1->attributes;
     $surveyinfo = array_map('flattenText', $surveyinfo);
     $aData['activated'] = $surveyinfo['active'];
     $qrrow = $qrrow->attributes;
     if (hasSurveyPermission($iSurveyID, 'surveycontent', 'read')) {
         if (count(Survey::model()->findByPk($iSurveyID)->additionalLanguages) != 0) {
             Yii::app()->loadHelper('surveytranslator');
             $tmp_survlangs = Survey::model()->findByPk($iSurveyID)->additionalLanguages;
             $baselang = Survey::model()->findByPk($iSurveyID)->language;
             $tmp_survlangs[] = $baselang;
             rsort($tmp_survlangs);
             $aData['tmp_survlangs'] = $tmp_survlangs;
         }
     }
     $aData['qtypes'] = $qtypes = getQuestionTypeList('', 'array');
     if ($action == 'editansweroptions' || $action == "editsubquestions" || $action == "editquestion" || $action == "editdefaultvalues" || $action == "editdefaultvalues" || $action == "copyquestion") {
         $qshowstyle = "style='display: none'";
     } else {
         $qshowstyle = "";
     }
     $aData['qshowstyle'] = $qshowstyle;
     $aData['action'] = $action;
     $aData['surveyid'] = $iSurveyID;
     $aData['qid'] = $qid;
     $aData['gid'] = $gid;
     $aData['clang'] = $clang;
     $aData['qrrow'] = $qrrow;
     $aData['baselang'] = $baselang;
     $aAttributesWithValues = Questions::model()->getAdvancedSettingsWithValues($qid, $qrrow['type'], $iSurveyID, $baselang);
     $DisplayArray = array();
     foreach ($aAttributesWithValues as $aAttribute) {
         if ($aAttribute['i18n'] == false && isset($aAttribute['value']) && $aAttribute['value'] != $aAttribute['default'] || $aAttribute['i18n'] == true && isset($aAttribute['value'][$baselang]) && $aAttribute['value'][$baselang] != $aAttribute['default']) {
             if ($aAttribute['inputtype'] == 'singleselect') {
                 $aAttribute['value'] = $aAttribute['options'][$aAttribute['value']];
             }
             /*
             if ($aAttribute['name']=='relevance')
             {
             $sRelevance = $aAttribute['value'];
             if ($sRelevance !== '' && $sRelevance !== '1' && $sRelevance !== '0')
             {
             LimeExpressionManager::ProcessString("{" . $sRelevance . "}");    // tests Relevance equation so can pretty-print it
             $aAttribute['value']= LimeExpressionManager::GetLastPrettyPrintExpression();
             }
             }
             */
             $DisplayArray[] = $aAttribute;
         }
     }
     $aData['advancedsettings'] = $DisplayArray;
     $aData['condarray'] = $condarray;
     $aData['sImageURL'] = Yii::app()->getConfig('adminimageurl');
     $aData['iIconSize'] = Yii::app()->getConfig('adminthemeiconsize');
     $questionsummary .= $this->getController()->render('/admin/survey/Question/questionbar_view', $aData, true);
     $finaldata['display'] = $questionsummary;
     $this->getController()->render('/survey_view', $finaldata);
 }
     }
     //check if there is a dualsclae_headerA/B
     $dshresult2 = $dshresults2[$key1][0];
     //get header
     foreach ($dshresult2 as $dshrow2) {
         $dshrow2 = array_values($dshrow2);
         $dualscaleheaderb = $dshrow2[0];
     }
     if (isset($dualscaleheaderb) && $dualscaleheaderb != "") {
         $labeltitle2 = $dualscaleheaderb;
     } else {
         //get label text
         $labeltitle2 = '';
     }
     echo " />&nbsp;<strong>" . _showSpeaker($niceqtext . " [" . str_replace("'", "`", $row[1]) . "] - " . $clang->gT("Label") . ": " . $labeltitle2) . "</strong><br />\n";
     $fresult = Answers::model()->getQuestionsForStatistics('*', "qid='{$flt['0']}' AND language = '{$language}' AND scale_id = 1", 'sortorder, code');
     //this is for debugging only
     //echo $fquery;
     echo "\t<select name='{$surveyid}X{$flt[1]}X{$flt[0]}{$row[0]}#{1}[]' multiple='multiple'>\n";
     //list answers
     foreach ($fresult as $frow) {
         echo "\t<option value='{$frow['code']}'";
         //pre-check
         if (isset($_POST[$myfield2]) && is_array($_POST[$myfield2]) && in_array($frow['code'], $_POST[$myfield2])) {
             echo " selected";
         }
         echo ">({$frow['code']}) " . flattenText($frow['answer'], true) . "</option>\n";
     }
     echo "\t</select>\n\t</td>\n";
     $counter2++;
 }
Exemple #29
-1
 /**
  * Пересчитывает результат теста (вместо процентов - баллы)
  * @return void
  */
 public function recalcAction()
 {
     if ($this->_authorize('test', 'edit')) {
         $link = $this->getRequest()->getParam('link');
         $objApplicantTests = new ApplicantTests();
         $applicantTest = $objApplicantTests->getTest($link);
         if (empty($applicantTest)) {
             exit;
         }
         $applicantId = $applicantTest->applicant_id;
         $testId = $applicantTest->test_id;
         $applicantTestId = $applicantTest->id;
         $objQuestion = new Questions();
         $questions = $objQuestion->getQuestions($testId);
         $questions = $this->convertArr($questions, 'tq_id');
         $objTestAnswers = new Answers();
         $answers = $objTestAnswers->getAnswers(array_keys($questions));
         // ключем $answers будет id вопроса
         $answers = $this->convertArr($answers, 'tq_id', true);
         $objApplicantAnswers = new ApplicantAnswers();
         $applicantAnswers = $objApplicantAnswers->getAnswers($applicantTestId);
         $applicantAnswers = $this->convertArr($applicantAnswers, 'answer_id');
         $result = $this->calcTestScore($questions, $answers, $applicantAnswers);
         $applicantTest->score = $result['score'];
         $applicantTest->percent = $result['percent'];
         $applicantTest->save();
     }
     $this->_helper->redirector('testing', 'test', null, array('link' => $link));
 }
 /**
  * 
  * @param type $iQuestionId
  * @param type $iSurveyId
  * @param type $iQuotaId
  * @return array
  */
 function getQuotaAnswers($iQuestionId, $iSurveyId, $iQuotaId)
 {
     $iQuestionId = sanitize_int($iQuestionId);
     $iSurveyId = sanitize_int($iSurveyId);
     $iQuotaId = sanitize_int($iQuotaId);
     $aData = $this->_getData($iSurveyId);
     $sBaseLang = $aData['sBaseLang'];
     $clang = $aData['clang'];
     $aQuestion = Questions::model()->findByPk(array('qid' => $iQuestionId, 'language' => $sBaseLang));
     $aQuestionType = $aQuestion['type'];
     if ($aQuestionType == 'M') {
         $aResults = Questions::model()->findAllByAttributes(array('parent_qid' => $iQuestionId));
         $aAnswerList = array();
         foreach ($aResults as $aDbAnsList) {
             $tmparrayans = array('Title' => $aQuestion['title'], 'Display' => substr($aDbAnsList['question'], 0, 40), 'code' => $aDbAnsList['title']);
             $aAnswerList[$aDbAnsList['title']] = $tmparrayans;
         }
     } elseif ($aQuestionType == 'G') {
         $aAnswerList = array('M' => array('Title' => $aQuestion['title'], 'Display' => $clang->gT("Male"), 'code' => 'M'), 'F' => array('Title' => $aQuestion['title'], 'Display' => $clang->gT("Female"), 'code' => 'F'));
     } elseif ($aQuestionType == 'L' || $aQuestionType == 'O' || $aQuestionType == '!') {
         $aAnsResults = Answers::model()->findAllByAttributes(array('qid' => $iQuestionId));
         $aAnswerList = array();
         foreach ($aAnsResults as $aDbAnsList) {
             $aAnswerList[$aDbAnsList['code']] = array('Title' => $aQuestion['title'], 'Display' => substr($aDbAnsList['answer'], 0, 40), 'code' => $aDbAnsList['code']);
         }
     } elseif ($aQuestionType == 'A') {
         $aAnsResults = Questions::model()->findAllByAttributes(array('parent_qid' => $iQuestionId));
         $aAnswerList = array();
         foreach ($aAnsResults as $aDbAnsList) {
             for ($x = 1; $x < 6; $x++) {
                 $tmparrayans = array('Title' => $aQuestion['title'], 'Display' => substr($aDbAnsList['question'], 0, 40) . ' [' . $x . ']', 'code' => $aDbAnsList['title']);
                 $aAnswerList[$aDbAnsList['title'] . "-" . $x] = $tmparrayans;
             }
         }
     } elseif ($aQuestionType == 'B') {
         $aAnsResults = Answers::model()->findAllByAttributes(array('qid' => $iQuestionId));
         $aAnswerList = array();
         foreach ($aAnsResults as $aDbAnsList) {
             for ($x = 1; $x < 11; $x++) {
                 $tmparrayans = array('Title' => $aQuestion['title'], 'Display' => substr($aDbAnsList['answer'], 0, 40) . ' [' . $x . ']', 'code' => $aDbAnsList['code']);
                 $aAnswerList[$aDbAnsList['code'] . "-" . $x] = $tmparrayans;
             }
         }
     } elseif ($aQuestionType == 'Y') {
         $aAnswerList = array('Y' => array('Title' => $aQuestion['title'], 'Display' => $clang->gT("Yes"), 'code' => 'Y'), 'N' => array('Title' => $aQuestion['title'], 'Display' => $clang->gT("No"), 'code' => 'N'));
     } elseif ($aQuestionType == 'I') {
         $slangs = Survey::model()->findByPk($iSurveyId)->additionalLanguages;
         array_unshift($slangs, $sBaseLang);
         while (list($key, $value) = each($slangs)) {
             $tmparrayans = array('Title' => $aQuestion['title'], 'Display' => getLanguageNameFromCode($value, false), $value);
             $aAnswerList[$value] = $tmparrayans;
         }
     }
     if (empty($aAnswerList)) {
         return array();
     } else {
         // Now we mark answers already used in this quota as such
         $aExistsingAnswers = Quota_members::model()->findAllByAttributes(array('sid' => $iSurveyId, 'qid' => $iQuestionId, 'quota_id' => $iQuotaId));
         foreach ($aExistsingAnswers as $aAnswerRow) {
             if (array_key_exists($aAnswerRow['code'], $aAnswerList)) {
                 $aAnswerList[$aAnswerRow['code']]['rowexists'] = '1';
             }
         }
         return $aAnswerList;
     }
 }