Esempio n. 1
0
function do_array_multiflexi($ia)
{
    global $dbprefix, $connect, $thissurvey, $clang;
    global $repeatheadings;
    global $notanswered;
    global $minrepeatheadings;

    if ($ia[8] == 'Y')
    {
        $checkconditionFunction = "checkconditions";
    }
    else
    {
        $checkconditionFunction = "noop_checkconditions";
    }

    //echo '<pre>'; print_r($_POST); echo '</pre>';
    $defaultvaluescript = '';
    $qquery = "SELECT other FROM {$dbprefix}questions WHERE qid=".$ia[0]." AND language='".$_SESSION['s_lang']."' and parent_qid=0";
    $qresult = db_execute_assoc($qquery);
    while($qrow = $qresult->FetchRow()) {$other = $qrow['other'];}

    $qidattributes=getQuestionAttributes($ia[0],$ia[4]);
    if (trim($qidattributes['multiflexible_max'])!='' && trim($qidattributes['multiflexible_min']) ==''){
        $maxvalue=$qidattributes['multiflexible_max'];
        if(isset($minvalue['value']) && $minvalue['value'] == 0) {$minvalue = 0;} else {$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']) ==''){
        if(isset($minvalue['value']) && $minvalue['value'] == 0) {$minvalue = 0;} else {$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'])!='' && $qidattributes['multiflexible_step'] > 0)
    {
        $stepvalue=$qidattributes['multiflexible_step'];
    }
    else
    {
        $stepvalue=1;
    }

    if($qidattributes['reverse']==1)
    {
        $tmp = $minvalue;
        $minvalue = $maxvalue;
        $maxvalue = $tmp;
        $reverse=true;
        $stepvalue=-$stepvalue;
    }
    else
    {
        $reverse=false;
    }

    $checkboxlayout=false;
    if ($qidattributes['multiflexible_checkbox']!=0)
    {
        $minvalue=0;
        $maxvalue=1;
        $checkboxlayout=true;
    }

    $inputboxlayout=false;
    if ($qidattributes['input_boxes']!=0)
    {
        $inputboxlayout=true;
    }

    if (trim($qidattributes['maximum_chars'])!='')
    {
        $maxsize=$qidattributes['maximum_chars'];
    }
    else
    {
        $maxsize=255;
    }

    if ($thissurvey['nokeyboard']=='Y')
    {
        vIncludeKeypad();
        $kpclass = "num-keypad";
    }
    else
    {
        $kpclass = "";
    }

    if (trim($qidattributes['answer_width'])!='')
    {
        $answerwidth=$qidattributes['answer_width'];
    }
    else
    {
        $answerwidth=20;
    }
    $columnswidth=100-($answerwidth*2);

    $lquery = "SELECT * FROM {$dbprefix}questions WHERE parent_qid={$ia[0]}  AND language='".$_SESSION['s_lang']."' and scale_id=1 ORDER BY question_order";
    $lresult = db_execute_assoc($lquery);
    if ($lresult->RecordCount() > 0)
    {
        while ($lrow=$lresult->FetchRow())
        {
            $labelans[]=$lrow['question'];
            $labelcode[]=$lrow['title'];
        }
        $numrows=count($labelans);
        if ($ia[6] != 'Y' && SHOW_NO_ANSWER == 1) {$numrows++;}
        $cellwidth=$columnswidth/$numrows;

        $cellwidth=sprintf('%02d', $cellwidth);

        $ansquery = "SELECT question FROM {$dbprefix}questions WHERE parent_qid=".$ia[0]." AND scale_id=0 AND question like '%|%'";
        $ansresult = db_execute_assoc($ansquery);
        if ($ansresult->RecordCount()>0) {$right_exists=true;$answerwidth=$answerwidth/2;} else {$right_exists=false;}
        // $right_exists is a flag to find out if there are any right hand answer parts. If there arent we can leave out the right td column
        if ($qidattributes['random_order']==1) {
            $ansquery = "SELECT * FROM {$dbprefix}questions WHERE parent_qid=$ia[0] AND scale_id=0 AND language='".$_SESSION['s_lang']."' ORDER BY ".db_random();
        }
        else
        {
            $ansquery = "SELECT * FROM {$dbprefix}questions WHERE parent_qid=$ia[0] AND scale_id=0 AND language='".$_SESSION['s_lang']."' ORDER BY question_order";
        }
        $ansresult = db_execute_assoc($ansquery);
        $anscount = $ansresult->RecordCount();
        $fn=1;

        $mycols = "\t<colgroup class=\"col-responses\">\n"
        . "\n\t<col class=\"answertext\" width=\"$answerwidth%\" />\n";

        $myheader = "\n\t<thead>\n"
        . "<tr>\n"
        . "\t<td >&nbsp;</td>\n";

        $odd_even = '';
        foreach ($labelans as $ld)
        {
            $myheader .= "\t<th>".$ld."</th>\n";
            $odd_even = alternation($odd_even);
            $mycols .= "<col class=\"$odd_even\" width=\"$cellwidth%\" />\n";
        }
        if ($right_exists)
        {
            $myheader .= "\t<td>&nbsp;</td>";
            $odd_even = alternation($odd_even);
            $mycols .= "<col class=\"answertextright $odd_even\" width=\"$answerwidth%\" />\n";
        }
        $myheader .= "</tr>\n"
        . "\t</thead>\n";
        $mycols .= "\t</colgroup>\n";

        $trbc = '';
        $answer = "\n<table class=\"question\" summary=\"".str_replace('"','' ,strip_tags($ia[3]))." - an array type question with dropdown responses\">\n" . $mycols . $myheader . "\n";

        while ($ansrow = $ansresult->FetchRow())
        {
            if (isset($repeatheadings) && $repeatheadings > 0 && ($fn-1) > 0 && ($fn-1) % $repeatheadings == 0)
            {
                if ( ($anscount - $fn + 1) >= $minrepeatheadings )
                {
                    $trbc = alternation($trbc , 'row');
                    $answer .= "<tbody>\n<tr class=\"$trbc repeat\">\n"
                    . "\t<td>&nbsp;</td>\n";
                    foreach ($labelans as $ld)
                    {
                        $answer .= "\t<th>".$ld."</th>\n";
                    }
                    $answer .= "</tr>\n</tbody>\n";
                }
            }
            $myfname = $ia[1].$ansrow['title'];
            $answertext=dTexts::run($ansrow['question']);
            $answertextsave=$answertext;
            /* Check if this item has not been answered: the 'notanswered' variable must be an array,
             containing a list of unanswered questions, the current question must be in the array,
             and there must be no answer available for the item in this session. */
            if ((is_array($notanswered)) && (array_search($ia[1], $notanswered) !== FALSE))
            {
                //Go through each labelcode and check for a missing answer! If any are found, highlight this line
                $emptyresult=0;
                foreach($labelcode as $ld)
                {
                    $myfname2=$myfname.'_'.$ld;
                    if($_SESSION[$myfname2] == "")
                    {
                        $emptyresult=1;
                    }
                }
                if ($emptyresult == 1)
                {
                    $answertext = '<span class="errormandatory">'.$answertext.'</span>';
                }
            }

            // Get array_filter stuff
            list($htmltbody2, $hiddenfield)=return_array_filter_strings($ia, $qidattributes, $thissurvey, $ansrow, $myfname, $trbc, $myfname);

            $answer .= $htmltbody2;

            if (strpos($answertext,'|')) {$answertext=substr($answertext,0, strpos($answertext,'|'));}

            $trbc = alternation($trbc , 'row');

            $answer .= "<tr class=\"$trbc\">\n"
            . "\t<th class=\"answertext\" width=\"$answerwidth%\">\n"
            . "$answertext\n"
            . $hiddenfield
            . "<input type=\"hidden\" name=\"java$myfname\" id=\"java$myfname\" value=\"";
            if (isset($_SESSION[$myfname]))
            {
                $answer .= $_SESSION[$myfname];
            }
            $answer .= "\" />\n\t</th>\n";
            $first_hidden_field = '';
            $thiskey=0;
            foreach ($labelcode as $ld)
            {

                if ($checkboxlayout == false)
                {
                    $myfname2=$myfname."_$ld";
                    if(isset($_SESSION[$myfname2]))
                    {
                        $myfname2_java_value = " value=\"$_SESSION[$myfname2]\" ";
                    }
                    else
                    {
                        $myfname2_java_value = "";
                    }
                    $answer .= "\t<td class=\"answer_cell_00$ld\">\n"
                    . "<label for=\"answer{$myfname2}\">\n"
                    . "\t<input type=\"hidden\" name=\"java{$myfname2}\" id=\"java{$myfname2}\" $myfname2_java_value />\n";

                    if($inputboxlayout == false) {
                        $answer .= "\t<select class=\"multiflexiselect\" name=\"$myfname2\" id=\"answer{$myfname2}\" title=\""
                        . html_escape($labelans[$thiskey]).'"'
                        . " onchange=\"$checkconditionFunction(this.value, this.name, this.type)\">\n"
                        . "<option value=\"\">".$clang->gT('...')."</option>\n";

                        for($ii=$minvalue; ($reverse? $ii>=$maxvalue:$ii<=$maxvalue); $ii+=$stepvalue) {
                            $answer .= "<option value=\"$ii\"";
                            if(isset($_SESSION[$myfname2]) && $_SESSION[$myfname2] == $ii) {
                                $answer .= SELECTED;
                            }
                            $answer .= ">$ii</option>\n";
                        }
                        $answer .= "\t</select>\n";
                    } elseif ($inputboxlayout == true)
                    {
                        $sSeperator = getRadixPointData($thissurvey['surveyls_numberformat']);
                        $sSeperator = $sSeperator['seperator'];
                        $answer .= "\t<input type='text' class=\"multiflexitext $kpclass\" name=\"$myfname2\" id=\"answer{$myfname2}\" maxlength=\"{$maxsize}\" size=5 title=\""
                        . html_escape($labelans[$thiskey]).'"'
                        . " onchange=\"$checkconditionFunction(this.value, this.name, this.type)\" onkeypress=\"return goodchars(event,'0123456789$sSeperator')\""
                        . " value=\"";
                        if(isset($_SESSION[$myfname2]) && $_SESSION[$myfname2]) {
                            $answer .= $_SESSION[$myfname2];
                        }
                        $answer .= "\" />\n";
                    }
                    $answer .= "</label>\n"
                    . "\t</td>\n";

                    $inputnames[]=$myfname2;
                    $thiskey++;
                }
                else
                {
                    $myfname2=$myfname."_$ld";
                    if(isset($_SESSION[$myfname2]) && $_SESSION[$myfname2] == '1')
                    {
                        $myvalue = '1';
                        $setmyvalue = CHECKED;
                    }
                    else
                    {
                        $myvalue = '0';
                        $setmyvalue = '';
                    }
                    $answer .= "\t<td class=\"answer_cell_00$ld\">\n"
                    //					. "<label for=\"answer{$myfname2}\">\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\" 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,'answer{$myfname2}',aelt.type);"
                    . " } else {"
                    . "  aelt.value=0;jelt.value=0;$checkconditionFunction(0,'answer{$myfname2}',aelt.type);"
                    . " }; return true;\" "
                    //					. " onchange=\"checkconditions(this.value, this.name, this.type)\" "
                    . " />\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\t</tbody>";
            //IF a MULTIPLE of flexi-redisplay figure, repeat the headings
            $fn++;
        }
        $answer .= "\n</table>\n";
    }
    else
    {
        $answer = "\n<p class=\"error\">".$clang->gT("Error: There are no answer options for this question and/or they don't exist in this language.")."</p>\n";
        $inputnames = '';
    }
    return array($answer, $inputnames);
}
/**
* 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.
*
* @returns  $totalquestions Total number of questions in the survey
*
*/
function buildsurveysession()
{
    global $thissurvey, $secerror, $clienttoken, $databasetype;
    global $tokensexist, $thistpl;
    global $surveyid, $dbprefix, $connect;
    global $register_errormsg, $clang;
    global $totalBoilerplatequestions;
    global $templang, $move, $rooturl, $publicurl;
    if (!isset($templang) || $templang == '') {
        $templang = $thissurvey['language'];
    }
    $totalBoilerplatequestions = 0;
    $loadsecurity = returnglobal('loadsecurity');
    // NO TOKEN REQUIRED BUT CAPTCHA ENABLED FOR SURVEY ACCESS
    if ($tokensexist == 0 && captcha_enabled('surveyaccessscreen', $thissurvey['usecaptcha'])) {
        // IF CAPTCHA ANSWER IS NOT CORRECT OR NOT SET
        if (!isset($loadsecurity) || !isset($_SESSION['secanswer']) || $loadsecurity != $_SESSION['secanswer']) {
            sendcacheheaders();
            doHeader();
            // No or bad answer to required security question
            echo templatereplace(file_get_contents("{$thistpl}/startpage.pstpl"));
            //echo makedropdownlist();
            echo templatereplace(file_get_contents("{$thistpl}/survey.pstpl"));
            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>\n\t\t\t        <form class='captcha' method='get' action='{$publicurl}/index.php'>\n\t\t\t        <table align='center'>\n\t\t\t\t        <tr>\n\t\t\t\t\t        <td align='right' valign='middle'>\n\t\t\t\t\t        <input type='hidden' name='sid' value='" . $surveyid . "' id='sid' />\n\t\t\t\t\t        <input type='hidden' name='lang' value='" . $templang . "' 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\t\t\t\t\t\t<input type='hidden' name='loadall' value='" . htmlspecialchars($_GET['loadall']) . "' id='loadall' />\n\t\t\t\t\t\t<input type='hidden' name='scid' value='" . returnglobal('scid') . "' id='scid' />\n\t\t\t\t\t\t<input type='hidden' name='loadname' value='" . htmlspecialchars($_GET['loadname']) . "' id='loadname' />\n\t\t\t\t\t\t<input type='hidden' name='loadpass' value='" . htmlspecialchars($_GET['loadpass']) . "' id='loadpass' />";
            }
            echo "\n\t\t\t\t        </td>\n\t\t\t        </tr>";
            if (function_exists("ImageCreate") && captcha_enabled('surveyaccessscreen', $thissurvey['usecaptcha'])) {
                echo "<tr>\n\t\t\t\t                <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='{$rooturl}/verification.php?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\t\t\t\t                </td>\n\t\t\t                </tr>";
            }
            echo "<tr><td colspan='2' align='center'><input class='submit' type='submit' value='" . $clang->gT("Continue") . "' /></td></tr>\n\t\t        </table>\n\t\t        </form>";
            echo templatereplace(file_get_contents("{$thistpl}/endpage.pstpl"));
            doFooter();
            exit;
        }
    }
    //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 && !returnglobal('token')) {
        if ($thissurvey['nokeyboard'] == 'Y') {
            vIncludeKeypad();
            $kpclass = "text-keypad";
        } else {
            $kpclass = "";
        }
        // DISPLAY REGISTER-PAGE if needed
        // DISPLAY CAPTCHA if needed
        sendcacheheaders();
        doHeader();
        echo templatereplace(file_get_contents("{$thistpl}/startpage.pstpl"));
        //echo makedropdownlist();
        echo templatereplace(file_get_contents("{$thistpl}/survey.pstpl"));
        if (isset($thissurvey) && $thissurvey['allowregister'] == "Y") {
            echo templatereplace(file_get_contents("{$thistpl}/register.pstpl"));
        } else {
            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>\n\t        <form id='tokenform' method='get' action='{$publicurl}/index.php'>\n                <ul>\n                <li>\n            <label for='token'>" . $clang->gT("Token") . "</label><input class='text {$kpclass}' id='token' type='text' name='token' />";
            echo "<input type='hidden' name='sid' value='" . $surveyid . "' id='sid' />\n\t\t\t\t<input type='hidden' name='lang' value='" . $templang . "' 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\t\t\t\t\t<input type='hidden' name='loadall' value='" . htmlspecialchars($_GET['loadall']) . "' id='loadall' />\n\t\t\t\t\t<input type='hidden' name='scid' value='" . returnglobal('scid') . "' id='scid' />\n\t\t\t\t\t<input type='hidden' name='loadname' value='" . htmlspecialchars($_GET['loadname']) . "' id='loadname' />\n\t\t\t\t\t<input type='hidden' name='loadpass' value='" . htmlspecialchars($_GET['loadpass']) . "' id='loadpass' />";
            }
            echo "</li>";
            if (function_exists("ImageCreate") && captcha_enabled('surveyaccessscreen', $thissurvey['usecaptcha'])) {
                echo "<li>\n\t\t\t                <label for='captchaimage'>" . $clang->gT("Security Question") . "</label><img id='captchaimage' src='{$rooturl}/verification.php?sid={$surveyid}' alt='captcha' /><input type='text' size='5' maxlength='3' name='loadsecurity' value='' />\n\t\t                  </li>";
            }
            echo "<li>\n                        <input class='submit' type='submit' value='" . $clang->gT("Continue") . "' />\n                      </li>\n            </ul>\n\t        </form></div>";
        }
        echo templatereplace(file_get_contents("{$thistpl}/endpage.pstpl"));
        doFooter();
        exit;
    } elseif ($tokensexist == 1 && returnglobal('token') && !captcha_enabled('surveyaccessscreen', $thissurvey['usecaptcha'])) {
        //check if tokens actually haven't been already used
        $areTokensUsed = usedTokens(db_quote(trim(strip_tags(returnglobal('token')))));
        //check if token actually does exist
        // check also if it is allowed to change survey after completion
        if ($thissurvey['alloweditaftercompletion'] == 'Y') {
            $tkquery = "SELECT COUNT(*) FROM " . db_table_name('tokens_' . $surveyid) . " WHERE token='" . db_quote(trim(strip_tags(returnglobal('token')))) . "' ";
        } else {
            $tkquery = "SELECT COUNT(*) FROM " . db_table_name('tokens_' . $surveyid) . " WHERE token='" . db_quote(trim(strip_tags(returnglobal('token')))) . "' AND (completed = 'N' or completed='')";
        }
        $tkresult = db_execute_num($tkquery);
        //Checked
        list($tkexist) = $tkresult->FetchRow();
        if (!$tkexist || $areTokensUsed && $thissurvey['alloweditaftercompletion'] != 'Y') {
            //TOKEN DOESN'T EXIST OR HAS ALREADY BEEN USED. EXPLAIN PROBLEM AND EXIT
            killSession();
            sendcacheheaders();
            doHeader();
            echo templatereplace(file_get_contents("{$thistpl}/startpage.pstpl"));
            echo templatereplace(file_get_contents("{$thistpl}/survey.pstpl"));
            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 />\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("{$thistpl}/endpage.pstpl"));
            doFooter();
            exit;
        }
    } elseif ($tokensexist == 1 && returnglobal('token') && captcha_enabled('surveyaccessscreen', $thissurvey['usecaptcha'])) {
        // IF CAPTCHA ANSWER IS CORRECT
        if (isset($loadsecurity) && isset($_SESSION['secanswer']) && $loadsecurity == $_SESSION['secanswer']) {
            //check if tokens actually haven't been already used
            $areTokensUsed = usedTokens(db_quote(trim(strip_tags(returnglobal('token')))));
            //check if token actually does exist
            if ($thissurvey['alloweditaftercompletion'] == 'Y') {
                $tkquery = "SELECT COUNT(*) FROM " . db_table_name('tokens_' . $surveyid) . " WHERE token='" . db_quote(trim(sanitize_xss_string(strip_tags(returnglobal('token'))))) . "'";
            } else {
                $tkquery = "SELECT COUNT(*) FROM " . db_table_name('tokens_' . $surveyid) . " WHERE token='" . db_quote(trim(sanitize_xss_string(strip_tags(returnglobal('token'))))) . "' AND (completed = 'N' or completed='')";
            }
            $tkresult = db_execute_num($tkquery);
            //Checked
            list($tkexist) = $tkresult->FetchRow();
            if (!$tkexist || $areTokensUsed && $thissurvey['alloweditaftercompletion'] != 'Y') {
                sendcacheheaders();
                doHeader();
                //TOKEN DOESN'T EXIST OR HAS ALREADY BEEN USED. EXPLAIN PROBLEM AND EXIT
                echo templatereplace(file_get_contents("{$thistpl}/startpage.pstpl"));
                echo templatereplace(file_get_contents("{$thistpl}/survey.pstpl"));
                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/>\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("{$thistpl}/endpage.pstpl"));
                doFooter();
                exit;
            }
        } else {
            if (!isset($move) || is_null($move)) {
                $gettoken = $clienttoken;
                sendcacheheaders();
                doHeader();
                // No or bad answer to required security question
                echo templatereplace(file_get_contents("{$thistpl}/startpage.pstpl"));
                echo templatereplace(file_get_contents("{$thistpl}/survey.pstpl"));
                // 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("{$thistpl}/register.pstpl"));
                } 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\t\t\t            <form id='tokenform' method='get' action='{$publicurl}/index.php'>\n                        <ul>\n                        <li>\n\t\t\t\t\t        <input type='hidden' name='sid' value='" . $surveyid . "' id='sid' />\n\t\t\t\t\t\t    <input type='hidden' name='lang' value='" . $templang . "' 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\t\t\t\t\t\t        <input type='hidden' name='scid' value='" . returnglobal('scid') . "' id='scid' />\n\t\t\t\t\t\t        <input type='hidden' name='loadname' value='" . htmlspecialchars($_GET['loadname']) . "' id='loadname' />\n\t\t\t\t\t\t        <input type='hidden' name='loadpass' value='" . htmlspecialchars($_GET['loadpass']) . "' id='loadpass' />";
                        }
                        echo '<label for="token">' . $clang->gT("Token") . "</label><input class='text' type='text' id='token' name='token'></li>";
                    } else {
                        echo $clang->gT("Please confirm the token by answering the security question below and click continue.") . "</p>\n\t\t\t            <form id='tokenform' method='get' action='{$publicurl}/index.php'>\n                        <ul>\n\t\t\t            <li>\n\t\t\t\t\t            <input type='hidden' name='sid' value='" . $surveyid . "' id='sid' />\n\t\t\t\t\t\t        <input type='hidden' name='lang' value='" . $templang . "' 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') . "' 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") && captcha_enabled('surveyaccessscreen', $thissurvey['usecaptcha'])) {
                        echo "<li>\n                            <label for='captchaimage'>" . $clang->gT("Security Question") . "</label><img id='captchaimage' src='{$rooturl}/verification.php?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\t\t                </ul>\n\t\t                </form>\n\t\t                </id>";
                }
                echo '</div>' . templatereplace(file_get_contents("{$thistpl}/endpage.pstpl"));
                doFooter();
                unset($_SESSION['srid']);
                exit;
            }
        }
    }
    //RESET ALL THE SESSION VARIABLES AND START AGAIN
    unset($_SESSION['grouplist']);
    unset($_SESSION['fieldarray']);
    unset($_SESSION['insertarray']);
    unset($_SESSION['thistoken']);
    unset($_SESSION['fieldnamesInfo']);
    $_SESSION['fieldnamesInfo'] = array();
    //RL: multilingual support
    if (isset($_GET['token']) && db_tables_exist($dbprefix . 'tokens_' . $surveyid)) {
        //get language from token (if one exists)
        $tkquery2 = "SELECT * FROM " . db_table_name('tokens_' . $surveyid) . " WHERE token='" . db_quote($clienttoken) . "' AND (completed = 'N' or completed='')";
        //echo $tkquery2;
        $result = db_execute_assoc($tkquery2) or safe_die("Couldn't get tokens<br />{$tkquery}<br />" . $connect->ErrorMsg());
        //Checked
        while ($rw = $result->FetchRow()) {
            $tklanguage = $rw['language'];
        }
    }
    if (returnglobal('lang')) {
        $language_to_set = returnglobal('lang');
    } elseif (isset($tklanguage)) {
        $language_to_set = $tklanguage;
    } else {
        $language_to_set = $thissurvey['language'];
    }
    if (!isset($_SESSION['s_lang'])) {
        SetSurveyLanguage($surveyid, $language_to_set);
    }
    UpdateSessionGroupList($_SESSION['s_lang']);
    // Optimized Query
    // Change query to use sub-select to see if conditions exist.
    $query = "SELECT " . db_table_name('questions') . ".*, " . db_table_name('groups') . ".*,\n" . " (SELECT count(1) FROM " . db_table_name('conditions') . "\n" . " WHERE " . db_table_name('questions') . ".qid = " . db_table_name('conditions') . ".qid) AS hasconditions,\n" . " (SELECT count(1) FROM " . db_table_name('conditions') . "\n" . " WHERE " . db_table_name('questions') . ".qid = " . db_table_name('conditions') . ".cqid) AS usedinconditions\n" . " FROM " . db_table_name('groups') . " INNER JOIN " . db_table_name('questions') . " ON " . db_table_name('groups') . ".gid = " . db_table_name('questions') . ".gid\n" . " WHERE " . db_table_name('questions') . ".sid=" . $surveyid . "\n" . " AND " . db_table_name('groups') . ".language='" . $_SESSION['s_lang'] . "'\n" . " AND " . db_table_name('questions') . ".language='" . $_SESSION['s_lang'] . "'\n" . " AND " . db_table_name('questions') . ".parent_qid=0\n" . " ORDER BY " . db_table_name('groups') . ".group_order," . db_table_name('questions') . ".question_order";
    //var_dump($_SESSION);
    $result = db_execute_assoc($query);
    //Checked
    $arows = $result->GetRows();
    $totalquestions = $result->RecordCount();
    //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['totalsteps'] = 1;
            break;
        case "G":
            if (isset($_SESSION['grouplist'])) {
                $_SESSION['totalsteps'] = count($_SESSION['grouplist']);
            }
            break;
        case "S":
            $_SESSION['totalsteps'] = $totalquestions;
    }
    if ($totalquestions == "0") {
        sendcacheheaders();
        doHeader();
        echo templatereplace(file_get_contents("{$thistpl}/startpage.pstpl"));
        echo templatereplace(file_get_contents("{$thistpl}/survey.pstpl"));
        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("{$thistpl}/endpage.pstpl"));
        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..
    $_SESSION['token'] = $clienttoken;
    if ($thissurvey['anonymized'] == "N") {
        $_SESSION['insertarray'][] = "token";
    }
    if ($tokensexist == 1 && $thissurvey['anonymized'] == "N" && db_tables_exist($dbprefix . 'tokens_' . $surveyid)) {
        //Gather survey data for "non anonymous" surveys, for use in presenting questions
        $_SESSION['thistoken'] = getTokenData($surveyid, $clienttoken);
    }
    $qtypes = getqtypelist('', 'array');
    $fieldmap = createFieldMap($surveyid, 'full', false, false, $_SESSION['s_lang']);
    // Randomization Groups
    // Find all defined randomization groups through question attribute values
    $randomGroups = array();
    if ($databasetype == 'odbc_mssql' || $databasetype == 'odbtp' || $databasetype == 'mssql_n' || $databasetype == 'mssqlnative') {
        $rgquery = "SELECT attr.qid, CAST(value as varchar(255)) FROM " . db_table_name('question_attributes') . " as attr right join " . db_table_name('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 " . db_table_name('question_attributes') . " as attr right join " . db_table_name('questions') . " as quests on attr.qid=quests.qid WHERE attribute='random_group' and value <> '' and sid={$surveyid} GROUP BY attr.qid, value";
    }
    $rgresult = db_execute_assoc($rgquery);
    while ($rgrow = $rgresult->FetchRow()) {
        // 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) {
        $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
        while (list($fieldkey, $fieldval) = each($fieldmap)) {
            $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
                    $oldQuestFlip = array_flip($oldQuestOrder[$gkey]);
                    $qfieldmap = createFieldMap($surveyid, 'full', true, $newQuestOrder[$gkey][$oldQuestFlip[$fieldval['qid']]], $_SESSION['s_lang']);
                    unset($qfieldmap['id']);
                    unset($qfieldmap['submitdate']);
                    unset($qfieldmap['lastpage']);
                    unset($qfieldmap['lastpage']);
                    unset($qfieldmap['token']);
                    foreach ($qfieldmap as $tkey => $tval) {
                        // Assign the swapped question (Might be more than one field)
                        $tval['random_gid'] = $fieldval['gid'];
                        //$tval['gid'] = $fieldval['gid'];
                        $copyFieldMap[$tkey] = $tval;
                    }
                    $found = 1;
                    break;
                } else {
                    $found = 2;
                }
            }
            if ($found == 2) {
                $copyFieldMap[$fieldkey] = $fieldval;
            }
            reset($randomGroups);
        }
        $fieldmap = $copyFieldMap;
    }
    //die(print_r($fieldmap));
    $_SESSION['fieldmap'] = $fieldmap;
    foreach ($fieldmap as $field) {
        if (isset($field['qid']) && $field['qid'] != '') {
            $_SESSION['fieldnamesInfo'][$field['fieldname']] = $field['sid'] . 'X' . $field['gid'] . 'X' . $field['qid'];
            $_SESSION['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['fieldarray'][$field['sid'] . 'X' . $field['gid'] . 'X' . $field['qid']])) {
                $_SESSION['fieldarray'][$field['sid'] . 'X' . $field['gid'] . 'X' . $field['qid']] = array($field['qid'], $field['sid'] . 'X' . $field['gid'] . 'X' . $field['qid'], $field['title'], $field['question'], $field['type'], $field['gid'], $field['mandatory'], $field['hasconditions'], $field['usedinconditions']);
            }
            if (isset($field['random_gid'])) {
                $_SESSION['fieldarray'][$field['sid'] . 'X' . $field['gid'] . 'X' . $field['qid']][10] = $field['random_gid'];
            }
        }
    }
    // Prefill question/answer from defaultvalues
    foreach ($fieldmap as $field) {
        if (isset($field['defaultvalue'])) {
            $_SESSION[$field['fieldname']] = $field['defaultvalue'];
        }
    }
    // Prefill questions/answers from command line params
    if (isset($_SESSION['insertarray'])) {
        foreach ($_SESSION['insertarray'] as $field) {
            if (isset($_GET[$field]) && $field != 'token') {
                $_SESSION[$field] = $_GET[$field];
            }
        }
    }
    if (isset($_SESSION['fieldarray'])) {
        $_SESSION['fieldarray'] = array_values($_SESSION['fieldarray']);
    }
    // Check if the current survey language is set - if not set it
    // this way it can be changed later (for example by a special question type)
    //Check if a passthru label and value have been included in the query url
    if (isset($_GET['passthru']) && $_GET['passthru'] != "") {
        if (isset($_GET[$_GET['passthru']]) && $_GET[$_GET['passthru']] != "") {
            $_SESSION['passthrulabel'] = $_GET['passthru'];
            $_SESSION['passthruvalue'] = $_GET[$_GET['passthru']];
        }
    } elseif (isset($_SERVER['QUERY_STRING'])) {
        $_SESSION['ls_initialquerystr'] = $_SERVER['QUERY_STRING'];
    }
    // END NEW
    // Fix totalquestions by substracting Test Display questions
    $sNoOfTextDisplayQuestions = (int) $connect->GetOne("SELECT count(*)\n" . " FROM " . db_table_name('questions') . " WHERE type='X'\n" . " AND sid={$surveyid}" . " AND language='" . $_SESSION['s_lang'] . "'" . " AND parent_qid=0");
    $_SESSION['therearexquestions'] = $totalquestions - $sNoOfTextDisplayQuestions;
    // must be global for THEREAREXQUESTIONS replacement field to work
    return $totalquestions - $sNoOfTextDisplayQuestions;
}