Пример #1
0
 /**
  * Mise  àjour d une fiche
  * @param $id the ID of the model to be displayed
  */
 public function actionUpdate($id)
 {
     $model = Questionnaire::model()->findByPk(new MongoID($id));
     $questionForm = new QuestionForm();
     $questionGroup = new QuestionGroup();
     // collect user input data
     if (isset($_POST['QuestionForm'])) {
         $questionForm->attributes = $_POST['QuestionForm'];
         //traitement ajout de question
         if ($questionForm->validate()) {
             $model = $this->saveQuestionnaireNewQuestion($model, $questionForm);
         }
     }
     if (isset($_POST['QuestionGroup'])) {
         $questionGroup->attributes = $_POST['QuestionGroup'];
         //copie du titre sur l option fr
         $questionGroup->title_fr = $questionGroup->title;
         if ($questionGroup->validate()) {
             $model = $this->saveQuestionnaireNewGroup($model, $questionGroup);
         }
     }
     //set du model sur la questionForm pour generer l arborescende de position de question
     $questionForm->questionnaire = $model;
     $this->render('update', array('model' => $model, 'questionForm' => $questionForm, 'questionGroup' => $questionGroup));
 }
 /**
  * testing method return array type
  */
 public function testTypeFunction()
 {
     $model = new QuestionGroup();
     $questionBlocForm = new QuestionBlocForm();
     $questionBlocForm->title = "Test";
     $questionBlocForm->questions = array();
     $questionBlocForm->parent_group = "Test";
     $questionBlocForm->id = "test";
     $questionBlocForm->title_fr = $questionBlocForm->title;
     $questionBloc = new QuestionBloc();
     $questionBloc->title = "Test";
     $questionBloc->questions = array();
     $questionBloc->parent_group = "Test";
     $questionBloc->title_fr = $questionBloc->title;
     $model->copy($questionBlocForm, $questionBloc);
     $this->assertFalse($model->deleteQuestion($model->id));
     $this->assertInternalType('array', $model->rules());
     $this->assertInternalType('array', $model->attributeLabels());
 }
Пример #3
0
 /**
  * This private function creates a sample group
  *
  * @param mixed $iSurveyID  The survey ID that the sample group will belong to
  */
 private function _createSampleGroup($iSurveyID)
 {
     // Now create a new dummy group
     $sLanguage = Survey::model()->findByPk($iSurveyID)->language;
     $aInsertData = array();
     $aInsertData[$sLanguage] = array('sid' => $iSurveyID, 'group_name' => gt('My first question group', 'html', $sLanguage), 'description' => '', 'group_order' => 1, 'language' => $sLanguage, 'grelevance' => '1');
     return QuestionGroup::model()->insertNewGroup($aInsertData);
 }
Пример #4
0
 private function _reorderGroup($iSurveyID)
 {
     $AOrgData = array();
     parse_str($_POST['orgdata'], $AOrgData);
     $grouporder = 0;
     foreach ($AOrgData['list'] as $ID => $parent) {
         if ($parent == 'root' && $ID[0] == 'g') {
             QuestionGroup::model()->updateAll(array('group_order' => $grouporder), 'gid=:gid', array(':gid' => (int) substr($ID, 1)));
             $grouporder++;
         } elseif ($ID[0] == 'q') {
             if (!isset($questionorder[(int) substr($parent, 1)])) {
                 $questionorder[(int) substr($parent, 1)] = 0;
             }
             Question::model()->updateAll(array('question_order' => $questionorder[(int) substr($parent, 1)], 'gid' => (int) substr($parent, 1)), 'qid=:qid', array(':qid' => (int) substr($ID, 1)));
             Question::model()->updateAll(array('gid' => (int) substr($parent, 1)), 'parent_qid=:parent_qid', array(':parent_qid' => (int) substr($ID, 1)));
             $questionorder[(int) substr($parent, 1)]++;
         }
     }
     LimeExpressionManager::SetDirtyFlag();
     // so refreshes syntax highlighting
     Yii::app()->session['flashmessage'] = gT("The new question group/question order was successfully saved.");
     $this->getController()->redirect(array('admin/survey/sa/view/surveyid/' . $iSurveyID));
 }
Пример #5
0
/**
* Import survey from an TSV file template that does not require or allow assigning of GID or QID values.
* NOTE:  This currently only supports import of one language
* @global type $connect
* @global type $dbprefix
* @global type $clang
* @global type $timeadjust
* @param type $sFullFilePath
* @return type
*
* @author TMSWhite
*/
function TSVImportSurvey($sFullFilePath)
{
    $clang = Yii::app()->lang;
    $insertdata = array();
    $results = array();
    $results['error'] = false;
    $baselang = 'en';
    // TODO set proper default
    $encoding = '';
    $handle = fopen($sFullFilePath, 'r');
    $bom = fread($handle, 2);
    rewind($handle);
    $aAttributeList = questionAttributes();
    // Excel tends to save CSV as UTF-16, which PHP does not properly detect
    if ($bom === chr(0xff) . chr(0xfe) || $bom === chr(0xfe) . chr(0xff)) {
        // UTF16 Byte Order Mark present
        $encoding = 'UTF-16';
    } else {
        $file_sample = fread($handle, 1000) + 'e';
        //read first 1000 bytes
        // + e is a workaround for mb_string bug
        rewind($handle);
        $encoding = mb_detect_encoding($file_sample, 'UTF-8, UTF-7, ASCII, EUC-JP,SJIS, eucJP-win, SJIS-win, JIS, ISO-2022-JP');
    }
    if ($encoding && $encoding != 'UTF-8') {
        stream_filter_append($handle, 'convert.iconv.' . $encoding . '/UTF-8');
    }
    $file = stream_get_contents($handle);
    fclose($handle);
    // fix Excel non-breaking space
    $file = str_replace("0xC20xA0", ' ', $file);
    $filelines = explode("\n", $file);
    $row = array_shift($filelines);
    $headers = explode("\t", $row);
    $rowheaders = array();
    foreach ($headers as $header) {
        $rowheaders[] = trim($header);
    }
    // remove BOM from the first header cell, if needed
    $rowheaders[0] = preg_replace("/^\\W+/", "", $rowheaders[0]);
    if (preg_match('/class$/', $rowheaders[0])) {
        $rowheaders[0] = 'class';
        // second attempt to remove BOM
    }
    $adata = array();
    foreach ($filelines as $rowline) {
        $rowarray = array();
        $row = explode("\t", $rowline);
        for ($i = 0; $i < count($rowheaders); ++$i) {
            $val = isset($row[$i]) ? $row[$i] : '';
            // if Excel was used, it surrounds strings with quotes and doubles internal double quotes.  Fix that.
            if (preg_match('/^".*"$/', $val)) {
                $val = str_replace('""', '"', substr($val, 1, -1));
            }
            $rowarray[$rowheaders[$i]] = $val;
        }
        $adata[] = $rowarray;
    }
    $results['defaultvalues'] = 0;
    $results['answers'] = 0;
    $results['surveys'] = 0;
    $results['languages'] = 0;
    $results['questions'] = 0;
    $results['subquestions'] = 0;
    $results['question_attributes'] = 0;
    $results['groups'] = 0;
    $results['importwarnings'] = array();
    // these aren't used here, but are needed to avoid errors in post-import display
    $results['assessments'] = 0;
    $results['quota'] = 0;
    $results['quotamembers'] = 0;
    $results['quotals'] = 0;
    // collect information about survey and its language settings
    $surveyinfo = array();
    $surveyls = array();
    foreach ($adata as $row) {
        switch ($row['class']) {
            case 'S':
                if (isset($row['text']) && $row['name'] != 'datecreated') {
                    $surveyinfo[$row['name']] = $row['text'];
                }
                break;
            case 'SL':
                if (!isset($surveyls[$row['language']])) {
                    $surveyls[$row['language']] = array();
                }
                if (isset($row['text'])) {
                    $surveyls[$row['language']][$row['name']] = $row['text'];
                }
                break;
        }
    }
    $iOldSID = 1;
    if (isset($surveyinfo['sid'])) {
        $iOldSID = (int) $surveyinfo['sid'];
    }
    // Create the survey entry
    $surveyinfo['startdate'] = NULL;
    $surveyinfo['active'] = 'N';
    // unset($surveyinfo['datecreated']);
    $iNewSID = Survey::model()->insertNewSurvey($surveyinfo);
    //or safeDie($clang->gT("Error").": Failed to insert survey<br />");
    if (!$iNewSID) {
        $results['error'] = Survey::model()->getErrors();
        $results['bFailed'] = true;
        return $results;
    }
    $surveyinfo['sid'] = $iNewSID;
    $results['surveys']++;
    $results['newsid'] = $iNewSID;
    $gid = 0;
    $gseq = 0;
    // group_order
    $qid = 0;
    $qseq = 0;
    // question_order
    $qtype = 'T';
    $aseq = 0;
    // answer sortorder
    // set the language for the survey
    $_title = 'Missing Title';
    foreach ($surveyls as $_lang => $insertdata) {
        $insertdata['surveyls_survey_id'] = $iNewSID;
        $insertdata['surveyls_language'] = $_lang;
        if (isset($insertdata['surveyls_title'])) {
            $_title = $insertdata['surveyls_title'];
        } else {
            $insertdata['surveyls_title'] = $_title;
        }
        $result = SurveyLanguageSetting::model()->insertNewSurvey($insertdata);
        //
        if (!$result) {
            $results['error'][] = $clang->gT("Error") . " : " . $clang->gT("Failed to insert survey language");
            break;
        }
        $results['languages']++;
    }
    $ginfo = array();
    $qinfo = array();
    $sqinfo = array();
    if (isset($surveyinfo['language'])) {
        $baselang = $surveyinfo['language'];
        // the base language
    }
    $rownumber = 1;
    $lastglang = '';
    foreach ($adata as $row) {
        $rownumber += 1;
        switch ($row['class']) {
            case 'G':
                // insert group
                $insertdata = array();
                $insertdata['sid'] = $iNewSID;
                $gname = !empty($row['name']) ? $row['name'] : 'G' . $gseq;
                $glang = !empty($row['language']) ? $row['language'] : $baselang;
                // when a multi-lang tsv-file without information on the group id/number (old style) is imported,
                // we make up this information by giving a number 0..[numberofgroups-1] per language.
                // the number and order of groups per language should be the same, so we can also import these files
                if ($lastglang != $glang) {
                    $iGroupcounter = 0;
                }
                $lastglang = $glang;
                //use group id/number from file. if missing, use an increasing number (s.a.)
                $sGroupseq = !empty($row['type/scale']) ? $row['type/scale'] : 'G' . $iGroupcounter++;
                $insertdata['group_name'] = $gname;
                $insertdata['grelevance'] = isset($row['relevance']) ? $row['relevance'] : '';
                $insertdata['description'] = isset($row['text']) ? $row['text'] : '';
                $insertdata['language'] = $glang;
                // For multi language survey: same gid/sort order across all languages
                if (isset($ginfo[$sGroupseq])) {
                    $gid = $ginfo[$sGroupseq]['gid'];
                    $insertdata['gid'] = $gid;
                    $insertdata['group_order'] = $ginfo[$sGroupseq]['group_order'];
                } else {
                    $insertdata['group_order'] = $gseq;
                }
                $newgid = QuestionGroup::model()->insertRecords($insertdata);
                if (!$newgid) {
                    $results['error'][] = $clang->gT("Error") . " : " . $clang->gT("Failed to insert group") . ". " . $clang->gT("Text file row number ") . $rownumber . " (" . $gname . ")";
                    break;
                }
                if (!isset($ginfo[$sGroupseq])) {
                    $results['groups']++;
                    $gid = $newgid;
                    $ginfo[$sGroupseq]['gid'] = $gid;
                    $ginfo[$sGroupseq]['group_order'] = $gseq++;
                }
                $qseq = 0;
                // reset the question_order
                break;
            case 'Q':
                // insert question
                $insertdata = array();
                $insertdata['sid'] = $iNewSID;
                $qtype = isset($row['type/scale']) ? $row['type/scale'] : 'T';
                $qname = isset($row['name']) ? $row['name'] : 'Q' . $qseq;
                $insertdata['gid'] = $gid;
                $insertdata['type'] = $qtype;
                $insertdata['title'] = $qname;
                $insertdata['question'] = isset($row['text']) ? $row['text'] : '';
                $insertdata['relevance'] = isset($row['relevance']) ? $row['relevance'] : '';
                $insertdata['preg'] = isset($row['validation']) ? $row['validation'] : '';
                $insertdata['help'] = isset($row['help']) ? $row['help'] : '';
                $insertdata['language'] = isset($row['language']) ? $row['language'] : $baselang;
                $insertdata['mandatory'] = isset($row['mandatory']) ? $row['mandatory'] : '';
                $lastother = $insertdata['other'] = isset($row['other']) ? $row['other'] : 'N';
                // Keep trace of other settings for sub question
                $insertdata['same_default'] = isset($row['same_default']) ? $row['same_default'] : 0;
                $insertdata['parent_qid'] = 0;
                // For multi numeric survey : same name, add the gid to have same name on different gid. Bad for EM.
                $fullqname = "G{$gid}_" . $qname;
                if (isset($qinfo[$fullqname])) {
                    $qseq = $qinfo[$fullqname]['question_order'];
                    $qid = $qinfo[$fullqname]['qid'];
                    $insertdata['qid'] = $qid;
                    $insertdata['question_order'] = $qseq;
                } else {
                    $insertdata['question_order'] = $qseq;
                }
                // Insert question and keep the qid for multi language survey
                $result = Question::model()->insertRecords($insertdata);
                if (!$result) {
                    $results['error'][] = $clang->gT("Error") . " : " . $clang->gT("Could not insert question") . ". " . $clang->gT("Text file row number ") . $rownumber . " (" . $qname . ")";
                    break;
                }
                $newqid = $result;
                if (!isset($qinfo[$fullqname])) {
                    $results['questions']++;
                    $qid = $newqid;
                    // save this for later
                    $qinfo[$fullqname]['qid'] = $qid;
                    $qinfo[$fullqname]['question_order'] = $qseq++;
                }
                $aseq = 0;
                //reset the answer sortorder
                $sqseq = 0;
                //reset the sub question sortorder
                // insert question attributes
                foreach ($row as $key => $val) {
                    switch ($key) {
                        case 'class':
                        case 'type/scale':
                        case 'name':
                        case 'text':
                        case 'validation':
                        case 'relevance':
                        case 'help':
                        case 'language':
                        case 'mandatory':
                        case 'other':
                        case 'same_default':
                        case 'default':
                            break;
                        default:
                            if ($key != '' && $val != '') {
                                $insertdata = array();
                                $insertdata['qid'] = $qid;
                                // check if attribute is a i18n attribute. If yes, set language, else set language to null in attribute table
                                if (isset($aAttributeList[$qtype][$key]['i18n']) && $aAttributeList[$qtype][$key]['i18n'] == 1) {
                                    $insertdata['language'] = isset($row['language']) ? $row['language'] : $baselang;
                                } else {
                                    $insertdata['language'] = NULL;
                                }
                                $insertdata['attribute'] = $key;
                                $insertdata['value'] = $val;
                                $result = QuestionAttribute::model()->insertRecords($insertdata);
                                //
                                if (!$result) {
                                    $results['importwarnings'][] = $clang->gT("Warning") . " : " . $clang->gT("Failed to insert question attribute") . ". " . $clang->gT("Text file row number ") . $rownumber . " ({$key})";
                                    break;
                                }
                                $results['question_attributes']++;
                            }
                            break;
                    }
                }
                // insert default value
                if (isset($row['default'])) {
                    $insertdata = array();
                    $insertdata['qid'] = $qid;
                    $insertdata['language'] = isset($row['language']) ? $row['language'] : $baselang;
                    $insertdata['defaultvalue'] = $row['default'];
                    $result = DefaultValue::model()->insertRecords($insertdata);
                    if (!$result) {
                        $results['importwarnings'][] = $clang->gT("Warning") . " : " . $clang->gT("Failed to insert default value") . ". " . $clang->gT("Text file row number ") . $rownumber;
                        break;
                    }
                    $results['defaultvalues']++;
                }
                break;
            case 'SQ':
                $sqname = isset($row['name']) ? $row['name'] : 'SQ' . $sqseq;
                if ($qtype == 'O' || $qtype == '|') {
                    // these are fake rows to show naming of comment and filecount fields
                } elseif ($sqname == 'other' && $lastother == "Y") {
                    if ($qtype == "!" || $qtype == "L") {
                        // only used to set default value for 'other' in these cases
                        if (isset($row['default'])) {
                            $insertdata = array();
                            $insertdata['qid'] = $qid;
                            $insertdata['specialtype'] = 'other';
                            $insertdata['language'] = isset($row['language']) ? $row['language'] : $baselang;
                            $insertdata['defaultvalue'] = $row['default'];
                            $result = DefaultValue::model()->insertRecords($insertdata);
                            if (!$result) {
                                $results['importwarnings'][] = $clang->gT("Warning") . " : " . $clang->gT("Failed to insert default value") . ". " . $clang->gT("Text file row number ") . $rownumber;
                                break;
                            }
                            $results['defaultvalues']++;
                        }
                    }
                } else {
                    $insertdata = array();
                    $scale_id = isset($row['type/scale']) ? $row['type/scale'] : 0;
                    $insertdata['sid'] = $iNewSID;
                    $insertdata['gid'] = $gid;
                    $insertdata['parent_qid'] = $qid;
                    $insertdata['type'] = $qtype;
                    $insertdata['title'] = $sqname;
                    $insertdata['question'] = isset($row['text']) ? $row['text'] : '';
                    $insertdata['relevance'] = isset($row['relevance']) ? $row['relevance'] : '';
                    $insertdata['preg'] = isset($row['validation']) ? $row['validation'] : '';
                    $insertdata['help'] = isset($row['help']) ? $row['help'] : '';
                    $insertdata['language'] = isset($row['language']) ? $row['language'] : $baselang;
                    $insertdata['mandatory'] = isset($row['mandatory']) ? $row['mandatory'] : '';
                    $insertdata['scale_id'] = $scale_id;
                    // For multi nueric language, qid is needed, why not gid. name is not unique.
                    $fullsqname = "G{$gid}Q{$qid}_{$scale_id}_{$sqname}";
                    if (isset($sqinfo[$fullsqname])) {
                        $qseq = $sqinfo[$fullsqname]['question_order'];
                        $sqid = $sqinfo[$fullsqname]['sqid'];
                        $insertdata['question_order'] = $qseq;
                        $insertdata['qid'] = $sqid;
                    } else {
                        $insertdata['question_order'] = $qseq;
                    }
                    // Insert sub question and keep the sqid for multi language survey
                    $newsqid = Question::model()->insertRecords($insertdata);
                    if (!$newsqid) {
                        $results['error'][] = $clang->gT("Error") . " : " . $clang->gT("Could not insert subquestion") . ". " . $clang->gT("Text file row number ") . $rownumber . " (" . $qname . ")";
                        break;
                    }
                    if (!isset($sqinfo[$fullsqname])) {
                        $sqinfo[$fullsqname]['question_order'] = $qseq++;
                        $sqid = $newsqid;
                        // save this for later
                        $sqinfo[$fullsqname]['sqid'] = $sqid;
                        $results['subquestions']++;
                    }
                    // insert default value
                    if (isset($row['default'])) {
                        $insertdata = array();
                        $insertdata['qid'] = $qid;
                        $insertdata['sqid'] = $sqid;
                        $insertdata['scale_id'] = $scale_id;
                        $insertdata['language'] = isset($row['language']) ? $row['language'] : $baselang;
                        $insertdata['defaultvalue'] = $row['default'];
                        $result = DefaultValue::model()->insertRecords($insertdata);
                        if (!$result) {
                            $results['importwarnings'][] = $clang->gT("Warning") . " : " . $clang->gT("Failed to insert default value") . ". " . $clang->gT("Text file row number ") . $rownumber;
                            break;
                        }
                        $results['defaultvalues']++;
                    }
                }
                break;
            case 'A':
                $insertdata = array();
                $insertdata['qid'] = $qid;
                $insertdata['code'] = isset($row['name']) ? $row['name'] : 'A' . $aseq;
                $insertdata['answer'] = isset($row['text']) ? $row['text'] : '';
                $insertdata['scale_id'] = isset($row['type/scale']) ? $row['type/scale'] : 0;
                $insertdata['language'] = isset($row['language']) ? $row['language'] : $baselang;
                $insertdata['assessment_value'] = (int) (isset($row['relevance']) ? $row['relevance'] : '');
                $insertdata['sortorder'] = ++$aseq;
                $result = Answer::model()->insertRecords($insertdata);
                // or safeDie("Error: Failed to insert answer<br />");
                if (!$result) {
                    $results['error'][] = $clang->gT("Error") . " : " . $clang->gT("Could not insert answer") . ". " . $clang->gT("Text file row number ") . $rownumber;
                }
                $results['answers']++;
                break;
        }
    }
    // Delete the survey if error found
    if (is_array($results['error'])) {
        $result = Survey::model()->deleteSurvey($iNewSID);
    } else {
        LimeExpressionManager::SetSurveyId($iNewSID);
        LimeExpressionManager::RevertUpgradeConditionsToRelevance($iNewSID);
        LimeExpressionManager::UpgradeConditionsToRelevance($iNewSID);
    }
    return $results;
}
Пример #6
0
 /**
  * Provides an interface for updating a group
  *
  * @access public
  * @param int $gid
  * @return void
  */
 public function update($gid)
 {
     $gid = (int) $gid;
     $group = QuestionGroup::model()->findByAttributes(array('gid' => $gid));
     $surveyid = $group->sid;
     if (Permission::model()->hasSurveyPermission($surveyid, 'surveycontent', 'update')) {
         Yii::app()->loadHelper('surveytranslator');
         $grplangs = Survey::model()->findByPk($surveyid)->additionalLanguages;
         $baselang = Survey::model()->findByPk($surveyid)->language;
         array_push($grplangs, $baselang);
         foreach ($grplangs as $grplang) {
             if (isset($grplang) && $grplang != "") {
                 $group_name = $_POST['group_name_' . $grplang];
                 $group_description = $_POST['description_' . $grplang];
                 $group_name = html_entity_decode($group_name, ENT_QUOTES, "UTF-8");
                 $group_description = html_entity_decode($group_description, ENT_QUOTES, "UTF-8");
                 // Fix bug with FCKEditor saving strange BR types
                 $group_name = fixCKeditorText($group_name);
                 $group_description = fixCKeditorText($group_description);
                 $aData = array('group_name' => $group_name, 'description' => $group_description, 'randomization_group' => $_POST['randomization_group'], 'grelevance' => $_POST['grelevance']);
                 $condition = array('gid' => $gid, 'sid' => $surveyid, 'language' => $grplang);
                 $group = QuestionGroup::model()->findByAttributes($condition);
                 foreach ($aData as $k => $v) {
                     $group->{$k} = $v;
                 }
                 $ugresult = $group->save();
                 if ($ugresult) {
                     $groupsummary = getGroupList($gid, $surveyid);
                 }
             }
         }
         Yii::app()->session['flashmessage'] = gT("Question group successfully saved.");
         $this->getController()->redirect(array('admin/survey/sa/view/surveyid/' . $surveyid . '/gid/' . $gid));
     }
 }
