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>";
     }
 }
 /**
  * Main function
  *
  * @param mixed $surveyid
  * @param mixed $args
  */
 function run($surveyid, $args)
 {
     global $errormsg;
     extract($args);
     if (!$thissurvey) {
         $thissurvey = getSurveyInfo($surveyid);
     }
     $LEMsessid = 'survey_' . $surveyid;
     $this->setJavascriptVar($surveyid);
     global $oTemplate;
     $sTemplatePath = $oTemplate->path;
     $sTemplateViewPath = $oTemplate->viewPath;
     //$sTemplatePath=getTemplatePath(Yii::app()->getConfig("defaulttemplate")).DIRECTORY_SEPARATOR;
     // TODO : check if necessary :
     /*
     if (isset ($_SESSION['survey_'.$surveyid]['templatepath']))
     {
         $sTemplatePath=$_SESSION['survey_'.$surveyid]['templatepath'];
     }
     */
     // $LEMdebugLevel - customizable debugging for Lime Expression Manager
     $LEMdebugLevel = 0;
     // LEM_DEBUG_TIMING;    // (LEM_DEBUG_TIMING + LEM_DEBUG_VALIDATION_SUMMARY + LEM_DEBUG_VALIDATION_DETAIL);
     $LEMskipReprocessing = false;
     // true if used GetLastMoveResult to avoid generation of unneeded extra JavaScript
     switch ($thissurvey['format']) {
         case "A":
             //All in one
             $surveyMode = 'survey';
             break;
         default:
         case "S":
             //One at a time
             $surveyMode = 'question';
             break;
         case "G":
             //Group at a time
             $surveyMode = 'group';
             break;
     }
     $radix = getRadixPointData($thissurvey['surveyls_numberformat']);
     $radix = $radix['separator'];
     $surveyOptions = array('active' => $thissurvey['active'] == 'Y', 'allowsave' => $thissurvey['allowsave'] == 'Y', 'anonymized' => $thissurvey['anonymized'] != 'N', 'assessments' => $thissurvey['assessments'] == 'Y', 'datestamp' => $thissurvey['datestamp'] == 'Y', 'deletenonvalues' => Yii::app()->getConfig('deletenonvalues'), 'hyperlinkSyntaxHighlighting' => ($LEMdebugLevel & LEM_DEBUG_VALIDATION_SUMMARY) == LEM_DEBUG_VALIDATION_SUMMARY, 'ipaddr' => $thissurvey['ipaddr'] == 'Y', 'radix' => $radix, 'refurl' => $thissurvey['refurl'] == "Y" && isset($_SESSION[$LEMsessid]['refurl']) ? $_SESSION[$LEMsessid]['refurl'] : NULL, 'savetimings' => $thissurvey['savetimings'] == "Y", 'surveyls_dateformat' => isset($thissurvey['surveyls_dateformat']) ? $thissurvey['surveyls_dateformat'] : 1, 'startlanguage' => isset(App()->language) ? App()->language : $thissurvey['language'], 'target' => Yii::app()->getConfig('uploaddir') . DIRECTORY_SEPARATOR . 'surveys' . DIRECTORY_SEPARATOR . $thissurvey['sid'] . DIRECTORY_SEPARATOR . 'files' . DIRECTORY_SEPARATOR, 'tempdir' => Yii::app()->getConfig('tempdir') . DIRECTORY_SEPARATOR, 'timeadjust' => isset($timeadjust) ? $timeadjust : 0, 'token' => isset($clienttoken) ? $clienttoken : NULL);
     //Security Checked: POST, GET, SESSION, REQUEST, returnGlobal, DB
     $previewgrp = false;
     if ($surveyMode == 'group' && isset($param['action']) && $param['action'] == 'previewgroup') {
         $previewgrp = true;
     }
     $previewquestion = false;
     if ($surveyMode == 'question' && isset($param['action']) && $param['action'] == 'previewquestion') {
         $previewquestion = true;
     }
     //        if (isset($param['newtest']) && $param['newtest'] == "Y")
     //            setcookie("limesurvey_timers", "0");   //@todo fix - sometimes results in headers already sent error
     $show_empty_group = false;
     if ($previewgrp || $previewquestion) {
         $_SESSION[$LEMsessid]['prevstep'] = 2;
         $_SESSION[$LEMsessid]['maxstep'] = 0;
     } else {
         //RUN THIS IF THIS IS THE FIRST TIME , OR THE FIRST PAGE ########################################
         if (!isset($_SESSION[$LEMsessid]['step'])) {
             buildsurveysession($surveyid);
             //TODO : check if necessary
             //$sTemplatePath = $_SESSION[$LEMsessid]['templatepath'];
             if ($surveyid != LimeExpressionManager::getLEMsurveyId()) {
                 LimeExpressionManager::SetDirtyFlag();
             }
             LimeExpressionManager::StartSurvey($surveyid, $surveyMode, $surveyOptions, false, $LEMdebugLevel);
             $_SESSION[$LEMsessid]['step'] = 0;
             if ($surveyMode == 'survey') {
                 LimeExpressionManager::JumpTo(1, false, false, true);
             } elseif (isset($thissurvey['showwelcome']) && $thissurvey['showwelcome'] == 'N') {
                 $moveResult = LimeExpressionManager::NavigateForwards();
                 //$_SESSION[$LEMsessid]['step']=1;
             }
         } elseif ($surveyid != LimeExpressionManager::getLEMsurveyId()) {
             $_SESSION[$LEMsessid]['step'] = $_SESSION[$LEMsessid]['step'] < 0 ? 0 : $_SESSION[$LEMsessid]['step'];
             //$_SESSION[$LEMsessid]['step'] can not be less than 0, fix it always #09772
             LimeExpressionManager::StartSurvey($surveyid, $surveyMode, $surveyOptions, false, $LEMdebugLevel);
             LimeExpressionManager::JumpTo($_SESSION[$LEMsessid]['step'], false, false);
         }
         $totalquestions = $_SESSION['survey_' . $surveyid]['totalquestions'];
         if (!isset($_SESSION[$LEMsessid]['totalsteps'])) {
             $_SESSION[$LEMsessid]['totalsteps'] = 0;
         }
         if (!isset($_SESSION[$LEMsessid]['maxstep'])) {
             $_SESSION[$LEMsessid]['maxstep'] = 0;
         }
         if (isset($_SESSION[$LEMsessid]['LEMpostKey']) && isset($_POST['LEMpostKey']) && $_POST['LEMpostKey'] != $_SESSION[$LEMsessid]['LEMpostKey']) {
             // then trying to resubmit (e.g. Next, Previous, Submit) from a cached copy of the page
             // Does not try to save anything from the page to the database
             $moveResult = LimeExpressionManager::GetLastMoveResult(true);
             if (isset($_POST['thisstep']) && isset($moveResult['seq']) && $_POST['thisstep'] == $moveResult['seq']) {
                 // then pressing F5 or otherwise refreshing the current page, which is OK
                 $LEMskipReprocessing = true;
                 $move = "movenext";
                 // so will re-display the survey
             } else {
                 // trying to use browser back buttons, which may be disallowed if no 'previous' button is present
                 $LEMskipReprocessing = true;
                 $move = "movenext";
                 // so will re-display the survey
                 $invalidLastPage = true;
                 $backpopup = gT("Please use the LimeSurvey navigation buttons or index.  It appears you attempted to use the browser back button to re-submit a page.");
             }
         }
         if (isset($move) && $move == "clearcancel") {
             $moveResult = LimeExpressionManager::JumpTo($_SESSION[$LEMsessid]['step'], false, true, false, true);
             //$backpopup=gT("Clear all need confirmation.");
         }
         if (isset($move)) {
             if (!in_array($move, array("clearall", "changelang", "saveall", "reload"))) {
                 $_SESSION[$LEMsessid]['prevstep'] = $_SESSION[$LEMsessid]['step'];
             } else {
                 // Accepted $move without error
                 $_SESSION[$LEMsessid]['prevstep'] = $move;
             }
         } else {
             //$_SESSION[$LEMsessid]['prevstep'] = $_SESSION[$LEMsessid]['step']-1; // Is this needed ?
         }
         if (!isset($_SESSION[$LEMsessid]['prevstep'])) {
             $_SESSION[$LEMsessid]['prevstep'] = $_SESSION[$LEMsessid]['step'] - 1;
             // this only happens on re-load
         }
         if (isset($_SESSION[$LEMsessid]['LEMtokenResume'])) {
             LimeExpressionManager::StartSurvey($thissurvey['sid'], $surveyMode, $surveyOptions, false, $LEMdebugLevel);
             if (isset($_SESSION[$LEMsessid]['maxstep']) && $_SESSION[$LEMsessid]['maxstep'] > $_SESSION[$LEMsessid]['step']) {
                 LimeExpressionManager::JumpTo($_SESSION[$LEMsessid]['maxstep'], false, false);
             }
             $moveResult = LimeExpressionManager::JumpTo($_SESSION[$LEMsessid]['step'], false, false);
             // if late in the survey, will re-validate contents, which may be overkill
             unset($_SESSION[$LEMsessid]['LEMtokenResume']);
         } else {
             if (!$LEMskipReprocessing) {
                 //Move current step ###########################################################################
                 if (isset($move) && $move == 'moveprev' && ($thissurvey['allowprev'] == 'Y' || $thissurvey['questionindex'] > 0)) {
                     $moveResult = LimeExpressionManager::NavigateBackwards();
                     if ($moveResult['at_start']) {
                         $_SESSION[$LEMsessid]['step'] = 0;
                         unset($moveResult);
                         // so display welcome page again
                     }
                 }
                 if (isset($move) && $move == "movenext") {
                     $moveResult = LimeExpressionManager::NavigateForwards();
                 }
                 if (isset($move) && $move == 'movesubmit') {
                     if ($surveyMode == 'survey') {
                         $moveResult = LimeExpressionManager::NavigateForwards();
                     } else {
                         // may be submitting from the navigation bar, in which case need to process all intervening questions
                         // in order to update equations and ensure there are no intervening relevant mandatory or relevant invalid questions
                         if ($thissurvey['questionindex'] == 2) {
                             // Must : save actual page , review whole before set finished to true (see #09906), index==1 seems to don't need it : (don't force move)
                             LimeExpressionManager::StartSurvey($surveyid, $surveyMode, $surveyOptions);
                         }
                         $moveResult = LimeExpressionManager::JumpTo($_SESSION[$LEMsessid]['totalsteps'] + 1, false);
                     }
                 }
                 if (isset($move) && $move == 'changelang') {
                     // jump to current step using new language, processing POST values
                     $moveResult = LimeExpressionManager::JumpTo($_SESSION[$LEMsessid]['step'], false, true, true, true);
                     // do process the POST data
                 }
                 if (isset($move) && isNumericInt($move) && $thissurvey['questionindex'] == 1) {
                     $move = (int) $move;
                     if ($move > 0 && ($move <= $_SESSION[$LEMsessid]['step'] || isset($_SESSION[$LEMsessid]['maxstep']) && $move <= $_SESSION[$LEMsessid]['maxstep'])) {
                         $moveResult = LimeExpressionManager::JumpTo($move, false);
                     }
                 } elseif (isset($move) && isNumericInt($move) && $thissurvey['questionindex'] == 2) {
                     $move = (int) $move;
                     $moveResult = LimeExpressionManager::JumpTo($move, false, true, true);
                 }
                 if (!isset($moveResult) && !($surveyMode != 'survey' && $_SESSION[$LEMsessid]['step'] == 0)) {
                     // Just in case not set via any other means, but don't do this if it is the welcome page
                     $moveResult = LimeExpressionManager::GetLastMoveResult(true);
                     $LEMskipReprocessing = true;
                 }
             }
         }
         if (isset($moveResult) && isset($moveResult['seq'])) {
             // With complete index, we need to revalidate whole group bug #08806. It's actually the only mode where we JumpTo with force
             if ($moveResult['finished'] == true && $move != 'movesubmit' && $thissurvey['questionindex'] == 2) {
                 //LimeExpressionManager::JumpTo(-1, false, false, true);
                 LimeExpressionManager::StartSurvey($surveyid, $surveyMode, $surveyOptions);
                 $moveResult = LimeExpressionManager::JumpTo($_SESSION[$LEMsessid]['totalsteps'] + 1, false, false, false);
                 // no preview, no save data and NO force
                 if (!$moveResult['mandViolation'] && $moveResult['valid'] && empty($moveResult['invalidSQs'])) {
                     $moveResult['finished'] = true;
                 }
             }
             if ($moveResult['finished'] == true) {
                 $move = 'movesubmit';
             } else {
                 $_SESSION[$LEMsessid]['step'] = $moveResult['seq'] + 1;
                 // step is index base 1
                 $stepInfo = LimeExpressionManager::GetStepIndexInfo($moveResult['seq']);
             }
             if ($move == "movesubmit" && $moveResult['finished'] == false) {
                 // then there are errors, so don't finalize the survey
                 $move = "movenext";
                 // so will re-display the survey
                 $invalidLastPage = true;
             }
         }
         // We do not keep the participant session anymore when the same browser is used to answer a second time a survey (let's think of a library PC for instance).
         // Previously we used to keep the session and redirect the user to the
         // submit page.
         if ($surveyMode != 'survey' && $_SESSION[$LEMsessid]['step'] == 0) {
             $_SESSION[$LEMsessid]['test'] = time();
             display_first_page();
             Yii::app()->end();
             // So we can still see debug messages
         }
         // TODO FIXME
         if ($thissurvey['active'] == "Y") {
             Yii::import("application.libraries.Save");
             $cSave = new Save();
         }
         if ($thissurvey['active'] == "Y" && Yii::app()->request->getPost('saveall')) {
             $bTokenAnswerPersitance = $thissurvey['tokenanswerspersistence'] == 'Y' && isset($surveyid) && tableExists('tokens_' . $surveyid);
             // must do this here to process the POSTed values
             $moveResult = LimeExpressionManager::JumpTo($_SESSION[$LEMsessid]['step'], false);
             // by jumping to current step, saves data so far
             if (!isset($_SESSION[$LEMsessid]['scid']) && !$bTokenAnswerPersitance) {
                 $cSave->showsaveform();
                 // generates a form and exits, awaiting input
             } else {
                 // Intentional retest of all conditions to be true, to make sure we do have tokens and surveyid
                 // Now update lastpage to $_SESSION[$LEMsessid]['step'] in SurveyDynamic, otherwise we land on
                 // the previous page when we return.
                 $iResponseID = $_SESSION[$LEMsessid]['srid'];
                 $oResponse = SurveyDynamic::model($surveyid)->findByPk($iResponseID);
                 $oResponse->lastpage = $_SESSION[$LEMsessid]['step'];
                 $oResponse->save();
             }
         }
         if ($thissurvey['active'] == "Y" && Yii::app()->request->getParam('savesubmit')) {
             // The response from the save form
             // CREATE SAVED CONTROL RECORD USING SAVE FORM INFORMATION
             $popup = $cSave->savedcontrol();
             if (isset($errormsg) && $errormsg != "") {
                 $cSave->showsaveform();
                 // reshow the form if there is an error
             }
             $moveResult = LimeExpressionManager::GetLastMoveResult(true);
             $LEMskipReprocessing = true;
             // TODO - does this work automatically for token answer persistence? Used to be savedsilent()
         }
         //Now, we check mandatory questions if necessary
         //CHECK IF ALL CONDITIONAL MANDATORY QUESTIONS THAT APPLY HAVE BEEN ANSWERED
         global $notanswered;
         if (isset($moveResult) && !$moveResult['finished']) {
             $unansweredSQList = $moveResult['unansweredSQs'];
             if (strlen($unansweredSQList) > 0) {
                 $notanswered = explode('|', $unansweredSQList);
             } else {
                 $notanswered = array();
             }
             //CHECK INPUT
             $invalidSQList = $moveResult['invalidSQs'];
             if (strlen($invalidSQList) > 0) {
                 $notvalidated = explode('|', $invalidSQList);
             } else {
                 $notvalidated = array();
             }
         }
         // CHECK UPLOADED FILES
         // TMSW - Move this into LEM::NavigateForwards?
         $filenotvalidated = checkUploadedFileValidity($surveyid, $move);
         //SEE IF THIS GROUP SHOULD DISPLAY
         $show_empty_group = false;
         if ($_SESSION[$LEMsessid]['step'] == 0) {
             $show_empty_group = true;
         }
         $redata = compact(array_keys(get_defined_vars()));
         //SUBMIT ###############################################################################
         if (isset($move) && $move == "movesubmit") {
             //                setcookie("limesurvey_timers", "", time() - 3600); // remove the timers cookies   //@todo fix - sometimes results in headers already sent error
             if ($thissurvey['refurl'] == "Y") {
                 if (!in_array("refurl", $_SESSION[$LEMsessid]['insertarray'])) {
                     $_SESSION[$LEMsessid]['insertarray'][] = "refurl";
                 }
             }
             resetTimers();
             //Before doing the "templatereplace()" function, check the $thissurvey['url']
             //field for limereplace stuff, and do transformations!
             $thissurvey['surveyls_url'] = passthruReplace($thissurvey['surveyls_url'], $thissurvey);
             $thissurvey['surveyls_url'] = templatereplace($thissurvey['surveyls_url'], array(), $redata, 'URLReplace', false, NULL, array(), true);
             // to do INSERTANS substitutions
             //END PAGE - COMMIT CHANGES TO DATABASE
             if ($thissurvey['active'] != "Y") {
                 if ($thissurvey['assessments'] == "Y") {
                     $assessments = doAssessment($surveyid);
                 }
                 sendCacheHeaders();
                 doHeader();
                 echo templatereplace(file_get_contents($sTemplateViewPath . "startpage.pstpl"), array(), $redata, 'SubmitStartpageI', false, NULL, array(), true);
                 //Check for assessments
                 if ($thissurvey['assessments'] == "Y" && $assessments) {
                     echo templatereplace(file_get_contents($sTemplateViewPath . "assessment.pstpl"), array(), $redata, 'SubmitAssessmentI', false, NULL, array(), true);
                 }
                 // fetch all filenames from $_SESSIONS['files'] and delete them all
                 // from the /upload/tmp/ directory
                 /* echo "<pre>";print_r($_SESSION);echo "</pre>";
                    for($i = 1; isset($_SESSION[$LEMsessid]['files'][$i]); $i++)
                    {
                    unlink('upload/tmp/'.$_SESSION[$LEMsessid]['files'][$i]['filename']);
                    }
                    */
                 // can't kill session before end message, otherwise INSERTANS doesn't work.
                 $completed = templatereplace($thissurvey['surveyls_endtext'], array(), $redata, 'SubmitEndtextI', false, NULL, array(), true);
                 $completed .= "<br /><strong><font size='2' color='red'>" . gT("Did Not Save") . "</font></strong><br /><br />\n\n";
                 $completed .= gT("Your survey responses have not been recorded. This survey is not yet active.") . "<br /><br />\n";
                 if ($thissurvey['printanswers'] == 'Y') {
                     // 'Clear all' link is only relevant for survey with printanswers enabled
                     // in other cases the session is cleared at submit time
                     $completed .= "<a href='" . Yii::app()->getController()->createUrl("survey/index/sid/{$surveyid}/move/clearall") . "'>" . gT("Clear Responses") . "</a><br /><br />\n";
                 }
             } else {
                 if ($thissurvey['usecookie'] == "Y" && $tokensexist != 1) {
                     setcookie("LS_" . $surveyid . "_STATUS", "COMPLETE", time() + 31536000);
                     //Cookie will expire in 365 days
                 }
                 $content = '';
                 $content .= templatereplace(file_get_contents($sTemplateViewPath . "startpage.pstpl"), array(), $redata, 'SubmitStartpage', false, NULL, array(), true);
                 //Check for assessments
                 if ($thissurvey['assessments'] == "Y") {
                     $assessments = doAssessment($surveyid);
                     if ($assessments) {
                         $content .= templatereplace(file_get_contents($sTemplateViewPath . "assessment.pstpl"), array(), $redata, 'SubmitAssessment', false, NULL, array(), true);
                     }
                 }
                 //Update the token if needed and send a confirmation email
                 if (isset($_SESSION['survey_' . $surveyid]['token'])) {
                     submittokens();
                 }
                 //Send notifications
                 sendSubmitNotifications($surveyid);
                 $content = '';
                 $content .= templatereplace(file_get_contents($sTemplateViewPath . "startpage.pstpl"), array(), $redata, 'SubmitStartpage', false, NULL, array(), true);
                 //echo $thissurvey['url'];
                 //Check for assessments
                 if ($thissurvey['assessments'] == "Y") {
                     $assessments = doAssessment($surveyid);
                     if ($assessments) {
                         $content .= templatereplace(file_get_contents($sTemplateViewPath . "assessment.pstpl"), array(), $redata, 'SubmitAssessment', false, NULL, array(), true);
                     }
                 }
                 if (trim(str_replace(array('<p>', '</p>'), '', $thissurvey['surveyls_endtext'])) == '') {
                     $completed = "<br /><span class='success'>" . gT("Thank you!") . "</span><br /><br />\n\n" . gT("Your survey responses have been recorded.") . "<br /><br />\n";
                 } else {
                     $completed = templatereplace($thissurvey['surveyls_endtext'], array(), $redata, 'SubmitAssessment', false, NULL, array(), true);
                 }
                 // Link to Print Answer Preview  **********
                 if ($thissurvey['printanswers'] == 'Y') {
                     $url = Yii::app()->getController()->createUrl("/printanswers/view/surveyid/{$surveyid}");
                     $completed .= "<br /><br />" . "<a class='printlink' href='{$url}'  target='_blank'>" . gT("Print your answers.") . "</a><br />\n";
                 }
                 //*****************************************
                 if ($thissurvey['publicstatistics'] == 'Y' && $thissurvey['printanswers'] == 'Y') {
                     $completed .= '<br />' . gT("or");
                 }
                 // Link to Public statistics  **********
                 if ($thissurvey['publicstatistics'] == 'Y') {
                     $url = Yii::app()->getController()->createUrl("/statistics_user/action/surveyid/{$surveyid}/language/" . $_SESSION[$LEMsessid]['s_lang']);
                     $completed .= "<br /><br />" . "<a class='publicstatisticslink' href='{$url}' target='_blank'>" . gT("View the statistics for this survey.") . "</a><br />\n";
                 }
                 //*****************************************
                 $_SESSION[$LEMsessid]['finished'] = true;
                 $_SESSION[$LEMsessid]['sid'] = $surveyid;
                 sendCacheHeaders();
                 if (isset($thissurvey['autoredirect']) && $thissurvey['autoredirect'] == "Y" && $thissurvey['surveyls_url']) {
                     //Automatically redirect the page to the "url" setting for the survey
                     header("Location: {$thissurvey['surveyls_url']}");
                 }
                 doHeader();
                 echo $content;
             }
             $redata['completed'] = $completed;
             // @todo Remove direct session access.
             $event = new PluginEvent('afterSurveyComplete');
             if (isset($_SESSION[$LEMsessid]['srid'])) {
                 $event->set('responseId', $_SESSION[$LEMsessid]['srid']);
             }
             $event->set('surveyId', $surveyid);
             App()->getPluginManager()->dispatchEvent($event);
             $blocks = array();
             foreach ($event->getAllContent() as $blockData) {
                 /* @var $blockData PluginEventContent */
                 $blocks[] = CHtml::tag('div', array('id' => $blockData->getCssId(), 'class' => $blockData->getCssClass()), $blockData->getContent());
             }
             $redata['completed'] = implode("\n", $blocks) . "\n" . $redata['completed'];
             $redata['thissurvey']['surveyls_url'] = $thissurvey['surveyls_url'];
             echo templatereplace(file_get_contents($sTemplateViewPath . "completed.pstpl"), array('completed' => $completed), $redata, 'SubmitCompleted', false, NULL, array(), true);
             echo "\n";
             if (($LEMdebugLevel & LEM_DEBUG_TIMING) == LEM_DEBUG_TIMING) {
                 echo LimeExpressionManager::GetDebugTimingMessage();
             }
             if (($LEMdebugLevel & LEM_DEBUG_VALIDATION_SUMMARY) == LEM_DEBUG_VALIDATION_SUMMARY) {
                 echo "<table><tr><td align='left'><b>Group/Question Validation Results:</b>" . $moveResult['message'] . "</td></tr></table>\n";
             }
             echo templatereplace(file_get_contents($sTemplateViewPath . "endpage.pstpl"), array(), $redata, 'SubmitEndpage', false, NULL, array(), true);
             doFooter();
             // The session cannot be killed until the page is completely rendered
             if ($thissurvey['printanswers'] != 'Y') {
                 killSurveySession($surveyid);
             }
             exit;
         }
     }
     $redata = compact(array_keys(get_defined_vars()));
     // IF GOT THIS FAR, THEN DISPLAY THE ACTIVE GROUP OF QUESTIONSs
     //SEE IF $surveyid EXISTS ####################################################################
     if ($surveyExists < 1) {
         //SURVEY DOES NOT EXIST. POLITELY EXIT.
         echo templatereplace(file_get_contents($sTemplateViewPath . "startpage.pstpl"), array(), $redata);
         echo "\t<center><br />\n";
         echo "\t" . gT("Sorry. There is no matching survey.") . "<br /></center>&nbsp;\n";
         echo templatereplace(file_get_contents($sTemplateViewPath . "endpage.pstpl"), array(), $redata);
         doFooter();
         exit;
     }
     createFieldMap($surveyid, 'full', false, false, $_SESSION[$LEMsessid]['s_lang']);
     //GET GROUP DETAILS
     if ($surveyMode == 'group' && $previewgrp) {
         //            setcookie("limesurvey_timers", "0"); //@todo fix - sometimes results in headers already sent error
         $_gid = sanitize_int($param['gid']);
         LimeExpressionManager::StartSurvey($thissurvey['sid'], 'group', $surveyOptions, false, $LEMdebugLevel);
         $gseq = LimeExpressionManager::GetGroupSeq($_gid);
         if ($gseq == -1) {
             echo gT('Invalid group number for this survey: ') . $_gid;
             exit;
         }
         $moveResult = LimeExpressionManager::JumpTo($gseq + 1, true);
         if (is_null($moveResult)) {
             echo gT('This group contains no questions.  You must add questions to this group before you can preview it');
             exit;
         }
         if (isset($moveResult)) {
             $_SESSION[$LEMsessid]['step'] = $moveResult['seq'] + 1;
             // step is index base 1?
         }
         $stepInfo = LimeExpressionManager::GetStepIndexInfo($moveResult['seq']);
         $gid = $stepInfo['gid'];
         $groupname = $stepInfo['gname'];
         $groupdescription = $stepInfo['gtext'];
     } else {
         if ($show_empty_group || !isset($_SESSION[$LEMsessid]['grouplist'])) {
             $gid = -1;
             // Make sure the gid is unused. This will assure that the foreach (fieldarray as ia) has no effect.
             $groupname = gT("Submit your answers");
             $groupdescription = gT("There are no more questions. Please press the <Submit> button to finish this survey.");
         } else {
             if ($surveyMode != 'survey') {
                 if ($previewquestion) {
                     $_qid = sanitize_int($param['qid']);
                     LimeExpressionManager::StartSurvey($surveyid, 'question', $surveyOptions, false, $LEMdebugLevel);
                     $qSec = LimeExpressionManager::GetQuestionSeq($_qid);
                     $moveResult = LimeExpressionManager::JumpTo($qSec + 1, true, false, true);
                     $stepInfo = LimeExpressionManager::GetStepIndexInfo($moveResult['seq']);
                 } else {
                     $stepInfo = LimeExpressionManager::GetStepIndexInfo($moveResult['seq']);
                 }
                 $gid = $stepInfo['gid'];
                 $groupname = $stepInfo['gname'];
                 $groupdescription = $stepInfo['gtext'];
             }
         }
     }
     if ($previewquestion) {
         $_SESSION[$LEMsessid]['step'] = 0;
         //maybe unset it after the question has been displayed?
     }
     if ($_SESSION[$LEMsessid]['step'] > $_SESSION[$LEMsessid]['maxstep']) {
         $_SESSION[$LEMsessid]['maxstep'] = $_SESSION[$LEMsessid]['step'];
     }
     // If the survey uses answer persistence and a srid is registered in SESSION
     // then loadanswers from this srid
     /* Only survey mode used this - should all?
        if ($thissurvey['tokenanswerspersistence'] == 'Y' &&
        $thissurvey['anonymized'] == "N" &&
        isset($_SESSION[$LEMsessid]['srid']) &&
        $thissurvey['active'] == "Y")
        {
        loadanswers();
        }
        */
     //******************************************************************************************************
     //PRESENT SURVEY
     //******************************************************************************************************
     $okToShowErrors = !$previewgrp && (isset($invalidLastPage) || $_SESSION[$LEMsessid]['prevstep'] == $_SESSION[$LEMsessid]['step']);
     Yii::app()->getController()->loadHelper('qanda');
     setNoAnswerMode($thissurvey);
     //Iterate through the questions about to be displayed:
     $inputnames = array();
     foreach ($_SESSION[$LEMsessid]['grouplist'] as $gl) {
         $gid = $gl['gid'];
         $qnumber = 0;
         if ($surveyMode != 'survey') {
             $onlyThisGID = $stepInfo['gid'];
             if ($onlyThisGID != $gid) {
                 continue;
             }
         }
         // TMSW - could iterate through LEM::currentQset instead
         //// To diplay one question, all the questions are processed ?
         foreach ($_SESSION[$LEMsessid]['fieldarray'] as $key => $ia) {
             ++$qnumber;
             $ia[9] = $qnumber;
             // incremental question count;
             if (isset($ia[10]) && $ia[10] == $gid || !isset($ia[10]) && $ia[5] == $gid) {
                 if ($surveyMode == 'question' && $ia[0] != $stepInfo['qid']) {
                     continue;
                 }
                 $qidattributes = getQuestionAttributeValues($ia[0]);
                 if ($ia[4] != '*' && ($qidattributes === false || !isset($qidattributes['hidden']) || $qidattributes['hidden'] == 1)) {
                     continue;
                 }
                 //Get the answers/inputnames
                 // TMSW - can content of retrieveAnswers() be provided by LEM?  Review scope of what it provides.
                 // TODO - retrieveAnswers is slow - queries database separately for each question. May be fixed in _CI or _YII ports, so ignore for now
                 list($plus_qanda, $plus_inputnames) = retrieveAnswers($ia, $surveyid);
                 if ($plus_qanda) {
                     $plus_qanda[] = $ia[4];
                     $plus_qanda[] = $ia[6];
                     // adds madatory identifyer for adding mandatory class to question wrapping div
                     // Add a finalgroup in qa array , needed for random attribute : TODO: find a way to have it in new quanda_helper in 2.1
                     if (isset($ia[10])) {
                         $plus_qanda['finalgroup'] = $ia[10];
                     } else {
                         $plus_qanda['finalgroup'] = $ia[5];
                     }
                     $qanda[] = $plus_qanda;
                 }
                 if ($plus_inputnames) {
                     $inputnames = addtoarray_single($inputnames, $plus_inputnames);
                 }
                 //Display the "mandatory" popup if necessary
                 // TMSW - get question-level error messages - don't call **_popup() directly
                 if ($okToShowErrors && $stepInfo['mandViolation']) {
                     list($mandatorypopup, $popup) = mandatory_popup($ia, $notanswered);
                 }
                 //Display the "validation" popup if necessary
                 if ($okToShowErrors && !$stepInfo['valid']) {
                     list($validationpopup, $vpopup) = validation_popup($ia, $notvalidated);
                 }
                 // Display the "file validation" popup if necessary
                 if ($okToShowErrors && isset($filenotvalidated)) {
                     list($filevalidationpopup, $fpopup) = file_validation_popup($ia, $filenotvalidated);
                 }
             }
             if ($ia[4] == "|") {
                 $upload_file = TRUE;
             }
         }
         //end iteration
     }
     if ($surveyMode != 'survey' && isset($thissurvey['showprogress']) && $thissurvey['showprogress'] == 'Y') {
         if ($show_empty_group) {
             $percentcomplete = makegraph($_SESSION[$LEMsessid]['totalsteps'] + 1, $_SESSION[$LEMsessid]['totalsteps']);
         } else {
             $percentcomplete = makegraph($_SESSION[$LEMsessid]['step'], $_SESSION[$LEMsessid]['totalsteps']);
         }
     }
     if (!(isset($languagechanger) && strlen($languagechanger) > 0) && function_exists('makeLanguageChangerSurvey')) {
         $languagechanger = makeLanguageChangerSurvey($_SESSION[$LEMsessid]['s_lang']);
     }
     //READ TEMPLATES, INSERT DATA AND PRESENT PAGE
     sendCacheHeaders();
     doHeader();
     /**
      * Question Index
      */
     $aQuestionindexbuttons = null;
     $aQuestionindexbuttonsmenu = null;
     if (!$previewgrp && !$previewquestion) {
         if ($surveyMode != 'survey' && $thissurvey['questionindex'] == 1) {
             //$aQuestionindex = $this->createIncrementalQuestionIndex($LEMsessid, $surveyMode);
             $aQuestionindexmenu = $this->createIncrementalQuestionIndexMenu($LEMsessid, $surveyMode);
         } elseif ($surveyMode != 'survey' && $thissurvey['questionindex'] == 2) {
             //$aQuestionindex = $this->createFullQuestionIndex($LEMsessid, $surveyMode);
             $aQuestionindexmenu = $this->createFullQuestionIndexMenu($LEMsessid, $surveyMode);
         }
         //$questionindex = (isset($aQuestionindex['menulist']))?$aQuestionindex['menulist']:'';
         $questionindexmenu = isset($aQuestionindexmenu['menulist']) ? $aQuestionindexmenu['menulist'] : '';
         //$aQuestionindexbuttons = (isset($aQuestionindex['buttons']))?$aQuestionindex['buttons']:'';
         $aQuestionindexbuttonsmenu = isset($aQuestionindexmenu['buttons']) ? $aQuestionindexmenu['buttons'] : '';
     }
     /////////////////////////////////
     // First call to templatereplace
     echo "<!-- SurveyRunTimeHelper -->";
     $redata = compact(array_keys(get_defined_vars()));
     echo templatereplace(file_get_contents($sTemplateViewPath . "startpage.pstpl"), array(), $redata);
     $aPopup = array();
     // We can move this part where we want now
     if (isset($backpopup)) {
         $aPopup[] = $backpopup;
         // If user click reload: no need other popup
     } else {
         if (isset($popup)) {
             $aPopup[] = $popup;
         }
         if (isset($vpopup)) {
             $aPopup[] = $vpopup;
         }
         if (isset($fpopup)) {
             $aPopup[] = $fpopup;
         }
     }
     Yii::app()->clientScript->registerScript("showpopup", "showpopup=" . (int) Yii::app()->getConfig('showpopups') . ";", CClientScript::POS_HEAD);
     //if(count($aPopup))
     Yii::app()->clientScript->registerScript('startPopup', "startPopups=" . json_encode($aPopup) . ";", CClientScript::POS_HEAD);
     //ALTER PAGE CLASS TO PROVIDE WHOLE-PAGE ALTERNATION
     if ($surveyMode != 'survey' && $_SESSION[$LEMsessid]['step'] != $_SESSION[$LEMsessid]['prevstep'] || isset($_SESSION[$LEMsessid]['stepno']) && $_SESSION[$LEMsessid]['stepno'] % 2) {
         if (!isset($_SESSION[$LEMsessid]['stepno'])) {
             $_SESSION[$LEMsessid]['stepno'] = 0;
         }
         if ($_SESSION[$LEMsessid]['step'] != $_SESSION[$LEMsessid]['prevstep']) {
             ++$_SESSION[$LEMsessid]['stepno'];
         }
         if ($_SESSION[$LEMsessid]['stepno'] % 2) {
             echo "<script type=\"text/javascript\">\n" . "  \$(\"body\").addClass(\"page-odd\");\n" . "</script>\n";
         }
     }
     $hiddenfieldnames = implode("|", $inputnames);
     if (isset($upload_file) && $upload_file) {
         echo CHtml::form(array("/survey/index", "sid" => $surveyid), 'post', array('enctype' => 'multipart/form-data', 'id' => 'limesurvey', 'name' => 'limesurvey', 'autocomplete' => 'off', 'class' => 'survey-form-container surveyRunTimeUploadFile')) . "\n\n            <!-- INPUT NAMES -->\n            <input type='hidden' name='fieldnames' value='{$hiddenfieldnames}' id='fieldnames' />\n";
     } else {
         echo CHtml::form(array("/survey/index", "sid" => $surveyid), 'post', array('id' => 'limesurvey', 'name' => 'limesurvey', 'autocomplete' => 'off', 'class' => 'survey-form-container  surveyRunTime')) . "\n\n            <!-- INPUT NAMES -->\n            <input type='hidden' name='fieldnames' value='{$hiddenfieldnames}' id='fieldnames' />\n";
     }
     // <-- END FEATURE - SAVE
     // The default submit button
     echo CHtml::htmlButton("default", array('type' => 'submit', 'id' => "defaultbtn", 'value' => "default", 'name' => 'move', 'class' => "submit noview", 'style' => 'display:none'));
     if ($surveyMode == 'survey') {
         if (isset($thissurvey['showwelcome']) && $thissurvey['showwelcome'] == 'N') {
             //Hide the welcome screen if explicitly set
         } else {
             echo templatereplace(file_get_contents($sTemplateViewPath . "welcome.pstpl"), array(), $redata) . "\n";
         }
         if ($thissurvey['anonymized'] == "Y") {
             echo templatereplace(file_get_contents($sTemplateViewPath . "privacy.pstpl"), array(), $redata) . "\n";
         }
     }
     // <-- START THE SURVEY -->
     if ($surveyMode != 'survey') {
         echo templatereplace(file_get_contents($sTemplateViewPath . "survey.pstpl"), array(), $redata);
     }
     // runonce element has been changed from a hidden to a text/display:none one. In order to workaround an not-reproduced issue #4453 (lemeur)
     // We don't need runonce actually (140228): the script was updated and replaced by EM see #08783 (grep show no other runonce)
     // echo "<input type='text' id='runonce' value='0' style='display: none;'/>";
     $showpopups = Yii::app()->getConfig('showpopups');
     //Display the "mandatory" message on page if necessary
     if (!$showpopups && $stepInfo['mandViolation'] && $okToShowErrors) {
         echo "<p class='errormandatory alert alert-danger' role='alert'>" . gT("One or more mandatory questions have not been answered. You cannot proceed until these have been completed.") . "</p>";
     }
     //Display the "validation" message on page if necessary
     if (!$showpopups && !$stepInfo['valid'] && $okToShowErrors) {
         echo "<p class='errormandatory alert alert-danger' role='alert'>" . gT("One or more questions have not been answered in a valid manner. You cannot proceed until these answers are valid.") . "</p>";
     }
     //Display the "file validation" message on page if necessary
     if (!$showpopups && isset($filenotvalidated) && $filenotvalidated == true && $okToShowErrors) {
         echo "<p class='errormandatory alert alert-danger' role='alert'>" . gT("One or more uploaded files are not in proper format/size. You cannot proceed until these files are valid.") . "</p>";
     }
     $_gseq = -1;
     foreach ($_SESSION[$LEMsessid]['grouplist'] as $gl) {
         $gid = $gl['gid'];
         ++$_gseq;
         $groupname = $gl['group_name'];
         $groupdescription = $gl['description'];
         if ($surveyMode != 'survey' && $gid != $onlyThisGID) {
             continue;
         }
         $redata = compact(array_keys(get_defined_vars()));
         Yii::app()->setConfig('gid', $gid);
         // To be used in templaterplace in whole group. Attention : it's the actual GID (not the GID of the question)
         echo "\n\n<!-- START THE GROUP (in SurveyRunTime ) -->\n";
         echo "\n\n<div id='group-{$_gseq}'";
         $gnoshow = LimeExpressionManager::GroupIsIrrelevantOrHidden($_gseq);
         if ($gnoshow && !$previewgrp) {
             echo " style='display: none;'";
         }
         echo " class='row'>\n";
         echo templatereplace(file_get_contents($sTemplateViewPath . "startgroup.pstpl"), array(), $redata);
         echo "\n";
         if (!$previewquestion && trim($redata['groupdescription']) == "") {
             echo templatereplace(file_get_contents($sTemplateViewPath . "groupdescription.pstpl"), array(), $redata);
         }
         echo "\n";
         echo "\n\n<!-- PRESENT THE QUESTIONS (in SurveyRunTime )  -->\n";
         foreach ($qanda as $qa) {
             // Test if finalgroup is in this qid (for all in one survey, else we do only qanda for needed question (in one by one or group by goup)
             if ($gid != $qa['finalgroup']) {
                 continue;
             }
             $qid = $qa[4];
             $qinfo = LimeExpressionManager::GetQuestionStatus($qid);
             $lastgrouparray = explode("X", $qa[7]);
             $lastgroup = $lastgrouparray[0] . "X" . $lastgrouparray[1];
             // id of the last group, derived from question id
             $lastanswer = $qa[7];
             $n_q_display = '';
             if ($qinfo['hidden'] && $qinfo['info']['type'] != '*') {
                 continue;
                 // skip this one
             }
             $aReplacement = array();
             $question = $qa[0];
             //===================================================================
             // The following four variables offer the templating system the
             // capacity to fully control the HTML output for questions making the
             // above echo redundant if desired.
             $question['sgq'] = $qa[7];
             $question['aid'] = !empty($qinfo['info']['aid']) ? $qinfo['info']['aid'] : 0;
             $question['sqid'] = !empty($qinfo['info']['sqid']) ? $qinfo['info']['sqid'] : 0;
             //===================================================================
             $question_template = file_get_contents($sTemplateViewPath . 'question.pstpl');
             // Fix old template : can we remove it ? Old template are surely already broken by another issue
             if (preg_match('/\\{QUESTION_ESSENTIALS\\}/', $question_template) === false || preg_match('/\\{QUESTION_CLASS\\}/', $question_template) === false) {
                 // if {QUESTION_ESSENTIALS} is present in the template but not {QUESTION_CLASS} remove it because you don't want id="" and display="" duplicated.
                 $question_template = str_replace('{QUESTION_ESSENTIALS}', '', $question_template);
                 $question_template = str_replace('{QUESTION_CLASS}', '', $question_template);
                 $question_template = "<div {QUESTION_ESSENTIALS} class='{QUESTION_CLASS} {QUESTION_MAN_CLASS} {QUESTION_INPUT_ERROR_CLASS}'" . $question_template . "</div>";
             }
             $redata = compact(array_keys(get_defined_vars()));
             $aQuestionReplacement = $this->getQuestionReplacement($qa);
             echo templatereplace($question_template, $aQuestionReplacement, $redata, false, false, $qa[4]);
         }
         if ($surveyMode == 'group') {
             echo "<input type='hidden' name='lastgroup' value='{$lastgroup}' id='lastgroup' />\n";
             // for counting the time spent on each group
         }
         if ($surveyMode == 'question') {
             echo "<input type='hidden' name='lastanswer' value='{$lastanswer}' id='lastanswer' />\n";
         }
         echo "\n\n<!-- END THE GROUP -->\n";
         echo templatereplace(file_get_contents($sTemplateViewPath . "endgroup.pstpl"), array(), $redata);
         echo "\n\n</div>\n";
         Yii::app()->setConfig('gid', '');
     }
     LimeExpressionManager::FinishProcessingGroup($LEMskipReprocessing);
     echo LimeExpressionManager::GetRelevanceAndTailoringJavaScript();
     LimeExpressionManager::FinishProcessingPage();
     /**
      * Navigator
      */
     if (!$previewgrp && !$previewquestion) {
         $aNavigator = surveymover();
         $moveprevbutton = $aNavigator['sMovePrevButton'];
         $movenextbutton = $aNavigator['sMoveNextButton'];
         $navigator = $moveprevbutton . ' ' . $movenextbutton;
         $redata = compact(array_keys(get_defined_vars()));
         echo "\n\n<!-- PRESENT THE NAVIGATOR -->\n";
         echo templatereplace(file_get_contents($sTemplateViewPath . "navigator.pstpl"), array(), $redata);
         echo "\n";
         if ($thissurvey['active'] != "Y") {
             echo "<p style='text-align:center' class='error'>" . gT("This survey is currently not active. You will not be able to save your responses.") . "</p>\n";
         }
         if ($surveyMode != 'survey' && $thissurvey['questionindex'] == 1) {
             $this->createIncrementalQuestionIndex($LEMsessid, $surveyMode);
             $this->createIncrementalQuestionIndexMenu($LEMsessid, $surveyMode);
         } elseif ($surveyMode != 'survey' && $thissurvey['questionindex'] == 2) {
             $this->createFullQuestionIndex($LEMsessid, $surveyMode);
             $this->createFullQuestionIndexMenu($LEMsessid, $surveyMode);
         }
         echo "<input type='hidden' name='thisstep' value='{$_SESSION[$LEMsessid]['step']}' id='thisstep' />\n";
         echo "<input type='hidden' name='sid' value='{$surveyid}' id='sid' />\n";
         echo "<input type='hidden' name='start_time' value='" . time() . "' id='start_time' />\n";
         $_SESSION[$LEMsessid]['LEMpostKey'] = mt_rand();
         echo "<input type='hidden' name='LEMpostKey' value='{$_SESSION[$LEMsessid]['LEMpostKey']}' id='LEMpostKey' />\n";
         if (isset($token) && !empty($token)) {
             echo "\n<input type='hidden' name='token' value='{$token}' id='token' />\n";
         }
     }
     if (($LEMdebugLevel & LEM_DEBUG_TIMING) == LEM_DEBUG_TIMING) {
         echo LimeExpressionManager::GetDebugTimingMessage();
     }
     if (($LEMdebugLevel & LEM_DEBUG_VALIDATION_SUMMARY) == LEM_DEBUG_VALIDATION_SUMMARY) {
         echo "<table><tr><td align='left'><b>Group/Question Validation Results:</b>" . $moveResult['message'] . "</td></tr></table>\n";
     }
     echo "</form>\n";
     echo templatereplace(file_get_contents($sTemplateViewPath . "endpage.pstpl"), array(), $redata);
     echo "\n";
     doFooter();
 }
    /**
     * Main function
     *
     * @param mixed $surveyid
     * @param mixed $args
     */
    function run($surveyid, $args)
    {
        global $errormsg;
        extract($args);
        $LEMsessid = 'survey_' . $surveyid;
        $sTemplatePath = getTemplatePath(Yii::app()->getConfig("defaulttemplate")) . DIRECTORY_SEPARATOR;
        if (isset($_SESSION['survey_' . $surveyid]['templatepath'])) {
            $sTemplatePath = $_SESSION['survey_' . $surveyid]['templatepath'];
        }
        // $LEMdebugLevel - customizable debugging for Lime Expression Manager
        $LEMdebugLevel = 0;
        // LEM_DEBUG_TIMING;    // (LEM_DEBUG_TIMING + LEM_DEBUG_VALIDATION_SUMMARY + LEM_DEBUG_VALIDATION_DETAIL);
        $LEMskipReprocessing = false;
        // true if used GetLastMoveResult to avoid generation of unneeded extra JavaScript
        switch ($thissurvey['format']) {
            case "A":
                //All in one
                $surveyMode = 'survey';
                break;
            default:
            case "S":
                //One at a time
                $surveyMode = 'question';
                break;
            case "G":
                //Group at a time
                $surveyMode = 'group';
                break;
        }
        $radix = getRadixPointData($thissurvey['surveyls_numberformat']);
        $radix = $radix['seperator'];
        $surveyOptions = array('active' => $thissurvey['active'] == 'Y', 'allowsave' => $thissurvey['allowsave'] == 'Y', 'anonymized' => $thissurvey['anonymized'] != 'N', 'assessments' => $thissurvey['assessments'] == 'Y', 'datestamp' => $thissurvey['datestamp'] == 'Y', 'hyperlinkSyntaxHighlighting' => ($LEMdebugLevel & LEM_DEBUG_VALIDATION_SUMMARY) == LEM_DEBUG_VALIDATION_SUMMARY, 'ipaddr' => $thissurvey['ipaddr'] == 'Y', 'radix' => $radix, 'refurl' => $thissurvey['refurl'] == "Y" ? $_SESSION[$LEMsessid]['refurl'] : NULL, 'savetimings' => $thissurvey['savetimings'] == "Y", 'surveyls_dateformat' => isset($thissurvey['surveyls_dateformat']) ? $thissurvey['surveyls_dateformat'] : 1, 'startlanguage' => isset($clang->langcode) ? $clang->langcode : $thissurvey['language'], 'target' => Yii::app()->getConfig('uploaddir') . DIRECTORY_SEPARATOR . 'surveys' . DIRECTORY_SEPARATOR . $thissurvey['sid'] . DIRECTORY_SEPARATOR . 'files' . DIRECTORY_SEPARATOR, 'tempdir' => Yii::app()->getConfig('tempdir') . DIRECTORY_SEPARATOR, 'timeadjust' => isset($timeadjust) ? $timeadjust : 0, 'token' => isset($clienttoken) ? $clienttoken : NULL);
        //Security Checked: POST, GET, SESSION, REQUEST, returnGlobal, DB
        $previewgrp = false;
        if ($surveyMode == 'group' && isset($param['action']) && $param['action'] == 'previewgroup') {
            $previewgrp = true;
        }
        $previewquestion = false;
        if ($surveyMode == 'question' && isset($param['action']) && $param['action'] == 'previewquestion') {
            $previewquestion = true;
        }
        //        if (isset($param['newtest']) && $param['newtest'] == "Y")
        //            setcookie("limesurvey_timers", "0");   //@todo fix - sometimes results in headers already sent error
        $show_empty_group = false;
        if ($previewgrp || $previewquestion) {
            $_SESSION[$LEMsessid]['prevstep'] = 1;
            $_SESSION[$LEMsessid]['maxstep'] = 0;
        } else {
            //RUN THIS IF THIS IS THE FIRST TIME , OR THE FIRST PAGE ########################################
            if (!isset($_SESSION[$LEMsessid]['step'])) {
                buildsurveysession($surveyid);
                $sTemplatePath = $_SESSION[$LEMsessid]['templatepath'];
                if ($surveyid != LimeExpressionManager::getLEMsurveyId()) {
                    LimeExpressionManager::SetDirtyFlag();
                }
                LimeExpressionManager::StartSurvey($surveyid, $surveyMode, $surveyOptions, false, $LEMdebugLevel);
                $_SESSION[$LEMsessid]['step'] = 0;
                if ($surveyMode == 'survey') {
                    $move = "movenext";
                    // to force a call to NavigateForwards()
                } elseif (isset($thissurvey['showwelcome']) && $thissurvey['showwelcome'] == 'N') {
                    $move = "movenext";
                    $_SESSION[$LEMsessid]['step'] = 1;
                }
            } else {
                if ($surveyid != LimeExpressionManager::getLEMsurveyId()) {
                    LimeExpressionManager::StartSurvey($surveyid, $surveyMode, $surveyOptions, false, $LEMdebugLevel);
                    LimeExpressionManager::JumpTo($_SESSION[$LEMsessid]['step'], false, false);
                }
            }
            $totalquestions = $_SESSION['survey_' . $surveyid]['totalquestions'];
            if (!isset($_SESSION[$LEMsessid]['totalsteps'])) {
                $_SESSION[$LEMsessid]['totalsteps'] = 0;
            }
            if (!isset($_SESSION[$LEMsessid]['maxstep'])) {
                $_SESSION[$LEMsessid]['maxstep'] = 0;
            }
            if (isset($_SESSION[$LEMsessid]['LEMpostKey']) && isset($_POST['LEMpostKey']) && $_POST['LEMpostKey'] != $_SESSION[$LEMsessid]['LEMpostKey']) {
                // then trying to resubmit (e.g. Next, Previous, Submit) from a cached copy of the page
                // Does not try to save anything from the page to the database
                $moveResult = LimeExpressionManager::GetLastMoveResult(true);
                if (isset($_POST['thisstep']) && isset($moveResult['seq']) && $_POST['thisstep'] == $moveResult['seq']) {
                    // then pressing F5 or otherwise refreshing the current page, which is OK
                    $LEMskipReprocessing = true;
                    $move = "movenext";
                    // so will re-display the survey
                } else {
                    // trying to use browser back buttons, which may be disallowed if no 'previous' button is present
                    $LEMskipReprocessing = true;
                    $move = "movenext";
                    // so will re-display the survey
                    $invalidLastPage = true;
                    $vpopup = "<script type=\"text/javascript\">\n\n                    <!--\n \$(document).ready(function(){\n                    alert(\"" . $clang->gT("Please use the LimeSurvey navigation buttons or index.  It appears you attempted to use the browser back button to re-submit a page.", "js") . "\");});\n //-->\n\n                    </script>\n";
                }
            }
            if (!(isset($_POST['saveall']) || isset($_POST['saveprompt']) || isset($_POST['loadall']) || isset($_GET['sid']) || $LEMskipReprocessing || isset($move) && preg_match('/^changelang_/', $move))) {
                $_SESSION[$LEMsessid]['prevstep'] = $_SESSION[$LEMsessid]['step'];
            }
            if (!isset($_SESSION[$LEMsessid]['prevstep'])) {
                $_SESSION[$LEMsessid]['prevstep'] = -1;
                // this only happens on re-load
            }
            if (isset($_SESSION[$LEMsessid]['LEMtokenResume'])) {
                LimeExpressionManager::StartSurvey($thissurvey['sid'], $surveyMode, $surveyOptions, false, $LEMdebugLevel);
                $moveResult = LimeExpressionManager::JumpTo($_SESSION[$LEMsessid]['step'], false, false);
                // if late in the survey, will re-validate contents, which may be overkill
                unset($_SESSION[$LEMsessid]['LEMtokenResume']);
            } else {
                if (!$LEMskipReprocessing) {
                    //Move current step ###########################################################################
                    if (isset($move) && $move == 'moveprev' && ($thissurvey['allowprev'] == 'Y' || $thissurvey['allowjumps'] == 'Y')) {
                        $moveResult = LimeExpressionManager::NavigateBackwards();
                        if ($moveResult['at_start']) {
                            $_SESSION[$LEMsessid]['step'] = 0;
                            unset($moveResult);
                            // so display welcome page again
                        }
                    }
                    if (isset($move) && $move == "movenext") {
                        $moveResult = LimeExpressionManager::NavigateForwards();
                    }
                    if (isset($move) && $move == 'movesubmit') {
                        if ($surveyMode == 'survey') {
                            $moveResult = LimeExpressionManager::NavigateForwards();
                        } else {
                            // may be submitting from the navigation bar, in which case need to process all intervening questions
                            // in order to update equations and ensure there are no intervening relevant mandatory or relevant invalid questions
                            $moveResult = LimeExpressionManager::JumpTo($_SESSION[$LEMsessid]['totalsteps'] + 1, false);
                        }
                    }
                    if (isset($move) && preg_match('/^changelang_/', $move)) {
                        // jump to current step using new language, processing POST values
                        $moveResult = LimeExpressionManager::JumpTo($_SESSION[$LEMsessid]['step'], false, true, false, true);
                        // do process the POST data
                    }
                    if (isset($move) && isNumericInt($move) && $thissurvey['allowjumps'] == 'Y') {
                        $move = (int) $move;
                        if ($move > 0 && ($move <= $_SESSION[$LEMsessid]['step'] || isset($_SESSION[$LEMsessid]['maxstep']) && $move <= $_SESSION[$LEMsessid]['maxstep'])) {
                            $moveResult = LimeExpressionManager::JumpTo($move, false);
                        }
                    }
                    if (!isset($moveResult) && !($surveyMode != 'survey' && $_SESSION[$LEMsessid]['step'] == 0)) {
                        // Just in case not set via any other means, but don't do this if it is the welcome page
                        $moveResult = LimeExpressionManager::GetLastMoveResult(true);
                        $LEMskipReprocessing = true;
                    }
                }
            }
            if (isset($moveResult)) {
                if ($moveResult['finished'] == true) {
                    $move = 'movesubmit';
                } else {
                    $_SESSION[$LEMsessid]['step'] = $moveResult['seq'] + 1;
                    // step is index base 1
                    $stepInfo = LimeExpressionManager::GetStepIndexInfo($moveResult['seq']);
                }
                if ($move == "movesubmit" && $moveResult['finished'] == false) {
                    // then there are errors, so don't finalize the survey
                    $move = "movenext";
                    // so will re-display the survey
                    $invalidLastPage = true;
                }
            }
            // We do not keep the participant session anymore when the same browser is used to answer a second time a survey (let's think of a library PC for instance).
            // Previously we used to keep the session and redirect the user to the
            // submit page.
            if ($surveyMode != 'survey' && $_SESSION[$LEMsessid]['step'] == 0) {
                $_SESSION[$LEMsessid]['test'] = time();
                display_first_page();
                exit;
            }
            //CHECK IF ALL MANDATORY QUESTIONS HAVE BEEN ANSWERED ############################################
            //First, see if we are moving backwards or doing a Save so far, and its OK not to check:
            if (isset($move) && ($move == "moveprev" || is_int($move) && $_SESSION[$LEMsessid]['prevstep'] == $_SESSION[$LEMsessid]['maxstep'] || $_SESSION[$LEMsessid]['prevstep'] == $_SESSION[$LEMsessid]['step']) || isset($_POST['saveall']) && $_POST['saveall'] == $clang->gT("Save your responses so far")) {
                if (Yii::app()->getConfig('allowmandbackwards') == 1) {
                    $backok = "Y";
                } else {
                    $backok = "N";
                }
            } else {
                $backok = "N";
                // NA, since not moving backwards
            }
            // TODO FIXME
            if ($thissurvey['active'] == "Y") {
                Yii::import("application.libraries.Save");
                $cSave = new Save();
            }
            if ($thissurvey['active'] == "Y" && isset($_POST['saveall'])) {
                // must do this here to process the POSTed values
                $moveResult = LimeExpressionManager::JumpTo($_SESSION[$LEMsessid]['step'], false);
                // by jumping to current step, saves data so far
                $cSave->showsaveform();
                // generates a form and exits, awaiting input
            }
            if ($thissurvey['active'] == "Y" && isset($_POST['saveprompt'])) {
                // The response from the save form
                // CREATE SAVED CONTROL RECORD USING SAVE FORM INFORMATION
                $flashmessage = $cSave->savedcontrol();
                if (isset($errormsg) && $errormsg != "") {
                    $cSave->showsaveform();
                    // reshow the form if there is an error
                }
                $moveResult = LimeExpressionManager::GetLastMoveResult(true);
                $LEMskipReprocessing = true;
                // TODO - does this work automatically for token answer persistence? Used to be savedsilent()
            }
            //Now, we check mandatory questions if necessary
            //CHECK IF ALL CONDITIONAL MANDATORY QUESTIONS THAT APPLY HAVE BEEN ANSWERED
            global $notanswered;
            if (isset($moveResult) && !$moveResult['finished']) {
                $unansweredSQList = $moveResult['unansweredSQs'];
                if (strlen($unansweredSQList) > 0 && $backok != "N") {
                    $notanswered = explode('|', $unansweredSQList);
                } else {
                    $notanswered = array();
                }
                //CHECK INPUT
                $invalidSQList = $moveResult['invalidSQs'];
                if (strlen($invalidSQList) > 0 && $backok != "N") {
                    $notvalidated = explode('|', $invalidSQList);
                } else {
                    $notvalidated = array();
                }
            }
            // CHECK UPLOADED FILES
            // TMSW - Move this into LEM::NavigateForwards?
            $filenotvalidated = checkUploadedFileValidity($surveyid, $move, $backok);
            //SEE IF THIS GROUP SHOULD DISPLAY
            $show_empty_group = false;
            if ($_SESSION[$LEMsessid]['step'] == 0) {
                $show_empty_group = true;
            }
            $redata = compact(array_keys(get_defined_vars()));
            //SUBMIT ###############################################################################
            if (isset($move) && $move == "movesubmit") {
                //                setcookie("limesurvey_timers", "", time() - 3600); // remove the timers cookies   //@todo fix - sometimes results in headers already sent error
                if ($thissurvey['refurl'] == "Y") {
                    if (!in_array("refurl", $_SESSION[$LEMsessid]['insertarray'])) {
                        $_SESSION[$LEMsessid]['insertarray'][] = "refurl";
                    }
                }
                resetTimers();
                //Before doing the "templatereplace()" function, check the $thissurvey['url']
                //field for limereplace stuff, and do transformations!
                $thissurvey['surveyls_url'] = passthruReplace($thissurvey['surveyls_url'], $thissurvey);
                $thissurvey['surveyls_url'] = templatereplace($thissurvey['surveyls_url'], $thissurvey);
                // to do INSERTANS substitutions
                //END PAGE - COMMIT CHANGES TO DATABASE
                if ($thissurvey['active'] != "Y") {
                    if ($thissurvey['assessments'] == "Y") {
                        $assessments = doAssessment($surveyid);
                    }
                    sendCacheHeaders();
                    doHeader();
                    echo templatereplace(file_get_contents($sTemplatePath . "startpage.pstpl"), array(), $redata);
                    //Check for assessments
                    if ($thissurvey['assessments'] == "Y" && $assessments) {
                        echo templatereplace(file_get_contents($sTemplatePath . "assessment.pstpl"), array(), $redata);
                    }
                    // fetch all filenames from $_SESSIONS['files'] and delete them all
                    // from the /upload/tmp/ directory
                    /* echo "<pre>";print_r($_SESSION);echo "</pre>";
                       for($i = 1; isset($_SESSION[$LEMsessid]['files'][$i]); $i++)
                       {
                       unlink('upload/tmp/'.$_SESSION[$LEMsessid]['files'][$i]['filename']);
                       }
                       */
                    // can't kill session before end message, otherwise INSERTANS doesn't work.
                    $completed = templatereplace($thissurvey['surveyls_endtext']);
                    $completed .= "<br /><strong><font size='2' color='red'>" . $clang->gT("Did Not Save") . "</font></strong><br /><br />\n\n";
                    $completed .= $clang->gT("Your survey responses have not been recorded. This survey is not yet active.") . "<br /><br />\n";
                    if ($thissurvey['printanswers'] == 'Y') {
                        // 'Clear all' link is only relevant for survey with printanswers enabled
                        // in other cases the session is cleared at submit time
                        $completed .= "<a href='" . Yii::app()->getController()->createUrl("survey/index/sid/{$surveyid}/move/clearall") . "'>" . $clang->gT("Clear Responses") . "</a><br /><br />\n";
                    }
                } else {
                    if ($thissurvey['usecookie'] == "Y" && $tokensexist != 1) {
                        setcookie("LS_" . $surveyid . "_STATUS", "COMPLETE", time() + 31536000);
                        //Cookie will expire in 365 days
                    }
                    $content = '';
                    $content .= templatereplace(file_get_contents($sTemplatePath . "startpage.pstpl"), array(), $redata);
                    //Check for assessments
                    if ($thissurvey['assessments'] == "Y") {
                        $assessments = doAssessment($surveyid);
                        if ($assessments) {
                            $content .= templatereplace(file_get_contents($sTemplatePath . "assessment.pstpl"), array(), $redata);
                        }
                    }
                    //Update the token if needed and send a confirmation email
                    if (isset($clienttoken) && $clienttoken) {
                        submittokens();
                    }
                    //Send notifications
                    sendSubmitNotifications($surveyid);
                    $content = '';
                    $content .= templatereplace(file_get_contents($sTemplatePath . "startpage.pstpl"), array(), $redata);
                    //echo $thissurvey['url'];
                    //Check for assessments
                    if ($thissurvey['assessments'] == "Y") {
                        $assessments = doAssessment($surveyid);
                        if ($assessments) {
                            $content .= templatereplace(file_get_contents($sTemplatePath . "assessment.pstpl"), array(), $redata);
                        }
                    }
                    if (trim(strip_tags($thissurvey['surveyls_endtext'])) == '') {
                        $completed = "<br /><span class='success'>" . $clang->gT("Thank you!") . "</span><br /><br />\n\n" . $clang->gT("Your survey responses have been recorded.") . "<br /><br />\n";
                    } else {
                        $completed = templatereplace($thissurvey['surveyls_endtext']);
                    }
                    // Link to Print Answer Preview  **********
                    if ($thissurvey['printanswers'] == 'Y') {
                        $url = Yii::app()->getController()->createUrl("printanswers/view/surveyid/{$surveyid}");
                        $completed .= "<br /><br />" . "<a class='printlink' href='{$url}'  target='_blank'>" . $clang->gT("Print your answers.") . "</a><br />\n";
                    }
                    //*****************************************
                    if ($thissurvey['publicstatistics'] == 'Y' && $thissurvey['printanswers'] == 'Y') {
                        $completed .= '<br />' . $clang->gT("or");
                    }
                    // Link to Public statistics  **********
                    if ($thissurvey['publicstatistics'] == 'Y') {
                        $url = Yii::app()->getController()->createUrl("statistics_user/action/surveyid/{$surveyid}/language/" . $_SESSION[$LEMsessid]['s_lang']);
                        $completed .= "<br /><br />" . "<a class='publicstatisticslink' href='{$url}' target='_blank'>" . $clang->gT("View the statistics for this survey.") . "</a><br />\n";
                    }
                    //*****************************************
                    $_SESSION[$LEMsessid]['finished'] = true;
                    $_SESSION[$LEMsessid]['sid'] = $surveyid;
                    sendCacheHeaders();
                    if (isset($thissurvey['autoredirect']) && $thissurvey['autoredirect'] == "Y" && $thissurvey['surveyls_url']) {
                        //Automatically redirect the page to the "url" setting for the survey
                        header("Location: {$thissurvey['surveyls_url']}");
                    }
                    doHeader();
                    echo $content;
                }
                $redata['completed'] = $completed;
                echo templatereplace(file_get_contents($sTemplatePath . "completed.pstpl"), array('completed' => $completed), $redata);
                echo "\n<br />\n";
                if (($LEMdebugLevel & LEM_DEBUG_TIMING) == LEM_DEBUG_TIMING) {
                    echo LimeExpressionManager::GetDebugTimingMessage();
                }
                if (($LEMdebugLevel & LEM_DEBUG_VALIDATION_SUMMARY) == LEM_DEBUG_VALIDATION_SUMMARY) {
                    echo "<table><tr><td align='left'><b>Group/Question Validation Results:</b>" . $moveResult['message'] . "</td></tr></table>\n";
                }
                echo templatereplace(file_get_contents($sTemplatePath . "endpage.pstpl"));
                doFooter();
                // The session cannot be killed until the page is completely rendered
                if ($thissurvey['printanswers'] != 'Y') {
                    killSurveySession($surveyid);
                }
                exit;
            }
        }
        $redata = compact(array_keys(get_defined_vars()));
        // IF GOT THIS FAR, THEN DISPLAY THE ACTIVE GROUP OF QUESTIONSs
        //SEE IF $surveyid EXISTS ####################################################################
        if ($surveyExists < 1) {
            //SURVEY DOES NOT EXIST. POLITELY EXIT.
            echo templatereplace(file_get_contents($sTemplatePath . "startpage.pstpl"), array(), $redata);
            echo "\t<center><br />\n";
            echo "\t" . $clang->gT("Sorry. There is no matching survey.") . "<br /></center>&nbsp;\n";
            echo templatereplace(file_get_contents($sTemplatePath . "endpage.pstpl"), array(), $redata);
            doFooter();
            exit;
        }
        createFieldMap($surveyid, 'full', false, false, $_SESSION[$LEMsessid]['s_lang']);
        //GET GROUP DETAILS
        if ($surveyMode == 'group' && $previewgrp) {
            //            setcookie("limesurvey_timers", "0"); //@todo fix - sometimes results in headers already sent error
            $_gid = sanitize_int($param['gid']);
            LimeExpressionManager::StartSurvey($thissurvey['sid'], 'group', $surveyOptions, false, $LEMdebugLevel);
            $gseq = LimeExpressionManager::GetGroupSeq($_gid);
            if ($gseq == -1) {
                echo $clang->gT('Invalid group number for this survey: ') . $_gid;
                exit;
            }
            $moveResult = LimeExpressionManager::JumpTo($gseq + 1, true);
            if (is_null($moveResult)) {
                echo $clang->gT('This group contains no questions.  You must add questions to this group before you can preview it');
                exit;
            }
            if (isset($moveResult)) {
                $_SESSION[$LEMsessid]['step'] = $moveResult['seq'] + 1;
                // step is index base 1?
            }
            $stepInfo = LimeExpressionManager::GetStepIndexInfo($moveResult['seq']);
            $gid = $stepInfo['gid'];
            $groupname = $stepInfo['gname'];
            $groupdescription = $stepInfo['gtext'];
        } else {
            if ($show_empty_group || !isset($_SESSION[$LEMsessid]['grouplist'])) {
                $gid = -1;
                // Make sure the gid is unused. This will assure that the foreach (fieldarray as ia) has no effect.
                $groupname = $clang->gT("Submit your answers");
                $groupdescription = $clang->gT("There are no more questions. Please press the <Submit> button to finish this survey.");
            } else {
                if ($surveyMode != 'survey') {
                    if ($previewquestion) {
                        $_qid = sanitize_int($param['qid']);
                        LimeExpressionManager::StartSurvey($surveyid, 'question', $surveyOptions, false, $LEMdebugLevel);
                        $qSec = LimeExpressionManager::GetQuestionSeq($_qid);
                        $moveResult = LimeExpressionManager::JumpTo($qSec + 1, true, false, true);
                        $stepInfo = LimeExpressionManager::GetStepIndexInfo($moveResult['seq']);
                    } else {
                        $stepInfo = LimeExpressionManager::GetStepIndexInfo($moveResult['seq']);
                    }
                    $gid = $stepInfo['gid'];
                    $groupname = $stepInfo['gname'];
                    $groupdescription = $stepInfo['gtext'];
                }
            }
        }
        if ($previewquestion) {
            $_SESSION[$LEMsessid]['step'] = 0;
            //maybe unset it after the question has been displayed?
        }
        if ($_SESSION[$LEMsessid]['step'] > $_SESSION[$LEMsessid]['maxstep']) {
            $_SESSION[$LEMsessid]['maxstep'] = $_SESSION[$LEMsessid]['step'];
        }
        // If the survey uses answer persistence and a srid is registered in SESSION
        // then loadanswers from this srid
        /* Only survey mode used this - should all?
           if ($thissurvey['tokenanswerspersistence'] == 'Y' &&
           $thissurvey['anonymized'] == "N" &&
           isset($_SESSION[$LEMsessid]['srid']) &&
           $thissurvey['active'] == "Y")
           {
           loadanswers();
           }
           */
        //******************************************************************************************************
        //PRESENT SURVEY
        //******************************************************************************************************
        $okToShowErrors = !$previewgrp && (isset($invalidLastPage) || $_SESSION[$LEMsessid]['prevstep'] == $_SESSION[$LEMsessid]['step']);
        Yii::app()->getController()->loadHelper('qanda');
        setNoAnswerMode($thissurvey);
        //Iterate through the questions about to be displayed:
        $inputnames = array();
        foreach ($_SESSION[$LEMsessid]['grouplist'] as $gl) {
            $gid = $gl[0];
            $qnumber = 0;
            if ($surveyMode != 'survey') {
                $onlyThisGID = $stepInfo['gid'];
                if ($onlyThisGID != $gid) {
                    continue;
                }
            }
            // TMSW - could iterate through LEM::currentQset instead
            foreach ($_SESSION[$LEMsessid]['fieldarray'] as $key => $ia) {
                ++$qnumber;
                $ia[9] = $qnumber;
                // incremental question count;
                if (isset($ia[10]) && $ia[10] == $gid || !isset($ia[10]) && $ia[5] == $gid) {
                    if ($surveyMode == 'question' && $ia[0] != $stepInfo['qid']) {
                        continue;
                    }
                    $qidattributes = getQuestionAttributeValues($ia[0], $ia[4]);
                    if ($ia[4] != '*' && ($qidattributes === false || !isset($qidattributes['hidden']) || $qidattributes['hidden'] == 1)) {
                        continue;
                    }
                    //Get the answers/inputnames
                    // TMSW - can content of retrieveAnswers() be provided by LEM?  Review scope of what it provides.
                    // TODO - retrieveAnswers is slow - queries database separately for each question. May be fixed in _CI or _YII ports, so ignore for now
                    list($plus_qanda, $plus_inputnames) = retrieveAnswers($ia, $surveyid);
                    if ($plus_qanda) {
                        $plus_qanda[] = $ia[4];
                        $plus_qanda[] = $ia[6];
                        // adds madatory identifyer for adding mandatory class to question wrapping div
                        $qanda[] = $plus_qanda;
                    }
                    if ($plus_inputnames) {
                        $inputnames = addtoarray_single($inputnames, $plus_inputnames);
                    }
                    //Display the "mandatory" popup if necessary
                    // TMSW - get question-level error messages - don't call **_popup() directly
                    if ($okToShowErrors && $stepInfo['mandViolation']) {
                        list($mandatorypopup, $popup) = mandatory_popup($ia, $notanswered);
                    }
                    //Display the "validation" popup if necessary
                    if ($okToShowErrors && !$stepInfo['valid']) {
                        list($validationpopup, $vpopup) = validation_popup($ia, $notvalidated);
                    }
                    // Display the "file validation" popup if necessary
                    if ($okToShowErrors && isset($filenotvalidated)) {
                        list($filevalidationpopup, $fpopup) = file_validation_popup($ia, $filenotvalidated);
                    }
                }
                if ($ia[4] == "|") {
                    $upload_file = TRUE;
                }
            }
            //end iteration
        }
        if ($surveyMode != 'survey' && isset($thissurvey['showprogress']) && $thissurvey['showprogress'] == 'Y') {
            if ($show_empty_group) {
                $percentcomplete = makegraph($_SESSION[$LEMsessid]['totalsteps'] + 1, $_SESSION[$LEMsessid]['totalsteps']);
            } else {
                $percentcomplete = makegraph($_SESSION[$LEMsessid]['step'], $_SESSION[$LEMsessid]['totalsteps']);
            }
        }
        if (!(isset($languagechanger) && strlen($languagechanger) > 0) && function_exists('makeLanguageChangerSurvey')) {
            $languagechanger = makeLanguageChangerSurvey($_SESSION[$LEMsessid]['s_lang']);
        }
        //READ TEMPLATES, INSERT DATA AND PRESENT PAGE
        sendCacheHeaders();
        doHeader();
        $redata = compact(array_keys(get_defined_vars()));
        echo templatereplace(file_get_contents($sTemplatePath . "startpage.pstpl"), array(), $redata);
        //popup need jquery
        if (isset($popup)) {
            echo $popup;
        }
        if (isset($vpopup)) {
            echo $vpopup;
        }
        if (isset($fpopup)) {
            echo $fpopup;
        }
        //ALTER PAGE CLASS TO PROVIDE WHOLE-PAGE ALTERNATION
        if ($surveyMode != 'survey' && $_SESSION[$LEMsessid]['step'] != $_SESSION[$LEMsessid]['prevstep'] || isset($_SESSION[$LEMsessid]['stepno']) && $_SESSION[$LEMsessid]['stepno'] % 2) {
            if (!isset($_SESSION[$LEMsessid]['stepno'])) {
                $_SESSION[$LEMsessid]['stepno'] = 0;
            }
            if ($_SESSION[$LEMsessid]['step'] != $_SESSION[$LEMsessid]['prevstep']) {
                ++$_SESSION[$LEMsessid]['stepno'];
            }
            if ($_SESSION[$LEMsessid]['stepno'] % 2) {
                echo "<script type=\"text/javascript\">\n" . "  \$(\"body\").addClass(\"page-odd\");\n" . "</script>\n";
            }
        }
        $hiddenfieldnames = implode("|", $inputnames);
        if (isset($upload_file) && $upload_file) {
            echo CHtml::form(array("survey/index"), 'post', array('enctype' => 'multipart/form-data', 'id' => 'limesurvey', 'name' => 'limesurvey', 'autocomplete' => 'off')) . "\n\n            <!-- INPUT NAMES -->\n            <input type='hidden' name='fieldnames' value='{$hiddenfieldnames}' id='fieldnames' />\n";
        } else {
            echo CHtml::form(array("survey/index"), 'post', array('id' => 'limesurvey', 'name' => 'limesurvey', 'autocomplete' => 'off')) . "\n\n            <!-- INPUT NAMES -->\n            <input type='hidden' name='fieldnames' value='{$hiddenfieldnames}' id='fieldnames' />\n";
        }
        echo sDefaultSubmitHandler();
        // <-- END FEATURE - SAVE
        if ($surveyMode == 'survey') {
            if (isset($thissurvey['showwelcome']) && $thissurvey['showwelcome'] == 'N') {
                //Hide the welcome screen if explicitly set
            } else {
                echo templatereplace(file_get_contents($sTemplatePath . "welcome.pstpl"), array(), $redata) . "\n";
            }
            if ($thissurvey['anonymized'] == "Y") {
                echo templatereplace(file_get_contents($sTemplatePath . "privacy.pstpl"), array(), $redata) . "\n";
            }
        }
        // <-- START THE SURVEY -->
        if ($surveyMode != 'survey') {
            echo templatereplace(file_get_contents($sTemplatePath . "survey.pstpl"), array(), $redata);
        }
        // the runonce element has been changed from a hidden to a text/display:none one
        // in order to workaround an not-reproduced issue #4453 (lemeur)
        echo "<input type='text' id='runonce' value='0' style='display: none;'/>\n        <!-- JAVASCRIPT FOR CONDITIONAL QUESTIONS -->\n        <script type='text/javascript'>\n        <!--\n";
        echo "var LEMradix='" . $radix . "';\n";
        echo "var numRegex = new RegExp('[^-' + LEMradix + '0-9]','g');\n";
        echo "var intRegex = new RegExp('[^-0-9]','g');\n";
        print <<<END
            function fixnum_checkconditions(value, name, type, evt_type, intonly)
            {
                newval = new String(value);
                if (typeof intonly !=='undefined' && intonly==1) {
                    newval = newval.replace(intRegex,'');
                }
                else {
                    newval = newval.replace(numRegex,'');
                }
                if (LEMradix === ',') {
                    newval = newval.split(',').join('.');
                }
                if (newval != '-' && newval != '.' && newval != '-.' && newval != parseFloat(newval)) {
                    newval = '';
                }
                displayVal = newval;
                if (LEMradix === ',') {
                    displayVal = displayVal.split('.').join(',');
                }
                if (name.match(/other\$/)) {
                    \$('#answer'+name+'text').val(displayVal);
                }
                \$('#answer'+name).val(displayVal);

                if (typeof evt_type === 'undefined')
                {
                    evt_type = 'onchange';
                }
                checkconditions(newval, name, type, evt_type);
            }

            function checkconditions(value, name, type, evt_type)
            {
                if (typeof evt_type === 'undefined')
                {
                    evt_type = 'onchange';
                }
                if (type == 'radio' || type == 'select-one')
                {
                    \$('#java'+name).val(value);
                }
                else if (type == 'checkbox')
                {
                    if (\$('#answer'+name).is(':checked'))
                    {
                        \$('#java'+name).val('Y');
                    } else
                    {
                        \$('#java'+name).val('');
                    }
                }
                else if (type == 'text' && name.match(/other\$/))
                {
                    \$('#java'+name).val(value);
                }
                ExprMgr_process_relevance_and_tailoring(evt_type,name,type);
END;
        if ($previewgrp) {
            // force the group to be visible, even if irrelevant - will not always work
            print <<<END
    \$('#relevanceG' + LEMgseq).val(1);
    \$(document).ready(function() {
        \$('#group-' + LEMgseq).show();
    });
    \$(document).change(function() {
        \$('#group-' + LEMgseq).show();
    });
    \$(document).bind('keydown',function(e) {
                if (e.keyCode == 9) {
                    \$('#group-' + LEMgseq).show();
                    return true;
                }
                return true;
            });

END;
        }
        print <<<END
            }
        // -->
        </script>
END;
        //Display the "mandatory" message on page if necessary
        if (isset($showpopups) && $showpopups == 0 && $stepInfo['mandViolation'] && $okToShowErrors) {
            echo "<p><span class='errormandatory'>" . $clang->gT("One or more mandatory questions have not been answered. You cannot proceed until these have been completed.") . "</span></p>";
        }
        //Display the "validation" message on page if necessary
        if (isset($showpopups) && $showpopups == 0 && !$stepInfo['valid'] && $okToShowErrors) {
            echo "<p><span class='errormandatory'>" . $clang->gT("One or more questions have not been answered in a valid manner. You cannot proceed until these answers are valid.") . "</span></p>";
        }
        //Display the "file validation" message on page if necessary
        if (isset($showpopups) && $showpopups == 0 && isset($filenotvalidated) && $filenotvalidated == true && $okToShowErrors) {
            echo "<p><span class='errormandatory'>" . $clang->gT("One or more uploaded files are not in proper format/size. You cannot proceed until these files are valid.") . "</span></p>";
        }
        $_gseq = -1;
        foreach ($_SESSION[$LEMsessid]['grouplist'] as $gl) {
            $gid = $gl[0];
            ++$_gseq;
            $groupname = $gl[1];
            $groupdescription = $gl[2];
            if ($surveyMode != 'survey' && $gid != $onlyThisGID) {
                continue;
            }
            $redata = compact(array_keys(get_defined_vars()));
            echo "\n\n<!-- START THE GROUP -->\n";
            echo "\n\n<div id='group-{$_gseq}'";
            $gnoshow = LimeExpressionManager::GroupIsIrrelevantOrHidden($_gseq);
            if ($gnoshow && !$previewgrp) {
                echo " style='display: none;'";
            }
            echo ">\n";
            echo templatereplace(file_get_contents($sTemplatePath . "startgroup.pstpl"), array(), $redata);
            echo "\n";
            if (!$previewquestion) {
                echo templatereplace(file_get_contents($sTemplatePath . "groupdescription.pstpl"), array(), $redata);
            }
            echo "\n";
            echo "\n\n<!-- PRESENT THE QUESTIONS -->\n";
            foreach ($qanda as $qa) {
                if ($gid != $qa[6]) {
                    continue;
                }
                $qid = $qa[4];
                $qinfo = LimeExpressionManager::GetQuestionStatus($qid);
                $lastgrouparray = explode("X", $qa[7]);
                $lastgroup = $lastgrouparray[0] . "X" . $lastgrouparray[1];
                // id of the last group, derived from question id
                $lastanswer = $qa[7];
                $q_class = getQuestionClass($qinfo['info']['type']);
                $man_class = '';
                if ($qinfo['info']['mandatory'] == 'Y') {
                    $man_class .= ' mandatory';
                }
                if ($qinfo['anyUnanswered'] && $_SESSION[$LEMsessid]['maxstep'] != $_SESSION[$LEMsessid]['step']) {
                    $man_class .= ' missing';
                }
                $n_q_display = '';
                if ($qinfo['hidden'] && $qinfo['info']['type'] != '*') {
                    continue;
                    // skip this one
                }
                if (!$qinfo['relevant'] || $qinfo['hidden'] && $qinfo['info']['type'] == '*') {
                    $n_q_display = ' style="display: none;"';
                }
                $question = $qa[0];
                //===================================================================
                // The following four variables offer the templating system the
                // capacity to fully control the HTML output for questions making the
                // above echo redundant if desired.
                $question['essentials'] = 'id="question' . $qa[4] . '"' . $n_q_display;
                $question['class'] = $q_class;
                $question['man_class'] = $man_class;
                $question['code'] = $qa[5];
                $question['sgq'] = $qa[7];
                $question['aid'] = !empty($qinfo['info']['aid']) ? $qinfo['info']['aid'] : 0;
                $question['sqid'] = !empty($qinfo['info']['sqid']) ? $qinfo['info']['sqid'] : 0;
                $question['type'] = $qinfo['info']['type'];
                //===================================================================
                $answer = $qa[1];
                $help = $qinfo['info']['help'];
                // $qa[2];
                $redata = compact(array_keys(get_defined_vars()));
                $question_template = file_get_contents($sTemplatePath . 'question.pstpl');
                if (preg_match('/\\{QUESTION_ESSENTIALS\\}/', $question_template) === false || preg_match('/\\{QUESTION_CLASS\\}/', $question_template) === false) {
                    // if {QUESTION_ESSENTIALS} is present in the template but not {QUESTION_CLASS} remove it because you don't want id="" and display="" duplicated.
                    $question_template = str_replace('{QUESTION_ESSENTIALS}', '', $question_template);
                    $question_template = str_replace('{QUESTION_CLASS}', '', $question_template);
                    echo '
                    <!-- NEW QUESTION -->
                    <div id="question' . $qa[4] . '" class="' . $q_class . $man_class . '"' . $n_q_display . '>';
                    echo templatereplace($question_template, array(), $redata, false, false, $qa[4]);
                    echo '</div>';
                } else {
                    // TMSW - eventually refactor so that only substitutes the QUESTION_** fields - doesn't need full power of template replace
                    // TMSW - also, want to return a string, and call templatereplace once on that result string once all done.
                    echo templatereplace($question_template, array(), $redata, false, false, $qa[4]);
                }
            }
            if ($surveyMode == 'group') {
                echo "<input type='hidden' name='lastgroup' value='{$lastgroup}' id='lastgroup' />\n";
                // for counting the time spent on each group
            }
            if ($surveyMode == 'question') {
                echo "<input type='hidden' name='lastanswer' value='{$lastanswer}' id='lastanswer' />\n";
            }
            echo "\n\n<!-- END THE GROUP -->\n";
            echo templatereplace(file_get_contents($sTemplatePath . "endgroup.pstpl"), array(), $redata);
            echo "\n\n</div>\n";
        }
        LimeExpressionManager::FinishProcessingGroup($LEMskipReprocessing);
        echo LimeExpressionManager::GetRelevanceAndTailoringJavaScript();
        LimeExpressionManager::FinishProcessingPage();
        if (!$previewgrp && !$previewquestion) {
            $navigator = surveymover();
            //This gets globalised in the templatereplace function
            $redata = compact(array_keys(get_defined_vars()));
            echo "\n\n<!-- PRESENT THE NAVIGATOR -->\n";
            echo templatereplace(file_get_contents($sTemplatePath . "navigator.pstpl"), array(), $redata);
            echo "\n";
            if ($thissurvey['active'] != "Y") {
                echo "<p style='text-align:center' class='error'>" . $clang->gT("This survey is currently not active. You will not be able to save your responses.") . "</p>\n";
            }
            if ($surveyMode != 'survey' && $thissurvey['allowjumps'] == 'Y') {
                echo "\n\n<!-- PRESENT THE INDEX -->\n";
                echo '<div id="index"><div class="container"><h2>' . $clang->gT("Question index") . '</h2>';
                $stepIndex = LimeExpressionManager::GetStepIndexInfo();
                $lastGseq = -1;
                $gseq = -1;
                $grel = true;
                for ($v = 0, $n = 0; $n != $_SESSION[$LEMsessid]['maxstep']; ++$n) {
                    if (!isset($stepIndex[$n])) {
                        continue;
                        // this is an invalid group - skip it
                    }
                    $stepInfo = $stepIndex[$n];
                    if ($surveyMode == 'question') {
                        if ($lastGseq != $stepInfo['gseq']) {
                            // show the group label
                            ++$gseq;
                            $g = $_SESSION[$LEMsessid]['grouplist'][$gseq];
                            $grel = !LimeExpressionManager::GroupIsIrrelevantOrHidden($gseq);
                            if ($grel) {
                                $gtitle = LimeExpressionManager::ProcessString($g[1]);
                                echo '<h3>' . flattenText($gtitle) . "</h3>";
                            }
                            $lastGseq = $stepInfo['gseq'];
                        }
                        if (!$grel || !$stepInfo['show']) {
                            continue;
                        }
                        $q = $_SESSION[$LEMsessid]['fieldarray'][$n];
                    } else {
                        ++$gseq;
                        if (!$stepInfo['show']) {
                            continue;
                        }
                        $g = $_SESSION[$LEMsessid]['grouplist'][$gseq];
                    }
                    if ($surveyMode == 'group') {
                        $indexlabel = LimeExpressionManager::ProcessString($g[1]);
                    } else {
                        $indexlabel = LimeExpressionManager::ProcessString($q[3]);
                    }
                    $sText = $surveyMode == 'group' ? flattenText($indexlabel) : flattenText($indexlabel);
                    $bGAnsw = !$stepInfo['anyUnanswered'];
                    ++$v;
                    $class = $n == $_SESSION[$LEMsessid]['step'] - 1 ? 'current' : ($bGAnsw ? 'answer' : 'missing');
                    if ($v % 2) {
                        $class .= " odd";
                    }
                    $s = $n + 1;
                    echo "<div class=\"row {$class}\" onclick=\"javascript:document.limesurvey.move.value = '{$s}'; document.limesurvey.submit();\"><span class=\"hdr\">{$v}</span><span title=\"{$sText}\">{$sText}</span></div>";
                }
                if ($_SESSION[$LEMsessid]['maxstep'] == $_SESSION[$LEMsessid]['totalsteps']) {
                    echo "<input class='submit' type='submit' accesskey='l' onclick=\"javascript:document.limesurvey.move.value = 'movesubmit';\" value=' " . $clang->gT("Submit") . " ' name='move2' />\n";
                }
                echo '</div></div>';
                /* Can be replaced by php or in global js */
                echo "<script type=\"text/javascript\">\n" . "  \$(\".outerframe\").addClass(\"withindex\");\n" . "  var idx = \$(\"#index\");\n" . "  var row = \$(\"#index .row.current\");\n" . "  idx.scrollTop(row.position().top - idx.height() / 2 - row.height() / 2);\n" . "</script>\n";
                echo "\n";
            }
            echo "<input type='hidden' name='thisstep' value='{$_SESSION[$LEMsessid]['step']}' id='thisstep' />\n";
            echo "<input type='hidden' name='sid' value='{$surveyid}' id='sid' />\n";
            echo "<input type='hidden' name='start_time' value='" . time() . "' id='start_time' />\n";
            $_SESSION[$LEMsessid]['LEMpostKey'] = mt_rand();
            echo "<input type='hidden' name='LEMpostKey' value='{$_SESSION[$LEMsessid]['LEMpostKey']}' id='LEMpostKey' />\n";
            if (isset($token) && !empty($token)) {
                echo "\n<input type='hidden' name='token' value='{$token}' id='token' />\n";
            }
        }
        if (($LEMdebugLevel & LEM_DEBUG_TIMING) == LEM_DEBUG_TIMING) {
            echo LimeExpressionManager::GetDebugTimingMessage();
        }
        if (($LEMdebugLevel & LEM_DEBUG_VALIDATION_SUMMARY) == LEM_DEBUG_VALIDATION_SUMMARY) {
            echo "<table><tr><td align='left'><b>Group/Question Validation Results:</b>" . $moveResult['message'] . "</td></tr></table>\n";
        }
        echo "</form>\n";
        echo templatereplace(file_get_contents($sTemplatePath . "endpage.pstpl"), array(), $redata);
        echo "\n";
        doFooter();
    }
