Exemple #1
0
function do_array_multiflexi($ia)
{
    global $thissurvey;
    $aLastMoveResult = LimeExpressionManager::GetLastMoveResult();
    $aMandatoryViolationSubQ = $aLastMoveResult['mandViolation'] && $ia[6] == 'Y' ? explode("|", $aLastMoveResult['unansweredSQs']) : array();
    $repeatheadings = Yii::app()->getConfig("repeatheadings");
    $minrepeatheadings = Yii::app()->getConfig("minrepeatheadings");
    $extraclass = "";
    $answertypeclass = "";
    $caption = gT("An array of sub-question on each cell. The sub-question text are in the table header and concerns line header. ");
    $checkconditionFunction = "fixnum_checkconditions";
    //echo '<pre>'; print_r($_POST); echo '</pre>';
    $defaultvaluescript = '';
    $qquery = "SELECT other FROM {{questions}} WHERE qid=" . $ia[0] . " AND language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "' and parent_qid=0";
    $other = Yii::app()->db->createCommand($qquery)->queryScalar();
    //Checked
    $aQuestionAttributes = getQuestionAttributeValues($ia[0]);
    if (trim($aQuestionAttributes['multiflexible_max']) != '' && trim($aQuestionAttributes['multiflexible_min']) == '') {
        $maxvalue = $aQuestionAttributes['multiflexible_max'];
        $extraclass .= " maxvalue maxvalue-" . trim($aQuestionAttributes['multiflexible_max']);
        if (isset($minvalue['value']) && $minvalue['value'] == 0) {
            $minvalue = 0;
        } else {
            $minvalue = 1;
        }
    }
    if (trim($aQuestionAttributes['multiflexible_min']) != '' && trim($aQuestionAttributes['multiflexible_max']) == '') {
        $minvalue = $aQuestionAttributes['multiflexible_min'];
        $extraclass .= " minvalue minvalue-" . trim($aQuestionAttributes['multiflexible_max']);
        $maxvalue = $aQuestionAttributes['multiflexible_min'] + 10;
    }
    if (trim($aQuestionAttributes['multiflexible_min']) == '' && trim($aQuestionAttributes['multiflexible_max']) == '') {
        if (isset($minvalue['value']) && $minvalue['value'] == 0) {
            $minvalue = 0;
        } else {
            $minvalue = 1;
        }
        $maxvalue = 10;
    }
    if (trim($aQuestionAttributes['multiflexible_min']) != '' && trim($aQuestionAttributes['multiflexible_max']) != '') {
        if ($aQuestionAttributes['multiflexible_min'] < $aQuestionAttributes['multiflexible_max']) {
            $minvalue = $aQuestionAttributes['multiflexible_min'];
            $maxvalue = $aQuestionAttributes['multiflexible_max'];
        }
    }
    if (trim($aQuestionAttributes['multiflexible_step']) != '' && $aQuestionAttributes['multiflexible_step'] > 0) {
        $stepvalue = $aQuestionAttributes['multiflexible_step'];
    } else {
        $stepvalue = 1;
    }
    if ($aQuestionAttributes['reverse'] == 1) {
        $tmp = $minvalue;
        $minvalue = $maxvalue;
        $maxvalue = $tmp;
        $reverse = true;
        $stepvalue = -$stepvalue;
    } else {
        $reverse = false;
    }
    $checkboxlayout = false;
    $inputboxlayout = false;
    if ($aQuestionAttributes['multiflexible_checkbox'] != 0) {
        $minvalue = 0;
        $maxvalue = 1;
        $checkboxlayout = true;
        $answertypeclass = " checkbox";
        $caption .= gT("Check or uncheck the answer for each subquestion. ");
    } elseif ($aQuestionAttributes['input_boxes'] != 0) {
        $inputboxlayout = true;
        $answertypeclass .= " numeric-item text";
        $extraclass .= " numberonly";
        $caption .= gT("Each answers are a number. ");
    } else {
        $answertypeclass = " dropdown";
        $caption .= gT("Select the answer for each subquestion. ");
    }
    if (ctype_digit(trim($aQuestionAttributes['repeat_headings'])) && trim($aQuestionAttributes['repeat_headings'] != "")) {
        $repeatheadings = intval($aQuestionAttributes['repeat_headings']);
        $minrepeatheadings = 0;
    }
    if (intval(trim($aQuestionAttributes['maximum_chars'])) > 0) {
        // Only maxlength attribute, use textarea[maxlength] jquery selector for textarea
        $maximum_chars = intval(trim($aQuestionAttributes['maximum_chars']));
        $maxlength = "maxlength='{$maximum_chars}' ";
        $extraclass .= " maxchars maxchars-" . $maximum_chars;
    } else {
        $maxlength = "";
    }
    if ($thissurvey['nokeyboard'] == 'Y') {
        includeKeypad();
        $kpclass = " num-keypad";
        $extraclass .= " inputkeypad";
    } else {
        $kpclass = "";
    }
    if (trim($aQuestionAttributes['answer_width']) != '') {
        $answerwidth = $aQuestionAttributes['answer_width'];
    } else {
        $answerwidth = 20;
    }
    $columnswidth = 100 - $answerwidth * 2;
    $lquery = "SELECT * FROM {{questions}} WHERE parent_qid={$ia[0]}  AND language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "' and scale_id=1 ORDER BY question_order";
    $lresult = dbExecuteAssoc($lquery);
    $aQuestions = $lresult->readAll();
    $labelans = array();
    $labelcode = array();
    foreach ($aQuestions as $lrow) {
        $labelans[] = $lrow['question'];
        $labelcode[] = $lrow['title'];
    }
    if ($numrows = count($labelans)) {
        if ($ia[6] != 'Y' && SHOW_NO_ANSWER == 1) {
            $numrows++;
        }
        $cellwidth = $columnswidth / $numrows;
        $cellwidth = sprintf('%02d', $cellwidth);
        $sQuery = "SELECT count(question) FROM {{questions}} WHERE parent_qid=" . $ia[0] . " AND scale_id=0 AND question like '%|%'";
        $iCount = Yii::app()->db->createCommand($sQuery)->queryScalar();
        if ($iCount > 0) {
            $right_exists = true;
            $answerwidth = $answerwidth / 2;
            $caption .= gT("The last cell give some information. ");
        } else {
            $right_exists = false;
        }
        // $right_exists is a flag to find out if there are any right hand answer parts. If there arent we can leave out the right td column
        if ($aQuestionAttributes['random_order'] == 1) {
            $ansquery = "SELECT * FROM {{questions}} WHERE parent_qid={$ia['0']} AND scale_id=0 AND language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "' ORDER BY " . dbRandom();
        } else {
            $ansquery = "SELECT * FROM {{questions}} WHERE parent_qid={$ia['0']} AND scale_id=0 AND language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "' ORDER BY question_order";
        }
        $ansresult = dbExecuteAssoc($ansquery)->readAll();
        //Checked
        if (trim($aQuestionAttributes['parent_order'] != '')) {
            $iParentQID = (int) $aQuestionAttributes['parent_order'];
            $aResult = array();
            $sessionao = $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['answer_order'];
            foreach ($sessionao[$iParentQID] as $aOrigRow) {
                $sCode = $aOrigRow['title'];
                foreach ($ansresult as $aRow) {
                    if ($sCode == $aRow['title']) {
                        $aResult[] = $aRow;
                    }
                }
            }
            $ansresult = $aResult;
        }
        $anscount = count($ansresult);
        $fn = 1;
        $mycols = "\t<colgroup class=\"col-responses\">\n" . "\n\t<col class=\"answertext\" width=\"{$answerwidth}%\" />\n";
        $answer_head_line = "\t<td >&nbsp;</td>\n";
        $odd_even = '';
        foreach ($labelans as $ld) {
            $answer_head_line .= "\t<th>" . $ld . "</th>\n";
            $odd_even = alternation($odd_even);
            $mycols .= "<col class=\"{$odd_even}\" width=\"{$cellwidth}%\" />\n";
        }
        if ($right_exists) {
            $answer_head_line .= "\t<td>&nbsp;</td>";
            $odd_even = alternation($odd_even);
            $mycols .= "<col class=\"answertextright {$odd_even}\" width=\"{$answerwidth}%\" />\n";
        }
        $answer_head = "\n\t<thead>\n<tr class=\"dontread\">\n" . $answer_head_line . "</tr>\n\t</thead>\n";
        $mycols .= "\t</colgroup>\n";
        $trbc = '';
        $answer = "\n<table class=\"question subquestions-list questions-list {$answertypeclass}-list {$extraclass}\" summary=\"{$caption}\">\n" . $mycols . $answer_head . "\n";
        $answer .= "<tbody>";
        foreach ($ansresult as $ansrow) {
            if (isset($repeatheadings) && $repeatheadings > 0 && $fn - 1 > 0 && ($fn - 1) % $repeatheadings == 0) {
                if ($anscount - $fn + 1 >= $minrepeatheadings) {
                    $answer .= "</tbody>\n<tbody>";
                    // Close actual body and open another one
                    $answer .= "<tr class=\"repeat headings dontread\">\n" . $answer_head_line . "</tr>\n\n";
                }
            }
            $myfname = $ia[1] . $ansrow['title'];
            $answertext = $ansrow['question'];
            $answertextsave = $answertext;
            /* Check the sub Q mandatory violation */
            if ($ia[6] == 'Y' && !empty($aMandatoryViolationSubQ)) {
                //Go through each labelcode and check for a missing answer! Default :If any are found, highlight this line, checkbox : if one is not found : don't highlight
                // PS : we really need a better system : event for EM !
                $emptyresult = $aQuestionAttributes['multiflexible_checkbox'] != 0 ? 1 : 0;
                foreach ($labelcode as $ld) {
                    $myfname2 = $myfname . '_' . $ld;
                    if ($aQuestionAttributes['multiflexible_checkbox'] != 0) {
                        if (!in_array($myfname2, $aMandatoryViolationSubQ)) {
                            $emptyresult = 0;
                        }
                    } else {
                        if (in_array($myfname2, $aMandatoryViolationSubQ)) {
                            $emptyresult = 1;
                        }
                    }
                }
                if ($emptyresult == 1) {
                    $answertext = '<span class="errormandatory">' . $answertext . '</span>';
                }
            }
            // Get array_filter stuff
            $trbc = alternation($trbc, 'row');
            list($htmltbody2, $hiddenfield) = return_array_filter_strings($ia, $aQuestionAttributes, $thissurvey, $ansrow, $myfname, $trbc, $myfname, "tr", "{$trbc} subquestions-list questions-list {$answertypeclass}-list");
            $answer .= $htmltbody2;
            if (strpos($answertext, '|')) {
                $answertext = substr($answertext, 0, strpos($answertext, '|'));
            }
            $answer .= "\t<th class=\"answertext\" width=\"{$answerwidth}%\">\n" . "{$answertext}\n" . $hiddenfield . "<input type=\"hidden\" name=\"java{$myfname}\" id=\"java{$myfname}\" value=\"";
            if (isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname])) {
                $answer .= $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname];
            }
            $answer .= "\" />\n\t</th>\n";
            $first_hidden_field = '';
            $thiskey = 0;
            foreach ($labelcode as $ld) {
                if ($checkboxlayout == false) {
                    $myfname2 = $myfname . "_{$ld}";
                    if (isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname2])) {
                        $myfname2_java_value = " value=\"{$_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname2]}\" ";
                    } else {
                        $myfname2_java_value = "";
                    }
                    $answer .= "\t<td class=\"answer_cell_00{$ld} question-item answer-item {$answertypeclass}-item {$extraclass}\">\n" . "\t<input type=\"hidden\" name=\"java{$myfname2}\" id=\"java{$myfname2}\" {$myfname2_java_value} />\n" . "<label class=\"hide read\" for=\"answer{$myfname2}\">{$labelans[$thiskey]}</label>\n";
                    $sSeparator = getRadixPointData($thissurvey['surveyls_numberformat']);
                    $sSeparator = $sSeparator['separator'];
                    if ($inputboxlayout == false) {
                        $answer .= "\t<select class=\"multiflexiselect\" name=\"{$myfname2}\" id=\"answer{$myfname2}\"" . " onchange=\"{$checkconditionFunction}(this.value, this.name, this.type)\">\n" . "<option value=\"\">" . gT('...') . "</option>\n";
                        for ($ii = $minvalue; $reverse ? $ii >= $maxvalue : $ii <= $maxvalue; $ii += $stepvalue) {
                            $answer .= '<option value="' . str_replace('.', $sSeparator, $ii) . '"';
                            if (isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname2]) && (string) $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname2] == (string) $ii) {
                                $answer .= SELECTED;
                            }
                            $answer .= ">" . str_replace('.', $sSeparator, $ii) . "</option>\n";
                        }
                        $answer .= "\t</select>\n";
                    } elseif ($inputboxlayout == true) {
                        $answer .= "\t<input type='text' class=\"multiflexitext text {$kpclass}\" name=\"{$myfname2}\" id=\"answer{$myfname2}\" {$maxlength} size=5 " . " onkeyup=\"{$checkconditionFunction}(this.value, this.name, this.type)\"" . " value=\"";
                        if (isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname2]) && is_numeric($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname2])) {
                            $answer .= str_replace('.', $sSeparator, $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname2]);
                        }
                        $answer .= "\" />\n";
                    }
                    $answer .= "\t</td>\n";
                    $inputnames[] = $myfname2;
                    $thiskey++;
                } else {
                    $myfname2 = $myfname . "_{$ld}";
                    if (isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname2]) && $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname2] == '1') {
                        $myvalue = '1';
                        $setmyvalue = CHECKED;
                    } else {
                        $myvalue = '';
                        $setmyvalue = '';
                    }
                    $answer .= "\t<td class=\"answer_cell_00{$ld} question-item answer-item {$answertypeclass}-item\">\n" . "\t<input type=\"hidden\" name=\"java{$myfname2}\" id=\"java{$myfname2}\" value=\"{$myvalue}\"/>\n" . "\t<input type=\"hidden\" name=\"{$myfname2}\" id=\"answer{$myfname2}\" value=\"{$myvalue}\" />\n";
                    $answer .= "\t<input type=\"checkbox\" class=\"checkbox {$extraclass}\" name=\"cbox_{$myfname2}\" id=\"cbox_{$myfname2}\" {$setmyvalue} " . " onclick=\"cancelBubbleThis(event); " . " aelt=document.getElementById('answer{$myfname2}');" . " jelt=document.getElementById('java{$myfname2}');" . " if(this.checked) {" . "  aelt.value=1;jelt.value=1;{$checkconditionFunction}(1,'{$myfname2}',aelt.type);" . " } else {" . "  aelt.value='';jelt.value='';{$checkconditionFunction}('','{$myfname2}',aelt.type);" . " }; return true;\" " . " />\n";
                    $answer .= "<label class=\"hide read\" for=\"cbox_{$myfname2}\">{$labelans[$thiskey]}</label>\n";
                    $inputnames[] = $myfname2;
                    //                    $answer .= "</label>\n"
                    $answer .= "" . "\t</td>\n";
                    $thiskey++;
                }
            }
            if (strpos($answertextsave, '|')) {
                $answertext = substr($answertextsave, strpos($answertextsave, '|') + 1);
                $answer .= "\t<td class=\"answertextright\" style='text-align:left;' width=\"{$answerwidth}%\">{$answertext}</td>\n";
            } elseif ($right_exists) {
                $answer .= "\t<td class=\"answertextright\" style='text-align:left;' width=\"{$answerwidth}%\">&nbsp;</td>\n";
            }
            $answer .= "</tr>\n";
            //IF a MULTIPLE of flexi-redisplay figure, repeat the headings
            $fn++;
        }
        $answer .= "\t</tbody>\n</table>\n";
    } else {
        $answer = "\n<p class=\"error\">" . gT("Error: There are no answer options for this question and/or they don't exist in this language.") . "</p>\n";
        $inputnames = '';
    }
    return array($answer, $inputnames);
}
/**
* 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');
}
Exemple #3
0
 public function doQuestion($ia)
 {
     global $thissurvey;
     if ($thissurvey['nokeyboard'] == 'Y') {
         includeKeypad();
         $kpclass = "text-keypad";
     } else {
         $kpclass = "";
     }
     $checkconditionFunction = "checkconditions";
     $aQuestionAttributes = getQuestionAttributeValues($ia[0]);
     $query = "SELECT other FROM {{questions}} WHERE qid=" . $ia[0] . " AND language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "' ";
     $result = Yii::app()->db->createCommand($query)->query();
     foreach ($result->readAll() as $row) {
         $other = $row['other'];
     }
     //question attribute random order set?
     if ($aQuestionAttributes['random_order'] == 1) {
         $ansquery = "SELECT * FROM {{answers}} WHERE qid={$ia['0']} AND language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "' and scale_id=0 ORDER BY " . dbRandom();
     } elseif ($aQuestionAttributes['alphasort'] == 1) {
         $ansquery = "SELECT * FROM {{answers}} WHERE qid={$ia['0']} AND language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "' and scale_id=0 ORDER BY answer";
     } else {
         $ansquery = "SELECT * FROM {{answers}} WHERE qid={$ia['0']} AND language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "' and scale_id=0 ORDER BY sortorder, answer";
     }
     $ansresult = dbExecuteAssoc($ansquery)->readAll();
     //Checked
     $anscount = count($ansresult);
     if (trim($aQuestionAttributes['display_columns']) != '') {
         $dcols = $aQuestionAttributes['display_columns'];
     } else {
         $dcols = 1;
     }
     if (trim($aQuestionAttributes['other_replace_text'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']]) != '') {
         $othertext = $aQuestionAttributes['other_replace_text'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']];
     } else {
         $othertext = gT('Other:');
     }
     if (isset($other) && $other == 'Y') {
         $anscount++;
     }
     //Count up for the Other answer
     if ($ia[6] != 'Y' && SHOW_NO_ANSWER == 1) {
         $anscount++;
     }
     //Count up if "No answer" is showing
     $wrapper = setupColumns($dcols, $anscount, "answers-list radio-list", "answer-item radio-item");
     $iBootCols = round(12 / $dcols);
     $ansByCol = round($anscount / $dcols);
     $ansByCol = $ansByCol > 0 ? $ansByCol : 1;
     //$answer = 'IKI: '.$iBootCols.' '.$ansByCol.' '.$wrapper['whole-start'];
     $answer = '<div class="row">';
     $answer .= '    <div class="col-xs-' . $iBootCols . '">AAAAAAAAAAAAAA';
     //Time Limit Code
     if (trim($aQuestionAttributes['time_limit']) != '') {
         $answer .= return_timer_script($aQuestionAttributes, $ia);
     }
     //End Time Limit Code
     // Get array_filter stuff
     $rowcounter = 0;
     $colcounter = 1;
     $trbc = '';
     foreach ($ansresult as $key => $ansrow) {
         $myfname = $ia[1] . $ansrow['code'];
         $check_ans = '';
         if ($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$ia[1]] == $ansrow['code']) {
             $check_ans = CHECKED;
         }
         list($htmltbody2, $hiddenfield) = return_array_filter_strings($ia, $aQuestionAttributes, $thissurvey, $ansrow, $myfname, '', $myfname, "div", "form-group answer-item radio-item");
         /*    if(substr($wrapper['item-start'],0,4) == "\t<li")
                     {
                         $startitem = "\t$htmltbody2\n";
                     } else {
                         $startitem = $wrapper['item-start'];
                     }
         
                     $answer .= $startitem;*/
         $answer .= "\t{$hiddenfield}\n";
         $answer .= '<div  class="form-group">';
         $answer .= '    <label for="answer' . $ia[1] . $ansrow['code'] . '" class="answertext control-label">' . $ansrow['answer'] . '</label>';
         $answer .= '        <input class="radio" type="radio" value="' . $ansrow['code'] . '" name="' . $ia[1] . '" id="answer' . $ia[1] . $ansrow['code'] . '"' . $check_ans . ' onclick="if (document.getElementById(\'answer' . $ia[1] . 'othertext\') != null) document.getElementById(\'answer' . $ia[1] . 'othertext\').value=\'\';' . $checkconditionFunction . '(this.value, this.name, this.type)" />';
         $answer .= $wrapper['item-end'];
         $answer .= '</div>';
         ++$rowcounter;
         //if ($rowcounter == $wrapper['maxrows'] && $colcounter < $wrapper['cols'] || (count($ansresult)-$key)==$wrapper['cols']-$colcounter)
         if ($rowcounter == $ansByCol && $colcounter < $wrapper['cols']) {
             if ($colcounter == $wrapper['cols']) {
                 //$answer .= 'là '.$wrapper['col-devide-last'];
                 $answer .= '    </div><!-- last -->';
             } else {
                 //$answer .= 'et là '.$wrapper['col-devide'];
                 $answer .= '    </div><!-- devide --> ';
                 $answer .= '    <div class="col-xs-' . $iBootCols . '">';
             }
             $rowcounter = 0;
             ++$colcounter;
         }
     }
     if (isset($other) && $other == 'Y') {
         $sSeparator = getRadixPointData($thissurvey['surveyls_numberformat']);
         $sSeparator = $sSeparator['separator'];
         if ($aQuestionAttributes['other_numbers_only'] == 1) {
             $oth_checkconditionFunction = 'fixnum_checkconditions';
         } else {
             $oth_checkconditionFunction = 'checkconditions';
         }
         if ($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$ia[1]] == '-oth-') {
             $check_ans = CHECKED;
         } else {
             $check_ans = '';
         }
         $thisfieldname = $ia[1] . 'other';
         if (isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$thisfieldname])) {
             $dispVal = $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$thisfieldname];
             if ($aQuestionAttributes['other_numbers_only'] == 1) {
                 $dispVal = str_replace('.', $sSeparator, $dispVal);
             }
             $answer_other = ' value="' . htmlspecialchars($dispVal, ENT_QUOTES) . '"';
         } else {
             $answer_other = ' value=""';
         }
         list($htmltbody2, $hiddenfield) = return_array_filter_strings($ia, $aQuestionAttributes, $thissurvey, array("code" => "other"), $thisfieldname, $trbc, $myfname, "div", "form-group answer-item radio-item other-item other");
         $answer .= "\t{$hiddenfield}\n";
         $answer .= '<div  class="form-group">';
         $answer .= '    <label for="SOTH' . $ia[1] . '" class="answertext control-label">' . $othertext . '</label>';
         $answer .= '    <input class="radio" type="radio" value="-oth-" name="' . $ia[1] . '" id="SOTH' . $ia[1] . '"' . $check_ans . ' onclick="' . $checkconditionFunction . '(this.value, this.name, this.type)" />';
         $answer .= '    <input type="text" class="text ' . $kpclass . '" id="answer' . $ia[1] . 'othertext" name="' . $ia[1] . 'other" title="' . gT('Other') . '"' . $answer_other . ' onkeyup="if($.trim($(this).val())!=\'\'){ $(\'#SOTH' . $ia[1] . '\').click(); }; ' . $oth_checkconditionFunction . '(this.value, this.name, this.type);" />';
         $answer .= $wrapper['item-end'];
         $answer .= '</div>';
         $inputnames[] = $thisfieldname;
         ++$rowcounter;
         if ($rowcounter == $ansByCol && $colcounter < $wrapper['cols']) {
             if ($colcounter == $wrapper['cols']) {
                 $answer .= '    </div><!-- last -->';
             } else {
                 $answer .= '    </div><!-- devide -->';
                 $answer .= '    <div class="col-xs-' . $iBootCols . '">';
             }
             $rowcounter = 0;
             ++$colcounter;
         }
     }
     if ($ia[6] != 'Y' && SHOW_NO_ANSWER == 1) {
         if (!isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$ia[1]]) || $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$ia[1]] == '' || $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$ia[1]] == ' ') {
             $check_ans = CHECKED;
             //Check the "no answer" radio button if there is no answer in session.
         } else {
             $check_ans = '';
         }
         $answer .= '<div  class="form-group">';
         $answer .= '    <label for="answer' . $ia[1] . 'NANS" class="answertext control-label">' . gT('No answer') . '</label>';
         $answer .= '        <input class="radio" type="radio" name="' . $ia[1] . '" id="answer' . $ia[1] . 'NANS" value=""' . $check_ans . ' onclick="if (document.getElementById(\'answer' . $ia[1] . 'othertext\') != null) document.getElementById(\'answer' . $ia[1] . 'othertext\').value=\'\';' . $checkconditionFunction . '(this.value, this.name, this.type)" />';
         $answer .= $wrapper['item-end'];
         $answer .= '</div>';
         // --> END NEW FEATURE - SAVE
         ++$rowcounter;
         //if ($rowcounter == $wrapper['maxrows'] && $colcounter < $wrapper['cols'])
         if ($rowcounter == $ansByCol && $colcounter < $wrapper['cols']) {
             if ($colcounter == $wrapper['cols']) {
                 //$answer .= $wrapper['col-devide-last'];
                 $answer .= '    </div><!-- last -->';
             } else {
                 //$answer .= $wrapper['col-devide'];
                 $answer .= '    </div><!-- devide -->';
                 $answer .= '    <div class="col-xs-' . $iBootCols . '">';
             }
             $rowcounter = 0;
             ++$colcounter;
         }
     }
     //END OF ITEMS
     //$answer .= $wrapper['whole-end'].'
     $answer .= '    <input type="hidden" name="java' . $ia[1] . '" id="java' . $ia[1] . "\" value=\"" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$ia[1]] . "\" />\n";
     $answer .= '</div> <!-- wrapper row -->';
     $inputnames[] = $ia[1];
     return array($answer, $inputnames);
 }