/**
* This function builds all the required session variables when a survey is first started and
* it loads any answer defaults from command line or from the table defaultvalues
* It is called from the related format script (group.php, question.php, survey.php)
* if the survey has just started.
*/
function buildsurveysession($surveyid, $preview = false)
{
    Yii::trace('start', 'survey.buildsurveysession');
    global $secerror, $clienttoken;
    global $tokensexist;
    //global $surveyid;
    global $move, $rooturl;
    $clang = Yii::app()->lang;
    $sLangCode = $clang->langcode;
    $languagechanger = makeLanguageChangerSurvey($sLangCode);
    if (!$preview) {
        $preview = Yii::app()->getConfig('previewmode');
    }
    $thissurvey = getSurveyInfo($surveyid, $sLangCode);
    $_SESSION['survey_' . $surveyid]['templatename'] = validateTemplateDir($thissurvey['template']);
    $_SESSION['survey_' . $surveyid]['templatepath'] = getTemplatePath($_SESSION['survey_' . $surveyid]['templatename']) . DIRECTORY_SEPARATOR;
    $sTemplatePath = $_SESSION['survey_' . $surveyid]['templatepath'];
    $loadsecurity = returnGlobal('loadsecurity', true);
    // NO TOKEN REQUIRED BUT CAPTCHA ENABLED FOR SURVEY ACCESS
    if ($tokensexist == 0 && isCaptchaEnabled('surveyaccessscreen', $thissurvey['usecaptcha']) && !isset($_SESSION['survey_' . $surveyid]['captcha_surveyaccessscreen']) && !$preview) {
        // IF CAPTCHA ANSWER IS NOT CORRECT OR NOT SET
        if (!isset($loadsecurity) || !isset($_SESSION['survey_' . $surveyid]['secanswer']) || $loadsecurity != $_SESSION['survey_' . $surveyid]['secanswer']) {
            sendCacheHeaders();
            doHeader();
            // No or bad answer to required security question
            $redata = compact(array_keys(get_defined_vars()));
            echo templatereplace(file_get_contents($sTemplatePath . "startpage.pstpl"), array(), $redata, 'frontend_helper[875]');
            //echo makedropdownlist();
            echo templatereplace(file_get_contents($sTemplatePath . "survey.pstpl"), array(), $redata, 'frontend_helper[877]');
            if (isset($loadsecurity)) {
                // was a bad answer
                echo "<font color='#FF0000'>" . $clang->gT("The answer to the security question is incorrect.") . "</font><br />";
            }
            echo "<p class='captcha'>" . $clang->gT("Please confirm access to survey by answering the security question below and click continue.") . "</p>" . CHtml::form(array("/survey/index/sid/{$surveyid}"), 'post', array('class' => 'captcha')) . "\n            <table align='center'>\n            <tr>\n            <td align='right' valign='middle'>\n            <input type='hidden' name='sid' value='" . $surveyid . "' id='sid' />\n            <input type='hidden' name='lang' value='" . $sLangCode . "' id='lang' />";
            // In case we this is a direct Reload previous answers URL, then add hidden fields
            if (isset($_GET['loadall']) && isset($_GET['scid']) && isset($_GET['loadname']) && isset($_GET['loadpass'])) {
                echo "\n                <input type='hidden' name='loadall' value='" . htmlspecialchars($_GET['loadall']) . "' id='loadall' />\n                <input type='hidden' name='scid' value='" . returnGlobal('scid', true) . "' id='scid' />\n                <input type='hidden' name='loadname' value='" . htmlspecialchars($_GET['loadname']) . "' id='loadname' />\n                <input type='hidden' name='loadpass' value='" . htmlspecialchars($_GET['loadpass']) . "' id='loadpass' />";
            }
            echo "\n            </td>\n            </tr>";
            if (function_exists("ImageCreate") && isCaptchaEnabled('surveyaccessscreen', $thissurvey['usecaptcha'])) {
                echo "<tr>\n                <td align='center' valign='middle'><label for='captcha'>" . $clang->gT("Security question:") . "</label></td><td align='left' valign='middle'><table><tr><td valign='middle'><img src='" . Yii::app()->getController()->createUrl('/verification/image/sid/' . $surveyid) . "' alt='captcha' /></td>\n                <td valign='middle'><input id='captcha' type='text' size='5' maxlength='3' name='loadsecurity' value='' /></td></tr></table>\n                </td>\n                </tr>";
            }
            echo "<tr><td colspan='2' align='center'><input class='submit' type='submit' value='" . $clang->gT("Continue") . "' /></td></tr>\n            </table>\n            </form>";
            echo templatereplace(file_get_contents($sTemplatePath . "endpage.pstpl"), array(), $redata, 'frontend_helper[1567]');
            doFooter();
            exit;
        } else {
            $_SESSION['survey_' . $surveyid]['captcha_surveyaccessscreen'] = true;
        }
    }
    //BEFORE BUILDING A NEW SESSION FOR THIS SURVEY, LET'S CHECK TO MAKE SURE THE SURVEY SHOULD PROCEED!
    // TOKEN REQUIRED BUT NO TOKEN PROVIDED
    if ($tokensexist == 1 && !$clienttoken && !$preview) {
        if ($thissurvey['nokeyboard'] == 'Y') {
            includeKeypad();
            $kpclass = "text-keypad";
        } else {
            $kpclass = "";
        }
        // DISPLAY REGISTER-PAGE if needed
        // DISPLAY CAPTCHA if needed
        sendCacheHeaders();
        doHeader();
        $redata = compact(array_keys(get_defined_vars()));
        echo templatereplace(file_get_contents($sTemplatePath . "startpage.pstpl"), array(), $redata, 'frontend_helper[1594]');
        //echo makedropdownlist();
        echo templatereplace(file_get_contents($sTemplatePath . "survey.pstpl"), array(), $redata, 'frontend_helper[1596]');
        if (isset($thissurvey) && $thissurvey['allowregister'] == "Y") {
            echo templatereplace(file_get_contents($sTemplatePath . "register.pstpl"), array(), $redata, 'frontend_helper[1599]');
        } else {
            // ->renderPartial('entertoken_view');
            if (isset($secerror)) {
                echo "<span class='error'>" . $secerror . "</span><br />";
            }
            echo '<div id="wrapper"><p id="tokenmessage">' . $clang->gT("This is a controlled survey. You need a valid token to participate.") . "<br />";
            echo $clang->gT("If you have been issued a token, please enter it in the box below and click continue.") . "</p>\n            <script type='text/javascript'>var focus_element='#token';</script>" . CHtml::form(array("/survey/index/sid/{$surveyid}"), 'post', array('id' => 'tokenform', 'autocomplete' => 'off')) . "\n            <ul>\n            <li>";
            ?>
            <label for='token'><?php 
            $clang->eT("Token:");
            ?>
</label><input class='text <?php 
            echo $kpclass;
            ?>
' id='token' type='password' name='token' value='' />
            <?php 
            echo "<input type='hidden' name='sid' value='" . $surveyid . "' id='sid' />\n            <input type='hidden' name='lang' value='" . $sLangCode . "' id='lang' />";
            if (isset($_GET['newtest']) && $_GET['newtest'] == "Y") {
                echo "  <input type='hidden' name='newtest' value='Y' id='newtest' />";
            }
            // If this is a direct Reload previous answers URL, then add hidden fields
            if (isset($_GET['loadall']) && isset($_GET['scid']) && isset($_GET['loadname']) && isset($_GET['loadpass'])) {
                echo "\n                <input type='hidden' name='loadall' value='" . htmlspecialchars($_GET['loadall']) . "' id='loadall' />\n                <input type='hidden' name='scid' value='" . returnGlobal('scid', true) . "' id='scid' />\n                <input type='hidden' name='loadname' value='" . htmlspecialchars($_GET['loadname']) . "' id='loadname' />\n                <input type='hidden' name='loadpass' value='" . htmlspecialchars($_GET['loadpass']) . "' id='loadpass' />";
            }
            echo "</li>";
            if (function_exists("ImageCreate") && isCaptchaEnabled('surveyaccessscreen', $thissurvey['usecaptcha'])) {
                echo "<li>\n                <label for='captchaimage'>" . $clang->gT("Security Question") . "</label><img id='captchaimage' src='" . Yii::app()->getController()->createUrl('/verification/image/sid/' . $surveyid) . "' alt='captcha' /><input type='text' size='5' maxlength='3' name='loadsecurity' value='' />\n                </li>";
            }
            echo "<li>\n            <input class='submit button' type='submit' value='" . $clang->gT("Continue") . "' />\n            </li>\n            </ul>\n            </form></div>";
        }
        echo templatereplace(file_get_contents($sTemplatePath . "endpage.pstpl"), array(), $redata, 'frontend_helper[1645]');
        doFooter();
        exit;
    } elseif ($tokensexist == 1 && $clienttoken && !isCaptchaEnabled('surveyaccessscreen', $thissurvey['usecaptcha'])) {
        //check if token actually does exist
        // check also if it is allowed to change survey after completion
        if ($thissurvey['alloweditaftercompletion'] == 'Y') {
            $oTokenEntry = Token::model($surveyid)->findByAttributes(array('token' => $clienttoken));
        } else {
            $oTokenEntry = Token::model($surveyid)->usable()->incomplete()->findByAttributes(array('token' => $clienttoken));
        }
        if (!isset($oTokenEntry)) {
            //TOKEN DOESN'T EXIST OR HAS ALREADY BEEN USED. EXPLAIN PROBLEM AND EXIT
            killSurveySession($surveyid);
            sendCacheHeaders();
            doHeader();
            $redata = compact(array_keys(get_defined_vars()));
            echo templatereplace(file_get_contents($sTemplatePath . "startpage.pstpl"), array(), $redata, 'frontend_helper[1676]');
            echo templatereplace(file_get_contents($sTemplatePath . "survey.pstpl"), array(), $redata, 'frontend_helper[1677]');
            echo '<div id="wrapper"><p id="tokenmessage">' . $clang->gT("This is a controlled survey. You need a valid token to participate.") . "<br /><br />\n" . "\t" . $clang->gT("The token you have provided is either not valid, or has already been used.") . "<br /><br />\n" . "\t" . sprintf($clang->gT("For further information please contact %s"), $thissurvey['adminname']) . " (<a href='mailto:{$thissurvey['adminemail']}'>" . "{$thissurvey['adminemail']}</a>)</p></div>\n";
            echo templatereplace(file_get_contents($sTemplatePath . "endpage.pstpl"), array(), $redata, 'frontend_helper[1684]');
            doFooter();
            exit;
        }
    } elseif ($tokensexist == 1 && $clienttoken && isCaptchaEnabled('surveyaccessscreen', $thissurvey['usecaptcha'])) {
        // IF CAPTCHA ANSWER IS CORRECT
        if (isset($loadsecurity) && isset($_SESSION['survey_' . $surveyid]['secanswer']) && $loadsecurity == $_SESSION['survey_' . $surveyid]['secanswer']) {
            if ($thissurvey['alloweditaftercompletion'] == 'Y') {
                $oTokenEntry = Token::model($surveyid)->findByAttributes(array('token' => $clienttoken));
            } else {
                $oTokenEntry = Token::model($surveyid)->incomplete()->findByAttributes(array('token' => $clienttoken));
            }
            if (!isset($oTokenEntry)) {
                sendCacheHeaders();
                doHeader();
                //TOKEN DOESN'T EXIST OR HAS ALREADY BEEN USED. EXPLAIN PROBLEM AND EXIT
                $redata = compact(array_keys(get_defined_vars()));
                echo templatereplace(file_get_contents($sTemplatePath . "startpage.pstpl"), array(), $redata, 'frontend_helper[1719]');
                echo templatereplace(file_get_contents($sTemplatePath . "survey.pstpl"), array(), $redata, 'frontend_helper[1720]');
                echo "\t<div id='wrapper'>\n" . "\t<p id='tokenmessage'>\n" . "\t" . $clang->gT("This is a controlled survey. You need a valid token to participate.") . "<br /><br />\n" . "\t" . $clang->gT("The token you have provided is either not valid, or has already been used.") . "<br/><br />\n" . "\t" . sprintf($clang->gT("For further information please contact %s"), $thissurvey['adminname']) . " (<a href='mailto:{$thissurvey['adminemail']}'>" . "{$thissurvey['adminemail']}</a>)\n" . "\t</p>\n" . "\t</div>\n";
                echo templatereplace(file_get_contents($sTemplatePath . "endpage.pstpl"), array(), $redata, 'frontend_helper[1731]');
                doFooter();
                exit;
            }
        } else {
            if (!isset($move) || is_null($move)) {
                unset($_SESSION['survey_' . $surveyid]['srid']);
                $gettoken = $clienttoken;
                sendCacheHeaders();
                doHeader();
                // No or bad answer to required security question
                $redata = compact(array_keys(get_defined_vars()));
                echo templatereplace(file_get_contents($sTemplatePath . "startpage.pstpl"), array(), $redata, 'frontend_helper[1745]');
                echo templatereplace(file_get_contents($sTemplatePath . "survey.pstpl"), array(), $redata, 'frontend_helper[1746]');
                // If token wasn't provided and public registration
                // is enabled then show registration form
                if (!isset($gettoken) && isset($thissurvey) && $thissurvey['allowregister'] == "Y") {
                    echo templatereplace(file_get_contents($sTemplatePath . "register.pstpl"), array(), $redata, 'frontend_helper[1751]');
                } else {
                    // only show CAPTCHA
                    echo '<div id="wrapper"><p id="tokenmessage">';
                    if (isset($loadsecurity)) {
                        // was a bad answer
                        echo "<span class='error'>" . $clang->gT("The answer to the security question is incorrect.") . "</span><br />";
                    }
                    echo $clang->gT("This is a controlled survey. You need a valid token to participate.") . "<br /><br />";
                    // IF TOKEN HAS BEEN GIVEN THEN AUTOFILL IT
                    // AND HIDE ENTRY FIELD
                    if (!isset($gettoken)) {
                        echo $clang->gT("If you have been issued a token, please enter it in the box below and click continue.") . "</p>\n                        <form id='tokenform' method='get' action='" . Yii::app()->getController()->createUrl("/survey/index") . "'>\n                        <ul>\n                        <li>\n                        <input type='hidden' name='sid' value='" . $surveyid . "' id='sid' />\n                        <input type='hidden' name='lang' value='" . $sLangCode . "' id='lang' />";
                        if (isset($_GET['loadall']) && isset($_GET['scid']) && isset($_GET['loadname']) && isset($_GET['loadpass'])) {
                            echo "<input type='hidden' name='loadall' value='" . htmlspecialchars($_GET['loadall']) . "' id='loadall' />\n                            <input type='hidden' name='scid' value='" . returnGlobal('scid', true) . "' id='scid' />\n                            <input type='hidden' name='loadname' value='" . htmlspecialchars($_GET['loadname']) . "' id='loadname' />\n                            <input type='hidden' name='loadpass' value='" . htmlspecialchars($_GET['loadpass']) . "' id='loadpass' />";
                        }
                        echo '<label for="token">' . $clang->gT("Token") . "</label><input class='text' type='password' id='token' name='token'></li>";
                    } else {
                        echo $clang->gT("Please confirm the token by answering the security question below and click continue.") . "</p>\n                    <form id='tokenform' method='get' action='" . Yii::app()->getController()->createUrl("/survey/index") . "'>\n                    <ul>\n                    <li>\n                    <input type='hidden' name='sid' value='" . $surveyid . "' id='sid' />\n                    <input type='hidden' name='lang' value='" . $sLangCode . "' id='lang' />";
                        if (isset($_GET['loadall']) && isset($_GET['scid']) && isset($_GET['loadname']) && isset($_GET['loadpass'])) {
                            echo "<input type='hidden' name='loadall' value='" . htmlspecialchars($_GET['loadall']) . "' id='loadall' />\n                        <input type='hidden' name='scid' value='" . returnGlobal('scid', true) . "' id='scid' />\n                        <input type='hidden' name='loadname' value='" . htmlspecialchars($_GET['loadname']) . "' id='loadname' />\n                        <input type='hidden' name='loadpass' value='" . htmlspecialchars($_GET['loadpass']) . "' id='loadpass' />";
                        }
                        echo '<label for="token">' . $clang->gT("Token:") . "</label><span id='token'>{$gettoken}</span>" . "<input type='hidden' name='token' value='{$gettoken}'></li>";
                    }
                    if (function_exists("ImageCreate") && isCaptchaEnabled('surveyaccessscreen', $thissurvey['usecaptcha'])) {
                        echo "<li>\n                    <label for='captchaimage'>" . $clang->gT("Security Question") . "</label><img id='captchaimage' src='" . Yii::app()->getController()->createUrl('/verification/image/sid/' . $surveyid) . "' alt='captcha' /><input type='text' size='5' maxlength='3' name='loadsecurity' value='' />\n                    </li>";
                    }
                    echo "<li><input class='submit' type='submit' value='" . $clang->gT("Continue") . "' /></li>\n                </ul>\n                </form>\n                </id>";
                }
                echo '</div>' . templatereplace(file_get_contents($sTemplatePath . "endpage.pstpl"), array(), $redata, 'frontend_helper[1817]');
                doFooter();
                exit;
            }
        }
    }
    //RESET ALL THE SESSION VARIABLES AND START AGAIN
    unset($_SESSION['survey_' . $surveyid]['grouplist']);
    unset($_SESSION['survey_' . $surveyid]['fieldarray']);
    unset($_SESSION['survey_' . $surveyid]['insertarray']);
    unset($_SESSION['survey_' . $surveyid]['fieldnamesInfo']);
    unset($_SESSION['survey_' . $surveyid]['fieldmap-' . $surveyid . '-randMaster']);
    unset($_SESSION['survey_' . $surveyid]['groupReMap']);
    $_SESSION['survey_' . $surveyid]['fieldnamesInfo'] = array();
    // Multi lingual support order : by REQUEST, if not by Token->language else by survey default language
    if (returnGlobal('lang', true)) {
        $language_to_set = returnGlobal('lang', true);
    } elseif (isset($oTokenEntry) && $oTokenEntry) {
        // If survey have token : we have a $oTokenEntry
        // Can use $oTokenEntry = Token::model($surveyid)->findByAttributes(array('token'=>$clienttoken)); if we move on another function : this par don't validate the token validity
        $language_to_set = $oTokenEntry->language;
    } else {
        $language_to_set = $thissurvey['language'];
    }
    if (!isset($_SESSION['survey_' . $surveyid]['s_lang'])) {
        SetSurveyLanguage($surveyid, $language_to_set);
    }
    UpdateGroupList($surveyid, $_SESSION['survey_' . $surveyid]['s_lang']);
    $sQuery = "SELECT count(*)\n" . " FROM {{groups}} INNER JOIN {{questions}} ON {{groups}}.gid = {{questions}}.gid\n" . " WHERE {{questions}}.sid=" . $surveyid . "\n" . " AND {{groups}}.language='" . $_SESSION['survey_' . $surveyid]['s_lang'] . "'\n" . " AND {{questions}}.language='" . $_SESSION['survey_' . $surveyid]['s_lang'] . "'\n" . " AND {{questions}}.parent_qid=0\n";
    $totalquestions = Yii::app()->db->createCommand($sQuery)->queryScalar();
    // Fix totalquestions by substracting Test Display questions
    $iNumberofQuestions = dbExecuteAssoc("SELECT count(*)\n" . " FROM {{questions}}" . " WHERE type in ('X','*')\n" . " AND sid={$surveyid}" . " AND language='" . $_SESSION['survey_' . $surveyid]['s_lang'] . "'" . " AND parent_qid=0")->read();
    $_SESSION['survey_' . $surveyid]['totalquestions'] = $totalquestions - (int) reset($iNumberofQuestions);
    //2. SESSION VARIABLE: totalsteps
    //The number of "pages" that will be presented in this survey
    //The number of pages to be presented will differ depending on the survey format
    switch ($thissurvey['format']) {
        case "A":
            $_SESSION['survey_' . $surveyid]['totalsteps'] = 1;
            break;
        case "G":
            if (isset($_SESSION['survey_' . $surveyid]['grouplist'])) {
                $_SESSION['survey_' . $surveyid]['totalsteps'] = count($_SESSION['survey_' . $surveyid]['grouplist']);
            }
            break;
        case "S":
            $_SESSION['survey_' . $surveyid]['totalsteps'] = $totalquestions;
    }
    if ($totalquestions == 0) {
        sendCacheHeaders();
        doHeader();
        $redata = compact(array_keys(get_defined_vars()));
        echo templatereplace(file_get_contents($sTemplatePath . "startpage.pstpl"), array(), $redata, 'frontend_helper[1914]');
        echo templatereplace(file_get_contents($sTemplatePath . "survey.pstpl"), array(), $redata, 'frontend_helper[1915]');
        echo "\t<div id='wrapper'>\n" . "\t<p id='tokenmessage'>\n" . "\t" . $clang->gT("This survey does not yet have any questions and cannot be tested or completed.") . "<br /><br />\n" . "\t" . sprintf($clang->gT("For further information please contact %s"), $thissurvey['adminname']) . " (<a href='mailto:{$thissurvey['adminemail']}'>" . "{$thissurvey['adminemail']}</a>)<br /><br />\n" . "\t</p>\n" . "\t</div>\n";
        echo templatereplace(file_get_contents($sTemplatePath . "endpage.pstpl"), array(), $redata, 'frontend_helper[1925]');
        doFooter();
        exit;
    }
    //Perform a case insensitive natural sort on group name then question title of a multidimensional array
    //    usort($arows, 'groupOrderThenQuestionOrder');
    //3. SESSION VARIABLE - insertarray
    //An array containing information about used to insert the data into the db at the submit stage
    //4. SESSION VARIABLE - fieldarray
    //See rem at end..
    if ($tokensexist == 1 && $clienttoken) {
        $_SESSION['survey_' . $surveyid]['token'] = $clienttoken;
    }
    if ($thissurvey['anonymized'] == "N") {
        $_SESSION['survey_' . $surveyid]['insertarray'][] = "token";
    }
    $qtypes = getQuestionTypeList('', 'array');
    $fieldmap = createFieldMap($surveyid, 'full', true, false, $_SESSION['survey_' . $surveyid]['s_lang']);
    // Randomization groups for groups
    $aRandomGroups = array();
    $aGIDCompleteMap = array();
    // first find all groups and their groups IDS
    $criteria = new CDbCriteria();
    $criteria->addColumnCondition(array('sid' => $surveyid, 'language' => $_SESSION['survey_' . $surveyid]['s_lang']));
    $criteria->addCondition("randomization_group != ''");
    $oData = QuestionGroup::model()->findAll($criteria);
    foreach ($oData as $aGroup) {
        $aRandomGroups[$aGroup['randomization_group']][] = $aGroup['gid'];
    }
    // Shuffle each group and create a map for old GID => new GID
    foreach ($aRandomGroups as $sGroupName => $aGIDs) {
        $aShuffledIDs = $aGIDs;
        shuffle($aShuffledIDs);
        $aGIDCompleteMap = $aGIDCompleteMap + array_combine($aGIDs, $aShuffledIDs);
    }
    $_SESSION['survey_' . $surveyid]['groupReMap'] = $aGIDCompleteMap;
    $randomized = false;
    // So we can trigger reorder once for group and question randomization
    // Now adjust the grouplist
    if (count($aRandomGroups) > 0 && !$preview) {
        $randomized = true;
        // So we can trigger reorder once for group and question randomization
        // Now adjust the grouplist
        Yii::import('application.helpers.frontend_helper', true);
        // make sure frontend helper is loaded
        UpdateGroupList($surveyid, $_SESSION['survey_' . $surveyid]['s_lang']);
        // ... and the fieldmap
        // First create a fieldmap with GID as key
        foreach ($fieldmap as $aField) {
            if (isset($aField['gid'])) {
                $GroupFieldMap[$aField['gid']][] = $aField;
            } else {
                $GroupFieldMap['other'][] = $aField;
            }
        }
        // swap it
        foreach ($GroupFieldMap as $iOldGid => $fields) {
            $iNewGid = $iOldGid;
            if (isset($aGIDCompleteMap[$iOldGid])) {
                $iNewGid = $aGIDCompleteMap[$iOldGid];
            }
            $newGroupFieldMap[$iNewGid] = $GroupFieldMap[$iNewGid];
        }
        $GroupFieldMap = $newGroupFieldMap;
        // and convert it back to a fieldmap
        unset($fieldmap);
        foreach ($GroupFieldMap as $aGroupFields) {
            foreach ($aGroupFields as $aField) {
                if (isset($aField['fieldname'])) {
                    $fieldmap[$aField['fieldname']] = $aField;
                    // isset() because of the shuffled flag above
                }
            }
        }
        unset($GroupFieldMap);
    }
    // Randomization groups for questions
    // Find all defined randomization groups through question attribute values
    $randomGroups = array();
    if (in_array(Yii::app()->db->getDriverName(), array('mssql', 'sqlsrv', 'dblib'))) {
        $rgquery = "SELECT attr.qid, CAST(value as varchar(255)) as value FROM {{question_attributes}} as attr right join {{questions}} as quests on attr.qid=quests.qid WHERE attribute='random_group' and CAST(value as varchar(255)) <> '' and sid={$surveyid} GROUP BY attr.qid, CAST(value as varchar(255))";
    } else {
        $rgquery = "SELECT attr.qid, value FROM {{question_attributes}} as attr right join {{questions}} as quests on attr.qid=quests.qid WHERE attribute='random_group' and value <> '' and sid={$surveyid} GROUP BY attr.qid, value";
    }
    $rgresult = dbExecuteAssoc($rgquery);
    foreach ($rgresult->readAll() as $rgrow) {
        // Get the question IDs for each randomization group
        $randomGroups[$rgrow['value']][] = $rgrow['qid'];
    }
    // If we have randomization groups set, then lets cycle through each group and
    // replace questions in the group with a randomly chosen one from the same group
    if (count($randomGroups) > 0 && !$preview) {
        $randomized = true;
        // So we can trigger reorder once for group and question randomization
        $copyFieldMap = array();
        $oldQuestOrder = array();
        $newQuestOrder = array();
        $randGroupNames = array();
        foreach ($randomGroups as $key => $value) {
            $oldQuestOrder[$key] = $randomGroups[$key];
            $newQuestOrder[$key] = $oldQuestOrder[$key];
            // We shuffle the question list to get a random key->qid which will be used to swap from the old key
            shuffle($newQuestOrder[$key]);
            $randGroupNames[] = $key;
        }
        // Loop through the fieldmap and swap each question as they come up
        foreach ($fieldmap as $fieldkey => $fieldval) {
            $found = 0;
            foreach ($randomGroups as $gkey => $gval) {
                // We found a qid that is in the randomization group
                if (isset($fieldval['qid']) && in_array($fieldval['qid'], $oldQuestOrder[$gkey])) {
                    // Get the swapped question
                    $idx = array_search($fieldval['qid'], $oldQuestOrder[$gkey]);
                    foreach ($fieldmap as $key => $field) {
                        if (isset($field['qid']) && $field['qid'] == $newQuestOrder[$gkey][$idx]) {
                            $field['random_gid'] = $fieldval['gid'];
                            // It is possible to swap to another group
                            $copyFieldMap[$key] = $field;
                        }
                    }
                    $found = 1;
                    break;
                } else {
                    $found = 2;
                }
            }
            if ($found == 2) {
                $copyFieldMap[$fieldkey] = $fieldval;
            }
            reset($randomGroups);
        }
        $fieldmap = $copyFieldMap;
    }
    if ($randomized === true) {
        // reset the sequencing counts
        $gseq = -1;
        $_gid = -1;
        $qseq = -1;
        $_qid = -1;
        $copyFieldMap = array();
        foreach ($fieldmap as $key => $val) {
            if ($val['gid'] != '') {
                if (isset($val['random_gid'])) {
                    $gid = $val['random_gid'];
                } else {
                    $gid = $val['gid'];
                }
                if ($gid != $_gid) {
                    $_gid = $gid;
                    ++$gseq;
                }
            }
            if ($val['qid'] != '' && $val['qid'] != $_qid) {
                $_qid = $val['qid'];
                ++$qseq;
            }
            if ($val['gid'] != '' && $val['qid'] != '') {
                $val['groupSeq'] = $gseq;
                $val['questionSeq'] = $qseq;
            }
            $copyFieldMap[$key] = $val;
        }
        $fieldmap = $copyFieldMap;
        unset($copyFieldMap);
        $_SESSION['survey_' . $surveyid]['fieldmap-' . $surveyid . $_SESSION['survey_' . $surveyid]['s_lang']] = $fieldmap;
        $_SESSION['survey_' . $surveyid]['fieldmap-' . $surveyid . '-randMaster'] = 'fieldmap-' . $surveyid . $_SESSION['survey_' . $surveyid]['s_lang'];
    }
    // TMSW Condition->Relevance:  don't need hasconditions, or usedinconditions
    $_SESSION['survey_' . $surveyid]['fieldmap'] = $fieldmap;
    foreach ($fieldmap as $field) {
        if (isset($field['qid']) && $field['qid'] != '') {
            $_SESSION['survey_' . $surveyid]['fieldnamesInfo'][$field['fieldname']] = $field['sid'] . 'X' . $field['gid'] . 'X' . $field['qid'];
            $_SESSION['survey_' . $surveyid]['insertarray'][] = $field['fieldname'];
            //fieldarray ARRAY CONTENTS -
            //            [0]=questions.qid,
            //            [1]=fieldname,
            //            [2]=questions.title,
            //            [3]=questions.question
            //                     [4]=questions.type,
            //            [5]=questions.gid,
            //            [6]=questions.mandatory,
            //            [7]=conditionsexist,
            //            [8]=usedinconditions
            //            [8]=usedinconditions
            //            [9]=used in group.php for question count
            //            [10]=new group id for question in randomization group (GroupbyGroup Mode)
            if (!isset($_SESSION['survey_' . $surveyid]['fieldarray'][$field['sid'] . 'X' . $field['gid'] . 'X' . $field['qid']])) {
                //JUST IN CASE : PRECAUTION!
                //following variables are set only if $style=="full" in createFieldMap() in common_helper.
                //so, if $style = "short", set some default values here!
                if (isset($field['title'])) {
                    $title = $field['title'];
                } else {
                    $title = "";
                }
                if (isset($field['question'])) {
                    $question = $field['question'];
                } else {
                    $question = "";
                }
                if (isset($field['mandatory'])) {
                    $mandatory = $field['mandatory'];
                } else {
                    $mandatory = 'N';
                }
                if (isset($field['hasconditions'])) {
                    $hasconditions = $field['hasconditions'];
                } else {
                    $hasconditions = 'N';
                }
                if (isset($field['usedinconditions'])) {
                    $usedinconditions = $field['usedinconditions'];
                } else {
                    $usedinconditions = 'N';
                }
                $_SESSION['survey_' . $surveyid]['fieldarray'][$field['sid'] . 'X' . $field['gid'] . 'X' . $field['qid']] = array($field['qid'], $field['sid'] . 'X' . $field['gid'] . 'X' . $field['qid'], $title, $question, $field['type'], $field['gid'], $mandatory, $hasconditions, $usedinconditions);
            }
            if (isset($field['random_gid'])) {
                $_SESSION['survey_' . $surveyid]['fieldarray'][$field['sid'] . 'X' . $field['gid'] . 'X' . $field['qid']][10] = $field['random_gid'];
            }
        }
    }
    // Prefill questions/answers from command line params
    $reservedGetValues = array('token', 'sid', 'gid', 'qid', 'lang', 'newtest', 'action');
    $startingValues = array();
    if (isset($_GET)) {
        foreach ($_GET as $k => $v) {
            if (!in_array($k, $reservedGetValues) && isset($_SESSION['survey_' . $surveyid]['fieldmap'][$k])) {
                $startingValues[$k] = $v;
            } else {
                // Search question codes to use those for prefilling.
                foreach ($_SESSION['survey_' . $surveyid]['fieldmap'] as $sgqa => $details) {
                    if ($details['title'] == $k) {
                        $startingValues[$sgqa] = $v;
                    }
                }
            }
        }
    }
    $_SESSION['survey_' . $surveyid]['startingValues'] = $startingValues;
    if (isset($_SESSION['survey_' . $surveyid]['fieldarray'])) {
        $_SESSION['survey_' . $surveyid]['fieldarray'] = array_values($_SESSION['survey_' . $surveyid]['fieldarray']);
    }
    //Check if a passthru label and value have been included in the query url
    $oResult = SurveyURLParameter::model()->getParametersForSurvey($surveyid);
    foreach ($oResult->readAll() as $aRow) {
        if (isset($_GET[$aRow['parameter']]) && !$preview) {
            $_SESSION['survey_' . $surveyid]['urlparams'][$aRow['parameter']] = $_GET[$aRow['parameter']];
            if ($aRow['targetqid'] != '') {
                foreach ($fieldmap as $sFieldname => $aField) {
                    if ($aRow['targetsqid'] != '') {
                        if ($aField['qid'] == $aRow['targetqid'] && $aField['sqid'] == $aRow['targetsqid']) {
                            $_SESSION['survey_' . $surveyid]['startingValues'][$sFieldname] = $_GET[$aRow['parameter']];
                            $_SESSION['survey_' . $surveyid]['startingValues'][$aRow['parameter']] = $_GET[$aRow['parameter']];
                        }
                    } else {
                        if ($aField['qid'] == $aRow['targetqid']) {
                            $_SESSION['survey_' . $surveyid]['startingValues'][$sFieldname] = $_GET[$aRow['parameter']];
                            $_SESSION['survey_' . $surveyid]['startingValues'][$aRow['parameter']] = $_GET[$aRow['parameter']];
                        }
                    }
                }
            }
        }
    }
    Yii::trace('end', 'survey.buildsurveysession');
}
Пример #8
0
 /**
  * Show printable survey
  */
 function index($surveyid, $lang = null)
 {
     $surveyid = sanitize_int($surveyid);
     if (!Permission::model()->hasSurveyPermission($surveyid, 'surveycontent', 'read')) {
         $aData['surveyid'] = $surveyid;
         App()->getClientScript()->registerPackage('jquery-superfish');
         $message['title'] = gT('Access denied!');
         $message['message'] = gT('You do not have sufficient rights to access this page.');
         $message['class'] = "error";
         $this->_renderWrappedTemplate('survey', array("message" => $message), $aData);
     } else {
         $aSurveyInfo = getSurveyInfo($surveyid, $lang);
         if (!$aSurveyInfo) {
             $this->getController()->error('Invalid survey ID');
         }
         SetSurveyLanguage($surveyid, $lang);
         $sLanguageCode = App()->language;
         $templatename = $aSurveyInfo['template'];
         $welcome = $aSurveyInfo['surveyls_welcometext'];
         $end = $aSurveyInfo['surveyls_endtext'];
         $surveyname = $aSurveyInfo['surveyls_title'];
         $surveydesc = $aSurveyInfo['surveyls_description'];
         $surveyactive = $aSurveyInfo['active'];
         $surveytable = "{{survey_" . $aSurveyInfo['sid'] . "}}";
         $surveyexpirydate = $aSurveyInfo['expires'];
         $surveyfaxto = $aSurveyInfo['faxto'];
         $dateformattype = $aSurveyInfo['surveyls_dateformat'];
         Yii::app()->loadHelper('surveytranslator');
         if (!is_null($surveyexpirydate)) {
             $dformat = getDateFormatData($dateformattype);
             $dformat = $dformat['phpdate'];
             $expirytimestamp = strtotime($surveyexpirydate);
             $expirytimeofday_h = date('H', $expirytimestamp);
             $expirytimeofday_m = date('i', $expirytimestamp);
             $surveyexpirydate = date($dformat, $expirytimestamp);
             if (!empty($expirytimeofday_h) || !empty($expirytimeofday_m)) {
                 $surveyexpirydate .= ' &ndash; ' . $expirytimeofday_h . ':' . $expirytimeofday_m;
             }
             sprintf(gT("Please submit by %s"), $surveyexpirydate);
         } else {
             $surveyexpirydate = '';
         }
         //Fix $templatename : control if print_survey.pstpl exist
         if (is_file(getTemplatePath($templatename) . DIRECTORY_SEPARATOR . 'print_survey.pstpl')) {
             $templatename = $templatename;
             // Change nothing
         } elseif (is_file(getTemplatePath(Yii::app()->getConfig("defaulttemplate")) . DIRECTORY_SEPARATOR . 'print_survey.pstpl')) {
             $templatename = Yii::app()->getConfig("defaulttemplate");
         } else {
             $templatename = "default";
         }
         $sFullTemplatePath = getTemplatePath($templatename) . DIRECTORY_SEPARATOR;
         $sFullTemplateUrl = getTemplateURL($templatename) . "/";
         define('PRINT_TEMPLATE_DIR', $sFullTemplatePath, true);
         define('PRINT_TEMPLATE_URL', $sFullTemplateUrl, true);
         LimeExpressionManager::StartSurvey($surveyid, 'survey', NULL, false, LEM_PRETTY_PRINT_ALL_SYNTAX);
         $moveResult = LimeExpressionManager::NavigateForwards();
         $condition = "sid = '{$surveyid}' AND language = '{$sLanguageCode}'";
         $degresult = QuestionGroup::model()->getAllGroups($condition, array('group_order'));
         //xiao,
         if (!isset($surveyfaxto) || !$surveyfaxto and isset($surveyfaxnumber)) {
             $surveyfaxto = $surveyfaxnumber;
             //Use system fax number if none is set in survey.
         }
         $headelements = getPrintableHeader();
         //if $showsgqacode is enabled at config.php show table name for reference
         $showsgqacode = Yii::app()->getConfig("showsgqacode");
         if (isset($showsgqacode) && $showsgqacode == true) {
             $surveyname = $surveyname . "<br />[" . gT('Database') . " " . gT('table') . ": {$surveytable}]";
         } else {
             $surveyname = $surveyname;
         }
         $survey_output = array('SITENAME' => Yii::app()->getConfig("sitename"), 'SURVEYNAME' => $surveyname, 'SURVEYDESCRIPTION' => $surveydesc, 'WELCOME' => $welcome, 'END' => $end, 'THEREAREXQUESTIONS' => 0, 'SUBMIT_TEXT' => gT("Submit Your Survey."), 'SUBMIT_BY' => $surveyexpirydate, 'THANKS' => gT("Thank you for completing this survey."), 'HEADELEMENTS' => $headelements, 'TEMPLATEURL' => PRINT_TEMPLATE_URL, 'FAXTO' => $surveyfaxto, 'PRIVACY' => '', 'GROUPS' => '');
         $survey_output['FAX_TO'] = '';
         if (!empty($surveyfaxto) && $surveyfaxto != '000-00000000') {
             $survey_output['FAX_TO'] = gT("Please fax your completed survey to:") . " {$surveyfaxto}";
         }
         $total_questions = 0;
         $mapquestionsNumbers = array();
         $answertext = '';
         // otherwise can throw an error on line 1617
         $fieldmap = createFieldMap($surveyid, 'full', false, false, $sLanguageCode);
         // =========================================================
         // START doin the business:
         foreach ($degresult->readAll() as $degrow) {
             // ---------------------------------------------------
             // START doing groups
             $deqresult = Question::model()->getQuestions($surveyid, $degrow['gid'], $sLanguageCode, 0, '"I"');
             $deqrows = array();
             //Create an empty array in case FetchRow does not return any rows
             foreach ($deqresult->readAll() as $deqrow) {
                 $deqrows[] = $deqrow;
             }
             // Get table output into array
             // Perform a case insensitive natural sort on group name then question title of a multidimensional array
             usort($deqrows, 'groupOrderThenQuestionOrder');
             if ($degrow['description']) {
                 $group_desc = $degrow['description'];
             } else {
                 $group_desc = '';
             }
             $group = array('GROUPNAME' => $degrow['group_name'], 'GROUPDESCRIPTION' => $group_desc, 'QUESTIONS' => '');
             // A group can have only hidden questions. In that case you don't want to see the group's header/description either.
             $bGroupHasVisibleQuestions = false;
             $gid = $degrow['gid'];
             //Alternate bgcolor for different groups
             if (!isset($group['ODD_EVEN']) || $group['ODD_EVEN'] == ' g-row-even') {
                 $group['ODD_EVEN'] = ' g-row-odd';
             } else {
                 $group['ODD_EVEN'] = ' g-row-even';
             }
             //Loop through questions
             foreach ($deqrows as $deqrow) {
                 // - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
                 // START doing questions
                 $qidattributes = getQuestionAttributeValues($deqrow['qid'], $deqrow['type']);
                 if ($qidattributes['hidden'] == 1 && $deqrow['type'] != '*') {
                     continue;
                 }
                 $bGroupHasVisibleQuestions = true;
                 //GET ANY CONDITIONS THAT APPLY TO THIS QUESTION
                 $printablesurveyoutput = '';
                 $sExplanation = '';
                 //reset conditions explanation
                 $s = 0;
                 // TMSW Condition->Relevance:  show relevance instead of this whole section to create $explanation
                 $scenarioresult = Condition::model()->getScenarios($deqrow['qid']);
                 $scenarioresult = $scenarioresult->readAll();
                 //Loop through distinct scenarios, thus grouping them together.
                 foreach ($scenarioresult as $scenariorow) {
                     if ($s == 0 && count($scenarioresult) > 1) {
                         $sExplanation .= '<p class="scenario">' . " -------- Scenario {$scenariorow['scenario']} --------</p>\n\n";
                     }
                     if ($s > 0) {
                         $sExplanation .= '<p class="scenario">' . ' -------- ' . gT("or") . " Scenario {$scenariorow['scenario']} --------</p>\n\n";
                     }
                     $x = 0;
                     $conditions1 = "qid={$deqrow['qid']} AND scenario={$scenariorow['scenario']}";
                     $distinctresult = Condition::model()->getSomeConditions(array('cqid', 'method', 'cfieldname'), $conditions1, array('cqid'), array('cqid', 'method', 'cfieldname'));
                     //Loop through each condition for a particular scenario.
                     foreach ($distinctresult->readAll() as $distinctrow) {
                         $condition = "qid = '{$distinctrow['cqid']}' AND parent_qid = 0 AND language = '{$sLanguageCode}'";
                         $subresult = Question::model()->find($condition);
                         if ($x > 0) {
                             $sExplanation .= ' <em class="scenario-and-separator">' . gT('and') . '</em> ';
                         }
                         if (trim($distinctrow['method']) == '') {
                             $distinctrow['method'] = '==';
                         }
                         if ($distinctrow['cqid']) {
                             // cqid != 0  ==> previous answer match
                             if ($distinctrow['method'] == '==') {
                                 $sExplanation .= gT("Answer was") . " ";
                             } elseif ($distinctrow['method'] == '!=') {
                                 $sExplanation .= gT("Answer was NOT") . " ";
                             } elseif ($distinctrow['method'] == '<') {
                                 $sExplanation .= gT("Answer was less than") . " ";
                             } elseif ($distinctrow['method'] == '<=') {
                                 $sExplanation .= gT("Answer was less than or equal to") . " ";
                             } elseif ($distinctrow['method'] == '>=') {
                                 $sExplanation .= gT("Answer was greater than or equal to") . " ";
                             } elseif ($distinctrow['method'] == '>') {
                                 $sExplanation .= gT("Answer was greater than") . " ";
                             } elseif ($distinctrow['method'] == 'RX') {
                                 $sExplanation .= gT("Answer matched (regexp)") . " ";
                             } else {
                                 $sExplanation .= gT("Answer was") . " ";
                             }
                         }
                         if (!$distinctrow['cqid']) {
                             // cqid == 0  ==> token attribute match
                             $tokenData = getTokenFieldsAndNames($surveyid);
                             preg_match('/^{TOKEN:([^}]*)}$/', $distinctrow['cfieldname'], $extractedTokenAttr);
                             $sExplanation .= "Your " . $tokenData[strtolower($extractedTokenAttr[1])]['description'] . " ";
                             if ($distinctrow['method'] == '==') {
                                 $sExplanation .= gT("is") . " ";
                             } elseif ($distinctrow['method'] == '!=') {
                                 $sExplanation .= gT("is NOT") . " ";
                             } elseif ($distinctrow['method'] == '<') {
                                 $sExplanation .= gT("is less than") . " ";
                             } elseif ($distinctrow['method'] == '<=') {
                                 $sExplanation .= gT("is less than or equal to") . " ";
                             } elseif ($distinctrow['method'] == '>=') {
                                 $sExplanation .= gT("is greater than or equal to") . " ";
                             } elseif ($distinctrow['method'] == '>') {
                                 $sExplanation .= gT("is greater than") . " ";
                             } elseif ($distinctrow['method'] == 'RX') {
                                 $sExplanation .= gT("is matched (regexp)") . " ";
                             } else {
                                 $sExplanation .= gT("is") . " ";
                             }
                             $answer_section = ' ' . $distinctrow['value'] . ' ';
                         }
                         $conresult = Condition::model()->getConditionsQuestions($distinctrow['cqid'], $deqrow['qid'], $scenariorow['scenario'], $sLanguageCode);
                         $conditions = array();
                         foreach ($conresult->readAll() as $conrow) {
                             $postans = "";
                             $value = $conrow['value'];
                             switch ($conrow['type']) {
                                 case "Y":
                                     switch ($conrow['value']) {
                                         case "Y":
                                             $conditions[] = gT("Yes");
                                             break;
                                         case "N":
                                             $conditions[] = gT("No");
                                             break;
                                     }
                                     break;
                                 case "G":
                                     switch ($conrow['value']) {
                                         case "M":
                                             $conditions[] = gT("Male");
                                             break;
                                         case "F":
                                             $conditions[] = gT("Female");
                                             break;
                                     }
                                     // switch
                                     break;
                                 case "A":
                                 case "B":
                                 case ":":
                                 case ";":
                                 case "5":
                                     $conditions[] = $conrow['value'];
                                     break;
                                 case "C":
                                     switch ($conrow['value']) {
                                         case "Y":
                                             $conditions[] = gT("Yes");
                                             break;
                                         case "U":
                                             $conditions[] = gT("Uncertain");
                                             break;
                                         case "N":
                                             $conditions[] = gT("No");
                                             break;
                                     }
                                     // switch
                                     break;
                                 case "E":
                                     switch ($conrow['value']) {
                                         case "I":
                                             $conditions[] = gT("Increase");
                                             break;
                                         case "D":
                                             $conditions[] = gT("Decrease");
                                             break;
                                         case "S":
                                             $conditions[] = gT("Same");
                                             break;
                                     }
                                 case "1":
                                     $labelIndex = preg_match("/^[^#]+#([01]{1})\$/", $conrow['cfieldname']);
                                     if ($labelIndex == 0) {
                                         // TIBO
                                         $condition = "qid='{$conrow['cqid']}' AND code='{$conrow['value']}' AND scale_id=0 AND language='{$sLanguageCode}'";
                                         $fresult = Answer::model()->getAllRecords($condition);
                                         foreach ($fresult->readAll() as $frow) {
                                             $postans = $frow['answer'];
                                             $conditions[] = $frow['answer'];
                                         }
                                         // while
                                     } elseif ($labelIndex == 1) {
                                         $condition = "qid='{$conrow['cqid']}' AND code='{$conrow['value']}' AND scale_id=1 AND language='{$sLanguageCode}'";
                                         $fresult = Answer::model()->getAllRecords($condition);
                                         foreach ($fresult->readAll() as $frow) {
                                             $postans = $frow['answer'];
                                             $conditions[] = $frow['answer'];
                                         }
                                         // while
                                     }
                                     break;
                                 case "L":
                                 case "!":
                                 case "O":
                                 case "R":
                                     $condition = "qid='{$conrow['cqid']}' AND code='{$conrow['value']}' AND language='{$sLanguageCode}'";
                                     $ansresult = Answer::model()->findAll($condition);
                                     foreach ($ansresult as $ansrow) {
                                         $conditions[] = $ansrow['answer'];
                                     }
                                     if ($conrow['value'] == "-oth-") {
                                         $conditions[] = gT("Other");
                                     }
                                     $conditions = array_unique($conditions);
                                     break;
                                 case "M":
                                 case "P":
                                     $condition = " parent_qid='{$conrow['cqid']}' AND title='{$conrow['value']}' AND language='{$sLanguageCode}'";
                                     $ansresult = Question::model()->findAll($condition);
                                     foreach ($ansresult as $ansrow) {
                                         $conditions[] = $ansrow['question'];
                                     }
                                     $conditions = array_unique($conditions);
                                     break;
                                 case "N":
                                 case "K":
                                     $conditions[] = $value;
                                     break;
                                 case "F":
                                 case "H":
                                 default:
                                     $value = substr($conrow['cfieldname'], strpos($conrow['cfieldname'], "X" . $conrow['cqid']) + strlen("X" . $conrow['cqid']), strlen($conrow['cfieldname']));
                                     $condition = " qid='{$conrow['cqid']}' AND code='{$conrow['value']}' AND language='{$sLanguageCode}'";
                                     $fresult = Answer::model()->getAllRecords($condition);
                                     foreach ($fresult->readAll() as $frow) {
                                         $postans = $frow['answer'];
                                         $conditions[] = $frow['answer'];
                                     }
                                     // while
                                     break;
                             }
                             // switch
                             // Now let's complete the answer text with the answer_section
                             $answer_section = "";
                             switch ($conrow['type']) {
                                 case "A":
                                 case "B":
                                 case "C":
                                 case "E":
                                 case "F":
                                 case "H":
                                 case "K":
                                     $thiscquestion = $fieldmap[$conrow['cfieldname']];
                                     $condition = "parent_qid='{$conrow['cqid']}' AND title='{$thiscquestion['aid']}' AND language='{$sLanguageCode}'";
                                     $ansresult = Question::model()->findAll($condition);
                                     foreach ($ansresult as $ansrow) {
                                         $answer_section = " (" . $ansrow['question'] . ")";
                                     }
                                     break;
                                 case "1":
                                     // dual: (Label 1), (Label 2)
                                     $labelIndex = substr($conrow['cfieldname'], -1);
                                     $thiscquestion = $fieldmap[$conrow['cfieldname']];
                                     $condition = "parent_qid='{$conrow['cqid']}' AND title='{$thiscquestion['aid']}' AND language='{$sLanguageCode}'";
                                     $ansresult = Question::model()->findAll($condition);
                                     $cqidattributes = getQuestionAttributeValues($conrow['cqid']);
                                     if ($labelIndex == 0) {
                                         if (trim($cqidattributes['dualscale_headerA'][$sLanguageCode]) != '') {
                                             $header = gT($cqidattributes['dualscale_headerA'][$sLanguageCode]);
                                         } else {
                                             $header = '1';
                                         }
                                     } elseif ($labelIndex == 1) {
                                         if (trim($cqidattributes['dualscale_headerB'][$sLanguageCode]) != '') {
                                             $header = gT($cqidattributes['dualscale_headerB'][$sLanguageCode]);
                                         } else {
                                             $header = '2';
                                         }
                                     }
                                     foreach ($ansresult as $ansrow) {
                                         $answer_section = " (" . $ansrow->question . " " . sprintf(gT("Label %s"), $header) . ")";
                                     }
                                     break;
                                 case ":":
                                 case ";":
                                     //multi flexi: ( answer [label] )
                                     $thiscquestion = $fieldmap[$conrow['cfieldname']];
                                     $condition = "parent_qid='{$conrow['cqid']}' AND title='{$thiscquestion['aid']}' AND language='{$sLanguageCode}'";
                                     $ansresult = Question::model()->findAll($condition);
                                     foreach ($ansresult as $ansrow) {
                                         $condition = "qid = '{$conrow['cqid']}' AND code = '{$conrow['value']}' AND language= '{$sLanguageCode}'";
                                         $fresult = Answer::model()->findAll($condition);
                                         foreach ($fresult as $frow) {
                                             //$conditions[]=$frow['title'];
                                             $answer_section = " (" . $ansrow->question . "[" . $frow['answer'] . "])";
                                         }
                                         // while
                                     }
                                     break;
                                 case "R":
                                     // (Rank 1), (Rank 2)... TIBO
                                     $thiscquestion = $fieldmap[$conrow['cfieldname']];
                                     $rankid = $thiscquestion['aid'];
                                     $answer_section = " (" . gT("RANK") . " {$rankid})";
                                     break;
                                 default:
                                     // nothing to add
                                     break;
                             }
                         }
                         if (count($conditions) > 1) {
                             $sExplanation .= "'" . implode("' <em class='scenario-or-separator'>" . gT("or") . "</em> '", $conditions) . "'";
                         } elseif (count($conditions) == 1) {
                             $sExplanation .= "'" . $conditions[0] . "'";
                         }
                         unset($conditions);
                         // Following line commented out because answer_section  was lost, but is required for some question types
                         //$explanation .= " ".gT("to question")." '".$mapquestionsNumbers[$distinctrow['cqid']]."' $answer_section ";
                         if ($distinctrow['cqid']) {
                             $sExplanation .= " <span class='scenario-at-separator'>" . gT("at question") . "</span> '" . $mapquestionsNumbers[$distinctrow['cqid']] . " [" . $subresult['title'] . "]' (" . strip_tags($subresult['question']) . "{$answer_section})";
                         } else {
                             $sExplanation .= " " . $distinctrow['value'];
                         }
                         //$distinctrow
                         $x++;
                     }
                     $s++;
                 }
                 $qinfo = LimeExpressionManager::GetQuestionStatus($deqrow['qid']);
                 $relevance = trim($qinfo['info']['relevance']);
                 $sEquation = $qinfo['relEqn'];
                 if (trim($relevance) != '' && trim($relevance) != '1') {
                     if (isset($qidattributes['printable_help'][$sLanguageCode]) && $qidattributes['printable_help'][$sLanguageCode] != '') {
                         $sExplanation = $qidattributes['printable_help'][$sLanguageCode];
                     } elseif ($sExplanation == '') {
                         $sExplanation = $sEquation;
                         $sEquation = '&nbsp;';
                         // No need to show it twice
                     }
                     $sExplanation = "<b>" . gT('Only answer this question if the following conditions are met:') . "</b><br/> " . $sExplanation;
                     if (Yii::app()->getConfig('showrelevance')) {
                         $sExplanation .= "<span class='printable_equation'><br>" . $sEquation . "</span>";
                     }
                 } else {
                     $sExplanation = '';
                 }
                 ++$total_questions;
                 //TIBO map question qid to their q number
                 $mapquestionsNumbers[$deqrow['qid']] = $total_questions;
                 //END OF GETTING CONDITIONS
                 $qid = $deqrow['qid'];
                 $fieldname = "{$surveyid}" . "X" . "{$gid}" . "X" . "{$qid}";
                 if (isset($showsgqacode) && $showsgqacode == true) {
                     $deqrow['question'] = $deqrow['question'] . "<br />" . gT("ID:") . " {$fieldname} <br />" . gT("Question code:") . " " . $deqrow['title'];
                 }
                 $question = array('QUESTION_NUMBER' => $total_questions, 'QUESTION_CODE' => $deqrow['title'], 'QUESTION_TEXT' => preg_replace('/(?:<br ?\\/?>|<\\/(?:p|h[1-6])>)$/is', '', $deqrow['question']), 'QUESTION_SCENARIO' => $sExplanation, 'QUESTION_MANDATORY' => '', 'QUESTION_ID' => $deqrow['qid'], 'QUESTION_CLASS' => getQuestionClass($deqrow['type']), 'QUESTION_TYPE_HELP' => $qinfo['validTip'], 'QUESTION_MAN_MESSAGE' => '', 'QUESTION_VALID_MESSAGE' => '', 'QUESTION_FILE_VALID_MESSAGE' => '', 'QUESTIONHELP' => '', 'ANSWER' => '');
                 $showqnumcode = Yii::app()->getConfig('showqnumcode');
                 if ($showqnumcode == 'choose' && ($aSurveyInfo['showqnumcode'] == 'N' || $aSurveyInfo['showqnumcode'] == 'X') || $showqnumcode == 'number' || $showqnumcode == 'none') {
                     $question['QUESTION_CODE'] = '';
                 }
                 if ($showqnumcode == 'choose' && ($aSurveyInfo['showqnumcode'] == 'C' || $aSurveyInfo['showqnumcode'] == 'X') || $showqnumcode == 'code' || $showqnumcode == 'none') {
                     $question['QUESTION_NUMBER'] = '';
                 }
                 if ($question['QUESTION_TYPE_HELP'] != "") {
                     $question['QUESTION_TYPE_HELP'] .= "<br />\n";
                 }
                 if ($deqrow['mandatory'] == 'Y') {
                     $question['QUESTION_MANDATORY'] = gT('*');
                     $question['QUESTION_CLASS'] .= ' mandatory';
                 }
                 //DIFFERENT TYPES OF DATA FIELD HERE
                 if ($deqrow['help']) {
                     $question['QUESTIONHELP'] = $deqrow['help'];
                 }
                 if (!empty($qidattributes['page_break'])) {
                     $question['QUESTION_CLASS'] .= ' breakbefore ';
                 }
                 if (isset($qidattributes['maximum_chars']) && $qidattributes['maximum_chars'] != '') {
                     $question['QUESTION_CLASS'] = "max-chars-{$qidattributes['maximum_chars']} " . $question['QUESTION_CLASS'];
                 }
                 switch ($deqrow['type']) {
                     // ==================================================================
                     case "5":
                         //5 POINT CHOICE
                         $question['QUESTION_TYPE_HELP'] .= gT('Please choose *only one* of the following:');
                         $question['ANSWER'] .= "\n\t<ul>\n";
                         for ($i = 1; $i <= 5; $i++) {
                             $question['ANSWER'] .= "\t\t<li>\n\t\t\t" . self::_input_type_image('radio', $i) . "\n\t\t\t{$i} " . self::_addsgqacode("({$i})") . "\n\t\t</li>\n";
                         }
                         $question['ANSWER'] .= "\t</ul>\n";
                         break;
                         // ==================================================================
                     // ==================================================================
                     case "D":
                         //DATE
                         $question['QUESTION_TYPE_HELP'] .= gT('Please enter a date:');
                         $question['ANSWER'] .= "\t" . self::_input_type_image('text', $question['QUESTION_TYPE_HELP'], 30, 1);
                         break;
                         // ==================================================================
                     // ==================================================================
                     case "G":
                         //GENDER
                         $question['QUESTION_TYPE_HELP'] .= gT("Please choose *only one* of the following:");
                         $question['ANSWER'] .= "\n\t<ul>\n";
                         $question['ANSWER'] .= "\t\t<li>\n\t\t\t" . self::_input_type_image('radio', gT("Female")) . "\n\t\t\t" . gT("Female") . " " . self::_addsgqacode("(F)") . "\n\t\t</li>\n";
                         $question['ANSWER'] .= "\t\t<li>\n\t\t\t" . self::_input_type_image('radio', gT("Male")) . "\n\t\t\t" . gT("Male") . " " . self::_addsgqacode("(M)") . "\n\t\t</li>\n";
                         $question['ANSWER'] .= "\t</ul>\n";
                         break;
                         // ==================================================================
                     // ==================================================================
                     case "L":
                         //LIST drop-down/radio-button list
                         // ==================================================================
                     //LIST drop-down/radio-button list
                     // ==================================================================
                     case "!":
                         //List - dropdown
                         if (isset($qidattributes['display_columns']) && trim($qidattributes['display_columns']) != '') {
                             $dcols = $qidattributes['display_columns'];
                         } else {
                             $dcols = 0;
                         }
                         if (isset($qidattributes['category_separator']) && trim($qidattributes['category_separator']) != '') {
                             $optCategorySeparator = $qidattributes['category_separator'];
                         } else {
                             unset($optCategorySeparator);
                         }
                         $question['QUESTION_TYPE_HELP'] .= gT("Please choose *only one* of the following:");
                         $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $sLanguageCode, $surveyid);
                         $dearesult = Answer::model()->getAllRecords(" qid='{$deqrow['qid']}' AND language='{$sLanguageCode}' ", array('sortorder', 'answer'));
                         $dearesult = $dearesult->readAll();
                         $deacount = count($dearesult);
                         if ($deqrow['other'] == "Y") {
                             $deacount++;
                         }
                         $wrapper = setupColumns(0, $deacount);
                         $question['ANSWER'] = $wrapper['whole-start'];
                         $rowcounter = 0;
                         $colcounter = 1;
                         foreach ($dearesult as $dearow) {
                             if (isset($optCategorySeparator)) {
                                 list($category, $answer) = explode($optCategorySeparator, $dearow['answer']);
                                 if ($category != '') {
                                     $dearow['answer'] = "({$category}) {$answer} " . self::_addsgqacode("(" . $dearow['code'] . ")");
                                 } else {
                                     $dearow['answer'] = $answer . self::_addsgqacode(" (" . $dearow['code'] . ")");
                                 }
                                 $question['ANSWER'] .= "\t" . $wrapper['item-start'] . "\t\t" . self::_input_type_image('radio', $dearow['answer']) . "\n\t\t\t" . $dearow['answer'] . "\n" . $wrapper['item-end'];
                             } else {
                                 $question['ANSWER'] .= "\t" . $wrapper['item-start'] . "\t\t" . self::_input_type_image('radio', $dearow['answer']) . "\n\t\t\t" . $dearow['answer'] . self::_addsgqacode(" (" . $dearow['code'] . ")") . "\n" . $wrapper['item-end'];
                             }
                             ++$rowcounter;
                             if ($rowcounter == $wrapper['maxrows'] && $colcounter < $wrapper['cols']) {
                                 if ($colcounter == $wrapper['cols'] - 1) {
                                     $question['ANSWER'] .= $wrapper['col-devide-last'];
                                 } else {
                                     $question['ANSWER'] .= $wrapper['col-devide'];
                                 }
                                 $rowcounter = 0;
                                 ++$colcounter;
                             }
                         }
                         if ($deqrow['other'] == 'Y') {
                             if (trim($qidattributes["other_replace_text"][$sLanguageCode]) == '') {
                                 $qidattributes["other_replace_text"][$sLanguageCode] = gT("Other");
                             }
                             //                    $printablesurveyoutput .="\t".$wrapper['item-start']."\t\t".self::_input_type_image('radio' , gT("Other"))."\n\t\t\t".gT("Other")."\n\t\t\t<input type='text' size='30' readonly='readonly' />\n".$wrapper['item-end'];
                             $question['ANSWER'] .= $wrapper['item-start-other'] . self::_input_type_image('radio', gT($qidattributes["other_replace_text"][$sLanguageCode])) . ' ' . gT($qidattributes["other_replace_text"][$sLanguageCode]) . self::_addsgqacode(" (-oth-)") . "\n\t\t\t" . self::_input_type_image('other') . self::_addsgqacode(" (" . $deqrow['sid'] . "X" . $deqrow['gid'] . "X" . $deqrow['qid'] . "other)") . "\n" . $wrapper['item-end'];
                         }
                         $question['ANSWER'] .= $wrapper['whole-end'];
                         //Let's break the presentation into columns.
                         break;
                         // ==================================================================
                     // ==================================================================
                     case "O":
                         //LIST WITH COMMENT
                         $question['QUESTION_TYPE_HELP'] .= gT("Please choose *only one* of the following:");
                         $dearesult = Answer::model()->getAllRecords(" qid='{$deqrow['qid']}' AND language='{$sLanguageCode}'", array('sortorder', 'answer'));
                         $question['ANSWER'] = "\t<ul>\n";
                         foreach ($dearesult->readAll() as $dearow) {
                             $question['ANSWER'] .= "\t\t<li>\n\t\t\t" . self::_input_type_image('radio', $dearow['answer']) . "\n\t\t\t" . $dearow['answer'] . self::_addsgqacode(" (" . $dearow['code'] . ")") . "\n\t\t</li>\n";
                         }
                         $question['ANSWER'] .= "\t</ul>\n";
                         $question['ANSWER'] .= "\t<p class=\"comment\">\n\t\t" . gT("Make a comment on your choice here:") . "\n";
                         $question['ANSWER'] .= "\t\t" . self::_input_type_image('textarea', gT("Make a comment on your choice here:"), 50, 8) . self::_addsgqacode(" (" . $deqrow['sid'] . "X" . $deqrow['gid'] . "X" . $deqrow['qid'] . "comment)") . "\n\t</p>\n";
                         break;
                         // ==================================================================
                     // ==================================================================
                     case "R":
                         //RANKING Type Question
                         $rearesult = Answer::model()->getAllRecords(" qid='{$deqrow['qid']}' AND language='{$sLanguageCode}'", array('sortorder', 'answer'));
                         $rearesult = $rearesult->readAll();
                         $reacount = count($rearesult);
                         $question['QUESTION_TYPE_HELP'] .= gT("Please number each box in order of preference from 1 to") . " {$reacount}";
                         $question['QUESTION_TYPE_HELP'] .= self::_min_max_answers_help($qidattributes, $sLanguageCode, $surveyid);
                         $question['ANSWER'] = "\n<ul>\n";
                         foreach ($rearesult as $rearow) {
                             $question['ANSWER'] .= "\t<li>\n\t" . self::_input_type_image('rank', '', 4, 1) . "\n\t\t&nbsp;" . $rearow['answer'] . self::_addsgqacode(" (" . $fieldname . $rearow['code'] . ")") . "\n\t</li>\n";
                         }
                         $question['ANSWER'] .= "\n</ul>\n";
                         break;
                         // ==================================================================
                     // ==================================================================
                     case "M":
                         //Multiple choice (Quite tricky really!)
                         if (trim($qidattributes['display_columns']) != '') {
                             $dcols = $qidattributes['display_columns'];
                         } else {
                             $dcols = 0;
                         }
                         $question['QUESTION_TYPE_HELP'] .= gT("Please choose *all* that apply:");
                         $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $sLanguageCode, $surveyid);
                         $mearesult = Question::model()->getAllRecords(" parent_qid='{$deqrow['qid']}' AND language='{$sLanguageCode}' ", array('question_order'));
                         $mearesult = $mearesult->readAll();
                         $meacount = count($mearesult);
                         if ($deqrow['other'] == 'Y') {
                             $meacount++;
                         }
                         $wrapper = setupColumns($dcols, $meacount);
                         $question['ANSWER'] = $wrapper['whole-start'];
                         $rowcounter = 0;
                         $colcounter = 1;
                         foreach ($mearesult as $mearow) {
                             $question['ANSWER'] .= $wrapper['item-start'] . self::_input_type_image('checkbox', $mearow['question']) . "\n\t\t" . $mearow['question'] . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . ") ") . $wrapper['item-end'];
                             ++$rowcounter;
                             if ($rowcounter == $wrapper['maxrows'] && $colcounter < $wrapper['cols']) {
                                 if ($colcounter == $wrapper['cols'] - 1) {
                                     $question['ANSWER'] .= $wrapper['col-devide-last'];
                                 } else {
                                     $question['ANSWER'] .= $wrapper['col-devide'];
                                 }
                                 $rowcounter = 0;
                                 ++$colcounter;
                             }
                         }
                         if ($deqrow['other'] == "Y") {
                             if (trim($qidattributes['other_replace_text'][$sLanguageCode]) == '') {
                                 $qidattributes["other_replace_text"][$sLanguageCode] = "Other";
                             }
                             if (!isset($mearow['answer'])) {
                                 $mearow['answer'] = "";
                             }
                             $question['ANSWER'] .= $wrapper['item-start-other'] . self::_input_type_image('checkbox', $mearow['answer']) . gT($qidattributes["other_replace_text"][$sLanguageCode]) . ":\n\t\t" . self::_input_type_image('other') . self::_addsgqacode(" (" . $fieldname . "other) ") . $wrapper['item-end'];
                         }
                         $question['ANSWER'] .= $wrapper['whole-end'];
                         //                }
                         break;
                         // ==================================================================
                     // ==================================================================
                     case "P":
                         //Multiple choice with comments
                         $question['QUESTION_TYPE_HELP'] .= gT("Please choose all that apply and provide a comment:");
                         $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $sLanguageCode, $surveyid);
                         $mearesult = Question::model()->getAllRecords("parent_qid='{$deqrow['qid']}'  AND language='{$sLanguageCode}'", array('question_order'));
                         //                $printablesurveyoutput .="\t\t\t<u>".gT("Please choose all that apply and provide a comment:")."</u><br />\n";
                         $j = 0;
                         $longest_string = 0;
                         foreach ($mearesult->readAll() as $mearow) {
                             $longest_string = longestString($mearow['question'], $longest_string);
                             $question['ANSWER'] .= "\t<li><span>\n\t\t" . self::_input_type_image('checkbox', $mearow['question']) . $mearow['question'] . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . ") ") . "</span>\n\t\t" . self::_input_type_image('text', 'comment box', 60) . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . "comment) ") . "\n\t</li>\n";
                             $j++;
                         }
                         if ($deqrow['other'] == "Y") {
                             $question['ANSWER'] .= "\t<li class=\"other\">\n\t\t<div class=\"other-replacetext\">" . gT('Other:') . self::_input_type_image('other', '', 1) . "</div>" . self::_input_type_image('othercomment', 'comment box', 50) . self::_addsgqacode(" (" . $fieldname . "other) ") . "\n\t</li>\n";
                             $j++;
                         }
                         $question['ANSWER'] = "\n<ul>\n" . $question['ANSWER'] . "</ul>\n";
                         break;
                         // ==================================================================
                     // ==================================================================
                     case "Q":
                         //MULTIPLE SHORT TEXT
                         $width = 60;
                         // ==================================================================
                     // ==================================================================
                     case "K":
                         //MULTIPLE NUMERICAL
                         $question['QUESTION_TYPE_HELP'] = "";
                         $width = isset($width) ? $width : 16;
                         //                            if (!empty($qidattributes['equals_num_value']))
                         //                            {
                         //                                $question['QUESTION_TYPE_HELP'] .= "* ".sprintf(gT('Total of all entries must equal %d'),$qidattributes['equals_num_value'])."<br />\n";
                         //                            }
                         //                            if (!empty($qidattributes['max_num_value']))
                         //                            {
                         //                                $question['QUESTION_TYPE_HELP'] .= sprintf(gT('Total of all entries must not exceed %d'), $qidattributes['max_num_value'])."<br />\n";
                         //                            }
                         //                            if (!empty($qidattributes['min_num_value']))
                         //                            {
                         //                                $question['QUESTION_TYPE_HELP'] .= sprintf(gT('Total of all entries must be at least %s'),$qidattributes['min_num_value'])."<br />\n";
                         //                            }
                         $question['QUESTION_TYPE_HELP'] .= gT("Please write your answer(s) here:");
                         $longest_string = 0;
                         $mearesult = Question::model()->getAllRecords("parent_qid='{$deqrow['qid']}' AND language='{$sLanguageCode}'", array('question_order'));
                         foreach ($mearesult->readAll() as $mearow) {
                             $longest_string = longestString($mearow['question'], $longest_string);
                             if (isset($qidattributes['slider_layout']) && $qidattributes['slider_layout'] == 1) {
                                 $mearow['question'] = explode(':', $mearow['question']);
                                 $mearow['question'] = $mearow['question'][0];
                             }
                             $question['ANSWER'] .= "\t<li>\n\t\t<span>" . $mearow['question'] . "</span>\n\t\t" . self::_input_type_image('text', $mearow['question'], $width) . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . ") ") . "\n\t</li>\n";
                         }
                         $question['ANSWER'] = "\n<ul>\n" . $question['ANSWER'] . "</ul>\n";
                         break;
                         // ==================================================================
                     // ==================================================================
                     case "S":
                         //SHORT TEXT
                         $question['QUESTION_TYPE_HELP'] .= gT("Please write your answer here:");
                         $question['ANSWER'] = self::_input_type_image('text', $question['QUESTION_TYPE_HELP'], 50);
                         break;
                         // ==================================================================
                     // ==================================================================
                     case "T":
                         //LONG TEXT
                         $question['QUESTION_TYPE_HELP'] .= gT("Please write your answer here:");
                         $question['ANSWER'] = self::_input_type_image('textarea', $question['QUESTION_TYPE_HELP'], '100%', 8);
                         break;
                         // ==================================================================
                     // ==================================================================
                     case "U":
                         //HUGE TEXT
                         $question['QUESTION_TYPE_HELP'] .= gT("Please write your answer here:");
                         $question['ANSWER'] = self::_input_type_image('textarea', $question['QUESTION_TYPE_HELP'], '100%', 30);
                         break;
                         // ==================================================================
                     // ==================================================================
                     case "N":
                         //NUMERICAL
                         $prefix = "";
                         $suffix = "";
                         if ($qidattributes['prefix'][$sLanguageCode] != "") {
                             $prefix = $qidattributes['prefix'][$sLanguageCode];
                         }
                         if ($qidattributes['suffix'][$sLanguageCode] != "") {
                             $suffix = $qidattributes['suffix'][$sLanguageCode];
                         }
                         $question['QUESTION_TYPE_HELP'] .= gT("Please write your answer here:");
                         $question['ANSWER'] = "<ul>\n\t<li>\n\t\t<span>{$prefix}</span>\n\t\t" . self::_input_type_image('text', $question['QUESTION_TYPE_HELP'], 20) . "\n\t\t<span>{$suffix}</span>\n\t\t</li>\n\t</ul>";
                         break;
                         // ==================================================================
                     // ==================================================================
                     case "Y":
                         //YES/NO
                         $question['QUESTION_TYPE_HELP'] .= gT("Please choose *only one* of the following:");
                         $question['ANSWER'] = "\n<ul>\n\t<li>\n\t\t" . self::_input_type_image('radio', gT('Yes')) . "\n\t\t" . gT('Yes') . self::_addsgqacode(" (Y)") . "\n\t</li>\n";
                         $question['ANSWER'] .= "\n\t<li>\n\t\t" . self::_input_type_image('radio', gT('No')) . "\n\t\t" . gT('No') . self::_addsgqacode(" (N)") . "\n\t</li>\n</ul>\n";
                         break;
                         // ==================================================================
                     // ==================================================================
                     case "A":
                         //ARRAY (5 POINT CHOICE)
                         $condition = "parent_qid = '{$deqrow['qid']}'  AND language= '{$sLanguageCode}'";
                         $question['QUESTION_TYPE_HELP'] .= gT("Please choose the appropriate response for each item:");
                         $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $sLanguageCode, $surveyid);
                         $question['ANSWER'] = "\n            <table>\n                <thead>\n                    <tr>\n                        <td>&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>";
                         $j = 0;
                         $rowclass = 'array1';
                         $mearesult = Question::model()->getAllRecords($condition, array('question_order'));
                         foreach ($mearesult->readAll() as $mearow) {
                             $question['ANSWER'] .= "\t\t<tr class=\"{$rowclass}\">\n";
                             $rowclass = alternation($rowclass, 'row');
                             //semantic differential question type?
                             if (strpos($mearow['question'], '|')) {
                                 $answertext = substr($mearow['question'], 0, strpos($mearow['question'], '|')) . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . ")") . " ";
                             } else {
                                 $answertext = $mearow['question'] . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . ")");
                             }
                             $question['ANSWER'] .= "\t\t\t<th class=\"answertext\">{$answertext}</th>\n";
                             for ($i = 1; $i <= 5; $i++) {
                                 $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio', $i) . "</td>\n";
                             }
                             $answertext .= $mearow['question'];
                             //semantic differential question type?
                             if (strpos($mearow['question'], '|')) {
                                 $answertext2 = substr($mearow['question'], strpos($mearow['question'], '|') + 1);
                                 $question['ANSWER'] .= "\t\t\t<th class=\"answertextright\">{$answertext2}</td>\n";
                             }
                             $question['ANSWER'] .= "\t\t</tr>\n";
                             $j++;
                         }
                         $question['ANSWER'] .= "\t</tbody>\n</table>\n";
                         break;
                         // ==================================================================
                     // ==================================================================
                     case "B":
                         //ARRAY (10 POINT CHOICE)
                         $question['QUESTION_TYPE_HELP'] .= gT("Please choose the appropriate response for each item:");
                         $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $sLanguageCode, $surveyid);
                         $question['ANSWER'] .= "\n<table>\n\t<thead>\n\t\t<tr>\n\t\t\t<td>&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";
                         $j = 0;
                         $rowclass = 'array1';
                         $mearesult = Question::model()->getAllRecords(" parent_qid='{$deqrow['qid']}' AND language='{$sLanguageCode}' ", array('question_order'));
                         foreach ($mearesult->readAll() as $mearow) {
                             $question['ANSWER'] .= "\t\t<tr class=\"{$rowclass}\">\n\t\t\t<th class=\"answertext\">{$mearow['question']}" . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . ")") . "</th>\n";
                             $rowclass = alternation($rowclass, 'row');
                             for ($i = 1; $i <= 10; $i++) {
                                 $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio', $i) . "</td>\n";
                             }
                             $question['ANSWER'] .= "\t\t</tr>\n";
                             $j++;
                         }
                         $question['ANSWER'] .= "\t</tbody>\n</table>\n";
                         break;
                         // ==================================================================
                     // ==================================================================
                     case "C":
                         //ARRAY (YES/UNCERTAIN/NO)
                         $question['QUESTION_TYPE_HELP'] .= gT("Please choose the appropriate response for each item:");
                         $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $sLanguageCode, $surveyid);
                         $question['ANSWER'] = '
         <table>
             <thead>
                 <tr>
                     <td>&nbsp;</td>
                     <th>' . gT("Yes") . self::_addsgqacode(" (Y)") . '</th>
                     <th>' . gT("Uncertain") . self::_addsgqacode(" (U)") . '</th>
                     <th>' . gT("No") . self::_addsgqacode(" (N)") . '</th>
                 </tr>
             </thead>
             <tbody>
         ';
                         $j = 0;
                         $rowclass = 'array1';
                         $mearesult = Question::model()->getAllRecords(" parent_qid='{$deqrow['qid']}'  AND language='{$sLanguageCode}' ", array('question_order'));
                         foreach ($mearesult->readAll() as $mearow) {
                             $question['ANSWER'] .= "\t\t<tr class=\"{$rowclass}\">\n";
                             $question['ANSWER'] .= "\t\t\t<th class=\"answertext\">{$mearow['question']}" . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . ")") . "</th>\n";
                             $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio', gT("Yes")) . "</td>\n";
                             $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio', gT("Uncertain")) . "</td>\n";
                             $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio', gT("No")) . "</td>\n";
                             $question['ANSWER'] .= "\t\t</tr>\n";
                             $j++;
                             $rowclass = alternation($rowclass, 'row');
                         }
                         $question['ANSWER'] .= "\t</tbody>\n</table>\n";
                         break;
                     case "E":
                         //ARRAY (Increase/Same/Decrease)
                         $question['QUESTION_TYPE_HELP'] .= gT("Please choose the appropriate response for each item:");
                         $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $sLanguageCode, $surveyid);
                         $question['ANSWER'] = '
         <table>
             <thead>
                 <tr>
                     <td>&nbsp;</td>
                     <th>' . gT("Increase") . self::_addsgqacode(" (I)") . '</th>
                     <th>' . gT("Same") . self::_addsgqacode(" (S)") . '</th>
                     <th>' . gT("Decrease") . self::_addsgqacode(" (D)") . '</th>
                 </tr>
             </thead>
             <tbody>
         ';
                         $j = 0;
                         $rowclass = 'array1';
                         $mearesult = Question::model()->getAllRecords(" parent_qid='{$deqrow['qid']}'  AND language='{$sLanguageCode}' ", array('question_order'));
                         foreach ($mearesult->readAll() as $mearow) {
                             $question['ANSWER'] .= "\t\t<tr class=\"{$rowclass}\">\n";
                             $question['ANSWER'] .= "\t\t\t<th class=\"answertext\">{$mearow['question']}" . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . ")") . "</th>\n";
                             $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio', gT("Increase")) . "</td>\n";
                             $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio', gT("Same")) . "</td>\n";
                             $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio', gT("Decrease")) . "</td>\n";
                             $question['ANSWER'] .= "\t\t</tr>\n";
                             $j++;
                             $rowclass = alternation($rowclass, 'row');
                         }
                         $question['ANSWER'] .= "\t</tbody>\n</table>\n";
                         break;
                         // ==================================================================
                     // ==================================================================
                     case ":":
                         //ARRAY (Multi Flexible) (Numbers)
                         $headstyle = "style='padding-left: 20px; padding-right: 7px'";
                         if (trim($qidattributes['multiflexible_max']) != '' && trim($qidattributes['multiflexible_min']) == '') {
                             $maxvalue = $qidattributes['multiflexible_max'];
                             $minvalue = 1;
                         }
                         if (trim($qidattributes['multiflexible_min']) != '' && trim($qidattributes['multiflexible_max']) == '') {
                             $minvalue = $qidattributes['multiflexible_min'];
                             $maxvalue = $qidattributes['multiflexible_min'] + 10;
                         }
                         if (trim($qidattributes['multiflexible_min']) == '' && trim($qidattributes['multiflexible_max']) == '') {
                             $minvalue = 1;
                             $maxvalue = 10;
                         }
                         if (trim($qidattributes['multiflexible_min']) != '' && trim($qidattributes['multiflexible_max']) != '') {
                             if ($qidattributes['multiflexible_min'] < $qidattributes['multiflexible_max']) {
                                 $minvalue = $qidattributes['multiflexible_min'];
                                 $maxvalue = $qidattributes['multiflexible_max'];
                             }
                         }
                         if (trim($qidattributes['multiflexible_step']) != '') {
                             $stepvalue = $qidattributes['multiflexible_step'];
                         } else {
                             $stepvalue = 1;
                         }
                         if ($qidattributes['multiflexible_checkbox'] != 0) {
                             $checkboxlayout = true;
                         } else {
                             $checkboxlayout = false;
                         }
                         $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $sLanguageCode, $surveyid);
                         $question['ANSWER'] .= "\n<table>\n\t<thead>\n\t\t<tr>\n\t\t\t<td>&nbsp;</td>\n";
                         $fresult = Question::model()->getAllRecords(" parent_qid='{$deqrow['qid']}' and scale_id=1 AND language='{$sLanguageCode}' ", array('question_order'));
                         $fresult = $fresult->readAll();
                         $fcount = count($fresult);
                         $fwidth = "120";
                         $i = 0;
                         //array to temporary store X axis question codes
                         $xaxisarray = array();
                         foreach ($fresult as $frow) {
                             $question['ANSWER'] .= "\t\t\t<th>{$frow['question']}</th>\n";
                             $i++;
                             //add current question code
                             $xaxisarray[$i] = $frow['title'];
                         }
                         $question['ANSWER'] .= "\t\t</tr>\n\t</thead>\n\n\t<tbody>\n";
                         $a = 1;
                         //Counter for pdfoutput
                         $rowclass = 'array1';
                         $mearesult = Question::model()->getAllRecords(" parent_qid='{$deqrow['qid']}' and scale_id=0 AND language='{$sLanguageCode}' ", array('question_order'));
                         $result = $mearesult->readAll();
                         foreach ($result as $frow) {
                             $question['ANSWER'] .= "\t<tr class=\"{$rowclass}\">\n";
                             $rowclass = alternation($rowclass, 'row');
                             $answertext = $frow['question'];
                             if (strpos($answertext, '|')) {
                                 $answertext = substr($answertext, 0, strpos($answertext, '|'));
                             }
                             $question['ANSWER'] .= "\t\t\t\t\t<th class=\"answertext\">{$answertext}</th>\n";
                             //$printablesurveyoutput .="\t\t\t\t\t<td>";
                             for ($i = 1; $i <= $fcount; $i++) {
                                 $question['ANSWER'] .= "\t\t\t<td>\n";
                                 if ($checkboxlayout === false) {
                                     $question['ANSWER'] .= "\t\t\t\t" . self::_input_type_image('text', '', 4) . self::_addsgqacode(" (" . $fieldname . $frow['title'] . "_" . $xaxisarray[$i] . ") ") . "\n";
                                 } else {
                                     $question['ANSWER'] .= "\t\t\t\t" . self::_input_type_image('checkbox') . self::_addsgqacode(" (" . $fieldname . $frow['title'] . "_" . $xaxisarray[$i] . ") ") . "\n";
                                 }
                                 $question['ANSWER'] .= "\t\t\t</td>\n";
                             }
                             $answertext = $frow['question'];
                             if (strpos($answertext, '|')) {
                                 $answertext = substr($answertext, strpos($answertext, '|') + 1);
                                 $question['ANSWER'] .= "\t\t\t<th class=\"answertextright\">{$answertext}</th>\n";
                             }
                             $question['ANSWER'] .= "\t\t</tr>\n";
                             $a++;
                         }
                         $question['ANSWER'] .= "\t</tbody>\n</table>\n";
                         break;
                         // ==================================================================
                     // ==================================================================
                     case ";":
                         //ARRAY (Multi Flexible) (text)
                         $headstyle = "style='padding-left: 20px; padding-right: 7px'";
                         $mearesult = Question::model()->getAllRecords(" parent_qid='{$deqrow['qid']}' AND scale_id=0 AND language='{$sLanguageCode}' ", array('question_order'));
                         $mearesult = $mearesult->readAll();
                         $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $sLanguageCode, $surveyid);
                         $question['ANSWER'] .= "\n<table>\n\t<thead>\n\t\t<tr>\n\t\t\t<td>&nbsp;</td>\n";
                         $fresult = Question::model()->getAllRecords(" parent_qid='{$deqrow['qid']}'  AND scale_id=1 AND language='{$sLanguageCode}' ", array('question_order'));
                         $fresult = $fresult->readAll();
                         $fcount = count($fresult);
                         $fwidth = "120";
                         $i = 0;
                         //array to temporary store X axis question codes
                         $xaxisarray = array();
                         foreach ($fresult as $frow) {
                             $question['ANSWER'] .= "\t\t\t<th>{$frow['question']}</th>\n";
                             $i++;
                             //add current question code
                             $xaxisarray[$i] = $frow['title'];
                         }
                         $question['ANSWER'] .= "\t\t</tr>\n\t</thead>\n\n<tbody>\n";
                         $a = 1;
                         $rowclass = 'array1';
                         foreach ($mearesult as $mearow) {
                             $question['ANSWER'] .= "\t\t<tr class=\"{$rowclass}\">\n";
                             $rowclass = alternation($rowclass, 'row');
                             $answertext = $mearow['question'];
                             if (strpos($answertext, '|')) {
                                 $answertext = substr($answertext, 0, strpos($answertext, '|'));
                             }
                             $question['ANSWER'] .= "\t\t\t<th class=\"answertext\">{$answertext}</th>\n";
                             for ($i = 1; $i <= $fcount; $i++) {
                                 $question['ANSWER'] .= "\t\t\t<td>\n";
                                 $question['ANSWER'] .= "\t\t\t\t" . self::_input_type_image('text', '', 23) . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . "_" . $xaxisarray[$i] . ") ") . "\n";
                                 $question['ANSWER'] .= "\t\t\t</td>\n";
                             }
                             $answertext = $mearow['question'];
                             if (strpos($answertext, '|')) {
                                 $answertext = substr($answertext, strpos($answertext, '|') + 1);
                                 $question['ANSWER'] .= "\t\t\t\t<th class=\"answertextright\">{$answertext}</th>\n";
                             }
                             $question['ANSWER'] .= "\t\t</tr>\n";
                             $a++;
                         }
                         $question['ANSWER'] .= "\t</tbody>\n</table>\n";
                         break;
                         // ==================================================================
                     // ==================================================================
                     case "F":
                         //ARRAY (Flexible Labels)
                         $question['QUESTION_TYPE_HELP'] .= gT("Please choose the appropriate response for each item:");
                         $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $sLanguageCode, $surveyid);
                         $fresult = Answer::model()->getAllRecords(" scale_id=0 AND qid='{$deqrow['qid']}'  AND language='{$sLanguageCode}'", array('sortorder', 'code'));
                         $fresult = $fresult->readAll();
                         $fcount = count($fresult);
                         $fwidth = "120";
                         $i = 1;
                         $column_headings = array();
                         foreach ($fresult as $frow) {
                             $column_headings[] = $frow['answer'] . self::_addsgqacode(" (" . $frow['code'] . ")");
                         }
                         if (trim($qidattributes['answer_width']) != '') {
                             $iAnswerWidth = 100 - $qidattributes['answer_width'];
                         } else {
                             $iAnswerWidth = 80;
                         }
                         if (count($column_headings) > 0) {
                             $col_width = round($iAnswerWidth / count($column_headings));
                         } else {
                             $heading = '';
                         }
                         $question['ANSWER'] .= "\n<table>\n\t<thead>\n\t\t<tr>\n";
                         $question['ANSWER'] .= "\t\t\t<td>&nbsp;</td>\n";
                         foreach ($column_headings as $heading) {
                             $question['ANSWER'] .= "\t\t\t<th style=\"width:{$col_width}%;\">{$heading}</th>\n";
                         }
                         $i++;
                         $question['ANSWER'] .= "\t\t</tr>\n\t</thead>\n\n\t<tbody>\n";
                         $counter = 1;
                         $rowclass = 'array1';
                         $mearesult = Question::model()->getAllRecords(" parent_qid='{$deqrow['qid']}'  AND language='{$sLanguageCode}' ", array('question_order'));
                         foreach ($mearesult->readAll() as $mearow) {
                             $question['ANSWER'] .= "\t\t<tr class=\"{$rowclass}\">\n";
                             $rowclass = alternation($rowclass, 'row');
                             if (trim($answertext) == '') {
                                 $answertext = '&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";
                             for ($i = 1; $i <= $fcount; $i++) {
                                 $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio') . "</td>\n";
                             }
                             $counter++;
                             $answertext = $mearow['question'];
                             //semantic differential question type?
                             if (strpos($mearow['question'], '|')) {
                                 $answertext2 = substr($mearow['question'], strpos($mearow['question'], '|') + 1);
                                 $question['ANSWER'] .= "\t\t\t<th class=\"answertextright\">{$answertext2}</th>\n";
                             }
                             $question['ANSWER'] .= "\t\t</tr>\n";
                         }
                         $question['ANSWER'] .= "\t</tbody>\n</table>\n";
                         break;
                         // ==================================================================
                     // ==================================================================
                     case "1":
                         //ARRAY (Flexible Labels) multi scale
                         $leftheader = $qidattributes['dualscale_headerA'][$sLanguageCode];
                         $rightheader = $qidattributes['dualscale_headerB'][$sLanguageCode];
                         $headstyle = 'style="padding-left: 20px; padding-right: 7px"';
                         $question['QUESTION_TYPE_HELP'] .= gT("Please choose the appropriate response for each item:");
                         $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $sLanguageCode, $surveyid);
                         $question['ANSWER'] .= "\n<table>\n\t<thead>\n";
                         $condition = "qid= '{$deqrow['qid']}'  AND language= '{$sLanguageCode}' AND scale_id=0";
                         $fresult = Answer::model()->getAllRecords($condition, array('sortorder', 'code'));
                         $fresult = $fresult->readAll();
                         $fcount = count($fresult);
                         $fwidth = "120";
                         $l1 = 0;
                         $printablesurveyoutput2 = "\t\t\t<td>&nbsp;</td>\n";
                         $myheader2 = '';
                         foreach ($fresult as $frow) {
                             $printablesurveyoutput2 .= "\t\t\t<th>{$frow['answer']}" . self::_addsgqacode(" (" . $frow['code'] . ")") . "</th>\n";
                             $myheader2 .= "<td></td>";
                             $l1++;
                         }
                         // second scale
                         $printablesurveyoutput2 .= "\t\t\t<td>&nbsp;</td>\n";
                         //$fquery1 = "SELECT * FROM {{answers}} WHERE qid='{$deqrow['qid']}'  AND language='{$sLanguageCode}' AND scale_id=1 ORDER BY sortorder, code";
                         // $fresult1 = Yii::app()->db->createCommand($fquery1)->query();
                         $fresult1 = Answer::model()->getAllRecords(" qid='{$deqrow['qid']}'  AND language='{$sLanguageCode}' AND scale_id=1 ", array('sortorder', 'code'));
                         $fresult1 = $fresult1->readAll();
                         $fcount1 = count($fresult1);
                         $fwidth = "120";
                         $l2 = 0;
                         //array to temporary store second scale question codes
                         $scale2array = array();
                         foreach ($fresult1 as $frow1) {
                             $printablesurveyoutput2 .= "\t\t\t<th>{$frow1['answer']}" . self::_addsgqacode(" (" . $frow1['code'] . ")") . "</th>\n";
                             //add current question code
                             $scale2array[$l2] = $frow1['code'];
                             $l2++;
                         }
                         // build header if needed
                         if ($leftheader != '' || $rightheader != '') {
                             $myheader = "\t\t\t<td>&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;
                         $mearesult = Question::model()->getAllRecords(" parent_qid={$deqrow['qid']}  AND language='{$sLanguageCode}' ", array('question_order'));
                         foreach ($mearesult->readAll() as $mearow) {
                             $question['ANSWER'] .= "\t\t<tr class=\"{$rowclass}\">\n";
                             $rowclass = alternation($rowclass, 'row');
                             $answertext = $mearow['question'] . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . "#0) / (" . $fieldname . $mearow['title'] . "#1)");
                             if (strpos($answertext, '|')) {
                                 $answertext = substr($answertext, 0, strpos($answertext, '|'));
                             }
                             $question['ANSWER'] .= "\t\t\t<th class=\"answertext\">{$answertext}</th>\n";
                             for ($i = 1; $i <= $fcount; $i++) {
                                 $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio') . "</td>\n";
                             }
                             $question['ANSWER'] .= "\t\t\t<td>&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";
                         break;
                         // ==================================================================
                     // ==================================================================
                     case "H":
                         //ARRAY (Flexible Labels) by Column
                         //$headstyle="style='border-left-style: solid; border-left-width: 1px; border-left-color: #AAAAAA'";
                         $headstyle = "style='padding-left: 20px; padding-right: 7px'";
                         $condition = "parent_qid= '{$deqrow['qid']}'  AND language= '{$sLanguageCode}'";
                         $fresult = Question::model()->getAllRecords($condition, array('question_order', 'title'));
                         $fresult = $fresult->readAll();
                         $question['QUESTION_TYPE_HELP'] .= gT("Please choose the appropriate response for each item:");
                         $question['ANSWER'] .= "\n<table>\n\t<thead>\n\t\t<tr>\n\t\t\t<td>&nbsp;</td>\n";
                         $fcount = count($fresult);
                         $fwidth = "120";
                         $i = 0;
                         foreach ($fresult as $frow) {
                             $question['ANSWER'] .= "\t\t\t<th>{$frow['question']}" . self::_addsgqacode(" (" . $fieldname . $frow['title'] . ")") . "</th>\n";
                             $i++;
                         }
                         $question['ANSWER'] .= "\t\t</tr>\n\t</thead>\n\n\t<tbody>\n";
                         $a = 1;
                         $rowclass = 'array1';
                         $mearesult = Answer::model()->getAllRecords(" qid='{$deqrow['qid']}' AND scale_id=0 AND language='{$sLanguageCode}' ", array('sortorder', 'code'));
                         foreach ($mearesult->readAll() as $mearow) {
                             //$_POST['type']=$type;
                             $question['ANSWER'] .= "\t\t<tr class=\"{$rowclass}\">\n";
                             $rowclass = alternation($rowclass, 'row');
                             $question['ANSWER'] .= "\t\t\t<th class=\"answertext\">{$mearow['answer']}" . self::_addsgqacode(" (" . $mearow['code'] . ")") . "</th>\n";
                             //$printablesurveyoutput .="\t\t\t\t\t<td>";
                             for ($i = 1; $i <= $fcount; $i++) {
                                 $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio') . "</td>\n";
                             }
                             //$printablesurveyoutput .="\t\t\t\t\t</tr></table></td>\n";
                             $question['ANSWER'] .= "\t\t</tr>\n";
                             $a++;
                         }
                         $question['ANSWER'] .= "\t</tbody>\n</table>\n";
                         break;
                     case "|":
                         // File Upload
                         $question['QUESTION_TYPE_HELP'] .= "Kindly attach the aforementioned documents along with the survey";
                         break;
                         // === END SWITCH ===================================================
                 }
                 $question['QUESTION_TYPE_HELP'] = self::_star_replace($question['QUESTION_TYPE_HELP']);
                 $group['QUESTIONS'] .= self::_populate_template('question', $question);
             }
             if ($bGroupHasVisibleQuestions) {
                 $survey_output['GROUPS'] .= self::_populate_template('group', $group);
             }
         }
         $survey_output['THEREAREXQUESTIONS'] = str_replace('{NUMBEROFQUESTIONS}', $total_questions, gT('There are {NUMBEROFQUESTIONS} questions in this survey'));
         // START recursive tag stripping.
         // PHP 5.1.0 introduced the count parameter for preg_replace() and thus allows this procedure to run with only one regular expression.
         // Previous version of PHP needs two regular expressions to do the same thing and thus will run a bit slower.
         $server_is_newer = version_compare(PHP_VERSION, '5.1.0', '>');
         $rounds = 0;
         while ($rounds < 1) {
             $replace_count = 0;
             if ($server_is_newer) {
                 $survey_output['GROUPS'] = preg_replace(array('/<td>(?:&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.
         echo self::_populate_template('survey', $survey_output);
     }
     // End print
 }
Пример #9
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 = Question::model()->findAllByAttributes(array('sid' => $iSurveyID));
         foreach ($oResult as $aRow) {
             Answer::model()->deleteAllByAttributes(array('qid' => $aRow['qid']));
             Condition::model()->deleteAllByAttributes(array('qid' => $aRow['qid']));
             QuestionAttribute::model()->deleteAllByAttributes(array('qid' => $aRow['qid']));
             DefaultValue::model()->deleteAllByAttributes(array('qid' => $aRow['qid']));
         }
         Question::model()->deleteAllByAttributes(array('sid' => $iSurveyID));
         Assessment::model()->deleteAllByAttributes(array('sid' => $iSurveyID));
         QuestionGroup::model()->deleteAllByAttributes(array('sid' => $iSurveyID));
         SurveyLanguageSetting::model()->deleteAllByAttributes(array('surveyls_survey_id' => $iSurveyID));
         Permission::model()->deleteAllByAttributes(array('entity_id' => $iSurveyID, 'entity' => 'survey'));
         SavedControl::model()->deleteAllByAttributes(array('sid' => $iSurveyID));
         SurveyURLParameter::model()->deleteAllByAttributes(array('sid' => $iSurveyID));
         //Remove any survey_links to the CPDB
         SurveyLink::model()->deleteLinksBySurvey($iSurveyID);
         Quota::model()->deleteQuota(array('sid' => $iSurveyID), true);
     }
 }