Example #4
0
{
    sendcacheheaders();
    doHeader();
    //SURVEY DOES NOT EXIST. POLITELY EXIT.
    echo templatereplace(file_get_contents("$thistpl/startpage.pstpl"));
    echo "\t<center><br />\n"
    ."\t".$clang->gT("Sorry. There is no matching survey.")."<br /></center>&nbsp;\n";
    echo templatereplace(file_get_contents("$thistpl/endpage.pstpl"));
    doFooter();
    exit;
}

//RUN THIS IF THIS IS THE FIRST TIME
if ((!isset($_SESSION['step']) || !$_SESSION['step'] || !isset($totalquestions))  && (!isset($notanswered) || !$notanswered) && (!isset($notvalidated) && !$notvalidated) && (!isset($filenotvalidated) || !$filenotvalidated))
{
    $totalquestions = buildsurveysession();
    $_SESSION['step'] = 1;
}

// If the survey uses answer persistence and a srid is registered in SESSION
// then loadanswers from this srid
if ($thissurvey['tokenanswerspersistence'] == 'Y' &&
$thissurvey['anonymized'] == "N" &&
isset($_SESSION['srid']) &&
$thissurvey['active'] == "Y")
{
    loadanswers();
}

//******************************************************************************************************
//PRESENT SURVEY
Example #5
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>";
        }
    }