Exemple #4
0
function do_array_multiflexi($ia)
{
    global $thissurvey;
    $answer = '';
    $aLastMoveResult = LimeExpressionManager::GetLastMoveResult();
    $aMandatoryViolationSubQ = $aLastMoveResult['mandViolation'] && $ia[6] == 'Y' ? explode("|", $aLastMoveResult['unansweredSQs']) : array();
    $repeatheadings = Yii::app()->getConfig("repeatheadings");
    $minrepeatheadings = Yii::app()->getConfig("minrepeatheadings");
    $extraclass = "";
    $answertypeclass = "";
    $caption = gT("A table of subquestions on each cell. The subquestion texts are in the colum header and concern the row header.");
    $checkconditionFunction = "fixnum_checkconditions";
    $defaultvaluescript = '';
    $qquery = "SELECT other FROM {{questions}} WHERE qid=" . $ia[0] . " AND language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "' and parent_qid=0";
    $other = Yii::app()->db->createCommand($qquery)->queryScalar();
    //Checked
    /*
     * Question Attributes
     */
    $aQuestionAttributes = QuestionAttribute::model()->getQuestionAttributes($ia[0]);
    // Define min and max value
    if (trim($aQuestionAttributes['multiflexible_max']) != '' && trim($aQuestionAttributes['multiflexible_min']) == '') {
        $maxvalue = $aQuestionAttributes['multiflexible_max'];
        $minvalue = 1;
        $extraclass .= " maxvalue maxvalue-" . trim($aQuestionAttributes['multiflexible_max']);
    }
    if (trim($aQuestionAttributes['multiflexible_min']) != '' && trim($aQuestionAttributes['multiflexible_max']) == '') {
        $minvalue = $aQuestionAttributes['multiflexible_min'];
        $maxvalue = $aQuestionAttributes['multiflexible_min'] + 10;
        $extraclass .= " minvalue minvalue-" . trim($aQuestionAttributes['multiflexible_max']);
    }
    if (trim($aQuestionAttributes['multiflexible_min']) == '' && trim($aQuestionAttributes['multiflexible_max']) == '') {
        $maxvalue = 10;
        $minvalue = isset($minvalue['value']) && $minvalue['value'] == 0 ? 0 : 1;
    }
    if (trim($aQuestionAttributes['multiflexible_min']) != '' && trim($aQuestionAttributes['multiflexible_max']) != '') {
        if ($aQuestionAttributes['multiflexible_min'] < $aQuestionAttributes['multiflexible_max']) {
            $minvalue = $aQuestionAttributes['multiflexible_min'];
            $maxvalue = $aQuestionAttributes['multiflexible_max'];
        }
    }
    $stepvalue = trim($aQuestionAttributes['multiflexible_step']) != '' && $aQuestionAttributes['multiflexible_step'] > 0 ? $aQuestionAttributes['multiflexible_step'] : 1;
    if ($aQuestionAttributes['reverse'] == 1) {
        $tmp = $minvalue;
        $minvalue = $maxvalue;
        $maxvalue = $tmp;
        $reverse = true;
        $stepvalue = -$stepvalue;
    } else {
        $reverse = false;
    }
    $checkboxlayout = false;
    $inputboxlayout = false;
    $textAlignment = 'right';
    if ($aQuestionAttributes['multiflexible_checkbox'] != 0) {
        $minvalue = 0;
        $maxvalue = 1;
        $checkboxlayout = true;
        $answertypeclass = " checkbox";
        $caption .= gT("Please check the matching combinations.");
        $textAlignment = 'center';
    } elseif ($aQuestionAttributes['input_boxes'] != 0) {
        $inputboxlayout = true;
        $answertypeclass .= " numeric-item text";
        $extraclass .= " numberonly";
        $caption .= gT("Please enter only numbers.");
        $textAlignment = 'right';
    } else {
        $answertypeclass = " dropdown";
        $caption .= gT("Please select an answer for each combination.");
    }
    if (ctype_digit(trim($aQuestionAttributes['repeat_headings'])) && trim($aQuestionAttributes['repeat_headings'] != "")) {
        $repeatheadings = intval($aQuestionAttributes['repeat_headings']);
        $minrepeatheadings = 0;
    }
    if (intval(trim($aQuestionAttributes['maximum_chars'])) > 0) {
        // Only maxlength attribute, use textarea[maxlength] jquery selector for textarea
        $maximum_chars = intval(trim($aQuestionAttributes['maximum_chars']));
        $maxlength = "maxlength='{$maximum_chars}' ";
        $extraclass .= " maxchars maxchars-" . $maximum_chars;
    } else {
        $maxlength = "";
    }
    if ($thissurvey['nokeyboard'] == 'Y') {
        includeKeypad();
        $kpclass = " num-keypad";
        $extraclass .= " inputkeypad";
    } else {
        $kpclass = "";
    }
    if (trim($aQuestionAttributes['answer_width']) != '') {
        $answerwidth = $aQuestionAttributes['answer_width'];
        $useAnswerWidth = true;
    } else {
        $answerwidth = 20;
        // If answerwidth is not given, we want to default to Bootstrap column.
        // Otherwise bug on phone screen.
        $useAnswerWidth = false;
    }
    $columnswidth = 100 - $answerwidth * 2;
    $lquery = "SELECT * FROM {{questions}} WHERE parent_qid={$ia[0]}  AND language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "' and scale_id=1 ORDER BY question_order";
    $lresult = dbExecuteAssoc($lquery);
    $aQuestions = $lresult->readAll();
    $labelans = array();
    $labelcode = array();
    foreach ($aQuestions as $lrow) {
        $labelans[] = $lrow['question'];
        $labelcode[] = $lrow['title'];
    }
    if ($numrows = count($labelans)) {
        if ($ia[6] != 'Y' && SHOW_NO_ANSWER == 1) {
            $numrows++;
        }
        $cellwidth = $columnswidth / $numrows;
        $cellwidth = sprintf('%02d', $cellwidth);
        $sQuery = "SELECT count(question) FROM {{questions}} WHERE parent_qid=" . $ia[0] . " AND scale_id=0 AND question like '%|%'";
        $iCount = Yii::app()->db->createCommand($sQuery)->queryScalar();
        if ($iCount > 0) {
            $right_exists = true;
            $answerwidth = $answerwidth / 2;
            $caption .= gT("The last cell gives some information.");
        } else {
            $right_exists = false;
        }
        // $right_exists is a flag to find out if there are any right hand answer parts. If there arent we can leave out the right td column
        if ($aQuestionAttributes['random_order'] == 1) {
            $ansquery = "SELECT * FROM {{questions}} WHERE parent_qid={$ia['0']} AND scale_id=0 AND language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "' ORDER BY " . dbRandom();
        } else {
            $ansquery = "SELECT * FROM {{questions}} WHERE parent_qid={$ia['0']} AND scale_id=0 AND language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "' ORDER BY question_order";
        }
        $ansresult = dbExecuteAssoc($ansquery)->readAll();
        //Checked
        if (trim($aQuestionAttributes['parent_order'] != '')) {
            $iParentQID = (int) $aQuestionAttributes['parent_order'];
            $aResult = array();
            $sessionao = isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['answer_order']) ? $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['answer_order'] : array();
            if (isset($sessionao[$iParentQID])) {
                foreach ($sessionao[$iParentQID] as $aOrigRow) {
                    $sCode = $aOrigRow['title'];
                    foreach ($ansresult as $aRow) {
                        if ($sCode == $aRow['title']) {
                            $aResult[] = $aRow;
                        }
                    }
                }
                $ansresult = $aResult;
            }
        }
        $anscount = count($ansresult);
        $fn = 1;
        $sAnswerRows = '';
        foreach ($ansresult as $j => $ansrow) {
            if (isset($repeatheadings) && $repeatheadings > 0 && $fn - 1 > 0 && ($fn - 1) % $repeatheadings == 0) {
                if ($anscount - $fn + 1 >= $minrepeatheadings) {
                    $sAnswerRows .= doRender('/survey/questions/arrays/multiflexi/rows/repeat_header', array('labelans' => $labelans, 'right_exists' => $right_exists, 'cellwidth' => $cellwidth, 'answerwidth' => $answerwidth, 'textAlignment' => $textAlignment), true);
                }
            }
            $myfname = $ia[1] . $ansrow['title'];
            $answertext = $ansrow['question'];
            $answertextsave = $answertext;
            /* Check the sub Q mandatory violation */
            $error = false;
            if ($ia[6] == 'Y' && !empty($aMandatoryViolationSubQ)) {
                //Go through each labelcode and check for a missing answer! Default :If any are found, highlight this line, checkbox : if one is not found : don't highlight
                // PS : we really need a better system : event for EM !
                $emptyresult = $aQuestionAttributes['multiflexible_checkbox'] != 0 ? 1 : 0;
                foreach ($labelcode as $ld) {
                    $myfname2 = $myfname . '_' . $ld;
                    if ($aQuestionAttributes['multiflexible_checkbox'] != 0) {
                        if (!in_array($myfname2, $aMandatoryViolationSubQ)) {
                            $emptyresult = 0;
                        }
                    } else {
                        if (in_array($myfname2, $aMandatoryViolationSubQ)) {
                            $emptyresult = 1;
                        }
                    }
                }
                $error = $emptyresult == 1 ? true : false;
            }
            $sSeparator = getRadixPointData($thissurvey['surveyls_numberformat']);
            $sSeparator = $sSeparator['separator'];
            // Get array_filter stuff
            $sDisplayStyle = return_display_style($ia, $aQuestionAttributes, $thissurvey, $myfname);
            if (strpos($answertext, '|')) {
                $answertext = substr($answertext, 0, strpos($answertext, '|'));
            }
            $row_value = isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname]) ? $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname] : '';
            $first_hidden_field = '';
            $thiskey = 0;
            $answer_tds = '';
            foreach ($labelcode as $i => $ld) {
                $myfname2 = $myfname . "_{$ld}";
                $value = isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname2]) ? $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname2] : '';
                // Possibly replace '.' with ','
                $surveyId = Yii::app()->getConfig('surveyID');
                $surveyLabel = 'survey_' . $surveyId;
                $fieldnameIsNumeric = isset($_SESSION[$surveyLabel][$myfname2]) && is_numeric($_SESSION[$surveyLabel][$myfname2]);
                if ($fieldnameIsNumeric) {
                    $value = str_replace('.', $sSeparator, $_SESSION[$surveyLabel][$myfname2]);
                }
                if ($checkboxlayout == false) {
                    $answer_tds .= doRender('/survey/questions/arrays/multiflexi/rows/cells/answer_td', array('dataTitle' => $labelans[$i], 'ld' => $ld, 'answertypeclass' => $answertypeclass, 'answertext' => $answertext, 'stepvalue' => $stepvalue, 'extraclass' => $extraclass, 'myfname2' => $myfname2, 'error' => $error, 'inputboxlayout' => $inputboxlayout, 'checkconditionFunction' => $checkconditionFunction, 'minvalue' => $minvalue, 'maxvalue' => $maxvalue, 'reverse' => $reverse, 'value' => $value, 'sSeparator' => $sSeparator, 'kpclass' => $kpclass, 'maxlength' => $maxlength), true);
                    $inputnames[] = $myfname2;
                    $thiskey++;
                } else {
                    if (isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname2]) && $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname2] == '1') {
                        $myvalue = '1';
                        $setmyvalue = CHECKED;
                    } else {
                        $myvalue = '';
                        $setmyvalue = '';
                    }
                    $answer_tds .= doRender('/survey/questions/arrays/multiflexi/rows/cells/answer_td_checkboxes', array('dataTitle' => $labelans[$i], 'ld' => $ld, 'answertypeclass' => $answertypeclass, 'value' => $myvalue, 'setmyvalue' => $setmyvalue, 'myfname2' => $myfname2, 'checkconditionFunction' => $checkconditionFunction, 'extraclass' => $extraclass), true);
                    $inputnames[] = $myfname2;
                    $thiskey++;
                }
            }
            $rightTd = false;
            $answertextright = '';
            if (strpos($answertextsave, '|')) {
                $answertextright = substr($answertextsave, strpos($answertextsave, '|') + 1);
                $rightTd = true;
            } elseif ($right_exists) {
                $rightTd = true;
            }
            $sAnswerRows .= doRender('/survey/questions/arrays/multiflexi/rows/answer_row', array('sDisplayStyle' => $sDisplayStyle, 'useAnswerWidth' => $useAnswerWidth, 'answerwidth' => $answerwidth, 'myfname' => $myfname, 'error' => $error, 'row_value' => $row_value, 'answertext' => $answertext, 'answertextright' => $answertextright, 'answer_tds' => $answer_tds, 'rightTd' => $rightTd, 'zebra' => 2 - $j % 2), true);
            $fn++;
        }
        $answer = doRender('/survey/questions/arrays/multiflexi/answer', array('answertypeclass' => $answertypeclass, 'extraclass' => $extraclass, 'answerwidth' => $answerwidth, 'labelans' => $labelans, 'cellwidth' => $cellwidth, 'right_exists' => $right_exists, 'sAnswerRows' => $sAnswerRows, 'textAlignment' => $textAlignment), true);
    } else {
        $answer = doRender('/survey/questions/arrays/multiflexi/empty_error', array(), true);
        $inputnames = '';
    }
    return array($answer, $inputnames);
}
/**
 * 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.
 * @param int $surveyid
 * @param boolean $preview Defaults to false
 * @return void
 */