Пример #10
0
 public function ajaxReloadPositionWidget($gid)
 {
     $oQuestionGroup = QuestionGroup::model()->find('gid=:gid', array(':gid' => $gid));
     if (is_a($oQuestionGroup, 'QuestionGroup') && Permission::model()->hasSurveyPermission($oQuestionGroup->sid, 'surveycontent', 'read')) {
         return App()->getController()->widget('ext.admin.survey.question.PositionWidget.PositionWidget', array('display' => 'form_group', 'oQuestionGroup' => $oQuestionGroup));
     }
 }
Пример #11
0
 private function _reorderGroup($iSurveyID)
 {
     $AOrgData = array();
     parse_str($_POST['orgdata'], $AOrgData);
     $grouporder = 0;
     foreach ($AOrgData['list'] as $ID => $parent) {
         if ($parent == 'root' && $ID[0] == 'g') {
             QuestionGroup::model()->updateAll(array('group_order' => $grouporder), 'gid=:gid', array(':gid' => (int) substr($ID, 1)));
             $grouporder++;
         } elseif ($ID[0] == 'q') {
             $qid = (int) substr($ID, 1);
             $gid = (int) substr($parent, 1);
             if (!isset($aQuestionOrder[$gid])) {
                 $aQuestionOrder[$gid] = 0;
             }
             $sBaseLanguage = Survey::model()->findByPk($iSurveyID)->language;
             $oQuestion = Question::model()->findByPk(array("qid" => $qid, 'language' => $sBaseLanguage));
             $oldGid = $oQuestion['gid'];
             if ($oldGid != $gid) {
                 fixMovedQuestionConditions($qid, $oldGid, $gid, $iSurveyID);
             }
             Question::model()->updateAll(array('question_order' => $aQuestionOrder[$gid], 'gid' => $gid), 'qid=:qid', array(':qid' => $qid));
             Question::model()->updateAll(array('gid' => $gid), 'parent_qid=:parent_qid', array(':parent_qid' => $qid));
             $aQuestionOrder[$gid]++;
         }
     }
     LimeExpressionManager::SetDirtyFlag();
     // so refreshes syntax highlighting
     Yii::app()->session['flashmessage'] = gT("The new question group/question order was successfully saved.");
     $this->getController()->redirect(array('admin/survey/sa/view/surveyid/' . $iSurveyID));
 }
