Esempio n. 1
0
    function action()
    {
        global $surveyid;
        global $thissurvey, $thisstep;
        global $clienttoken, $tokensexist, $token;
        global $clang;
        $clang = Yii::app()->lang;
        @ini_set('session.gc_maxlifetime', Yii::app()->getConfig('iSessionExpirationTime'));
        $this->_loadRequiredHelpersAndLibraries();
        $param = $this->_getParameters(func_get_args(), $_POST);
        $surveyid = $param['sid'];
        Yii::app()->setConfig('surveyID', $surveyid);
        $thisstep = $param['thisstep'];
        $move = $param['move'];
        $clienttoken = $param['token'];
        $standardtemplaterootdir = Yii::app()->getConfig('standardtemplaterootdir');
        // unused vars in this method (used in methods using compacted method vars)
        @($loadname = $param['loadname']);
        @($loadpass = $param['loadpass']);
        $sitename = Yii::app()->getConfig('sitename');
        if (isset($param['newtest']) && $param['newtest'] == "Y") {
            killSurveySession($surveyid);
        }
        list($surveyExists, $isSurveyActive) = $this->_surveyExistsAndIsActive($surveyid);
        // collect all data in this method to pass on later
        $redata = compact(array_keys(get_defined_vars()));
        $clang = $this->_loadLimesurveyLang($surveyid);
        if ($this->_isClientTokenDifferentFromSessionToken($clienttoken, $surveyid)) {
            $asMessage = array($clang->gT('Token mismatch'), $clang->gT('The token you provided doesn\'t match the one in your session.'), $clang->gT('Please wait to begin with a new session.'));
            $this->_createNewUserSessionAndRedirect($surveyid, $redata, __LINE__, $asMessage);
        }
        if ($this->_isSurveyFinished($surveyid)) {
            $asMessage = array($clang->gT('Previous session is set to be finished.'), $clang->gT('Your browser reports that it was used previously to answer this survey. We are resetting the session so that you can start from the beginning.'), $clang->gT('Please wait to begin with a new session.'));
            $this->_createNewUserSessionAndRedirect($surveyid, $redata, __LINE__, $asMessage);
        }
        if ($this->_isPreviewAction($param) && !$this->_canUserPreviewSurvey($surveyid)) {
            $asMessage = array($clang->gT('Error'), $clang->gT('We are sorry but you don\'t have permissions to do this.'));
            $this->_niceExit($redata, __LINE__, null, $asMessage);
        }
        if ($this->_surveyCantBeViewedWithCurrentPreviewAccess($surveyid, $isSurveyActive, $surveyExists)) {
            $bPreviewRight = $this->_userHasPreviewAccessSession($surveyid);
            if ($bPreviewRight === false) {
                $asMessage = array($clang->gT("Error"), $clang->gT("We are sorry but you don't have permissions to do this."), sprintf($clang->gT("Please contact %s ( %s ) for further assistance."), $thissurvey['adminname'], $thissurvey['adminemail']));
                $this->_niceExit($redata, __LINE__, null, $asMessage);
            }
        }
        // TODO can this be moved to the top?
        // (Used to be global, used in ExpressionManager, merged into amVars. If not filled in === '')
        // can this be added in the first computation of $redata?
        if (isset($_SESSION['survey_' . $surveyid]['srid'])) {
            $saved_id = $_SESSION['survey_' . $surveyid]['srid'];
        }
        // recompute $redata since $saved_id used to be a global
        $redata = compact(array_keys(get_defined_vars()));
        /*if ( $this->_didSessionTimeOut() )
          {
          // @TODO is this still required ?
          $asMessage = array(
          $clang->gT("Error"),
          $clang->gT("We are sorry but your session has expired."),
          $clang->gT("Either you have been inactive for too long, you have cookies disabled for your browser, or there were problems with your connection."),
          sprintf($clang->gT("Please contact %s ( %s ) for further assistance."),$thissurvey['adminname'],$thissurvey['adminemail'])
          );
          $this->_niceExit($redata, __LINE__, null, $asMessage);
          };*/
        // Set the language of the survey, either from POST, GET parameter of session var
        if (!empty($_REQUEST['lang'])) {
            $sTempLanguage = sanitize_languagecode($_REQUEST['lang']);
        } elseif (!empty($param['lang'])) {
            $sTempLanguage = sanitize_languagecode($param['lang']);
        } elseif (isset($_SESSION['survey_' . $surveyid]['s_lang'])) {
            $sTempLanguage = $_SESSION['survey_' . $surveyid]['s_lang'];
        } else {
            $sTempLanguage = '';
        }
        //CHECK FOR REQUIRED INFORMATION (sid)
        if ($surveyid && $surveyExists) {
            LimeExpressionManager::SetSurveyId($surveyid);
            // must be called early - it clears internal cache if a new survey is being used
            $clang = SetSurveyLanguage($surveyid, $sTempLanguage);
            UpdateSessionGroupList($surveyid, $sTempLanguage);
            // to refresh the language strings in the group list session variable
            UpdateFieldArray();
            // to refresh question titles and question text
        } else {
            if (!is_null($param['lang'])) {
                $sDisplayLanguage = $param['lang'];
            } else {
                $sDisplayLanguage = Yii::app()->getConfig('defaultlang');
            }
            $clang = $this->_loadLimesurveyLang($sDisplayLanguage);
            $languagechanger = makeLanguageChanger($sDisplayLanguage);
            //Find out if there are any publicly available surveys
            $query = "SELECT sid, surveyls_title, publicstatistics, language\n            FROM {{surveys}}\n            INNER JOIN {{surveys_languagesettings}}\n            ON ( surveyls_survey_id = sid  )\n            AND (surveyls_language=language)\n            WHERE\n            active='Y'\n            AND listpublic='Y'\n            AND ((expires >= '" . date("Y-m-d H:i") . "') OR (expires is null))\n            AND ((startdate <= '" . date("Y-m-d H:i") . "') OR (startdate is null))\n            ORDER BY surveyls_title";
            $result = dbExecuteAssoc($query, false, true) or safeDie("Could not connect to database. If you try to install LimeSurvey please refer to the <a href='http://docs.limesurvey.org'>installation docs</a> and/or contact the system administrator of this webpage.");
            //Checked
            $list = array();
            foreach ($result->readAll() as $rows) {
                $querylang = "SELECT surveyls_title\n                FROM {{surveys_languagesettings}}\n                WHERE surveyls_survey_id={$rows['sid']}\n                AND surveyls_language='{$sDisplayLanguage}'";
                $resultlang = Yii::app()->db->createCommand($querylang)->queryRow();
                if ($resultlang['surveyls_title']) {
                    $rows['surveyls_title'] = $resultlang['surveyls_title'];
                    $langtag = "";
                } else {
                    $langtag = "lang=\"{$rows['language']}\"";
                }
                $link = "<li><a href='" . $this->getController()->createUrl('/survey/index/sid/' . $rows['sid']);
                if (isset($param['lang']) && $langtag == "") {
                    $link .= "/lang-" . sanitize_languagecode($param['lang']);
                }
                $link .= "' {$langtag} class='surveytitle'>" . $rows['surveyls_title'] . "</a>\n";
                if ($rows['publicstatistics'] == 'Y') {
                    $link .= "<a href='" . $this->getController()->createUrl("/statistics_user/action/surveyid/" . $rows['sid']) . "/language/" . $sDisplayLanguage . "'>(" . $clang->gT('View statistics') . ")</a>";
                }
                $link .= "</li>\n";
                $list[] = $link;
            }
            //Check for inactive surveys which allow public registration.
            // TODO add a new template replace {SURVEYREGISTERLIST} ?
            $squery = "SELECT sid, surveyls_title, publicstatistics, language\n            FROM {{surveys}}\n            INNER JOIN {{surveys_languagesettings}}\n            ON (surveyls_survey_id = sid)\n            AND (surveyls_language=language)\n            WHERE allowregister='Y'\n            AND active='Y'\n            AND listpublic='Y'\n            AND ((expires >= '" . date("Y-m-d H:i") . "') OR (expires is null))\n            AND (startdate >= '" . date("Y-m-d H:i") . "')\n            ORDER BY surveyls_title";
            $sresult = dbExecuteAssoc($squery) or safeDie("Couldn't execute {$squery}");
            $aRows = $sresult->readAll();
            if (count($aRows) > 0) {
                $list[] = "</ul>" . " <div class=\"survey-list-heading\">" . $clang->gT("Following survey(s) are not yet active but you can register for them.") . "</div>" . " <ul>";
                // TODO give it to template
                foreach ($aRows as $rows) {
                    $querylang = "SELECT surveyls_title\n                    FROM {{surveys_languagesettings}}\n                    WHERE surveyls_survey_id={$rows['sid']}\n                    AND surveyls_language='{$sDisplayLanguage}'";
                    $resultlang = Yii::app()->db->createCommand($querylang)->queryRow();
                    if ($resultlang['surveyls_title']) {
                        $rows['surveyls_title'] = $resultlang['surveyls_title'];
                        $langtag = "";
                    } else {
                        $langtag = "lang=\"{$rows['language']}\"";
                    }
                    $link = "<li><a href=\"#\" id='inactivesurvey' onclick = 'sendreq(" . $rows['sid'] . ");' ";
                    //$link = "<li><a href=\"#\" id='inactivesurvey' onclick = 'convertGETtoPOST(".$this->getController()->createUrl('survey/send/')."?sid={$rows['sid']}&amp;)sendreq(".$rows['sid'].",".$rows['startdate'].",".$rows['expires'].");' ";
                    $link .= " {$langtag} class='surveytitle'>" . $rows['surveyls_title'] . "</a>\n";
                    $link .= "</li><div id='regform'></div>\n";
                    $list[] = $link;
                }
            }
            if (count($list) < 1) {
                $list[] = "<li class='surveytitle'>" . $clang->gT("No available surveys") . "</li>";
            }
            if (!$surveyid) {
                $thissurvey['name'] = Yii::app()->getConfig("sitename");
                $nosid = $clang->gT("You have not provided a survey identification number");
            } else {
                $thissurvey['name'] = $clang->gT("The survey identification number is invalid");
                $nosid = $clang->gT("The survey identification number is invalid");
            }
            $surveylist = array("nosid" => $nosid, "contact" => sprintf($clang->gT("Please contact %s ( %s ) for further assistance."), Yii::app()->getConfig("siteadminname"), encodeEmail(Yii::app()->getConfig("siteadminemail"))), "listheading" => $clang->gT("The following surveys are available:"), "list" => implode("\n", $list));
            $data['thissurvey'] = $thissurvey;
            //$data['privacy'] = $privacy;
            $data['surveylist'] = $surveylist;
            $data['surveyid'] = $surveyid;
            $data['templatedir'] = getTemplatePath(Yii::app()->getConfig("defaulttemplate"));
            $data['templateurl'] = getTemplateURL(Yii::app()->getConfig("defaulttemplate")) . "/";
            $data['templatename'] = Yii::app()->getConfig("defaulttemplate");
            $data['sitename'] = Yii::app()->getConfig("sitename");
            $data['languagechanger'] = $languagechanger;
            //A nice exit
            sendCacheHeaders();
            doHeader();
            $this->_printTemplateContent(getTemplatePath(Yii::app()->getConfig("defaulttemplate")) . "/startpage.pstpl", $data, __LINE__);
            $this->_printTemplateContent(getTemplatePath(Yii::app()->getConfig("defaulttemplate")) . "/surveylist.pstpl", $data, __LINE__);
            echo '<script type="text/javascript" >
            function sendreq(surveyid)
            {

            $.ajax({
            type: "GET",
            url: "' . $this->getController()->createUrl("/register/ajaxregisterform/surveyid") . '/" + surveyid,
            }).done(function(msg) {
            document.getElementById("regform").innerHTML = msg;
            });
            }
            </script>';
            $this->_printTemplateContent(getTemplatePath(Yii::app()->getConfig("defaulttemplate")) . "/endpage.pstpl", $data, __LINE__);
            doFooter();
            exit;
        }
        // Get token
        if (!isset($token)) {
            $token = $clienttoken;
        }
        //GET BASIC INFORMATION ABOUT THIS SURVEY
        $thissurvey = getSurveyInfo($surveyid, $_SESSION['survey_' . $surveyid]['s_lang']);
        //SEE IF SURVEY USES TOKENS
        if ($surveyExists == 1 && tableExists('{{tokens_' . $thissurvey['sid'] . '}}')) {
            $tokensexist = 1;
        } else {
            $tokensexist = 0;
            unset($_POST['token']);
            unset($param['token']);
            unset($token);
            unset($clienttoken);
        }
        //SET THE TEMPLATE DIRECTORY
        $thistpl = getTemplatePath($thissurvey['templatedir']);
        $timeadjust = Yii::app()->getConfig("timeadjust");
        //MAKE SURE SURVEY HASN'T EXPIRED
        if ($thissurvey['expiry'] != '' and dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust) > $thissurvey['expiry'] && $thissurvey['active'] != 'N') {
            $redata = compact(array_keys(get_defined_vars()));
            $asMessage = array($clang->gT("Error"), $clang->gT("This survey is no longer available."), sprintf($clang->gT("Please contact %s ( %s ) for further assistance."), $thissurvey['adminname'], $thissurvey['adminemail']));
            $this->_niceExit($redata, __LINE__, $thistpl, $asMessage);
        }
        //MAKE SURE SURVEY IS ALREADY VALID
        if ($thissurvey['startdate'] != '' and dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust) < $thissurvey['startdate'] && $thissurvey['active'] != 'N') {
            $redata = compact(array_keys(get_defined_vars()));
            $asMessage = array($clang->gT("Error"), $clang->gT("This survey is not yet started."), sprintf($clang->gT("Please contact %s ( %s ) for further assistance."), $thissurvey['adminname'], $thissurvey['adminemail']));
            $this->_niceExit($redata, __LINE__, $thistpl, $asMessage);
        }
        //CHECK FOR PREVIOUSLY COMPLETED COOKIE
        //If cookies are being used, and this survey has been completed, a cookie called "PHPSID[sid]STATUS" will exist (ie: SID6STATUS) and will have a value of "COMPLETE"
        $sCookieName = "LS_" . $surveyid . "_STATUS";
        if (isset($_COOKIE[$sCookieName]) && $_COOKIE[$sCookieName] == "COMPLETE" && $thissurvey['usecookie'] == "Y" && $tokensexist != 1 && (!isset($param['newtest']) || $param['newtest'] != "Y")) {
            $redata = compact(array_keys(get_defined_vars()));
            $asMessage = array($clang->gT("Error"), $clang->gT("You have already completed this survey."), sprintf($clang->gT("Please contact %s ( %s ) for further assistance."), $thissurvey['adminname'], $thissurvey['adminemail']));
            $this->_niceExit($redata, __LINE__, $thistpl, $asMessage);
        }
        if (isset($_GET['loadall']) && $_GET['loadall'] == "reload") {
            if (returnGlobal('loadname') && returnGlobal('loadpass')) {
                $_POST['loadall'] = "reload";
            }
        }
        //LOAD SAVED SURVEY
        if (isset($_POST['loadall']) && $_POST['loadall'] == "reload") {
            $errormsg = "";
            if (!isset($param['loadname']) || $param['loadname'] == null) {
                $errormsg .= $clang->gT("You did not provide a name") . "<br />\n";
            }
            if (!isset($param['loadpass']) || $param['loadpass'] == null) {
                $errormsg .= $clang->gT("You did not provide a password") . "<br />\n";
            }
            // if security question answer is incorrect
            // Not called if scid is set in GET params (when using email save/reload reminder URL)
            if (function_exists("ImageCreate") && isCaptchaEnabled('saveandloadscreen', $thissurvey['usecaptcha'])) {
                if ((!isset($_POST['loadsecurity']) || !isset($_SESSION['survey_' . $surveyid]['secanswer']) || $_POST['loadsecurity'] != $_SESSION['survey_' . $surveyid]['secanswer']) && !isset($_GET['scid'])) {
                    $errormsg .= $clang->gT("The answer to the security question is incorrect.") . "<br />\n";
                }
            }
            // Load session before loading the values from the saved data
            if (isset($_GET['loadall'])) {
                buildsurveysession($surveyid);
            }
            $_SESSION['survey_' . $surveyid]['holdname'] = $param['loadname'];
            //Session variable used to load answers every page.
            $_SESSION['survey_' . $surveyid]['holdpass'] = $param['loadpass'];
            //Session variable used to load answers every page.
            if ($errormsg == "") {
                loadanswers();
            }
            $move = "movenext";
            if ($errormsg) {
                $_POST['loadall'] = $clang->gT("Load unfinished survey");
            }
        }
        //Allow loading of saved survey
        if (isset($_POST['loadall']) && $_POST['loadall'] == $clang->gT("Load unfinished survey")) {
            $redata = compact(array_keys(get_defined_vars()));
            Yii::import("application.libraries.Load_answers");
            $tmp = new Load_answers();
            $tmp->run($redata);
        }
        //Check if TOKEN is used for EVERY PAGE
        //This function fixes a bug where users able to submit two surveys/votes
        //by checking that the token has not been used at each page displayed.
        // bypass only this check at first page (Step=0) because
        // this check is done in buildsurveysession and error message
        // could be more interresting there (takes into accound captcha if used)
        if ($tokensexist == 1 && isset($token) && $token && isset($_SESSION['survey_' . $surveyid]['step']) && $_SESSION['survey_' . $surveyid]['step'] > 0 && tableExists("tokens_{$surveyid}}}")) {
            //check if tokens actually haven't been already used
            $areTokensUsed = usedTokens(trim(strip_tags(returnGlobal('token'))), $surveyid);
            // check if token actually does exist
            // check also if it is allowed to change survey after completion
            if ($thissurvey['alloweditaftercompletion'] == 'Y') {
                $sQuery = "SELECT * FROM {{tokens_" . $surveyid . "}} WHERE token='" . $token . "'";
            } else {
                $sQuery = "SELECT * FROM {{tokens_" . $surveyid . "}} WHERE token='" . $token . "' AND (completed = 'N' or completed='')";
            }
            $aRow = Yii::app()->db->createCommand($sQuery)->queryRow();
            $tokendata = $aRow;
            if (!$aRow || $areTokensUsed && $thissurvey['alloweditaftercompletion'] != 'Y') {
                sendCacheHeaders();
                doHeader();
                //TOKEN DOESN'T EXIST OR HAS ALREADY BEEN USED. EXPLAIN PROBLEM AND EXIT
                $redata = compact(array_keys(get_defined_vars()));
                $this->_printTemplateContent($thistpl . '/startpage.pstpl', $redata, __LINE__);
                $this->_printTemplateContent($thistpl . '/survey.pstpl', $redata, __LINE__);
                $asMessage = array(null, $clang->gT("This is a controlled survey. You need a valid token to participate."), sprintf($clang->gT("For further information please contact %s"), $thissurvey['adminname'] . " (<a href='mailto:{$thissurvey['adminemail']}'>" . "{$thissurvey['adminemail']}</a>)"));
                $this->_niceExit($redata, __LINE__, $thistpl, $asMessage, true);
            }
        }
        if ($tokensexist == 1 && isset($token) && $token && tableExists("{{tokens_" . $surveyid . "}}")) {
            // check also if it is allowed to change survey after completion
            if ($thissurvey['alloweditaftercompletion'] == 'Y') {
                $tkquery = "SELECT * FROM {{tokens_" . $surveyid . "}} WHERE token='" . $token . "'";
            } else {
                $tkquery = "SELECT * FROM {{tokens_" . $surveyid . "}} WHERE token='" . $token . "' AND (completed = 'N' or completed='')";
            }
            $tkresult = dbExecuteAssoc($tkquery);
            //Checked
            $tokendata = $tkresult->read();
            if (isset($tokendata['validfrom']) && (trim($tokendata['validfrom']) != '' && $tokendata['validfrom'] > dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust)) || isset($tokendata['validuntil']) && (trim($tokendata['validuntil']) != '' && $tokendata['validuntil'] < dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust))) {
                sendCacheHeaders();
                doHeader();
                //TOKEN DOESN'T EXIST OR HAS ALREADY BEEN USED. EXPLAIN PROBLEM AND EXIT
                $redata = compact(array_keys(get_defined_vars()));
                $this->_printTemplateContent($thistpl . '/startpage.pstpl', $redata, __LINE__);
                $this->_printTemplateContent($thistpl . '/survey.pstpl', $redata, __LINE__);
                $asMessage = array(null, $clang->gT("We are sorry but you are not allowed to enter this survey."), $clang->gT("Your token seems to be valid but can be used only during a certain time period."), sprintf($clang->gT("For further information please contact %s"), $thissurvey['adminname'] . " (<a href='mailto:{$thissurvey['adminemail']}'>" . "{$thissurvey['adminemail']}</a>)"));
                $this->_niceExit($redata, __LINE__, $thistpl, $asMessage, true);
            }
        }
        //Clear session and remove the incomplete response if requested.
        if (isset($move) && $move == "clearall") {
            // delete the response but only if not already completed
            $s_lang = $_SESSION['survey_' . $surveyid]['s_lang'];
            if (isset($_SESSION['survey_' . $surveyid]['srid']) && !Survey_dynamic::model($surveyid)->isCompleted($_SESSION['survey_' . $surveyid]['srid'])) {
                // delete the response but only if not already completed
                $result = dbExecuteAssoc('DELETE FROM {{survey_' . $surveyid . '}} WHERE id=' . $_SESSION['survey_' . $surveyid]['srid'] . " AND submitdate IS NULL");
                if ($result->count() > 0) {
                    // Using count() here *should* be okay for MSSQL because it is a delete statement
                    // find out if there are any fuqt questions - checked
                    $fieldmap = createFieldMap($surveyid, 'short', false, false, $s_lang);
                    foreach ($fieldmap as $field) {
                        if ($field['type'] == "|" && !strpos($field['fieldname'], "_filecount")) {
                            if (!isset($qid)) {
                                $qid = array();
                            }
                            $qid[] = $field['fieldname'];
                        }
                    }
                    // if yes, extract the response json to those questions
                    if (isset($qid)) {
                        $query = "SELECT * FROM {{survey_" . $surveyid . "}} WHERE id=" . $_SESSION['survey_' . $surveyid]['srid'];
                        $result = dbExecuteAssoc($query);
                        foreach ($result->readAll() as $row) {
                            foreach ($qid as $question) {
                                $json = $row[$question];
                                if ($json == "" || $json == NULL) {
                                    continue;
                                }
                                // decode them
                                $phparray = json_decode($json);
                                foreach ($phparray as $metadata) {
                                    $target = Yii::app()->getConfig("uploaddir") . "/surveys/" . $surveyid . "/files/";
                                    // delete those files
                                    unlink($target . $metadata->filename);
                                }
                            }
                        }
                    }
                    // done deleting uploaded files
                }
                // also delete a record from saved_control when there is one
                dbExecuteAssoc('DELETE FROM {{saved_control}} WHERE srid=' . $_SESSION['survey_' . $surveyid]['srid'] . ' AND sid=' . $surveyid);
            }
            killSurveySession($surveyid);
            sendCacheHeaders();
            doHeader();
            $redata = compact(array_keys(get_defined_vars()));
            $this->_printTemplateContent($thistpl . '/startpage.pstpl', $redata, __LINE__);
            echo "\n\n<!-- JAVASCRIPT FOR CONDITIONAL QUESTIONS -->\n" . "\t<script type='text/javascript'>\n" . "\t<!--\n" . "function checkconditions(value, name, type, evt_type)\n" . "\t{\n" . "\t}\n" . "\t//-->\n" . "\t</script>\n\n";
            //Present the clear all page using clearall.pstpl template
            $this->_printTemplateContent($thistpl . '/clearall.pstpl', $redata, __LINE__);
            $this->_printTemplateContent($thistpl . '/endpage.pstpl', $redata, __LINE__);
            doFooter();
            exit;
        }
        //Check to see if a refering URL has been captured.
        if (!isset($_SESSION['survey_' . $surveyid]['refurl'])) {
            $_SESSION['survey_' . $surveyid]['refurl'] = GetReferringUrl();
            // do not overwrite refurl
        }
        // Let's do this only if
        //  - a saved answer record hasn't been loaded through the saved feature
        //  - the survey is not anonymous
        //  - the survey is active
        //  - a token information has been provided
        //  - the survey is setup to allow token-response-persistence
        if (!isset($_SESSION['survey_' . $surveyid]['srid']) && $thissurvey['anonymized'] == "N" && $thissurvey['active'] == "Y" && isset($token) && $token != '') {
            // load previous answers if any (dataentry with nosubmit)
            $sQuery = "SELECT id,submitdate,lastpage FROM {$thissurvey['tablename']} WHERE {$thissurvey['tablename']}.token='{$token}' order by id desc";
            $aRow = Yii::app()->db->createCommand($sQuery)->queryRow();
            if ($aRow) {
                if ($aRow['submitdate'] == '' && $thissurvey['tokenanswerspersistence'] == 'Y' || $aRow['submitdate'] != '' && $thissurvey['alloweditaftercompletion'] == 'Y') {
                    $_SESSION['survey_' . $surveyid]['srid'] = $aRow['id'];
                    if (!is_null($aRow['lastpage']) && $aRow['submitdate'] == '') {
                        $_SESSION['survey_' . $surveyid]['LEMtokenResume'] = true;
                        $_SESSION['survey_' . $surveyid]['step'] = $aRow['lastpage'];
                    }
                }
                buildsurveysession($surveyid);
                loadanswers();
            }
        }
        //        // SAVE POSTED ANSWERS TO DATABASE IF MOVE (NEXT,PREV,LAST, or SUBMIT) or RETURNING FROM SAVE FORM
        //        if (isset($move) || isset($_POST['saveprompt']))
        //        {
        //            $redata = compact(array_keys(get_defined_vars()));
        //            //save.php
        //            Yii::import("application.libraries.Save");
        //            $tmp = new Save();
        //            $tmp->run($redata);
        //
        //            // RELOAD THE ANSWERS INCASE SOMEONE ELSE CHANGED THEM
        //            if ($thissurvey['active'] == "Y" &&
        //            ( $thissurvey['allowsave'] == "Y" || $thissurvey['tokenanswerspersistence'] == "Y") )
        //            {
        //                loadanswers();
        //            }
        //        }
        if (isset($param['action']) && $param['action'] == 'previewgroup') {
            $thissurvey['format'] = 'G';
            buildsurveysession($surveyid, true);
        }
        if (isset($param['action']) && $param['action'] == 'previewquestion') {
            $thissurvey['format'] = 'S';
            buildsurveysession($surveyid, true);
        }
        sendCacheHeaders();
        //Send local variables to the appropriate survey type
        unset($redata);
        $redata = compact(array_keys(get_defined_vars()));
        Yii::import('application.helpers.SurveyRuntimeHelper');
        $tmp = new SurveyRuntimeHelper();
        $tmp->run($surveyid, $redata);
        if (isset($_POST['saveall']) || isset($flashmessage)) {
            echo "<script type='text/javascript'> \$(document).ready( function() { alert('" . $clang->gT("Your responses were successfully saved.", "js") . "');}) </script>";
        }
    }