function buildsurveysession($surveyid, $preview = false)
{
    Yii::trace('start', 'survey.buildsurveysession');
    global $secerror, $clienttoken;
    global $tokensexist;
    global $move, $rooturl;
    $sLangCode = App()->language;
    $languagechanger = makeLanguageChangerSurvey($sLangCode);
    if (!$preview) {
        $preview = Yii::app()->getConfig('previewmode');
    }
    $thissurvey = getSurveyInfo($surveyid, $sLangCode);
    if ($thissurvey['nokeyboard'] == 'Y') {
        includeKeypad();
        $kpclass = "text-keypad";
    } else {
        $kpclass = '';
    }
    // $thissurvey['template'] already fixed by model : but why put this in session ?
    $_SESSION['survey_' . $surveyid]['templatename'] = $thissurvey['template'];
    $_SESSION['survey_' . $surveyid]['templatepath'] = getTemplatePath($thissurvey['template']) . DIRECTORY_SEPARATOR;
    $sTemplatePath = $_SESSION['survey_' . $surveyid]['templatepath'];
    $oTemplate = Template::model()->getInstance('', $surveyid);
    $sTemplatePath = $oTemplate->path;
    $sTemplateViewPath = $oTemplate->viewPath;
    /**
     * This method has multiple outcomes that virtually do the same thing
     * Possible scenarios/subscenarios are =>
     *   - No token required & no captcha required
     *   - No token required & captcha required
     *       > captcha may be wrong
     *   - token required & captcha required
     *       > token may be wrong/used
     *       > captcha may be wrong
     */
    $scenarios = array("tokenRequired" => $tokensexist == 1, "captchaRequired" => isCaptchaEnabled('surveyaccessscreen', $thissurvey['usecaptcha']) && !isset($_SESSION['survey_' . $surveyid]['captcha_surveyaccessscreen']));
    /**
     *   Set subscenarios depending on scenario outcome
     */
    $subscenarios = array("captchaCorrect" => false, "tokenValid" => false);
    //Check the scenario for token required
    if ($scenarios['tokenRequired']) {
        //Check for the token-validity
        if ($thissurvey['alloweditaftercompletion'] == 'Y') {
            $oTokenEntry = Token::model($surveyid)->findByAttributes(array('token' => $clienttoken));
        } else {
            $oTokenEntry = Token::model($surveyid)->usable()->incomplete()->findByAttributes(array('token' => $clienttoken));
        }
        $subscenarios['tokenValid'] = !empty($oTokenEntry) && $clienttoken != "";
    } else {
        $subscenarios['tokenValid'] = true;
    }
    //Check the scenario for captcha required
    if ($scenarios['captchaRequired']) {
        //Check if the Captcha was correct
        $loadsecurity = returnGlobal('loadsecurity', true);
        $captcha = Yii::app()->getController()->createAction('captcha');
        $subscenarios['captchaCorrect'] = $captcha->validate($loadsecurity, false);
    } else {
        $subscenarios['captchaCorrect'] = true;
        $loadsecurity = false;
    }
    //RenderWay defines which html gets rendered to the user_error
    // Possibilities are main,register,correct
    $renderCaptcha = "";
    $renderToken = "";
    //Define array to render the partials
    $aEnterTokenData = array();
    $aEnterTokenData['bNewTest'] = false;
    $aEnterTokenData['bDirectReload'] = false;
    $aEnterTokenData['error'] = $secerror;
    $aEnterTokenData['iSurveyId'] = $surveyid;
    $aEnterTokenData['sKpClass'] = $kpclass;
    // ???
    $aEnterTokenData['sLangCode'] = $sLangCode;
    if (isset($_GET['bNewTest']) && $_GET['newtest'] == "Y") {
        $aEnterTokenData['bNewTest'] = true;
    }
    // If this is a direct Reload previous answers URL, then add hidden fields
    if (isset($loadall) && isset($scid) && isset($loadname) && isset($loadpass)) {
        $aEnterTokenData['bDirectReload'] = true;
        $aEnterTokenData['sCid'] = $scid;
        $aEnterTokenData['sLoadname'] = htmlspecialchars($loadname);
        $aEnterTokenData['sLoadpass'] = htmlspecialchars($loadpass);
    }
    $FlashError = "";
    // Scenario => Captcha required
    if ($scenarios['captchaRequired'] && !$preview) {
        list($renderCaptcha, $FlashError) = testCaptcha($aEnterTokenData, $subscenarios, $surveyid, $loadsecurity);
    }
    // Scenario => Token required
    if ($scenarios['tokenRequired'] && !$preview) {
        //Test if token is valid
        list($renderToken, $FlashError) = testIfTokenIsValid($subscenarios, $thissurvey, $aEnterTokenData, $clienttoken);
    }
    //If there were errors, display through yii->FlashMessage
    if ($FlashError !== "") {
        $aEnterTokenData['errorMessage'] = $FlashError;
    }
    $renderWay = getRenderWay($renderToken, $renderCaptcha);
    $redata = compact(array_keys(get_defined_vars()));
    renderRenderWayForm($renderWay, $redata, $scenarios, $sTemplateViewPath, $aEnterTokenData, $surveyid);
    // Reset all the session variables and start again
    resetAllSessionVariables($surveyid);
    // 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'];
    }
    // Always SetSurveyLanguage : surveys controller SetSurveyLanguage too, if different : broke survey (#09769)
    SetSurveyLanguage($surveyid, $language_to_set);
    UpdateGroupList($surveyid, $_SESSION['survey_' . $surveyid]['s_lang']);
    $totalquestions = Question::model()->getTotalQuestions($surveyid);
    $iTotalGroupsWithoutQuestions = QuestionGroup::model()->getTotalGroupsWithoutQuestions($surveyid);
    // Fix totalquestions by substracting Test Display questions
    $iNumberofQuestions = Question::model()->getNumberOfQuestions($surveyid);
    $_SESSION['survey_' . $surveyid]['totalquestions'] = $totalquestions - (int) reset($iNumberofQuestions);
    // 2. SESSION VARIABLE: totalsteps
    setTotalSteps($surveyid, $thissurvey, $totalquestions);
    // Break out and crash if there are no questions!
    if ($totalquestions == 0 || $iTotalGroupsWithoutQuestions > 0) {
        $redata = compact(array_keys(get_defined_vars()));
        breakOutAndCrash($redata, $sTemplateViewPath, $totalquestions, $iTotalGroupsWithoutQuestions, $thissurvey);
    }
    //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']);
    //$seed = ls\mersenne\getSeed($surveyid, $preview);
    // Randomization groups for groups
    list($fieldmap, $randomized1) = randomizationGroup($surveyid, $fieldmap, $preview);
    // Randomization groups for questions
    list($fieldmap, $randomized2) = randomizationQuestion($surveyid, $fieldmap, $preview);
    $randomized = $randomized1 || $randomized2;
    if ($randomized === true) {
        $fieldmap = finalizeRandomization($fieldmap);
        $_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;
    initFieldArray($surveyid, $fieldmap);
    // Prefill questions/answers from command line params
    prefillFromCommandLine($surveyid);
    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
    checkPassthruLabel($surveyid, $preview, $fieldmap);
    Yii::trace('end', 'survey.buildsurveysession');
    //traceVar($_SESSION['survey_' . $surveyid]);
}