Пример #12
0
 public function getbuttons()
 {
     $sSummaryUrl = App()->createUrl("/admin/survey/sa/view/surveyid/" . $this->sid);
     $sEditUrl = App()->createUrl("/admin/survey/sa/editlocalsettings/surveyid/" . $this->sid);
     $sDeleteUrl = App()->createUrl("/admin/survey/sa/delete/surveyid/" . $this->sid);
     $sStatUrl = App()->createUrl("/admin/statistics/sa/simpleStatistics/surveyid/" . $this->sid);
     $sAddGroup = App()->createUrl("/admin/questiongroups/sa/add/surveyid/" . $this->sid);
     $sAddquestion = App()->createUrl("/admin/questions/sa/newquestion/surveyid/" . $this->sid);
     $button = '<a class="btn btn-default" href="' . $sSummaryUrl . '" role="button" data-toggle="tooltip" title="' . gT('Survey summary') . '"><span class="glyphicon glyphicon-list-alt" ></span></a>';
     $button .= '<a class="btn btn-default" href="' . $sEditUrl . '" role="button" data-toggle="tooltip" title="' . gT('General settings & texts') . '"><span class="glyphicon glyphicon-pencil" ></span></a>';
     $button .= '<a class="btn btn-default" href="' . $sDeleteUrl . '" role="button" data-toggle="tooltip" title="' . gT('Delete') . '"><span class="text-danger glyphicon glyphicon-trash" ></span></a>';
     if (Permission::model()->hasSurveyPermission($this->sid, 'statistics', 'read') && $this->active == 'Y') {
         $button .= '<a class="btn btn-default" href="' . $sStatUrl . '" role="button" data-toggle="tooltip" title="' . gT('Statistics') . '"><span class="glyphicon glyphicon-stats text-success" ></span></a>';
     }
     if ($this->active != 'Y') {
         $groupCount = QuestionGroup::model()->countByAttributes(array('sid' => $this->sid, 'language' => $this->language));
         //Checked
         if ($groupCount > 0) {
             $button .= '<a class="btn btn-default" href="' . $sAddquestion . '" role="button" data-toggle="tooltip" title="' . gT('Add new question') . '"><span class="icon-add text-success" ></span></a>';
         } else {
             $button .= '<a class="btn btn-default" href="' . $sAddGroup . '" role="button" data-toggle="tooltip" title="' . gT('Add new group') . '"><span class="icon-add text-success" ></span></a>';
         }
     }
     $previewUrl = Yii::app()->createUrl("survey/index/sid/");
     $previewUrl .= '/' . $this->sid;
     //$button = '<a class="btn btn-default open-preview" aria-data-url="'.$previewUrl.'" aria-data-language="'.$this->language.'" href="# role="button" ><span class="glyphicon glyphicon-eye-open"  ></span></a> ';
     return $button;
 }