/**
 * 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)
{
    global $secerror, $clienttoken;
    global $tokensexist;
    //global $surveyid;
    global $templang, $move, $rooturl;
    $clang = Yii::app()->lang;
    $thissurvey = getSurveyInfo($surveyid);
    if (empty($templang)) {
        $templang = $thissurvey['language'];
    }
    $_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');
    // NO TOKEN REQUIRED BUT CAPTCHA ENABLED FOR SURVEY ACCESS
    if ($tokensexist == 0 && isCaptchaEnabled('surveyaccessscreen', $thissurvey['usecaptcha'])) {
        // 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[1525]');
            //echo makedropdownlist();
            echo templatereplace(file_get_contents($sTemplatePath . "survey.pstpl"), array(), $redata, 'frontend_helper[1527]');
            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='" . $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                    <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 "\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;
        }
    }
    //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')) . "\n                <ul>\n                <li>";
            ?>
            <label for='token'><?php 
            $clang->eT("Token:");
            ?>
</label><input class='text <?php 
            echo $kpclass;
            ?>
' id='token' type='text' name='token' />
            <?php 
            echo "<input type='hidden' name='sid' value='" . $surveyid . "' id='sid' />\n            <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                <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 "</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' 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 tokens actually haven't been already used
        $areTokensUsed = usedTokens(trim(strip_tags($clienttoken)), $surveyid);
        //check if token actually does exist
        // check also if it is allowed to change survey after completion
        if ($thissurvey['alloweditaftercompletion'] == 'Y') {
            $oTokenEntry = Tokens_dynamic::model($surveyid)->find('token=:token', array(':token' => trim(strip_tags($clienttoken))));
        } else {
            $oTokenEntry = Tokens_dynamic::model($surveyid)->find("token=:token AND (completed = 'N' or completed='')", array(':token' => trim(strip_tags($clienttoken))));
        }
        if (is_null($oTokenEntry) || $areTokensUsed && $thissurvey['alloweditaftercompletion'] != 'Y') {
            //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']) {
            //check if tokens actually haven't been already used
            $areTokensUsed = usedTokens(trim(strip_tags($clienttoken)), $surveyid);
            //check if token actually does exist
            $oTokenEntry = Tokens_dynamic::model($surveyid)->find('token=:token', array(':token' => trim(strip_tags($clienttoken))));
            if ($thissurvey['alloweditaftercompletion'] == 'Y') {
                $oTokenEntry = Tokens_dynamic::model($surveyid)->find('token=:token', array(':token' => trim(strip_tags($clienttoken))));
            } else {
                $oTokenEntry = Tokens_dynamic::model($surveyid)->find("token=:token  AND (completed = 'N' or completed='')", array(':token' => trim(strip_tags($clienttoken))));
            }
            if (is_null($oTokenEntry) || $areTokensUsed && $thissurvey['alloweditaftercompletion'] != 'Y') {
                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='" . $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><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                    <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='" . $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") && 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]['thistoken']);
    unset($_SESSION['survey_' . $surveyid]['fieldnamesInfo']);
    unset($_SESSION['survey_' . $surveyid]['fieldmap-' . $surveyid . '-randMaster']);
    unset($_SESSION['survey_' . $surveyid]['groupReMap']);
    $_SESSION['survey_' . $surveyid]['fieldnamesInfo'] = array();
    //RL: multilingual support
    if (isset($_GET['token']) && tableExists('{{tokens_' . $surveyid . '}}')) {
        //get language from token (if one exists)
        $tkquery2 = "SELECT * FROM {{tokens_" . $surveyid . "}} WHERE token='" . $clienttoken . "' AND (completed = 'N' or completed='')";
        //echo $tkquery2;
        $result = dbExecuteAssoc($tkquery2) or safeDie("Couldn't get tokens<br />{$tkquery}<br />");
        //Checked
        foreach ($result->readAll() as $rw) {
            $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['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..
    $_SESSION['survey_' . $surveyid]['token'] = $clienttoken;
    if ($thissurvey['anonymized'] == "N") {
        $_SESSION['survey_' . $surveyid]['insertarray'][] = "token";
    }
    if ($tokensexist == 1 && $thissurvey['anonymized'] == "N" && tableExists('{{tokens_' . $surveyid . '}}')) {
        //Gather survey data for "non anonymous" surveys, for use in presenting questions
        $_SESSION['survey_' . $surveyid]['thistoken'] = getTokenData($surveyid, $clienttoken);
    }
    $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 = Groups::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) {
        $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'))) {
        $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) {
        $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 Conditions->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;
            }
        }
    }
    $_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 = Survey_url_parameters::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']];
                        }
                    }
                }
            }
        }
    }
}
/**
* 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;
}