Example #1
0
 function action()
 {
     global $surveyid;
     global $thissurvey, $thisstep;
     global $clienttoken, $tokensexist, $token;
     // only attempt to change session lifetime if using a DB backend
     // with file based sessions, it's up to the admin to configure maxlifetime
     if (isset(Yii::app()->session->connectionID)) {
         @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 = getMove();
     Yii::app()->setConfig('move', $move);
     $clienttoken = trim($param['token']);
     $standardtemplaterootdir = Yii::app()->getConfig('standardtemplaterootdir');
     if (is_null($thissurvey) && !is_null($surveyid)) {
         $thissurvey = getSurveyInfo($surveyid);
     }
     // 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);
     }
     $surveyExists = $surveyid && Survey::model()->findByPk($surveyid);
     $isSurveyActive = $surveyExists && Survey::model()->findByPk($surveyid)->active == "Y";
     // collect all data in this method to pass on later
     $redata = compact(array_keys(get_defined_vars()));
     $this->_loadLimesurveyLang($surveyid);
     if ($this->_isClientTokenDifferentFromSessionToken($clienttoken, $surveyid)) {
         $sReloadUrl = $this->getController()->createUrl("/survey/index/sid/{$surveyid}", array('token' => $clienttoken, 'lang' => App()->language, 'newtest' => 'Y'));
         $asMessage = array(gT('Token mismatch'), gT('The token you provided doesn\'t match the one in your session.'), "<a class='reloadlink newsurvey' href={$sReloadUrl}>" . gT("Click here to start the survey.") . "</a>");
         $this->_createNewUserSessionAndRedirect($surveyid, $redata, __LINE__, $asMessage);
     }
     if ($this->_isSurveyFinished($surveyid) && ($thissurvey['alloweditaftercompletion'] != 'Y' || $thissurvey['tokenanswerspersistence'] != 'Y')) {
         $aReloadUrlParam = array('lang' => App()->language, 'newtest' => 'Y');
         if ($clienttoken) {
             $aReloadUrlParam['token'] = $clienttoken;
         }
         $sReloadUrl = $this->getController()->createUrl("/survey/index/sid/{$surveyid}", $aReloadUrlParam);
         $asMessage = array(gT('Previous session is set to be finished.'), 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.'), "<a class='reloadlink newsurvey' href={$sReloadUrl}>" . gT("Click here to start the survey.") . "</a>");
         $this->_createNewUserSessionAndRedirect($surveyid, $redata, __LINE__, $asMessage);
     }
     $previewmode = false;
     if (isset($param['action']) && in_array($param['action'], array('previewgroup', 'previewquestion'))) {
         if (!$this->_canUserPreviewSurvey($surveyid)) {
             $asMessage = array(gT('Error'), gT("We are sorry but you don't have permissions to do this."));
             $this->_niceExit($redata, __LINE__, null, $asMessage);
         } else {
             if (intval($param['qid']) && $param['action'] == 'previewquestion') {
                 $previewmode = 'question';
             }
             if (intval($param['gid']) && $param['action'] == 'previewgroup') {
                 $previewmode = 'group';
             }
         }
     }
     Yii::app()->setConfig('previewmode', $previewmode);
     if ($this->_surveyCantBeViewedWithCurrentPreviewAccess($surveyid, $isSurveyActive, $surveyExists)) {
         $bPreviewRight = $this->_userHasPreviewAccessSession($surveyid);
         if ($bPreviewRight === false) {
             $asMessage = array(gT("Error"), gT("We are sorry but you don't have permissions to do this."), sprintf(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($surveyid)) {
         // @TODO is this still required ?
         $asMessage = array(gT("Error"), gT("We are sorry but your session has expired."), gT("Either you have been inactive for too long, you have cookies disabled for your browser, or there were problems with your connection."), sprintf(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
     // Keep the old value, because SetSurveyLanguage update $_SESSION
     $sOldLang = isset($_SESSION['survey_' . $surveyid]['s_lang']) ? $_SESSION['survey_' . $surveyid]['s_lang'] : "";
     // Keep the old value, because SetSurveyLanguage update $_SESSION
     if (!empty($param['lang'])) {
         $sDisplayLanguage = $param['lang'];
         // $param take lang from returnGlobal and returnGlobal sanitize langagecode
     } elseif (isset($_SESSION['survey_' . $surveyid]['s_lang'])) {
         $sDisplayLanguage = $_SESSION['survey_' . $surveyid]['s_lang'];
     } elseif (Survey::model()->findByPk($surveyid)) {
         $sDisplayLanguage = Survey::model()->findByPk($surveyid)->language;
     } else {
         $sDisplayLanguage = Yii::app()->getConfig('defaultlang');
     }
     //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
         SetSurveyLanguage($surveyid, $sDisplayLanguage);
         if ($previewmode) {
             LimeExpressionManager::SetPreviewMode($previewmode);
         }
         if (App()->language != $sOldLang) {
             UpdateGroupList($surveyid, App()->language);
             // to refresh the language strings in the group list session variable
             UpdateFieldArray();
             // to refresh question titles and question text
         }
     } else {
         throw new CHttpException(404, "The survey in which you are trying to participate does not seem to exist. It may have been deleted or the link you were given is outdated or incorrect.");
     }
     // Get token
     if (!isset($token)) {
         $token = $clienttoken;
     }
     //GET BASIC INFORMATION ABOUT THIS SURVEY
     $thissurvey = getSurveyInfo($surveyid, $_SESSION['survey_' . $surveyid]['s_lang']);
     $event = new PluginEvent('beforeSurveyPage');
     $event->set('surveyId', $surveyid);
     App()->getPluginManager()->dispatchEvent($event);
     if (!is_null($event->get('template'))) {
         $thissurvey['templatedir'] = $event->get('template');
     }
     //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
     global $oTemplate;
     $thistpl = $oTemplate->viewPath;
     $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' && !$previewmode) {
         $redata = compact(array_keys(get_defined_vars()));
         $asMessage = array(gT("Error"), gT("This survey is no longer available."), sprintf(gT("Please contact %s ( %s ) for further assistance."), $thissurvey['adminname'], $thissurvey['adminemail']));
         $this->_niceExit($redata, __LINE__, $thissurvey['templatedir'], $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' && !$previewmode) {
         $redata = compact(array_keys(get_defined_vars()));
         $asMessage = array(gT("Error"), gT("This survey is not yet started."), sprintf(gT("Please contact %s ( %s ) for further assistance."), $thissurvey['adminname'], $thissurvey['adminemail']));
         $this->_niceExit($redata, __LINE__, $thissurvey['templatedir'], $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(gT("Error"), gT("You have already completed this survey."), sprintf(gT("Please contact %s ( %s ) for further assistance."), $thissurvey['adminname'], $thissurvey['adminemail']));
         $this->_niceExit($redata, __LINE__, $thissurvey['templatedir'], $asMessage);
     }
     //LOAD SAVED SURVEY
     if (Yii::app()->request->getParam('loadall') == "reload") {
         $errormsg = "";
         $sLoadName = Yii::app()->request->getParam('loadname');
         $sLoadPass = Yii::app()->request->getParam('loadpass');
         if (isset($sLoadName) && !$sLoadName) {
             $errormsg .= gT("You did not provide a name") . "<br />\n";
         }
         if (isset($sLoadPass) && !$sLoadPass) {
             $errormsg .= 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']) && is_null(Yii::app()->request->getQuery('scid'))) {
             $sLoadSecurity = Yii::app()->request->getPost('loadsecurity');
             if (empty($sLoadSecurity)) {
                 $errormsg .= gT("You did not answer to the security question.") . "<br />\n";
             } elseif (!isset($_SESSION['survey_' . $surveyid]['secanswer']) || $sLoadSecurity != $_SESSION['survey_' . $surveyid]['secanswer']) {
                 $errormsg .= gT("The answer to the security question is incorrect.") . "<br />\n";
             }
         }
         if ($errormsg == "") {
             LimeExpressionManager::SetDirtyFlag();
             buildsurveysession($surveyid);
             if (loadanswers()) {
                 Yii::app()->setConfig('move', 'reload');
                 $move = "reload";
                 // veyRunTimeHelper use $move in $arg
             } else {
                 $errormsg .= gT("There is no matching saved survey");
             }
         }
         if ($errormsg) {
             Yii::app()->setConfig('move', "loadall");
             // Show loading form
         }
     }
     //Allow loading of saved survey
     if (Yii::app()->getConfig('move') == "loadall") {
         $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 also if it is allowed to change survey after completion
         if ($thissurvey['alloweditaftercompletion'] == 'Y') {
             $tokenInstance = Token::model($surveyid)->findByAttributes(array('token' => $token));
         } else {
             $tokenInstance = Token::model($surveyid)->usable()->incomplete()->findByAttributes(array('token' => $token));
         }
         if (!isset($tokenInstance) && !$previewmode) {
             //TOKEN DOESN'T EXIST OR HAS ALREADY BEEN USED. EXPLAIN PROBLEM AND EXIT
             $asMessage = array(null, gT("This is a controlled survey. You need a valid token to participate."), sprintf(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 . "}}") && !$previewmode) {
         // check also if it is allowed to change survey after completion
         if ($thissurvey['alloweditaftercompletion'] == 'Y') {
             $tokenInstance = Token::model($surveyid)->editable()->findByAttributes(array('token' => $token));
         } else {
             $tokenInstance = Token::model($surveyid)->usable()->incomplete()->findByAttributes(array('token' => $token));
         }
         if (!isset($tokenInstance)) {
             $oToken = Token::model($surveyid)->findByAttributes(array('token' => $token));
             if ($oToken) {
                 $now = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", Yii::app()->getConfig("timeadjust"));
                 if ($oToken->completed != 'N' && !empty($oToken->completed)) {
                     $sError = gT("This invitation has already been used.");
                 } elseif (strtotime($now) < strtotime($oToken->validfrom)) {
                     $sError = gT("This invitation is not valid yet.");
                 } elseif (strtotime($now) > strtotime($oToken->validuntil)) {
                     $sError = gT("This invitation is not valid anymore.");
                 } else {
                     $sError = gT("This is a controlled survey. You need a valid token to participate.");
                 }
             } else {
                 $sError = gT("This is a controlled survey. You need a valid token to participate.");
             }
             $asMessage = array($sError, gT("We are sorry but you are not allowed to enter this survey."), sprintf(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']) && !SurveyDynamic::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)
         $oResponses = Response::model($surveyid)->findAllByAttributes(array('token' => $token), array('order' => 'id DESC'));
         if (!empty($oResponses)) {
             /**
              * We fire the response selection event when at least 1 response was found.
              * If there is just 1 response the plugin still has to option to choose
              * NOT to use it.
              */
             $event = new PluginEvent('beforeLoadResponse');
             $event->set('responses', $oResponses);
             $event->set('surveyId', $surveyid);
             App()->pluginManager->dispatchEvent($event);
             $oResponse = $event->get('response');
             // If $oResponse is false we act as if no response was found.
             // This allows a plugin to deny continuing a response.
             if ($oResponse !== false) {
                 // If plugin does not set a response we use the first one found, (this replicates pre-plugin behavior)
                 if (!isset($oResponse) && (!isset($oResponses[0]->submitdate) || $thissurvey['alloweditaftercompletion'] == 'Y') && $thissurvey['tokenanswerspersistence'] == 'Y') {
                     $oResponse = $oResponses[0];
                 }
                 if (isset($oResponse)) {
                     $_SESSION['survey_' . $surveyid]['srid'] = $oResponse->id;
                     if (!empty($oResponse->lastpage)) {
                         $_SESSION['survey_' . $surveyid]['LEMtokenResume'] = true;
                         // If the response was completed and user is allowed to edit after completion start at the beginning and not at the last page - just makes more sense
                         if (!($oResponse->submitdate && $thissurvey['alloweditaftercompletion'] == 'Y')) {
                             $_SESSION['survey_' . $surveyid]['step'] = $oResponse->lastpage;
                         }
                     }
                     buildsurveysession($surveyid);
                     if (!empty($oResponse->submitdate)) {
                         $_SESSION['survey_' . $surveyid]['maxstep'] = $_SESSION['survey_' . $surveyid]['totalsteps'];
                     }
                     loadanswers();
                 }
             }
         }
     }
     // Preview action : Preview right already tested before
     if ($previewmode) {
         // Unset all SESSION: be sure to have the last version
         unset($_SESSION['fieldmap-' . $surveyid . App()->language]);
         // Needed by createFieldMap: else fieldmap can be outdated
         unset($_SESSION['survey_' . $surveyid]);
         if ($param['action'] == 'previewgroup') {
             $thissurvey['format'] = 'G';
         } elseif ($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('" . gT("Your responses were successfully saved.", "js") . "');}) </script>";
     }
 }
Example #2
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>";
        }
    }
}
// Set the language of the survey, either from POST, GET parameter of session var
if (isset($_POST['lang']) && $_POST['lang'] != '') {
    $templang = sanitize_languagecode($_POST['lang']);
    $clang = SetSurveyLanguage($surveyid, $templang);
    UpdateSessionGroupList($templang);
    // to refresh the language strings in the group list session variable
    UpdateFieldArray();
    // to refresh question titles and question text
} else {
    if (isset($_GET['lang']) && $surveyid) {
        $templang = sanitize_languagecode($_GET['lang']);
        $clang = SetSurveyLanguage($surveyid, $templang);
        UpdateSessionGroupList($templang);
        // to refresh the language strings in the group list session variable
        UpdateFieldArray();
        // to refresh question titles and question text
    }
}
if (isset($_SESSION['s_lang'])) {
    $clang = SetSurveyLanguage($surveyid, $_SESSION['s_lang']);
} elseif (isset($surveyid) && $surveyid) {
    $baselang = GetBaseLanguageFromSurveyID($surveyid);
    $clang = SetSurveyLanguage($surveyid, $baselang);
} else {
    $baselang = $defaultlang;
}
if (isset($_REQUEST['embedded_inc'])) {
    safe_die('You cannot start this script directly');
}
//CHECK FOR REQUIRED INFORMATION (sid)
Example #4
0
function loadanswers()
{
    global $dbprefix, $surveyid, $errormsg;
    global $thissurvey, $thisstep, $clang;
    global $databasetype, $clienttoken;
    $scid = returnglobal('scid');
    if (isset($_POST['loadall']) && $_POST['loadall'] == "reload") {
        $query = "SELECT * FROM " . db_table_name('saved_control') . " INNER JOIN {$thissurvey['tablename']}\n\t\t\tON " . db_table_name('saved_control') . ".srid = {$thissurvey['tablename']}.id\n\t\t\tWHERE " . db_table_name('saved_control') . ".sid={$surveyid}\n";
        if (isset($scid)) {
            $query .= "AND " . db_table_name('saved_control') . ".scid={$scid}\n";
        }
        $query .= "AND " . db_table_name('saved_control') . ".identifier = '" . auto_escape($_SESSION['holdname']) . "' ";
        if ($databasetype == 'odbc_mssql' || $databasetype == 'odbtp' || $databasetype == 'mssql_n' || $databasetype == 'mssqlnative') {
            $query .= "AND CAST(" . db_table_name('saved_control') . ".access_code as varchar(32))= '" . md5(auto_unescape($_SESSION['holdpass'])) . "'\n";
        } else {
            $query .= "AND " . db_table_name('saved_control') . ".access_code = '" . md5(auto_unescape($_SESSION['holdpass'])) . "'\n";
        }
    } elseif (isset($_SESSION['srid'])) {
        $query = "SELECT * FROM {$thissurvey['tablename']}\n\t\t\tWHERE {$thissurvey['tablename']}.id=" . $_SESSION['srid'] . "\n";
    } else {
        return;
    }
    $result = db_execute_assoc($query) or safe_die("Error loading results<br />{$query}<br />" . $connect->ErrorMsg());
    //Checked
    if ($result->RecordCount() < 1) {
        $errormsg .= $clang->gT("There is no matching saved survey") . "<br />\n";
    } else {
        //A match has been found. Let's load the values!
        //If this is from an email, build surveysession first
        $row = $result->FetchRow();
        foreach ($row as $column => $value) {
            if ($column == "token") {
                $clienttoken = $value;
                $token = $value;
            } elseif ($column == "saved_thisstep") {
                $_SESSION['step'] = $value;
                $thisstep = $value - 1;
            } elseif ($column == 'lastpage' && isset($_GET['token'])) {
                if ($value < 1) {
                    $value = 1;
                }
                $_SESSION['step'] = $value;
                $thisstep = $value - 1;
            } elseif ($column == 'startlanguage') {
                $clang = SetSurveyLanguage($surveyid, $value);
                UpdateSessionGroupList($value);
                // to refresh the language strings in the group list session variable
                UpdateFieldArray();
                // to refresh question titles and question text
            } elseif ($column == "scid") {
                $_SESSION['scid'] = $value;
            } elseif ($column == "srid") {
                $_SESSION['srid'] = $value;
            } elseif ($column == "datestamp") {
                $_SESSION['datestamp'] = $value;
            }
            if ($column == "startdate") {
                $_SESSION['startdate'] = $value;
            } else {
                //Only make session variables for those in insertarray[]
                if (in_array($column, $_SESSION['insertarray'])) {
                    if (($_SESSION['fieldmap'][$column]['type'] == 'N' || $_SESSION['fieldmap'][$column]['type'] == 'K' || $_SESSION['fieldmap'][$column]['type'] == 'D') && $value == null) {
                        // For type N,K,D NULL in DB is to be considered as NoAnswer in any case.
                        // We need to set the _SESSION[field] value to '' in order to evaluate conditions.
                        // This is especially important for the deletenonvalue feature,
                        // otherwise we would erase any answer with condition such as EQUALS-NO-ANSWER on such
                        // question types (NKD)
                        $_SESSION[$column] = '';
                    } else {
                        $_SESSION[$column] = $value;
                    }
                }
                // if (in_array(
            }
            // else
        }
        // foreach
    }
    return true;
}
Example #5
0
// Set the language of the survey, either from POST, GET parameter of session var
if (isset($_POST['lang']) && $_POST['lang']!='')  // this one comes from the language question
{
    $templang = sanitize_languagecode($_POST['lang']);
    $clang = SetSurveyLanguage( $surveyid, $templang);
    UpdateSessionGroupList($templang);  // to refresh the language strings in the group list session variable

    UpdateFieldArray();        // to refresh question titles and question text
}
else
if (isset($_GET['lang']) && $surveyid)
{
    $templang = sanitize_languagecode($_GET['lang']);
    $clang = SetSurveyLanguage( $surveyid, $templang);
    UpdateSessionGroupList($templang);  // to refresh the language strings in the group list session variable
    UpdateFieldArray();        // to refresh question titles and question text
}

if (isset($_SESSION['s_lang']))
{
    $clang = SetSurveyLanguage( $surveyid, $_SESSION['s_lang']);
}
elseif (isset($surveyid) && $surveyid)
{
    $baselang = GetBaseLanguageFromSurveyID($surveyid);
    $clang = SetSurveyLanguage( $surveyid, $baselang);
}
else
{
    $baselang=$defaultlang;
}