Пример #13
0
/**
 * Randomization group for groups
 * @param int $surveyid
 * @param array $fieldmap
 * @param boolean $preview
 * @return array ($fieldmap, $randomized)
 */
function randomizationGroup($surveyid, array $fieldmap, $preview)
{
    // Randomization groups for groups
    $aRandomGroups = array();
    $aGIDCompleteMap = array();
    // First find all groups and their groups IDS
    $criteria = new CDbCriteria();
    $criteria->addColumnCondition(array('sid' => $surveyid, 'language' => $_SESSION['survey_' . $surveyid]['s_lang']));
    $criteria->addCondition("randomization_group != ''");
    $oData = QuestionGroup::model()->findAll($criteria);
    foreach ($oData as $aGroup) {
        $aRandomGroups[$aGroup['randomization_group']][] = $aGroup['gid'];
    }
    // Shuffle each group and create a map for old GID => new GID
    foreach ($aRandomGroups as $sGroupName => $aGIDs) {
        $aShuffledIDs = $aGIDs;
        shuffle($aShuffledIDs);
        $aGIDCompleteMap = $aGIDCompleteMap + array_combine($aGIDs, $aShuffledIDs);
    }
    $_SESSION['survey_' . $surveyid]['groupReMap'] = $aGIDCompleteMap;
    $randomized = false;
    // So we can trigger reorder once for group and question randomization
    // Now adjust the grouplist
    if (count($aRandomGroups) > 0 && !$preview) {
        $randomized = true;
        // So we can trigger reorder once for group and question randomization
        // Now adjust the grouplist
        Yii::import('application.helpers.frontend_helper', true);
        // make sure frontend helper is loaded
        UpdateGroupList($surveyid, $_SESSION['survey_' . $surveyid]['s_lang']);
        // ... and the fieldmap
        // First create a fieldmap with GID as key
        foreach ($fieldmap as $aField) {
            if (isset($aField['gid'])) {
                $GroupFieldMap[$aField['gid']][] = $aField;
            } else {
                $GroupFieldMap['other'][] = $aField;
            }
        }
        // swap it
        foreach ($GroupFieldMap as $iOldGid => $fields) {
            $iNewGid = $iOldGid;
            if (isset($aGIDCompleteMap[$iOldGid])) {
                $iNewGid = $aGIDCompleteMap[$iOldGid];
            }
            $newGroupFieldMap[$iNewGid] = $GroupFieldMap[$iNewGid];
        }
        $GroupFieldMap = $newGroupFieldMap;
        // and convert it back to a fieldmap
        unset($fieldmap);
        foreach ($GroupFieldMap as $aGroupFields) {
            foreach ($aGroupFields as $aField) {
                if (isset($aField['fieldname'])) {
                    $fieldmap[$aField['fieldname']] = $aField;
                    // isset() because of the shuffled flag above
                }
            }
        }
    }
    return array($fieldmap, $randomized);
}
 /**
  * Mise  àjour d un formulaire /mode edition
  * @param $id the ID of the model to be displayed
  */
 public function actionUpdate($id)
 {
     $model = Questionnaire::model()->findByPk(new MongoID($id));
     $questionBlocForm = new QuestionBlocForm();
     $questionForm = new QuestionForm();
     $questionGroup = new QuestionGroup();
     // collect user input data
     if (isset($_POST['QuestionForm'])) {
         $questionForm->attributes = $_POST['QuestionForm'];
         if ($questionForm->validatewithId($model)) {
             if ($questionForm->help == "") {
                 $questionForm->help = null;
             }
             //traitement ajout de question
             if ($questionForm->validate()) {
                 $model = $model->saveQuestionnaireNewQuestion($questionForm);
             } else {
                 Yii::app()->user->setFlash('error', Yii::t('common', 'questionNotAdded'));
             }
         } else {
             Yii::app()->user->setFlash('error', Yii::t('common', 'questionNotAdded'));
         }
     }
     if (isset($_POST['QuestionGroup'])) {
         $questionGroup->attributes = $_POST['QuestionGroup'];
         if ($questionGroup->validatewithId($model)) {
             //copie du titre sur l option fr
             $questionGroup->title_fr = $questionGroup->title;
             if ($questionGroup->validate()) {
                 $model = $model->saveQuestionnaireNewGroup($questionGroup);
             }
         } else {
             Yii::app()->user->setFlash('error', Yii::t('common', 'tabNotAdded'));
         }
     }
     if (isset($_POST['QuestionBlocForm'])) {
         $questionBlocForm->attributes = $_POST['QuestionBlocForm'];
         if ($questionBlocForm->validatewithId($model)) {
             $questionBloc = QuestionBloc::model()->findByPk(new MongoId($questionBlocForm->title));
             $questionBlocForm->title_fr = $questionBlocForm->title;
             $computedGroup = new QuestionGroup();
             $computedGroup->copy($questionBlocForm, $questionBloc);
             if ($computedGroup->validate()) {
                 $model = $model->saveQuestionnaireNewGroup($computedGroup);
             }
             if (isset($questionBloc->questions) && $questionBloc->questions != null && count($questionBloc->questions) > 0) {
                 foreach ($questionBloc->questions as $question => $value) {
                     $currentQuestion = Question::model()->findByPk(new MongoId($value));
                     $questionForm->copy($currentQuestion, $computedGroup);
                     $model->saveQuestionnaireNewQuestionBloc($questionForm);
                 }
             }
         } else {
             Yii::app()->user->setFlash('error', Yii::t('common', 'tabNotAdded'));
         }
     }
     if (isset($_POST['old_onglet'])) {
         foreach ($model->questions_group as $onglet) {
             if ($onglet->id == $_POST['old_onglet']) {
                 $onglet->title = $_POST['new_onglet'];
                 $onglet->title_fr = $_POST['new_onglet'];
                 if ($model->save()) {
                     Yii::app()->user->setFlash('success', Yii::t('common', 'tabUpdated'));
                 } else {
                     Yii::app()->user->setFlash('error', Yii::t('common', 'tabNotUpdated'));
                 }
             }
         }
     }
     if (isset($_POST['old_question'])) {
         foreach ($model->questions_group as $onglet) {
             foreach ($onglet->questions as $question) {
                 if ($question->id == $_POST['old_question']) {
                     $question->label = $_POST['new_question'];
                     $question->label_fr = $_POST['new_question'];
                     if ($model->save()) {
                         Yii::app()->user->setFlash('success', Yii::t('common', 'questionUpdated'));
                     } else {
                         Yii::app()->user->setFlash('error', Yii::t('common', 'questionNotUpdated'));
                     }
                 }
             }
         }
     }
     //  set du model sur la questionForm pour generer l arborescende de position de question
     $questionForm->questionnaire = $model;
     $questionGroup->questionnaire = $model;
     $this->render('update', array('model' => $model, 'questionForm' => $questionForm, 'questionGroup' => $questionGroup, 'questionBloc' => $questionBlocForm));
 }