Example #6
0
//Check to see if a refering URL has been captured.
GetReferringUrl();
// 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 ($thissurvey['tokenanswerspersistence'] == 'Y' && !isset($_SESSION['srid']) && $thissurvey['private'] == "N" && $thissurvey['active'] == "Y" && isset($token) && $token != '') {
    // load previous answers if any (dataentry with nosubmit)
    $srquery = "SELECT id FROM {$thissurvey['tablename']}" . " WHERE {$thissurvey['tablename']}.token='" . db_quote($token) . "'\n";
    $result = $connect->GetOne($srquery);
    if ($result !== false && !is_null($result)) {
        $_SESSION['srid'] = $result;
    }
    buildsurveysession();
    loadanswers();
}
// SAVE POSTED ANSWERS TO DATABASE IF MOVE (NEXT,PREV,LAST, or SUBMIT) or RETURNING FROM SAVE FORM
if (isset($move) || isset($_POST['saveprompt'])) {
    require_once "save.php";
    // RELOAD THE ANSWERS INCASE SOMEONE ELSE CHANGED THEM
    if ($thissurvey['active'] == "Y" && $thissurvey['allowsave'] == "Y") {
        loadanswers();
    }
}
sendcacheheaders();
//CALL APPROPRIATE SCRIPT
switch ($thissurvey['format']) {
    case "A":
        //All in one
Example #7
0
    if ($result->RecordCount() > 0) {
        $row = $result->FetchRow();
        if ($row['submitdate'] == '' && $thissurvey['tokenanswerspersistence'] == 'Y' || $row['submitdate'] != '' && $thissurvey['alloweditaftercompletion'] == 'Y') {
            $_SESSION['srid'] = $row['id'];
            if (!is_null($row['lastpage']) && $row['submitdate'] == '') {
                $_SESSION['LEMtokenResume'] = true;
                $_SESSION['step'] = $row['lastpage'];
            }
        }
        buildsurveysession();
        loadanswers();
    }
}
if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'previewgroup') {
    $thissurvey['format'] = 'G';
    buildsurveysession(true);
}
sendcacheheaders();
//CALL APPROPRIATE SCRIPT
require_once "group.php";
// works for all survey styles - rename to navigation_controller.php?
//queXS Addition
if (isset($_POST['move']) || isset($_POST['saveprompt'])) {
    savedcontrol();
}
/* queXS Removal
if (isset($_POST['saveall']) || isset($flashmessage))
{
    echo "<script language='JavaScript'> $(document).ready( function() {alert('".$clang->gT("Your responses were successfully saved.","js")."');}) </script>";
}
end queXS Removal */