Пример #15
0
 protected function menuGroup($groupId)
 {
     $group = QuestionGroup::model()->findByAttributes(array('gid' => $groupId));
     $menu['title'] = "Group {$group->group_name} (id: {$groupId})";
     $menu['role'] = 'group';
     $menu['imageUrl'] = App()->getConfig('adminimageurl');
     $menu['items']['left'][] = array('alt' => gT('Preview this group'), 'type' => 'link', 'image' => 'preview.png', 'target' => '_blank', 'href' => array('groups/preview', 'id' => $groupId));
     $menu['items']['left'][] = 'separator';
     $menu['items']['left'][] = array('alt' => gT('Edit current question group'), 'type' => 'link', 'image' => 'edit.png', 'href' => array('admin/questiongroups', 'sa' => 'edit', 'surveyid' => $group->sid, 'gid' => $groupId));
     $menu['items']['left'][] = 'separator';
     $menu['items']['left'][] = 'separator';
     $menu['items']['right'][] = array('type' => 'select', 'title' => gT('Questions'), 'name' => 'id', 'route' => 'questions/update', 'values' => Question::model()->findListByAttributes(array('sid' => $group->sid, 'gid' => $groupId), 'code', 'qid'), 'value' => $this->questionId);
     $menu['items']['right'][] = array('alt' => gT('Add new question to group'), 'type' => 'link', 'image' => 'add.png', 'href' => array('questions/create', 'gid' => $groupId));
     return $menu;
 }
Пример #16
0
 /**
  * This function checks the LimeSurvey database for logical consistency and returns an according array
  * containing all issues in the particular tables.
  * @returns Array with all found issues.
  */
 protected function _checkintegrity()
 {
     $clang = Yii::app()->lang;
     /*** Plainly delete survey permissions if the survey or user does not exist ***/
     $users = User::model()->findAll();
     $uids = array();
     foreach ($users as $user) {
         $uids[] = $user['uid'];
     }
     $oCriteria = new CDbCriteria();
     $oCriteria->addNotInCondition('uid', $uids, 'OR');
     $surveys = Survey::model()->findAll();
     $sids = array();
     foreach ($surveys as $survey) {
         $sids[] = $survey['sid'];
     }
     $oCriteria->addNotInCondition('entity_id', $sids, 'OR');
     $oCriteria->addCondition("entity='survey'");
     Permission::model()->deleteAll($oCriteria);
     // Deactivate surveys that have a missing response table
     foreach ($surveys as $survey) {
         if ($survey['active'] == 'Y' && !tableExists("{{survey_{$survey['sid']}}}")) {
             Survey::model()->updateByPk($survey['sid'], array('active' => 'N'));
         }
     }
     unset($surveys);
     // Fix subquestions
     fixSubquestions();
     /*** Check for active survey tables with missing survey entry and rename them ***/
     $sDBPrefix = Yii::app()->db->tablePrefix;
     $sQuery = dbSelectTablesLike('{{survey}}\\_%');
     $aResult = dbQueryOrFalse($sQuery);
     foreach ($aResult->readAll() as $aRow) {
         $sTableName = substr(reset($aRow), strlen($sDBPrefix));
         if ($sTableName == 'survey_links' || $sTableName == 'survey_url_parameters') {
             continue;
         }
         $aTableName = explode('_', $sTableName);
         if (isset($aTableName[1]) && ctype_digit($aTableName[1])) {
             $iSurveyID = $aTableName[1];
             if (!in_array($iSurveyID, $sids)) {
                 $sDate = date('YmdHis') . rand(1, 1000);
                 $sOldTable = "survey_{$iSurveyID}";
                 $sNewTable = "old_survey_{$iSurveyID}_{$sDate}";
                 try {
                     $deactivateresult = Yii::app()->db->createCommand()->renameTable("{{{$sOldTable}}}", "{{{$sNewTable}}}");
                 } catch (CDbException $e) {
                     die('Couldn\'t make backup of the survey table. Please try again. The database reported the following error:<br />' . htmlspecialchars($e) . '<br />');
                 }
             }
         }
     }
     /*** Check for active token tables with missing survey entry ***/
     $aResult = dbQueryOrFalse(dbSelectTablesLike('{{tokens}}\\_%'));
     foreach ($aResult->readAll() as $aRow) {
         $sTableName = substr(reset($aRow), strlen($sDBPrefix));
         $iSurveyID = substr($sTableName, strpos($sTableName, '_') + 1);
         if (!in_array($iSurveyID, $sids)) {
             $sDate = date('YmdHis') . rand(1, 1000);
             $sOldTable = "tokens_{$iSurveyID}";
             $sNewTable = "old_tokens_{$iSurveyID}_{$sDate}";
             try {
                 $deactivateresult = Yii::app()->db->createCommand()->renameTable("{{{$sOldTable}}}", "{{{$sNewTable}}}");
             } catch (CDbException $e) {
                 die('Couldn\'t make backup of the survey table. Please try again. The database reported the following error:<br />' . htmlspecialchars($e) . '<br />');
             }
         }
     }
     /**********************************************************************/
     /*     Check conditions                                               */
     /**********************************************************************/
     $okQuestion = array();
     $sQuery = 'SELECT cqid,cid,cfieldname FROM {{conditions}}';
     $aConditions = Yii::app()->db->createCommand($sQuery)->queryAll();
     foreach ($aConditions as $condition) {
         if ($condition['cqid'] != 0) {
             // skip case with cqid=0 for codnitions on {TOKEN:EMAIL} for instance
             if (!array_key_exists($condition['cqid'], $okQuestion)) {
                 $iRowCount = Question::model()->countByAttributes(array('qid' => $condition['cqid']));
                 if (Question::model()->hasErrors()) {
                     safeDie(Question::model()->getError());
                 }
                 if (!$iRowCount) {
                     $aDelete['conditions'][] = array('cid' => $condition['cid'], 'reason' => $clang->gT('No matching CQID'));
                 } else {
                     $okQuestion[$condition['cqid']] = $condition['cqid'];
                 }
             }
         }
         if ($condition['cfieldname']) {
             if (preg_match('/^\\+{0,1}[0-9]+X[0-9]+X*$/', $condition['cfieldname'])) {
                 // only if cfieldname isn't Tag such as {TOKEN:EMAIL} or any other token
                 list($surveyid, $gid, $rest) = explode('X', $condition['cfieldname']);
                 $iRowCount = count(QuestionGroup::model()->findAllByAttributes(array('gid' => $gid)));
                 if (QuestionGroup::model()->hasErrors()) {
                     safeDie(QuestionGroup::model()->getError());
                 }
                 if (!$iRowCount) {
                     $aDelete['conditions'][] = array('cid' => $condition['cid'], 'reason' => $clang->gT('No matching CFIELDNAME group!') . " ({$gid}) ({$condition['cfieldname']})");
                 }
             }
         } elseif (!$condition['cfieldname']) {
             $aDelete['conditions'][] = array('cid' => $condition['cid'], 'reason' => $clang->gT('No CFIELDNAME field set!') . " ({$condition['cfieldname']})");
         }
     }
     unset($okQuestion);
     unset($aConditions);
     /**********************************************************************/
     /*     Check question attributes                                      */
     /**********************************************************************/
     $question_attributes = QuestionAttribute::model()->findAllBySql('select qid from {{question_attributes}} where qid not in (select qid from {{questions}})');
     if (QuestionAttribute::model()->hasErrors()) {
         safeDie(QuestionAttribute::model()->getError());
     }
     foreach ($question_attributes as $question_attribute) {
         $aDelete['questionattributes'][] = array('qid' => $question_attribute['qid']);
     }
     // foreach
     /**********************************************************************/
     /*     Check default values                                           */
     /**********************************************************************/
     $oCriteria = new CDbCriteria();
     $oCriteria->join = 'LEFT JOIN {{questions}} q ON t.qid=q.qid';
     $oCriteria->condition = 'q.qid IS NULL';
     $aRecords = DefaultValue::model()->findAll($oCriteria);
     $aDelete['defaultvalues'] = count($aRecords);
     if (DefaultValue::model()->hasErrors()) {
         safeDie(DefaultValue::model()->getError());
     }
     /**********************************************************************/
     /*     Check quotas                                                   */
     /**********************************************************************/
     $surveys = Survey::model()->findAll();
     if (Survey::model()->hasErrors()) {
         safeDie(Survey::model()->getError());
     }
     $sids = array();
     foreach ($surveys as $survey) {
         $sids[] = $survey['sid'];
     }
     $oCriteria = new CDbCriteria();
     $oCriteria->addNotInCondition('sid', $sids);
     $aDelete['quotas'] = count(Quota::model()->findAll($oCriteria));
     if (Quota::model()->hasErrors()) {
         safeDie(Quota::model()->getError());
     }
     /**********************************************************************/
     /*     Check quota languagesettings                                   */
     /**********************************************************************/
     $quotas = Quota::model()->findAll();
     if (Quota::model()->hasErrors()) {
         safeDie(Quota::model()->getError());
     }
     $ids = array();
     foreach ($quotas as $quota) {
         $ids[] = $quota['id'];
     }
     $oCriteria = new CDbCriteria();
     $oCriteria->addNotInCondition('quotals_quota_id', $ids);
     $aDelete['quotals'] = count(QuotaLanguageSetting::model()->findAll($oCriteria));
     if (QuotaLanguageSetting::model()->hasErrors()) {
         safeDie(QuotaLanguageSetting::model()->getError());
     }
     /**********************************************************************/
     /*     Check quota members                                   */
     /**********************************************************************/
     $oCriteria = new CDbCriteria();
     $oCriteria->join = 'LEFT JOIN {{questions}} q ON t.qid=q.qid LEFT JOIN {{surveys}} s ON t.sid=s.sid';
     $oCriteria->condition = '(q.qid IS NULL) OR (s.sid IS NULL)';
     $aDelete['quotamembers'] = count(QuotaMember::model()->findAll($oCriteria));
     if (QuotaMember::model()->hasErrors()) {
         safeDie(QuotaMember::model()->getError());
     }
     /**********************************************************************/
     /*     Check assessments                                              */
     /**********************************************************************/
     $oCriteria = new CDbCriteria();
     $oCriteria->compare('scope', 'T');
     $assessments = Assessment::model()->findAll($oCriteria);
     if (Assessment::model()->hasErrors()) {
         safeDie(Assessment::model()->getError());
     }
     foreach ($assessments as $assessment) {
         $iAssessmentCount = count(Survey::model()->findAllByPk($assessment['sid']));
         if (Survey::model()->hasErrors()) {
             safeDie(Survey::model()->getError());
         }
         if (!$iAssessmentCount) {
             $aDelete['assessments'][] = array('id' => $assessment['id'], 'assessment' => $assessment['name'], 'reason' => $clang->gT('No matching survey'));
         }
     }
     $oCriteria = new CDbCriteria();
     $oCriteria->compare('scope', 'G');
     $assessments = Assessment::model()->findAll($oCriteria);
     if (Assessment::model()->hasErrors()) {
         safeDie(Assessment::model()->getError());
     }
     foreach ($assessments as $assessment) {
         $iAssessmentCount = count(QuestionGroup::model()->findAllByPk(array('gid' => $assessment['gid'], 'language' => $assessment['language'])));
         if (QuestionGroup::model()->hasErrors()) {
             safeDie(QuestionGroup::model()->getError());
         }
         if (!$iAssessmentCount) {
             $aDelete['assessments'][] = array('id' => $assessment['id'], 'assessment' => $assessment['name'], 'reason' => $clang->gT('No matching group'));
         }
     }
     unset($assessments);
     /**********************************************************************/
     /*     Check answers                                                  */
     /**********************************************************************/
     $oCriteria = new CDbCriteria();
     $oCriteria->join = 'LEFT JOIN {{questions}} q ON t.qid=q.qid';
     $oCriteria->condition = '(q.qid IS NULL)';
     $answers = Answer::model()->findAll($oCriteria);
     foreach ($answers as $answer) {
         $aDelete['answers'][] = array('qid' => $answer['qid'], 'code' => $answer['code'], 'reason' => $clang->gT('No matching question'));
     }
     /***************************************************************************/
     /*   Check survey languagesettings and restore them if they don't exist    */
     /***************************************************************************/
     $surveys = Survey::model()->findAll();
     foreach ($surveys as $survey) {
         $aLanguages = $survey->additionalLanguages;
         $aLanguages[] = $survey->language;
         foreach ($aLanguages as $langname) {
             if ($langname) {
                 $oLanguageSettings = SurveyLanguageSetting::model()->find('surveyls_survey_id=:surveyid AND surveyls_language=:langname', array(':surveyid' => $survey->sid, ':langname' => $langname));
                 if (!$oLanguageSettings) {
                     $oLanguageSettings = new SurveyLanguageSetting();
                     $languagedetails = getLanguageDetails($langname);
                     $insertdata = array('surveyls_survey_id' => $survey->sid, 'surveyls_language' => $langname, 'surveyls_title' => '', 'surveyls_dateformat' => $languagedetails['dateformat']);
                     foreach ($insertdata as $k => $v) {
                         $oLanguageSettings->{$k} = $v;
                     }
                     $usresult = $oLanguageSettings->save();
                 }
             }
         }
     }
     /**********************************************************************/
     /*     Check survey language settings                                 */
     /**********************************************************************/
     $surveys = Survey::model()->findAll();
     if (Survey::model()->hasErrors()) {
         safeDie(Survey::model()->getError());
     }
     $sids = array();
     foreach ($surveys as $survey) {
         $sids[] = $survey['sid'];
     }
     $oCriteria = new CDbCriteria();
     $oCriteria->addNotInCondition('surveyls_survey_id', $sids);
     $surveys_languagesettings = SurveyLanguageSetting::model()->findAll($oCriteria);
     if (SurveyLanguageSetting::model()->hasErrors()) {
         safeDie(SurveyLanguageSetting::model()->getError());
     }
     foreach ($surveys_languagesettings as $surveys_languagesetting) {
         $aDelete['surveylanguagesettings'][] = array('slid' => $surveys_languagesetting['surveyls_survey_id'], 'reason' => $clang->gT('The related survey is missing.'));
     }
     /**********************************************************************/
     /*     Check questions                                                */
     /**********************************************************************/
     $oCriteria = new CDbCriteria();
     $oCriteria->join = 'LEFT JOIN {{surveys}} s ON t.sid=s.sid LEFT JOIN {{groups}} g ON t.gid=g.gid';
     $oCriteria->condition = '(g.gid IS NULL) OR (s.sid IS NULL)';
     $questions = Question::model()->findAll($oCriteria);
     if (Question::model()->hasErrors()) {
         safeDie(Question::model()->getError());
     }
     foreach ($questions as $question) {
         $aDelete['questions'][] = array('qid' => $question['qid'], 'reason' => $clang->gT('No matching group') . " ({$question['gid']})");
     }
     /**********************************************************************/
     /*     Check groups                                                   */
     /**********************************************************************/
     $surveys = Survey::model()->findAll();
     if (Survey::model()->hasErrors()) {
         safeDie(Survey::model()->getError());
     }
     $sids = array();
     foreach ($surveys as $survey) {
         $sids[] = $survey['sid'];
     }
     $oCriteria = new CDbCriteria();
     $oCriteria->addNotInCondition('sid', $sids);
     $groups = QuestionGroup::model()->findAll($oCriteria);
     foreach ($groups as $group) {
         $aDelete['groups'][] = array('gid' => $group['gid'], 'reason' => $clang->gT('There is no matching survey.') . ' SID:' . $group['sid']);
     }
     /**********************************************************************/
     /*     Check old survey tables                                        */
     /**********************************************************************/
     //1: Get list of 'old_survey' tables and extract the survey id
     //2: Check if that survey id still exists
     //3: If it doesn't offer it for deletion
     $sQuery = dbSelectTablesLike('{{old_survey}}%');
     $aTables = Yii::app()->db->createCommand($sQuery)->queryColumn();
     $aOldSIDs = array();
     $aSIDs = array();
     foreach ($aTables as $sTable) {
         list($sOldText, $SurveyText, $iSurveyID, $sDate) = explode('_', substr($sTable, strlen($sDBPrefix)));
         $aOldSIDs[] = $iSurveyID;
         $aFullOldSIDs[$iSurveyID][] = $sTable;
     }
     $aOldSIDs = array_unique($aOldSIDs);
     //$sQuery = 'SELECT sid FROM {{surveys}} ORDER BY sid';
     //$oResult = dbExecuteAssoc($sQuery) or safeDie('Couldn\'t get unique survey ids');
     $surveys = Survey::model()->findAll();
     if (Survey::model()->hasErrors()) {
         safeDie(Survey::model()->getError());
     }
     $aSIDs = array();
     foreach ($surveys as $survey) {
         $aSIDs[] = $survey['sid'];
     }
     foreach ($aOldSIDs as $iOldSID) {
         if (!in_array($iOldSID, $aSIDs)) {
             foreach ($aFullOldSIDs[$iOldSID] as $sTableName) {
                 $aDelete['orphansurveytables'][] = $sTableName;
             }
         } else {
             foreach ($aFullOldSIDs[$iOldSID] as $sTableName) {
                 $aTableParts = explode('_', substr($sTableName, strlen($sDBPrefix)));
                 if (count($aTableParts) == 4) {
                     $sOldText = $aTableParts[0];
                     $SurveyText = $aTableParts[1];
                     $iSurveyID = $aTableParts[2];
                     $sDateTime = $aTableParts[3];
                     $sType = $clang->gT('responses');
                 } elseif (count($aTableParts) == 5) {
                     //This is a timings table (
                     $sOldText = $aTableParts[0];
                     $SurveyText = $aTableParts[1];
                     $iSurveyID = $aTableParts[2];
                     $sDateTime = $aTableParts[4];
                     $sType = $clang->gT('timings');
                 }
                 $iYear = substr($sDateTime, 0, 4);
                 $iMonth = substr($sDateTime, 4, 2);
                 $iDay = substr($sDateTime, 6, 2);
                 $iHour = substr($sDateTime, 8, 2);
                 $iMinute = substr($sDateTime, 10, 2);
                 $sDate = date('d M Y  H:i', mktime($iHour, $iMinute, 0, $iMonth, $iDay, $iYear));
                 $sQuery = 'SELECT count(*) as recordcount FROM ' . $sTableName;
                 $aFirstRow = Yii::app()->db->createCommand($sQuery)->queryRow();
                 if ($aFirstRow['recordcount'] == 0) {
                     // empty table - so add it to immediate deletion
                     $aDelete['orphansurveytables'][] = $sTableName;
                 } else {
                     $aOldSurveyTableAsk[] = array('table' => $sTableName, 'details' => sprintf($clang->gT('Survey ID %d saved at %s containing %d record(s) (%s)'), $iSurveyID, $sDate, $aFirstRow['recordcount'], $sType));
                 }
             }
         }
     }
     /**********************************************************************/
     /*     CHECK OLD TOKEN  TABLES                                        */
     /**********************************************************************/
     //1: Get list of 'old_token' tables and extract the survey id
     //2: Check if that survey id still exists
     //3: If it doesn't offer it for deletion
     $sQuery = dbSelectTablesLike('{{old_token}}%');
     $aTables = Yii::app()->db->createCommand($sQuery)->queryColumn();
     $aOldTokenSIDs = array();
     $aTokenSIDs = array();
     $aFullOldTokenSIDs = array();
     foreach ($aTables as $sTable) {
         list($sOldText, $SurveyText, $iSurveyID, $sDateTime) = explode('_', substr($sTable, strlen($sDBPrefix)));
         $aTokenSIDs[] = $iSurveyID;
         $aFullOldTokenSIDs[$iSurveyID][] = $sTable;
     }
     $aOldTokenSIDs = array_unique($aTokenSIDs);
     $surveys = Survey::model()->findAll();
     if (Survey::model()->hasErrors()) {
         safeDie(Survey::model()->getError());
     }
     $aSIDs = array();
     foreach ($surveys as $survey) {
         $aSIDs[] = $survey['sid'];
     }
     foreach ($aOldTokenSIDs as $iOldTokenSID) {
         if (!in_array($iOldTokenSID, $aOldTokenSIDs)) {
             foreach ($aFullOldTokenSIDs[$iOldTokenSID] as $sTableName) {
                 $aDelete['orphantokentables'][] = $sTableName;
             }
         } else {
             foreach ($aFullOldTokenSIDs[$iOldTokenSID] as $sTableName) {
                 list($sOldText, $sTokensText, $iSurveyID, $sDateTime) = explode('_', substr($sTableName, strlen($sDBPrefix)));
                 $iYear = substr($sDateTime, 0, 4);
                 $iMonth = substr($sDateTime, 4, 2);
                 $iDay = substr($sDateTime, 6, 2);
                 $iHour = substr($sDateTime, 8, 2);
                 $iMinute = substr($sDateTime, 10, 2);
                 $sDate = date('D, d M Y  h:i a', mktime($iHour, $iMinute, 0, $iMonth, $iDay, $iYear));
                 $sQuery = 'SELECT count(*) as recordcount FROM ' . $sTableName;
                 $aFirstRow = Yii::app()->db->createCommand($sQuery)->queryRow();
                 if ($aFirstRow['recordcount'] == 0) {
                     // empty table - so add it to immediate deletion
                     $aDelete['orphantokentables'][] = $sTableName;
                 } else {
                     $aOldTokenTableAsk[] = array('table' => $sTableName, 'details' => sprintf($clang->gT('Survey ID %d saved at %s containing %d record(s)'), $iSurveyID, $sDate, $aFirstRow['recordcount']));
                 }
             }
         }
     }
     if ($aDelete['defaultvalues'] == 0 && $aDelete['quotamembers'] == 0 && $aDelete['quotas'] == 0 && $aDelete['quotals'] == 0 && count($aDelete) == 4) {
         $aDelete['integrityok'] = true;
     } else {
         $aDelete['integrityok'] = false;
     }
     if (!isset($aOldTokenTableAsk) && !isset($aOldSurveyTableAsk)) {
         $aDelete['redundancyok'] = true;
     } else {
         $aDelete['redundancyok'] = false;
         $aDelete['redundanttokentables'] = array();
         $aDelete['redundantsurveytables'] = array();
         if (isset($aOldTokenTableAsk)) {
             $aDelete['redundanttokentables'] = $aOldTokenTableAsk;
         }
         if (isset($aOldSurveyTableAsk)) {
             $aDelete['redundantsurveytables'] = $aOldSurveyTableAsk;
         }
     }
     /**********************************************************************/
     /*     CHECK CPDB SURVEY_LINKS TABLE FOR REDUNDENT TOKEN TABLES       */
     /**********************************************************************/
     //1: Get distinct list of survey_link survey ids, check if tokens
     //   table still exists for each one, and remove if not
     /* TODO */
     /**********************************************************************/
     /*     CHECK CPDB SURVEY_LINKS TABLE FOR REDUNDENT TOKEN ENTRIES      */
     /**********************************************************************/
     //1: For each survey_link, see if the matching entry still exists in
     //   the token table and remove if it doesn't.
     /* TODO */
     return $aDelete;
 }
Пример #17
0
 private function _collectGroupData($iSurveyID)
 {
     $aData = array();
     $groups = QuestionGroup::model()->findAllByAttributes(array('sid' => $iSurveyID));
     foreach ($groups as $group) {
         $groupId = $group->attributes['gid'];
         $groupName = $group->attributes['group_name'];
         $aData['groups'][$groupId] = $groupName;
     }
     return $aData;
 }
 public static function deleteWithDependency($groupId, $surveyId)
 {
     // Abort if the survey is active
     $surveyIsActive = Survey::model()->findByPk($surveyId)->active !== 'N';
     if ($surveyIsActive) {
         Yii::app()->user->setFlash('error', gt("Can't delete question group when the survey is active"));
         return null;
     }
     $questionIds = QuestionGroup::getQuestionIdsInGroup($groupId);
     Question::deleteAllById($questionIds);
     Assessment::model()->deleteAllByAttributes(array('sid' => $surveyId, 'gid' => $groupId));
     return QuestionGroup::model()->deleteAllByAttributes(array('sid' => $surveyId, 'gid' => $groupId));
 }
 /**
  * Returns group info needed for indexes
  * @param <type> $surveyid
  * @param string $lang
  * @return <type>
  */
 function getGroupInfoForEM($surveyid, $lang = NULL)
 {
     if (is_null($lang) && isset($_SESSION['LEMlang'])) {
         $lang = $_SESSION['LEMlang'];
     } elseif (is_null($lang)) {
         $lang = Survey::model()->findByPk($surveyid)->language;
     }
     $oQuestionGroups = QuestionGroup::model()->findAll(array('condition' => "sid=:sid and language=:language", 'order' => 'group_order', 'params' => array(":sid" => $surveyid, ':language' => $lang)));
     $qinfo = array();
     $_order = 0;
     foreach ($oQuestionGroups as $oQuestionGroup) {
         $gid[$oQuestionGroup->gid] = array('group_order' => $_order, 'gid' => $oQuestionGroup->gid, 'group_name' => $oQuestionGroup->group_name, 'description' => $oQuestionGroup->description, 'grelevance' => !($this->sPreviewMode == 'question' || $this->sPreviewMode == 'group') ? $oQuestionGroup->grelevance : 1, 'randomization_group' => $oQuestionGroup->randomization_group);
         $qinfo[$_order] = $gid[$oQuestionGroup->gid];
         ++$_order;
     }
     // Needed for Randomization group.
     $groupRemap = !$this->sPreviewMode && !empty($_SESSION['survey_' . $surveyid]['groupReMap']) && !empty($_SESSION['survey_' . $surveyid]['grouplist']);
     if ($groupRemap) {
         $_order = 0;
         $qinfo = array();
         foreach ($_SESSION['survey_' . $surveyid]['grouplist'] as $info) {
             $gid[$info['gid']]['group_order'] = $_order;
             $qinfo[$_order] = $gid[$info['gid']];
             ++$_order;
         }
     }
     return $qinfo;
 }
Пример #20
0
 public static function deleteWithDependency($groupId, $surveyId)
 {
     $questionIds = QuestionGroup::getQuestionIdsInGroup($groupId);
     Question::deleteAllById($questionIds);
     Assessment::model()->deleteAllByAttributes(array('sid' => $surveyId, 'gid' => $groupId));
     return QuestionGroup::model()->deleteAllByAttributes(array('sid' => $surveyId, 'gid' => $groupId));
 }
Пример #21
0
function group_export($action, $iSurveyID, $gid)
{
    $fn = "limesurvey_group_{$gid}.lsg";
    $xml = getXMLWriter();
    viewHelper::disableHtmlLogging();
    header("Content-Type: application/force-download");
    header("Content-Disposition: attachment; filename={$fn}");
    header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
    // Date in the past
    header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Pragma: cache");
    // HTTP/1.0
    $xml->openUri('php://output');
    $xml->setIndent(true);
    $xml->startDocument('1.0', 'UTF-8');
    $xml->startElement('document');
    $xml->writeElement('LimeSurveyDocType', 'Group');
    $xml->writeElement('DBVersion', getGlobalSetting("DBVersion"));
    $xml->startElement('languages');
    $lresult = QuestionGroup::model()->findAllByAttributes(array('gid' => $gid), array('select' => 'language', 'group' => 'language'));
    foreach ($lresult as $row) {
        $xml->writeElement('language', $row->language);
    }
    $xml->endElement();
    groupGetXMLStructure($xml, $gid);
    $xml->endElement();
    // close columns
    $xml->endDocument();
}
Пример #22
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) . "}}");
         }
         /* Remove User/global settings part : need Question and QuestionGroup*/
         // Settings specific for this survey
         $oCriteria = new CDbCriteria();
         $oCriteria->compare('stg_name', 'last_%', true, 'AND', false);
         $oCriteria->compare('stg_value', $iSurveyID, false, 'AND');
         SettingGlobal::model()->deleteAll($oCriteria);
         // Settings specific for this survey, 2nd part
         $oCriteria = new CDbCriteria();
         $oCriteria->compare('stg_name', 'last_%' . $iSurveyID . '%', true, 'AND', false);
         SettingGlobal::model()->deleteAll($oCriteria);
         // All Group id from this survey for ALL users
         $aGroupId = CHtml::listData(QuestionGroup::model()->findAll(array('select' => 'gid', 'condition' => 'sid=:sid', 'params' => array(':sid' => $iSurveyID))), 'gid', 'gid');
         $oCriteria = new CDbCriteria();
         $oCriteria->compare('stg_name', 'last_question_gid_%', true, 'AND', false);
         if (Yii::app()->db->getDriverName() == 'pgsql') {
             $oCriteria->addInCondition('CAST(stg_value as ' . App()->db->schema->getColumnType("integer") . ')', $aGroupId);
         } else {
             $oCriteria->addInCondition('stg_value', $aGroupId);
         }
         SettingGlobal::model()->deleteAll($oCriteria);
         // All Question id from this survey for ALL users
         $aQuestionId = CHtml::listData(Question::model()->findAll(array('select' => 'qid', 'condition' => 'sid=:sid', 'params' => array(':sid' => $iSurveyID))), 'qid', 'qid');
         $oCriteria = new CDbCriteria();
         $oCriteria->compare('stg_name', 'last_question_%', true, 'OR', false);
         if (Yii::app()->db->getDriverName() == 'pgsql') {
             $oCriteria->addInCondition('CAST(stg_value as ' . App()->db->schema->getColumnType("integer") . ')', $aQuestionId);
         } else {
             $oCriteria->addInCondition('stg_value', $aQuestionId);
         }
         SettingGlobal::model()->deleteAll($oCriteria);
         $oResult = Question::model()->findAllByAttributes(array('sid' => $iSurveyID));
         foreach ($oResult as $aRow) {
             Answer::model()->deleteAllByAttributes(array('qid' => $aRow['qid']));
             Condition::model()->deleteAllByAttributes(array('qid' => $aRow['qid']));
             QuestionAttribute::model()->deleteAllByAttributes(array('qid' => $aRow['qid']));
             DefaultValue::model()->deleteAllByAttributes(array('qid' => $aRow['qid']));
         }
         Question::model()->deleteAllByAttributes(array('sid' => $iSurveyID));
         Assessment::model()->deleteAllByAttributes(array('sid' => $iSurveyID));
         QuestionGroup::model()->deleteAllByAttributes(array('sid' => $iSurveyID));
         SurveyLanguageSetting::model()->deleteAllByAttributes(array('surveyls_survey_id' => $iSurveyID));
         Permission::model()->deleteAllByAttributes(array('entity_id' => $iSurveyID, 'entity' => 'survey'));
         SavedControl::model()->deleteAllByAttributes(array('sid' => $iSurveyID));
         SurveyURLParameter::model()->deleteAllByAttributes(array('sid' => $iSurveyID));
         //Remove any survey_links to the CPDB
         SurveyLink::model()->deleteLinksBySurvey($iSurveyID);
         Quota::model()->deleteQuota(array('sid' => $iSurveyID), true);
     }
 }
Пример #23
0
 /**
  * Gets a key value list using the group name as value and the group id
  * as key.
  * @param type $surveyId
  * @return type
  */
 public function getGroupList($surveyId)
 {
     $result = QuestionGroup::model()->findListByAttributes(array('sid' => $surveyId), 'group_name');
     return $result;
 }
 /**
  * RPC Routine to edit question groups
  *
  * @access public
  * @param string $sSessionKey - Auth credentials
  * @param int $userName - the user to whom the participant belongs to
  * @param string $email - Participants email
  * 
  * */
 public function set_question_group($sSessionKey, $group_id)
 {
     // Check sessionkey
     if (!$this->_checkSessionKey($sSessionKey)) {
         return array('status' => 'Invalid session key');
     }
     // Check permissions
     if (Permission::model()->hasSurveyPermission($surveyid, 'surveycontent', 'update')) {
         return array('status' => 'No permission');
     }
     $gid = (int) $gid;
     $group = QuestionGroup::model()->findByAttributes(array('gid' => $gid));
     $surveyid = $group->sid;
     Yii::app()->loadHelper('surveytranslator');
     $grplangs = Survey::model()->findByPk($surveyid)->additionalLanguages;
     $baselang = Survey::model()->findByPk($surveyid)->language;
     array_push($grplangs, $baselang);
     foreach ($grplangs as $grplang) {
         if (isset($grplang) && $grplang != "") {
             $group_name = $_POST['group_name_' . $grplang];
             $group_description = $_POST['description_' . $grplang];
             $group_name = html_entity_decode($group_name, ENT_QUOTES, "UTF-8");
             $group_description = html_entity_decode($group_description, ENT_QUOTES, "UTF-8");
             // Fix bug with FCKEditor saving strange BR types
             $group_name = fixCKeditorText($group_name);
             $group_description = fixCKeditorText($group_description);
             $aData = array('group_name' => $group_name, 'description' => $group_description, 'randomization_group' => $_POST['randomization_group'], 'grelevance' => $_POST['grelevance']);
             $condition = array('gid' => $gid, 'sid' => $surveyid, 'language' => $grplang);
             $group = QuestionGroup::model()->findByAttributes($condition);
             foreach ($aData as $k => $v) {
                 $group->{$k} = $v;
             }
             $ugresult = $group->save();
             if ($ugresult) {
                 $groupsummary = getGroupList($gid, $surveyid);
             }
         }
     }
 }
Пример #25
0
 private function query($type, $action, $iSurveyID, $tolang, $baselang, $id1 = "", $id2 = "", $iScaleID = "", $new = "")
 {
     $amTypeOptions = array();
     switch ($action) {
         case "queryto":
             $baselang = $tolang;
         case "querybase":
             switch ($type) {
                 case 'title':
                 case 'description':
                 case 'welcome':
                 case 'end':
                 case 'emailinvite':
                 case 'emailinvitebody':
                 case 'emailreminder':
                 case 'emailreminderbody':
                 case 'emailconfirmation':
                 case 'emailconfirmationbody':
                 case 'emailregistration':
                 case 'emailregistrationbody':
                 case 'email_confirm':
                 case 'email_confirmbody':
                     return SurveyLanguageSetting::model()->findAllByPk(array('surveyls_survey_id' => $iSurveyID, 'surveyls_language' => $baselang));
                 case 'group':
                 case 'group_desc':
                     return QuestionGroup::model()->findAllByAttributes(array('sid' => $iSurveyID, 'language' => $baselang), array('order' => 'gid'));
                 case 'question':
                 case 'question_help':
                     return Question::model()->with('parents', 'groups')->findAllByAttributes(array('sid' => $iSurveyID, 'language' => $baselang, 'parent_qid' => 0), array('order' => 'groups.group_order, t.question_order, t.scale_id'));
                 case 'subquestion':
                     return Question::model()->with('parents', 'groups')->findAllByAttributes(array('sid' => $iSurveyID, 'language' => $baselang), array('order' => 'groups.group_order, parents.question_order, t.scale_id, t.question_order', 'condition' => 'parents.language=:baselang1 AND groups.language=:baselang2 AND t.parent_qid>0', 'params' => array(':baselang1' => $baselang, ':baselang2' => $baselang)));
                 case 'answer':
                     return Answer::model()->with('questions', 'groups')->findAllByAttributes(array('language' => $baselang), array('order' => 'groups.group_order, questions.question_order, t.scale_id, t.sortorder', 'condition' => 'questions.sid=:sid AND questions.language=:baselang1 AND groups.language=:baselang2', 'params' => array(':baselang1' => $baselang, ':baselang2' => $baselang, ':sid' => $iSurveyID)));
             }
         case "queryupdate":
             switch ($type) {
                 case 'title':
                     return SurveyLanguageSetting::model()->updateByPk(array('surveyls_survey_id' => $iSurveyID, 'surveyls_language' => $tolang), array('surveyls_title' => $new));
                 case 'description':
                     return SurveyLanguageSetting::model()->updateByPk(array('surveyls_survey_id' => $iSurveyID, 'surveyls_language' => $tolang), array('surveyls_description' => $new));
                 case 'welcome':
                     return SurveyLanguageSetting::model()->updateByPk(array('surveyls_survey_id' => $iSurveyID, 'surveyls_language' => $tolang), array('surveyls_welcometext' => $new));
                 case 'end':
                     return SurveyLanguageSetting::model()->updateByPk(array('surveyls_survey_id' => $iSurveyID, 'surveyls_language' => $tolang), array('surveyls_endtext' => $new));
                 case 'emailinvite':
                     return SurveyLanguageSetting::model()->updateByPk(array('surveyls_survey_id' => $iSurveyID, 'surveyls_language' => $tolang), array('surveyls_email_invite_subj' => $new));
                 case 'emailinvitebody':
                     return SurveyLanguageSetting::model()->updateByPk(array('surveyls_survey_id' => $iSurveyID, 'surveyls_language' => $tolang), array('surveyls_email_invite' => $new));
                 case 'emailreminder':
                     return SurveyLanguageSetting::model()->updateByPk(array('surveyls_survey_id' => $iSurveyID, 'surveyls_language' => $tolang), array('surveyls_email_remind_subj' => $new));
                 case 'emailreminderbody':
                     return SurveyLanguageSetting::model()->updateByPk(array('surveyls_survey_id' => $iSurveyID, 'surveyls_language' => $tolang), array('surveyls_email_remind' => $new));
                 case 'emailconfirmation':
                     return SurveyLanguageSetting::model()->updateByPk(array('surveyls_survey_id' => $iSurveyID, 'surveyls_language' => $tolang), array('surveyls_email_confirm_subj' => $new));
                 case 'emailconfirmationbody':
                     return SurveyLanguageSetting::model()->updateByPk(array('surveyls_survey_id' => $iSurveyID, 'surveyls_language' => $tolang), array('surveyls_email_confirm' => $new));
                 case 'emailregistration':
                     return SurveyLanguageSetting::model()->updateByPk(array('surveyls_survey_id' => $iSurveyID, 'surveyls_language' => $tolang), array('surveyls_email_register_subj' => $new));
                 case 'emailregistrationbody':
                     return SurveyLanguageSetting::model()->updateByPk(array('surveyls_survey_id' => $iSurveyID, 'surveyls_language' => $tolang), array('surveyls_email_register' => $new));
                 case 'email_confirm':
                     return SurveyLanguageSetting::model()->updateByPk(array('surveyls_survey_id' => $iSurveyID, 'surveyls_language' => $tolang), array('surveyls_email_confirm_subject' => $new));
                 case 'email_confirmbody':
                     return SurveyLanguageSetting::model()->updateByPk(array('surveyls_survey_id' => $iSurveyID, 'surveyls_language' => $tolang), array('surveyls_email_confirm' => $new));
                 case 'group':
                     return QuestionGroup::model()->updateByPk(array('gid' => $id1, 'language' => $tolang), array('group_name' => $new), 'sid=:sid', array(':sid' => $iSurveyID));
                 case 'group_desc':
                     return QuestionGroup::model()->updateByPk(array('gid' => $id1, 'language' => $tolang), array('description' => $new), 'sid=:sid', array(':sid' => $iSurveyID));
                 case 'question':
                     return Question::model()->updateByPk(array('qid' => $id1, 'language' => $tolang), array('question' => $new), 'sid=:sid AND parent_qid=0', array(':sid' => $iSurveyID));
                 case 'question_help':
                     return Question::model()->updateByPk(array('qid' => $id1, 'language' => $tolang), array('help' => $new), 'sid=:sid AND parent_qid=0', array(':sid' => $iSurveyID));
                 case 'subquestion':
                     return Question::model()->updateByPk(array('qid' => $id1, 'language' => $tolang), array('question' => $new), 'sid=:sid', array(':sid' => $iSurveyID));
                 case 'answer':
                     return Answer::model()->updateByPk(array('qid' => $id1, 'code' => $id2, 'language' => $tolang, 'scale_id' => $iScaleID), array('answer' => $new));
             }
     }
 }
Пример #26
0
 /**
  * Return all group of the active survey
  * Used to render group filter in questions list
  */
 public function getAllGroups()
 {
     $language = Survey::model()->findByPk($this->sid)->language;
     return QuestionGroup::model()->findAll("sid=:sid and language=:lang", array(':sid' => $this->sid, ':lang' => $language));
     //return QuestionGroup::model()->getGroups($this->sid);
 }
Пример #27
0
 /**
  * RPC Routine to return the ids and info of (sub-)questions of a survey/group.
  * Returns array of ids and info.
  *
  * @access public
  * @param string $sSessionKey Auth credentials
  * @param int $iSurveyID Id of the survey to list questions
  * @param int $iGroupID Optional id of the group to list questions
  * @param string $sLanguage Optional parameter language for multilingual questions
  * @return array The list of questions
  */
 public function list_questions($sSessionKey, $iSurveyID, $iGroupID = NULL, $sLanguage = NULL)
 {
     if ($this->_checkSessionKey($sSessionKey)) {
         Yii::app()->loadHelper("surveytranslator");
         $oSurvey = Survey::model()->findByPk($iSurveyID);
         if (!isset($oSurvey)) {
             return array('status' => 'Error: Invalid survey ID');
         }
         if (Permission::model()->hasSurveyPermission($iSurveyID, 'survey', 'read')) {
             if (is_null($sLanguage)) {
                 $sLanguage = $oSurvey->language;
             }
             if (!array_key_exists($sLanguage, getLanguageDataRestricted())) {
                 return array('status' => 'Error: Invalid language');
             }
             if ($iGroupID != NULL) {
                 $oGroup = QuestionGroup::model()->findByAttributes(array('gid' => $iGroupID));
                 $sGroupSurveyID = $oGroup['sid'];
                 if ($sGroupSurveyID != $iSurveyID) {
                     return array('status' => 'Error: IMissmatch in surveyid and groupid');
                 } else {
                     $aQuestionList = Question::model()->findAllByAttributes(array("sid" => $iSurveyID, "gid" => $iGroupID, "language" => $sLanguage));
                 }
             } else {
                 $aQuestionList = Question::model()->findAllByAttributes(array("sid" => $iSurveyID, "language" => $sLanguage));
             }
             if (count($aQuestionList) == 0) {
                 return array('status' => 'No questions found');
             }
             foreach ($aQuestionList as $oQuestion) {
                 $aData[] = array('id' => $oQuestion->primaryKey) + $oQuestion->attributes;
             }
             return $aData;
         } else {
             return array('status' => 'No permission');
         }
     } else {
         return array('status' => 'Invalid session key');
     }
 }
 /**
  * Show survey summary
  * @param int Survey id
  * @param string Action to be performed
  */
 function _surveysummary($aData)
 {
     $iSurveyID = $aData['surveyid'];
     $aSurveyInfo = getSurveyInfo($iSurveyID);
     $oSurvey = $aData['oSurvey'];
     $baselang = $aSurveyInfo['language'];
     $activated = $aSurveyInfo['active'];
     $condition = array('sid' => $iSurveyID, 'parent_qid' => 0, 'language' => $baselang);
     $sumresult3 = Question::model()->findAllByAttributes($condition);
     //Checked
     $sumcount3 = count($sumresult3);
     $condition = array('sid' => $iSurveyID, 'language' => $baselang);
     $sumresult2 = QuestionGroup::model()->findAllByAttributes($condition);
     //Checked
     $sumcount2 = count($sumresult2);
     //SURVEY SUMMARY
     $aAdditionalLanguages = $oSurvey->additionalLanguages;
     $surveysummary2 = "";
     if ($aSurveyInfo['anonymized'] != "N") {
         $surveysummary2 .= gT("Responses to this survey are anonymized.") . "<br />";
     } else {
         $surveysummary2 .= gT("Responses to this survey are NOT anonymized.") . "<br />";
     }
     if ($aSurveyInfo['format'] == "S") {
         $surveysummary2 .= gT("It is presented question by question.") . "<br />";
     } elseif ($aSurveyInfo['format'] == "G") {
         $surveysummary2 .= gT("It is presented group by group.") . "<br />";
     } else {
         $surveysummary2 .= gT("It is presented on one single page.") . "<br />";
     }
     if ($aSurveyInfo['questionindex'] > 0) {
         if ($aSurveyInfo['format'] == 'A') {
             $surveysummary2 .= gT("No question index will be shown with this format.") . "<br />";
         } elseif ($aSurveyInfo['questionindex'] == 1) {
             $surveysummary2 .= gT("A question index will be shown; participants will be able to jump between viewed questions.") . "<br />";
         } elseif ($aSurveyInfo['questionindex'] == 2) {
             $surveysummary2 .= gT("A full question index will be shown; participants will be able to jump between relevant questions.") . "<br />";
         }
     }
     if ($aSurveyInfo['datestamp'] == "Y") {
         $surveysummary2 .= gT("Responses will be date stamped.") . "<br />";
     }
     if ($aSurveyInfo['ipaddr'] == "Y") {
         $surveysummary2 .= gT("IP Addresses will be logged") . "<br />";
     }
     if ($aSurveyInfo['refurl'] == "Y") {
         $surveysummary2 .= gT("Referrer URL will be saved.") . "<br />";
     }
     if ($aSurveyInfo['usecookie'] == "Y") {
         $surveysummary2 .= gT("It uses cookies for access control.") . "<br />";
     }
     if ($aSurveyInfo['allowregister'] == "Y") {
         $surveysummary2 .= gT("If tokens are used, the public may register for this survey") . "<br />";
     }
     if ($aSurveyInfo['allowsave'] == "Y" && $aSurveyInfo['tokenanswerspersistence'] == 'N') {
         $surveysummary2 .= gT("Participants can save partially finished surveys") . "<br />\n";
     }
     if ($aSurveyInfo['emailnotificationto'] != '') {
         $surveysummary2 .= gT("Basic email notification is sent to:") . ' ' . htmlspecialchars($aSurveyInfo['emailnotificationto']) . "<br />\n";
     }
     if ($aSurveyInfo['emailresponseto'] != '') {
         $surveysummary2 .= gT("Detailed email notification with response data is sent to:") . ' ' . htmlspecialchars($aSurveyInfo['emailresponseto']) . "<br />\n";
     }
     $dateformatdetails = getDateFormatData(Yii::app()->session['dateformat']);
     if (trim($aSurveyInfo['startdate']) != '') {
         Yii::import('application.libraries.Date_Time_Converter');
         $datetimeobj = new Date_Time_Converter($aSurveyInfo['startdate'], 'Y-m-d H:i:s');
         $aData['startdate'] = $datetimeobj->convert($dateformatdetails['phpdate'] . ' H:i');
     } else {
         $aData['startdate'] = "-";
     }
     if (trim($aSurveyInfo['expires']) != '') {
         //$constructoritems = array($surveyinfo['expires'] , "Y-m-d H:i:s");
         Yii::import('application.libraries.Date_Time_Converter');
         $datetimeobj = new Date_Time_Converter($aSurveyInfo['expires'], 'Y-m-d H:i:s');
         //$datetimeobj = new Date_Time_Converter($surveyinfo['expires'] , "Y-m-d H:i:s");
         $aData['expdate'] = $datetimeobj->convert($dateformatdetails['phpdate'] . ' H:i');
     } else {
         $aData['expdate'] = "-";
     }
     if (!$aSurveyInfo['language']) {
         $aData['language'] = getLanguageNameFromCode($currentadminlang, false);
     } else {
         $aData['language'] = getLanguageNameFromCode($aSurveyInfo['language'], false);
     }
     // get the rowspan of the Additionnal languages row
     // is at least 1 even if no additionnal language is present
     $additionnalLanguagesCount = count($aAdditionalLanguages);
     $first = true;
     if ($aSurveyInfo['surveyls_urldescription'] == "") {
         $aSurveyInfo['surveyls_urldescription'] = htmlspecialchars($aSurveyInfo['surveyls_url']);
     }
     if ($aSurveyInfo['surveyls_url'] != "") {
         $aData['endurl'] = " <a target='_blank' href=\"" . htmlspecialchars($aSurveyInfo['surveyls_url']) . "\" title=\"" . htmlspecialchars($aSurveyInfo['surveyls_url']) . "\">" . flattenText($aSurveyInfo['surveyls_urldescription']) . "</a>";
     } else {
         $aData['endurl'] = "-";
     }
     $aData['sumcount3'] = $sumcount3;
     $aData['sumcount2'] = $sumcount2;
     if ($activated == "N") {
         $aData['activatedlang'] = gT("No");
     } else {
         $aData['activatedlang'] = gT("Yes");
     }
     $aData['activated'] = $activated;
     if ($activated == "Y") {
         $aData['surveydb'] = Yii::app()->db->tablePrefix . "survey_" . $iSurveyID;
     }
     $aData['warnings'] = "";
     if ($activated == "N" && $sumcount3 == 0) {
         $aData['warnings'] = gT("Survey cannot be activated yet.") . "<br />\n";
         if ($sumcount2 == 0 && Permission::model()->hasSurveyPermission($iSurveyID, 'surveycontent', 'create')) {
             $aData['warnings'] .= "<span class='statusentryhighlight'>[" . gT("You need to add question groups") . "]</span><br />";
         }
         if ($sumcount3 == 0 && Permission::model()->hasSurveyPermission($iSurveyID, 'surveycontent', 'create')) {
             $aData['warnings'] .= "<span class='statusentryhighlight'>[" . gT("You need to add questions") . "]</span><br />";
         }
     }
     $aData['hints'] = $surveysummary2;
     //return (array('column'=>array($columns_used,$hard_limit) , 'size' => array($length, $size_limit) ));
     //        $aData['tableusage'] = getDBTableUsage($iSurveyID);
     // ToDo: Table usage is calculated on every menu display which is too slow with bug surveys.
     // Needs to be moved to a database field and only updated if there are question/subquestions added/removed (it's currently also not functional due to the port)
     //
     $aData['tableusage'] = false;
     $aData['aAdditionalLanguages'] = $aAdditionalLanguages;
     $aData['surveyinfo'] = $aSurveyInfo;
     $aData['groups_count'] = $sumcount2;
     $this->getController()->renderPartial("/admin/survey/surveySummary_view", $aData);
 }
Пример #29
0
/**
* Replaces EM variable codes in a current survey with a new one
*
* @param mixed $iSurveyID The survey ID
* @param mixed $aCodeMap The codemap array (old_code=>new_code)
*/
function replaceExpressionCodes($iSurveyID, $aCodeMap)
{
    $arQuestions = Question::model()->findAll("sid=:sid", array(':sid' => $iSurveyID));
    foreach ($arQuestions as $arQuestion) {
        $bModified = false;
        foreach ($aCodeMap as $sOldCode => $sNewCode) {
            // Don't search/replace old codes that are too short or were numeric (because they would not have been usable in EM expressions anyway)
            if (strlen($sOldCode) > 1 && !is_numeric($sOldCode[0])) {
                $sOldCode = preg_quote($sOldCode, '/');
                $arQuestion->relevance = preg_replace("~{[^}]*\\K{$sOldCode}(?=[^}]*?})~", $sNewCode, $arQuestion->relevance, -1, $iCount);
                $bModified = $bModified || $iCount;
                $arQuestion->question = preg_replace("~{[^}]*\\K{$sOldCode}(?=[^}]*?})~", $sNewCode, $arQuestion->question, -1, $iCount);
                $bModified = $bModified || $iCount;
            }
        }
        if ($bModified) {
            $arQuestion->save();
        }
    }
    $arGroups = QuestionGroup::model()->findAll("sid=:sid", array(':sid' => $iSurveyID));
    foreach ($arGroups as $arGroup) {
        $bModified = false;
        foreach ($aCodeMap as $sOldCode => $sNewCode) {
            $sOldCode = preg_quote($sOldCode, '/');
            $arGroup->grelevance = preg_replace("~{[^}]*\\K{$sOldCode}(?=[^}]*?})~", $sNewCode, $arGroup->grelevance, -1, $iCount);
            $bModified = $bModified || $iCount;
            $arGroup->description = preg_replace("~{[^}]*\\K{$sOldCode}(?=[^}]*?})~", $sNewCode, $arGroup->description, -1, $iCount);
            $bModified = $bModified || $iCount;
        }
        if ($bModified) {
            $arGroup->save();
        }
    }
}
Пример #30
0
 /**
  * Return all group of the active survey
  * Used to render group filter in questions list
  */
 public function getAllGroups()
 {
     return QuestionGroup::model()->findAll("sid=:sid", array(':sid' => $this->sid));
 }