Example #1
0
 function run($args)
 {
     extract($args);
     $redata = compact(array_keys(get_defined_vars()));
     $sTemplatePath = $_SESSION['survey_' . $surveyid]['templatepath'];
     sendCacheHeaders();
     doHeader();
     echo templatereplace(file_get_contents($sTemplatePath . "startpage.pstpl"), array(), $redata);
     echo "\n\n<!-- JAVASCRIPT FOR CONDITIONAL QUESTIONS -->\n" . "\t<script type='text/javascript'>\n" . "function checkconditions(value, name, type, evt_type)\n" . "\t{\n" . "\t}\n" . "\t</script>\n\n";
     echo CHtml::form(array("/survey/index", "sid" => $surveyid), 'post') . "\n";
     echo templatereplace(file_get_contents($sTemplatePath . "load.pstpl"), array(), $redata);
     //PRESENT OPTIONS SCREEN (Replace with Template Later)
     //END
     echo "<input type='hidden' name='loadall' value='reload' />\n";
     if (isset($clienttoken) && $clienttoken != "") {
         echo "<input type='hidden' name='token' value='{$clienttoken}' />\n";
     }
     echo "</form>";
     echo templatereplace(file_get_contents($sTemplatePath . "endpage.pstpl"), array(), $redata);
     doFooter();
     exit;
 }
Example #2
0
 function _niceExit(&$redata, $iDebugLine, $sTemplateDir = null, $asMessage = array())
 {
     if (isset($redata['surveyid']) && $redata['surveyid'] && !isset($thisurvey)) {
         $thissurvey = getSurveyInfo($redata['surveyid']);
         $sTemplateDir = getTemplatePath($thissurvey['template']);
     } else {
         $sTemplateDir = getTemplatePath($sTemplateDir);
     }
     sendCacheHeaders();
     doHeader();
     $this->_printTemplateContent($sTemplateDir . '/startpage.pstpl', $redata, $iDebugLine);
     $this->_printMessage($asMessage);
     $this->_printTemplateContent($sTemplateDir . '/endpage.pstpl', $redata, $iDebugLine);
     doFooter();
     exit;
 }
 /**
  * register::index()
  * Process register form data and take appropriate action
  * @return
  */
 function actionIndex($iSurveyID = null)
 {
     Yii::app()->loadHelper('database');
     Yii::app()->loadHelper('replacements');
     $sLanguage = Yii::app()->request->getParam('lang', '');
     if ($iSurveyID == null) {
         $iSurveyID = Yii::app()->request->getPost('sid');
     }
     if (!$iSurveyID) {
         $this->redirect(Yii::app()->baseUrl);
     }
     if ($sLanguage == "") {
         $sBaseLanguage = Survey::model()->findByPk($iSurveyID)->language;
     } else {
         $sBaseLanguage = $sLanguage;
     }
     Yii::import('application.libraries.Limesurvey_lang');
     Yii::app()->lang = new Limesurvey_lang($sBaseLanguage);
     $clang = Yii::app()->lang;
     $thissurvey = getSurveyInfo($iSurveyID, $sBaseLanguage);
     $register_errormsg = "";
     // Check the security question's answer
     if (function_exists("ImageCreate") && isCaptchaEnabled('registrationscreen', $thissurvey['usecaptcha'])) {
         if (!isset($_POST['loadsecurity']) || !isset($_SESSION['survey_' . $iSurveyID]['secanswer']) || Yii::app()->request->getPost('loadsecurity') != $_SESSION['survey_' . $iSurveyID]['secanswer']) {
             $register_errormsg .= $clang->gT("The answer to the security question is incorrect.") . "<br />\n";
         }
     }
     //Check that the email is a valid style address
     if (!validateEmailAddress(Yii::app()->request->getPost('register_email'))) {
         $register_errormsg .= $clang->gT("The email you used is not valid. Please try again.");
     }
     // Check for additional fields
     $attributeinsertdata = array();
     foreach (GetParticipantAttributes($iSurveyID) as $field => $data) {
         if (empty($data['show_register']) || $data['show_register'] != 'Y') {
             continue;
         }
         $value = sanitize_xss_string(Yii::app()->request->getPost('register_' . $field));
         if (trim($value) == '' && $data['mandatory'] == 'Y') {
             $register_errormsg .= sprintf($clang->gT("%s cannot be left empty"), $thissurvey['attributecaptions'][$field]);
         }
         $attributeinsertdata[$field] = $value;
     }
     if ($register_errormsg != "") {
         $_SESSION['survey_' . $iSurveyID]['register_errormsg'] = $register_errormsg;
         $this->redirect($this->createUrl("survey/index/sid/{$iSurveyID}", array('lang' => $sBaseLanguage)));
     }
     //Check if this email already exists in token database
     $oToken = TokenDynamic::model($iSurveyID)->find('email=:email', array(':email' => Yii::app()->request->getPost('register_email')));
     if ($oToken) {
         $register_errormsg = $clang->gT("The email you used has already been registered.");
         $_SESSION['survey_' . $iSurveyID]['register_errormsg'] = $register_errormsg;
         $this->redirect($this->createUrl("survey/index/sid/{$iSurveyID}", array('lang' => $sBaseLanguage)));
         //include "index.php";
         //exit;
     }
     $mayinsert = false;
     // Get the survey settings for token length
     $tokenlength = $thissurvey['tokenlength'];
     //if tokenlength is not set or there are other problems use the default value (15)
     if (!isset($tokenlength) || $tokenlength == '') {
         $tokenlength = 15;
     }
     while ($mayinsert != true) {
         $newtoken = randomChars($tokenlength);
         $oTokenExist = TokenDynamic::model($iSurveyID)->find('token=:token', array(':token' => $newtoken));
         if (!$oTokenExist) {
             $mayinsert = true;
         }
     }
     $postfirstname = sanitize_xss_string(strip_tags(Yii::app()->request->getPost('register_firstname')));
     $postlastname = sanitize_xss_string(strip_tags(Yii::app()->request->getPost('register_lastname')));
     $starttime = sanitize_xss_string(Yii::app()->request->getPost('startdate'));
     $endtime = sanitize_xss_string(Yii::app()->request->getPost('enddate'));
     /*$postattribute1=sanitize_xss_string(strip_tags(returnGlobal('register_attribute1')));
       $postattribute2=sanitize_xss_string(strip_tags(returnGlobal('register_attribute2')));   */
     // Insert new entry into tokens db
     $oToken = Token::create($thissurvey['sid']);
     $oToken->firstname = $postfirstname;
     $oToken->lastname = $postlastname;
     $oToken->email = Yii::app()->request->getPost('register_email');
     $oToken->emailstatus = 'OK';
     $oToken->token = $newtoken;
     if ($starttime && $endtime) {
         $oToken->validfrom = $starttime;
         $oToken->validuntil = $endtime;
     }
     $oToken->setAttributes($attributeinsertdata, false);
     $result = $oToken->save();
     //$tid = $oToken->tid;// Not needed any more
     $fieldsarray["{ADMINNAME}"] = $thissurvey['adminname'];
     $fieldsarray["{ADMINEMAIL}"] = $thissurvey['adminemail'];
     $fieldsarray["{SURVEYNAME}"] = $thissurvey['name'];
     $fieldsarray["{SURVEYDESCRIPTION}"] = $thissurvey['description'];
     $fieldsarray["{FIRSTNAME}"] = $postfirstname;
     $fieldsarray["{LASTNAME}"] = $postlastname;
     $fieldsarray["{EXPIRY}"] = $thissurvey["expiry"];
     $fieldsarray["{TOKEN}"] = $oToken->token;
     $fieldsarray["{EMAIL}"] = $oToken->email;
     $token = $oToken->token;
     $message = $thissurvey['email_register'];
     $subject = $thissurvey['email_register_subj'];
     $from = "{$thissurvey['adminname']} <{$thissurvey['adminemail']}>";
     $surveylink = $this->createAbsoluteUrl("/survey/index/sid/{$iSurveyID}", array('lang' => $sBaseLanguage, 'token' => $newtoken));
     $optoutlink = $this->createAbsoluteUrl("/optout/tokens/surveyid/{$iSurveyID}", array('langcode' => $sBaseLanguage, 'token' => $newtoken));
     $optinlink = $this->createAbsoluteUrl("/optin/tokens/surveyid/{$iSurveyID}", array('langcode' => $sBaseLanguage, 'token' => $newtoken));
     if (getEmailFormat($iSurveyID) == 'html') {
         $useHtmlEmail = true;
         $fieldsarray["{SURVEYURL}"] = "<a href='{$surveylink}'>" . $surveylink . "</a>";
         $fieldsarray["{OPTOUTURL}"] = "<a href='{$optoutlink}'>" . $optoutlink . "</a>";
         $fieldsarray["{OPTINURL}"] = "<a href='{$optinlink}'>" . $optinlink . "</a>";
     } else {
         $useHtmlEmail = false;
         $fieldsarray["{SURVEYURL}"] = $surveylink;
         $fieldsarray["{OPTOUTURL}"] = $optoutlink;
         $fieldsarray["{OPTINURL}"] = $optinlink;
     }
     $message = ReplaceFields($message, $fieldsarray);
     $subject = ReplaceFields($subject, $fieldsarray);
     $html = "";
     //Set variable
     $sitename = Yii::app()->getConfig('sitename');
     if (SendEmailMessage($message, $subject, Yii::app()->request->getPost('register_email'), $from, $sitename, $useHtmlEmail, getBounceEmail($iSurveyID))) {
         // TLR change to put date into sent
         $today = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i", Yii::app()->getConfig('timeadjust'));
         $oToken->sent = $today;
         $oToken->save();
         $html = "<div id='wrapper' class='message tokenmessage'>" . "<p>" . $clang->gT("Thank you for registering to participate in this survey.") . "</p>\n" . "<p>" . $clang->gT("An email has been sent to the address you provided with access details for this survey. Please follow the link in that email to proceed.") . "</p>\n" . "<p>" . $clang->gT("Survey administrator") . " {ADMINNAME} ({ADMINEMAIL})</p>" . "</div>\n";
         $html = ReplaceFields($html, $fieldsarray);
     } else {
         $html = "Email Error";
     }
     //PRINT COMPLETED PAGE
     if (!$thissurvey['template']) {
         $thistpl = getTemplatePath(validateTemplateDir('default'));
     } else {
         $thistpl = getTemplatePath(validateTemplateDir($thissurvey['template']));
     }
     // Same fix than http://bugs.limesurvey.org/view.php?id=8441
     ob_start(function ($buffer, $phase) {
         App()->getClientScript()->render($buffer);
         App()->getClientScript()->reset();
         return $buffer;
     });
     ob_implicit_flush(false);
     sendCacheHeaders();
     doHeader();
     Yii::app()->lang = $clang;
     // fetch the defined variables and pass it to the header footer templates.
     $redata = compact(array_keys(get_defined_vars()));
     $this->_printTemplateContent($thistpl . '/startpage.pstpl', $redata, __LINE__);
     $this->_printTemplateContent($thistpl . '/survey.pstpl', $redata, __LINE__);
     echo $html;
     $this->_printTemplateContent($thistpl . '/endpage.pstpl', $redata, __LINE__);
     doFooter();
     ob_flush();
 }
 /**
  * printanswers::view()
  * View answers at the end of a survey in one place. To export as pdf, set 'usepdfexport' = 1 in lsconfig.php and $printableexport='pdf'.
  * @param mixed $surveyid
  * @param bool $printableexport
  * @return
  */
 function actionView($surveyid, $printableexport = FALSE)
 {
     Yii::app()->loadHelper("frontend");
     Yii::import('application.libraries.admin.pdf');
     $iSurveyID = (int) $surveyid;
     $sExportType = $printableexport;
     Yii::app()->loadHelper('database');
     if (isset($_SESSION['survey_' . $iSurveyID]['sid'])) {
         $iSurveyID = $_SESSION['survey_' . $iSurveyID]['sid'];
     } else {
         //die('Invalid survey/session');
     }
     // Get the survey inforamtion
     // Set the language for dispay
     if (isset($_SESSION['survey_' . $iSurveyID]['s_lang'])) {
         $sLanguage = $_SESSION['survey_' . $iSurveyID]['s_lang'];
     } elseif (Survey::model()->findByPk($iSurveyID)) {
         $sLanguage = Survey::model()->findByPk($iSurveyID)->language;
     } else {
         $iSurveyID = 0;
         $sLanguage = Yii::app()->getConfig("defaultlang");
     }
     $clang = SetSurveyLanguage($iSurveyID, $sLanguage);
     $aSurveyInfo = getSurveyInfo($iSurveyID, $sLanguage);
     //SET THE TEMPLATE DIRECTORY
     if (!isset($aSurveyInfo['templatedir']) || !$aSurveyInfo['templatedir']) {
         $aSurveyInfo['templatedir'] = Yii::app()->getConfig('defaulttemplate');
     }
     $sTemplate = validateTemplateDir($aSurveyInfo['templatedir']);
     //Survey is not finished or don't exist
     if (!isset($_SESSION['survey_' . $iSurveyID]['finished']) || !isset($_SESSION['survey_' . $iSurveyID]['srid'])) {
         sendCacheHeaders();
         doHeader();
         echo templatereplace(file_get_contents(getTemplatePath($sTemplate) . '/startpage.pstpl'), array());
         echo "<center><br />\n" . "\t<font color='RED'><strong>" . $clang->gT("Error") . "</strong></font><br />\n" . "\t" . $clang->gT("We are sorry but your session has expired.") . "<br />" . $clang->gT("Either you have been inactive for too long, you have cookies disabled for your browser, or there were problems with your connection.") . "<br />\n" . "\t" . sprintf($clang->gT("Please contact %s ( %s ) for further assistance."), Yii::app()->getConfig("siteadminname"), Yii::app()->getConfig("siteadminemail")) . "\n" . "</center><br />\n";
         echo templatereplace(file_get_contents(getTemplatePath($sTemplate) . '/endpage.pstpl'), array());
         doFooter();
         exit;
     }
     //Fin session time out
     $sSRID = $_SESSION['survey_' . $iSurveyID]['srid'];
     //I want to see the answers with this id
     //Ensure script is not run directly, avoid path disclosure
     //if (!isset($rootdir) || isset($_REQUEST['$rootdir'])) {die( "browse - Cannot run this script directly");}
     if ($aSurveyInfo['printanswers'] == 'N') {
         die;
         //Die quietly if print answers is not permitted
     }
     //CHECK IF SURVEY IS ACTIVATED AND EXISTS
     $sSurveyName = $aSurveyInfo['surveyls_title'];
     $sAnonymized = $aSurveyInfo['anonymized'];
     //OK. IF WE GOT THIS FAR, THEN THE SURVEY EXISTS AND IT IS ACTIVE, SO LETS GET TO WORK.
     //SHOW HEADER
     $sOutput = CHtml::form(array("printanswers/view/surveyid/{$iSurveyID}/printableexport/pdf"), 'post') . "<center><input type='submit' value='" . $clang->gT("PDF export") . "'id=\"exportbutton\"/><input type='hidden' name='printableexport' /></center></form>";
     if ($sExportType == 'pdf') {
         //require (Yii::app()->getConfig('rootdir').'/application/config/tcpdf.php');
         Yii::import('application.libraries.admin.pdf', true);
         Yii::import('application.helpers.pdfHelper');
         $aPdfLanguageSettings = pdfHelper::getPdfLanguageSettings($clang->langcode);
         $oPDF = new pdf();
         $oPDF->SetTitle($clang->gT("Survey name (ID)", 'unescaped') . ": {$sSurveyName} ({$iSurveyID})");
         $oPDF->SetSubject($sSurveyName);
         $oPDF->SetDisplayMode('fullpage', 'two');
         $oPDF->setLanguageArray($aPdfLanguageSettings['lg']);
         $oPDF->setHeaderFont(array($aPdfLanguageSettings['pdffont'], '', PDF_FONT_SIZE_MAIN));
         $oPDF->setFooterFont(array($aPdfLanguageSettings['pdffont'], '', PDF_FONT_SIZE_DATA));
         $oPDF->SetFont($aPdfLanguageSettings['pdffont'], '', $aPdfLanguageSettings['pdffontsize']);
         $oPDF->AddPage();
         $oPDF->titleintopdf($clang->gT("Survey name (ID)", 'unescaped') . ": {$sSurveyName} ({$iSurveyID})");
     }
     $sOutput .= "\t<div class='printouttitle'><strong>" . $clang->gT("Survey name (ID):") . "</strong> {$sSurveyName} ({$iSurveyID})</div><p>&nbsp;\n";
     LimeExpressionManager::StartProcessingPage(true);
     // means that all variables are on the same page
     // Since all data are loaded, and don't need JavaScript, pretend all from Group 1
     LimeExpressionManager::StartProcessingGroup(1, $aSurveyInfo['anonymized'] != "N", $iSurveyID);
     $printanswershonorsconditions = Yii::app()->getConfig('printanswershonorsconditions');
     $aFullResponseTable = getFullResponseTable($iSurveyID, $sSRID, $sLanguage, $printanswershonorsconditions);
     //Get the fieldmap @TODO: do we need to filter out some fields?
     if ($aSurveyInfo['datestamp'] != "Y" || $sAnonymized == 'Y') {
         unset($aFullResponseTable['submitdate']);
     } else {
         unset($aFullResponseTable['id']);
     }
     unset($aFullResponseTable['token']);
     unset($aFullResponseTable['lastpage']);
     unset($aFullResponseTable['startlanguage']);
     unset($aFullResponseTable['datestamp']);
     unset($aFullResponseTable['startdate']);
     $sOutput .= "<table class='printouttable' >\n";
     foreach ($aFullResponseTable as $sFieldname => $fname) {
         if (substr($sFieldname, 0, 4) == 'gid_') {
             $sOutput .= "\t<tr class='printanswersgroup'><td colspan='2'>{$fname[0]}</td></tr>\n";
         } elseif (substr($sFieldname, 0, 4) == 'qid_') {
             $sOutput .= "\t<tr class='printanswersquestionhead'><td colspan='2'>{$fname[0]}</td></tr>\n";
         } elseif ($sFieldname == 'submitdate') {
             if ($sAnonymized != 'Y') {
                 $sOutput .= "\t<tr class='printanswersquestion'><td>{$fname[0]} {$fname[1]} {$sFieldname}</td><td class='printanswersanswertext'>{$fname[2]}</td></tr>";
             }
         } else {
             $sOutput .= "\t<tr class='printanswersquestion'><td>{$fname[0]} {$fname[1]}</td><td class='printanswersanswertext'>" . flattenText($fname[2]) . "</td></tr>";
         }
     }
     $sOutput .= "</table>\n";
     $sData['thissurvey'] = $aSurveyInfo;
     $sOutput = templatereplace($sOutput, array(), $sData, '', $aSurveyInfo['anonymized'] == "Y", NULL, array(), true);
     // Do a static replacement
     if ($sExportType == 'pdf') {
         $oPDF->writeHTML($sOutput);
         header("Pragma: public");
         header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
         $sExportFileName = sanitize_filename($sSurveyName);
         $oPDF->Output($sExportFileName . "-" . $iSurveyID . ".pdf", "D");
     } else {
         ob_start(function ($buffer, $phase) {
             App()->getClientScript()->render($buffer);
             App()->getClientScript()->reset();
             return $buffer;
         });
         ob_implicit_flush(false);
         sendCacheHeaders();
         doHeader();
         echo templatereplace(file_get_contents(getTemplatePath($sTemplate) . '/startpage.pstpl'), array(), $sData);
         echo templatereplace(file_get_contents(getTemplatePath($sTemplate) . '/printanswers.pstpl'), array('ANSWERTABLE' => $sOutput), $sData);
         echo templatereplace(file_get_contents(getTemplatePath($sTemplate) . '/endpage.pstpl'), array(), $sData);
         echo "</body></html>";
         ob_flush();
     }
     LimeExpressionManager::FinishProcessingGroup();
     LimeExpressionManager::FinishProcessingPage();
 }
 private function _renderHtml($html, $thistpl)
 {
     sendCacheHeaders();
     doHeader();
     $data['html'] = $html;
     $data['thistpl'] = $thistpl;
     $this->render('/opt_view', $data);
     doFooter();
 }
/**
* Shows the welcome page, used in group by group and question by question mode
*/
function display_first_page()
{
    global $token, $surveyid, $thissurvey, $navigator;
    $totalquestions = $_SESSION['survey_' . $surveyid]['totalquestions'];
    $clang = Yii::app()->lang;
    // Fill some necessary var for template
    $navigator = surveymover();
    $sitename = Yii::app()->getConfig('sitename');
    $languagechanger = makeLanguageChangerSurvey($clang->langcode);
    sendCacheHeaders();
    doHeader();
    LimeExpressionManager::StartProcessingPage();
    LimeExpressionManager::StartProcessingGroup(-1, false, $surveyid);
    // start on welcome page
    $redata = compact(array_keys(get_defined_vars()));
    $sTemplatePath = $_SESSION['survey_' . $surveyid]['templatepath'];
    echo templatereplace(file_get_contents($sTemplatePath . "startpage.pstpl"), array(), $redata, 'frontend_helper[2757]');
    echo CHtml::form(array("/survey/index"), 'post', array('id' => 'limesurvey', 'name' => 'limesurvey', 'autocomplete' => 'off'));
    echo "\n\n<!-- START THE SURVEY -->\n";
    echo templatereplace(file_get_contents($sTemplatePath . "welcome.pstpl"), array(), $redata, 'frontend_helper[2762]') . "\n";
    if ($thissurvey['anonymized'] == "Y") {
        echo templatereplace(file_get_contents($sTemplatePath . "/privacy.pstpl"), array(), $redata, 'frontend_helper[2765]') . "\n";
    }
    echo templatereplace(file_get_contents($sTemplatePath . "navigator.pstpl"), array(), $redata, 'frontend_helper[2767]');
    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";
    }
    echo "\n<input type='hidden' name='sid' value='{$surveyid}' id='sid' />\n";
    if (isset($token) && !empty($token)) {
        echo "\n<input type='hidden' name='token' value='{$token}' id='token' />\n";
    }
    echo "\n<input type='hidden' name='lastgroupname' value='_WELCOME_SCREEN_' id='lastgroupname' />\n";
    //This is to ensure consistency with mandatory checks, and new group test
    $loadsecurity = returnGlobal('loadsecurity', true);
    if (isset($loadsecurity)) {
        echo "\n<input type='hidden' name='loadsecurity' value='{$loadsecurity}' id='loadsecurity' />\n";
    }
    $_SESSION['survey_' . $surveyid]['LEMpostKey'] = mt_rand();
    echo "<input type='hidden' name='LEMpostKey' value='{$_SESSION['survey_' . $surveyid]['LEMpostKey']}' id='LEMpostKey' />\n";
    echo "<input type='hidden' name='thisstep' id='thisstep' value='0' />\n";
    echo "\n</form>\n";
    echo templatereplace(file_get_contents($sTemplatePath . "endpage.pstpl"), array(), $redata, 'frontend_helper[2782]');
    echo LimeExpressionManager::GetRelevanceAndTailoringJavaScript();
    LimeExpressionManager::FinishProcessingPage();
    doFooter();
}
Example #7
0
 function _niceExit(&$redata, $iDebugLine, $sTemplateDir = null, $asMessage = array())
 {
     global $oTemplate;
     $asMessage[] = "<input type='hidden' class='hidemenubutton'/>";
     if (isset($redata['surveyid']) && $redata['surveyid'] && !isset($thisurvey)) {
         $thissurvey = getSurveyInfo($redata['surveyid']);
         $sTemplateDir = $oTemplate->viewPath;
     } else {
         $sTemplateDir = $oTemplate->viewPath;
     }
     sendCacheHeaders();
     doHeader();
     $oTemplate = $this->oTemplate;
     //$oTemplate->viewPath;
     echo "<!-- survey/index/_niceExit -->";
     $this->_printTemplateContent($oTemplate->viewPath . '/startpage.pstpl', $redata, $iDebugLine);
     $this->_printMessage($asMessage);
     $this->_printTemplateContent($oTemplate->viewPath . '/endpage.pstpl', $redata, $iDebugLine);
     doFooter();
     exit;
 }
 private function _renderHtml($html, $thistpl, $aSurveyInfo)
 {
     sendCacheHeaders();
     doHeader();
     $aSupportData = array('thissurvey' => $aSurveyInfo);
     // $oTemplate is a global variable defined in controller/survey/index
     global $oTemplate;
     $sTemplatePath = $oTemplate->path;
     $thistpl = $oTemplate->viewPath;
     echo templatereplace(file_get_contents($thistpl . 'startpage.pstpl'), array(), $aSupportData);
     $aData['html'] = $html;
     $aData['thistpl'] = $thistpl;
     $this->render('/opt_view', $aData);
     echo templatereplace(file_get_contents($thistpl . 'endpage.pstpl'), array(), $aSupportData);
     doFooter();
 }
Example #9
0
/**
 * check_quota() returns quota information for the current survey
 * @param string $checkaction - action the function must take after completing:
 * 								enforce: Enforce the quota action
 * 								return: Return the updated quota array from getQuotaAnswers()
 * @param string $surveyid - Survey identification number
 * @return array - nested array, Quotas->Members->Fields, includes quota status and which members matched in session.
 */
function check_quota($checkaction, $surveyid)
{
    if (!isset($_SESSION['s_lang'])) {
        return;
    }
    global $thistpl, $clang, $clienttoken, $publicurl;
    $global_matched = false;
    $quota_info = getQuotaInformation($surveyid, $_SESSION['s_lang']);
    $x = 0;
    if (count($quota_info) > 0) {
        // Check each quota on saved data to see if it is full
        $querycond = array();
        foreach ($quota_info as $quota) {
            if (count($quota['members']) > 0) {
                $fields_list = array();
                // Keep a list of fields for easy reference
                $y = 0;
                // We need to make the conditions for the select statement here
                // I'm supporting more than one field for a question/answer, not sure if this is necessary.
                unset($querycond);
                foreach ($quota['members'] as $member) {
                    $fields_query = array();
                    $select_query = " (";
                    foreach ($member['fieldnames'] as $fieldname) {
                        $fields_list[] = $fieldname;
                        $fields_query[] = db_quote_id($fieldname) . " = '{$member['value']}'";
                        // Check which quota fields and codes match in session, for later use.
                        // Incase of multiple fields for an answer - only needs to match once.
                        if (isset($_SESSION[$fieldname]) && $_SESSION[$fieldname] == $member['value']) {
                            $quota_info[$x]['members'][$y]['insession'] = "true";
                        }
                    }
                    $select_query .= implode(' OR ', $fields_query) . ' )';
                    $querycond[] = $select_query;
                    unset($fields_query);
                    $y++;
                }
                // Lets only continue if any of the quota fields is in the posted page
                $matched_fields = false;
                if (isset($_POST['fieldnames'])) {
                    $posted_fields = explode("|", $_POST['fieldnames']);
                    foreach ($fields_list as $checkfield) {
                        if (in_array($checkfield, $posted_fields)) {
                            $matched_fields = true;
                            $global_matched = true;
                        }
                    }
                }
                // A field was submitted that is part of the quota
                if ($matched_fields == true) {
                    // Check the status of the quota, is it full or not
                    $querysel = "SELECT id FROM " . db_table_name('survey_' . $surveyid) . "\n\t\t\t\t\t             WHERE " . implode(' AND ', $querycond) . " " . "\n\t\t\t\t\t\t\t\t AND submitdate IS NOT NULL";
                    $result = db_execute_assoc($querysel) or safe_die($connect->ErrorMsg());
                    //Checked
                    $quota_check = $result->FetchRow();
                    if ($result->RecordCount() >= $quota['Limit']) {
                        // Now we have to check if the quota matches in the current session
                        // This will let us know if this person is going to exceed the quota
                        $counted_matches = 0;
                        foreach ($quota_info[$x]['members'] as $member) {
                            if (isset($member['insession']) && $member['insession'] == "true") {
                                $counted_matches++;
                            }
                        }
                        if ($counted_matches == count($quota['members'])) {
                            // They are going to exceed the quota if data is submitted
                            $quota_info[$x]['status'] = "matched";
                        } else {
                            $quota_info[$x]['status'] = "notmatched";
                        }
                    } else {
                        // Quota is no in danger of being exceeded.
                        $quota_info[$x]['status'] = "notmatched";
                    }
                }
            }
            $x++;
        }
    } else {
        return false;
    }
    // Now we have all the information we need about the quotas and their status.
    // Lets see what we should do now
    if ($checkaction == 'return') {
        return $quota_info;
    } else {
        if ($global_matched == true && $checkaction == 'enforce') {
            // Need to add quota action enforcement here.
            reset($quota_info);
            $tempmsg = "";
            $found = false;
            foreach ($quota_info as $quota) {
                if (isset($quota['status']) && $quota['status'] == "matched" && (isset($quota['Action']) && $quota['Action'] == "1")) {
                    // If a token is used then mark the token as completed
                    if (isset($clienttoken) && $clienttoken) {
                        submittokens(true);
                    }
                    session_destroy();
                    sendcacheheaders();
                    if ($quota['AutoloadUrl'] == 1 && $quota['Url'] != "") {
                        header("Location: " . $quota['Url']);
                    }
                    doHeader();
                    echo templatereplace(file_get_contents("{$thistpl}/startpage.pstpl"));
                    echo "\t<div class='quotamessage'>\n";
                    echo "\t" . $quota['Message'] . "<br /><br />\n";
                    echo "\t<a href='" . $quota['Url'] . "'>" . $quota['UrlDescrip'] . "</a><br />\n";
                    echo "\t</div>\n";
                    echo templatereplace(file_get_contents("{$thistpl}/endpage.pstpl"));
                    doFooter();
                    exit;
                }
                if (isset($quota['status']) && $quota['status'] == "matched" && (isset($quota['Action']) && $quota['Action'] == "2")) {
                    sendcacheheaders();
                    doHeader();
                    echo templatereplace(file_get_contents("{$thistpl}/startpage.pstpl"));
                    echo "\t<div class='quotamessage'>\n";
                    echo "\t" . $quota['Message'] . "<br /><br />\n";
                    echo "\t<a href='" . $quota['Url'] . "'>" . $quota['UrlDescrip'] . "</a><br />\n";
                    echo "<form method='post' action='{$publicurl}/index.php' id='limesurvey' name='limesurvey'><input type=\"hidden\" name=\"move\" value=\"movenext\" id=\"movenext\" /><input class='submit' accesskey='p' type='button' onclick=\"javascript:document.limesurvey.move.value = 'moveprev'; document.limesurvey.submit();\" value=' &lt;&lt; " . $clang->gT("Previous") . " ' name='move2' />\n\t\t\t\t\t<input type='hidden' name='thisstep' value='" . $_SESSION['step'] . "' id='thisstep' />\n\t\t\t\t\t<input type='hidden' name='sid' value='" . returnglobal('sid') . "' id='sid' />\n\t\t\t\t\t<input type='hidden' name='token' value='" . $clienttoken . "' id='token' /></form>\n";
                    echo "\t</div>\n";
                    echo templatereplace(file_get_contents("{$thistpl}/endpage.pstpl"));
                    doFooter();
                    exit;
                }
            }
        } else {
            // Unknown value
            return false;
        }
    }
}
/**
 * Shows the welcome page, used in group by group and question by question mode
 */
function display_first_page()
{
    global $clang, $thistpl, $token, $surveyid, $thissurvey, $navigator, $publicurl;
    sendcacheheaders();
    doHeader();
    echo templatereplace(file_get_contents("{$thistpl}/startpage.pstpl"));
    echo "\n<form method='post' action='{$publicurl}/index.php' id='limesurvey' name='limesurvey' autocomplete='off'>\n";
    echo "\n\n<!-- START THE SURVEY -->\n";
    echo templatereplace(file_get_contents("{$thistpl}/welcome.pstpl")) . "\n";
    if ($thissurvey['anonymized'] == "Y") {
        echo templatereplace(file_get_contents("{$thistpl}/privacy.pstpl")) . "\n";
    }
    $navigator = surveymover();
    echo templatereplace(file_get_contents("{$thistpl}/navigator.pstpl"));
    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";
    }
    echo "\n<input type='hidden' name='sid' value='{$surveyid}' id='sid' />\n";
    if (isset($token) && !empty($token)) {
        echo "\n<input type='hidden' name='token' value='{$token}' id='token' />\n";
    }
    echo "\n<input type='hidden' name='lastgroupname' value='_WELCOME_SCREEN_' id='lastgroupname' />\n";
    //This is to ensure consistency with mandatory checks, and new group test
    $loadsecurity = returnglobal('loadsecurity');
    if (isset($loadsecurity)) {
        echo "\n<input type='hidden' name='loadsecurity' value='{$loadsecurity}' id='loadsecurity' />\n";
    }
    echo "\n</form>\n";
    echo templatereplace(file_get_contents("{$thistpl}/endpage.pstpl"));
    doFooter();
}
Example #11
0
function accessDenied($sMsg = "You are not allowed to view this page!")
{
    doHeader("Access Denied!");
    print "<span class=errorMsg>{$sMsg}</span>";
    doFooter();
    die;
}
 /**
  * Display needed public page
  * @param $iSurveyId
  */
 private function display($iSurveyId)
 {
     $sLanguage = Yii::app()->language;
     $aData['surveyid'] = $surveyid = $iSurveyId;
     $aData['thissurvey'] = getSurveyInfo($iSurveyId, $sLanguage);
     $sTemplate = getTemplatePath($aData['thissurvey']['template']);
     Yii::app()->setConfig('surveyID', $iSurveyId);
     //Needed for languagechanger
     $aData['sitename'] = Yii::app()->getConfig('sitename');
     $aData['aRegisterErrors'] = $this->aRegisterErrors;
     $aData['sMessage'] = $this->sMessage;
     sendCacheHeaders();
     doHeader();
     $aViewData['sTemplate'] = $sTemplate;
     if (!$this->sMessage) {
         $aData['languagechanger'] = makeLanguageChangerSurvey($sLanguage);
         // Only show language changer shown the form is shown, not after submission
         $aViewData['content'] = self::getRegisterForm($iSurveyId);
     } else {
         $aViewData['content'] = templatereplace($this->sMessage);
     }
     $aViewData['aData'] = $aData;
     // Test if we come from index or from register
     if (empty(App()->clientScript->scripts)) {
         App()->getClientScript()->registerPackage('jqueryui');
         App()->getClientScript()->registerPackage('jquery-touch-punch');
         App()->getClientScript()->registerScriptFile(Yii::app()->getConfig('generalscripts') . "survey_runtime.js");
         useFirebug();
         $this->render('/register/display', $aViewData);
     } else {
         // urvey/index need renderPartial
         $this->renderPartial('/register/display', $aViewData);
     }
     doFooter();
 }
Example #13
0
 /**
  * Render something
  *
  * @param string $html
  * @param array $aSurveyInfo
  * @param int $iSurveyID
  * @return void
  */
 private function _renderHtml($html, $aSurveyInfo, $iSurveyID)
 {
     sendCacheHeaders();
     doHeader();
     $aSupportData = array('thissurvey' => $aSurveyInfo);
     $oTemplate = Template::model()->getInstance(null, $iSurveyID);
     if ($oTemplate->cssFramework == 'bootstrap') {
         App()->bootstrap->register();
     }
     $thistpl = $oTemplate->viewPath;
     Yii::app()->clientScript->registerPackage('survey-template');
     ob_start(function ($buffer, $phase) {
         App()->getClientScript()->render($buffer);
         App()->getClientScript()->reset();
         return $buffer;
     });
     echo templatereplace(file_get_contents($thistpl . 'startpage.pstpl'), array(), $aSupportData);
     $aData['html'] = $html;
     $aData['thistpl'] = $thistpl;
     $this->renderPartial('/opt_view', $aData);
     echo templatereplace(file_get_contents($thistpl . 'endpage.pstpl'), array(), $aSupportData);
     doFooter();
     ob_flush();
 }
 /**
  * printanswers::view()
  * View answers at the end of a survey in one place. To export as pdf, set 'usepdfexport' = 1 in lsconfig.php and $printableexport='pdf'.
  * @param mixed $surveyid
  * @param bool $printableexport
  * @return
  */
 function actionView($surveyid, $printableexport = FALSE)
 {
     global $siteadminname, $siteadminemail;
     Yii::app()->loadHelper("frontend");
     Yii::import('application.libraries.admin.pdf');
     $surveyid = (int) $surveyid;
     Yii::app()->loadHelper('database');
     if (isset($_SESSION['survey_' . $surveyid]['sid'])) {
         $surveyid = $_SESSION['survey_' . $surveyid]['sid'];
     } else {
         die('Invalid survey/session');
     }
     //Debut session time out
     if (!isset($_SESSION['survey_' . $surveyid]['finished']) || !isset($_SESSION['survey_' . $surveyid]['srid'])) {
         //require_once($rootdir.'/classes/core/language.php');
         $baselang = Survey::model()->findByPk($surveyid)->language;
         Yii::import('application.libraries.Limesurvey_lang', true);
         $clang = new Limesurvey_lang($baselang);
         //A nice exit
         sendCacheHeaders();
         doHeader();
         echo templatereplace(file_get_contents(getTemplatePath(validateTemplateDir("default")) . "/startpage.pstpl"), array(), array());
         echo "<center><br />\n" . "\t<font color='RED'><strong>" . $clang->gT("Error") . "</strong></font><br />\n" . "\t" . $clang->gT("We are sorry but your session has expired.") . "<br />" . $clang->gT("Either you have been inactive for too long, you have cookies disabled for your browser, or there were problems with your connection.") . "<br />\n" . "\t" . sprintf($clang->gT("Please contact %s ( %s ) for further assistance."), $siteadminname, $siteadminemail) . "\n" . "</center><br />\n";
         echo templatereplace(file_get_contents(getTemplatePath(validateTemplateDir("default")) . "/endpage.pstpl"), array(), array());
         doFooter();
         exit;
     }
     //Fin session time out
     $id = $_SESSION['survey_' . $surveyid]['srid'];
     //I want to see the answers with this id
     $clang = $_SESSION['survey_' . $surveyid]['s_lang'];
     //Ensure script is not run directly, avoid path disclosure
     //if (!isset($rootdir) || isset($_REQUEST['$rootdir'])) {die( "browse - Cannot run this script directly");}
     // Set the language for dispay
     //require_once($rootdir.'/classes/core/language.php');  // has been secured
     if (isset($_SESSION['survey_' . $surveyid]['s_lang'])) {
         $clang = SetSurveyLanguage($surveyid, $_SESSION['survey_' . $surveyid]['s_lang']);
         $language = $_SESSION['survey_' . $surveyid]['s_lang'];
     } else {
         $language = Survey::model()->findByPk($surveyid)->language;
         $clang = SetSurveyLanguage($surveyid, $language);
     }
     // Get the survey inforamtion
     $thissurvey = getSurveyInfo($surveyid, $language);
     //SET THE TEMPLATE DIRECTORY
     if (!isset($thissurvey['templatedir']) || !$thissurvey['templatedir']) {
         $thistpl = validateTemplateDir("default");
     } else {
         $thistpl = validateTemplateDir($thissurvey['templatedir']);
     }
     if ($thissurvey['printanswers'] == 'N') {
         die;
         //Die quietly if print answers is not permitted
     }
     //CHECK IF SURVEY IS ACTIVATED AND EXISTS
     $surveytable = "{{survey_{$surveyid}}}";
     $surveyname = $thissurvey['surveyls_title'];
     $anonymized = $thissurvey['anonymized'];
     //OK. IF WE GOT THIS FAR, THEN THE SURVEY EXISTS AND IT IS ACTIVE, SO LETS GET TO WORK.
     //SHOW HEADER
     $printoutput = '';
     $printoutput .= "<form action='" . Yii::app()->getController()->createUrl('printanswers/view/surveyid/' . $surveyid . '/printableexport/pdf') . "' method='post'>\n<center><input type='submit' value='" . $clang->gT("PDF export") . "'id=\"exportbutton\"/><input type='hidden' name='printableexport' /></center></form>";
     if ($printableexport == 'pdf') {
         require Yii::app()->getConfig('rootdir') . '/application/config/tcpdf.php';
         Yii::import('application.libraries.admin.pdf', true);
         $pdf = new pdf();
         $pdf->setConfig($tcpdf);
         //$pdf->SetFont($pdfdefaultfont,'',$pdffontsize);
         $pdf->AddPage();
         //$pdf->titleintopdf($clang->gT("Survey name (ID)",'unescaped').": {$surveyname} ({$surveyid})");
         $pdf->SetTitle($clang->gT("Survey name (ID)", 'unescaped') . ": {$surveyname} ({$surveyid})");
     }
     $printoutput .= "\t<div class='printouttitle'><strong>" . $clang->gT("Survey name (ID):") . "</strong> {$surveyname} ({$surveyid})</div><p>&nbsp;\n";
     LimeExpressionManager::StartProcessingPage(true);
     // means that all variables are on the same page
     // Since all data are loaded, and don't need JavaScript, pretend all from Group 1
     LimeExpressionManager::StartProcessingGroup(1, $thissurvey['anonymized'] != "N", $surveyid);
     $aFullResponseTable = getFullResponseTable($surveyid, $id, $language, true);
     //Get the fieldmap @TODO: do we need to filter out some fields?
     unset($aFullResponseTable['id']);
     unset($aFullResponseTable['token']);
     unset($aFullResponseTable['lastpage']);
     unset($aFullResponseTable['startlanguage']);
     unset($aFullResponseTable['datestamp']);
     unset($aFullResponseTable['startdate']);
     $printoutput .= "<table class='printouttable' >\n";
     if ($printableexport == 'pdf') {
         $pdf->intopdf($clang->gT("Question", 'unescaped') . ": " . $clang->gT("Your answer", 'unescaped'));
     }
     $oldgid = 0;
     $oldqid = 0;
     foreach ($aFullResponseTable as $sFieldname => $fname) {
         if (substr($sFieldname, 0, 4) == 'gid_') {
             if ($printableexport) {
                 $pdf->intopdf(flattenText($fname[0], false, true));
                 $pdf->ln(2);
             } else {
                 $printoutput .= "\t<tr class='printanswersgroup'><td colspan='2'>{$fname[0]}</td></tr>\n";
             }
         } elseif (substr($sFieldname, 0, 4) == 'qid_') {
             if ($printableexport == 'pdf') {
                 $pdf->intopdf(flattenText($fname[0] . $fname[1], false, true) . ": " . $fname[2]);
                 $pdf->ln(2);
             } else {
                 $printoutput .= "\t<tr class='printanswersquestionhead'><td  colspan='2'>{$fname[0]}</td></tr>\n";
             }
         } elseif ($sFieldname == 'submitdate') {
             if ($anonymized != 'Y') {
                 if ($printableexport == 'pdf') {
                     $pdf->intopdf(flattenText($fname[0] . $fname[1], false, true) . ": " . $fname[2]);
                     $pdf->ln(2);
                 } else {
                     $printoutput .= "\t<tr class='printanswersquestion'><td>{$fname[0]} {$fname[1]} {$sFieldname}</td><td class='printanswersanswertext'>{$fname[2]}</td></tr>";
                 }
             }
         } else {
             if ($printableexport == 'pdf') {
                 $pdf->intopdf(flattenText($fname[0] . $fname[1], false, true) . ": " . $fname[2]);
                 $pdf->ln(2);
             } else {
                 $printoutput .= "\t<tr class='printanswersquestion'><td>{$fname[0]} {$fname[1]}</td><td class='printanswersanswertext'>{$fname[2]}</td></tr>";
             }
         }
     }
     $printoutput .= "</table>\n";
     if ($printableexport == 'pdf') {
         header("Pragma: public");
         header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
         $sExportFileName = sanitize_filename($surveyname);
         $pdf->Output($sExportFileName . "-" . $surveyid . ".pdf", "D");
     }
     //Display the page with user answers
     if (!$printableexport) {
         sendCacheHeaders();
         doHeader();
         echo templatereplace(file_get_contents(getTemplatePath($thistpl) . '/startpage.pstpl'));
         echo templatereplace(file_get_contents(getTemplatePath($thistpl) . '/printanswers.pstpl'), array('ANSWERTABLE' => $printoutput));
         echo templatereplace(file_get_contents(getTemplatePath($thistpl) . '/endpage.pstpl'));
         echo "</body></html>";
     }
     LimeExpressionManager::FinishProcessingGroup();
     LimeExpressionManager::FinishProcessingPage();
 }
 private function _renderHtml($html, $thistpl, $aSurveyInfo)
 {
     sendCacheHeaders();
     doHeader();
     $aSupportData = array('thissurvey' => $aSurveyInfo);
     $oTemplate = Template::model()->getInstance();
     $sTemplatePath = $oTemplate->path;
     $thistpl = $oTemplate->viewPath;
     echo templatereplace(file_get_contents($thistpl . 'startpage.pstpl'), array(), $aSupportData);
     $aData['html'] = $html;
     $aData['thistpl'] = $thistpl;
     $this->render('/opt_view', $aData);
     echo templatereplace(file_get_contents($thistpl . 'endpage.pstpl'), array(), $aSupportData);
     doFooter();
 }
 private function _renderHtml($html, $thistpl, $aSurveyInfo)
 {
     sendCacheHeaders();
     doHeader();
     $aSupportData = array('thissurvey' => $aSurveyInfo);
     echo templatereplace(file_get_contents($thistpl . DIRECTORY_SEPARATOR . 'startpage.pstpl'), array(), $aSupportData);
     $aData['html'] = $html;
     $aData['thistpl'] = $thistpl;
     $this->render('/opt_view', $aData);
     echo templatereplace(file_get_contents($thistpl . DIRECTORY_SEPARATOR . 'endpage.pstpl'), array(), $aSupportData);
     doFooter();
 }
Example #17
0
    public function beforeSurveyPage() {

        $oEvent = $this->event;
        $iSurveyId = $oEvent->get('surveyId');
        $bUse = $this->get('bUse', 'Survey', $iSurveyId);

        if ($bUse) { //Only private surveys with authsaml plugin enabled
            if ($this->ssp->isAuthenticated()) { //Only idp users                
                $sLanguage = Yii::app()->request->getParam('lang');
                $aSurveyInfo = getSurveyInfo($iSurveyId, $sLanguage);
                $aSurveyIdpAttributes = array_diff(json_decode($this->get('surveyIdpAttributes', 'Survey', $iSurveyId), true), array('none'));

                if ($this->checkIdpAttributes($aSurveyIdpAttributes)) {
                    $oToken = TokenDynamic::model($iSurveyId)->find('email=:email', array(':email' => $this->getUserMail()));

                    if ($oToken) { //Allow survey access if the token is given
                        if (Yii::app()->request->getParam('token')) {
                            return;
                        }
                        $sToken = $oToken->token;
                    } else {//Creation of the token
                        $oToken = Token::create($iSurveyId);
                        $oToken->firstname = $this->getUserGivenName();
                        $oToken->lastname = $this->getUserSurName();
                        $oToken->email = $this->getUserMail();
                        $oToken->emailstatus = 'OK';
                        $oToken->language = $sLanguage;
                        if ($aSurveyInfo['startdate']) {
                            $oToken->validfrom = $aSurveyInfo['startdate'];
                        }
                        if ($aSurveyInfo['expires']) {
                            $oToken->validuntil = $aSurveyInfo['expires'];
                        }
                        $oToken->save();
                        $iTokenId = $oToken->tid;
                        $sToken = TokenDynamic::model($iSurveyId)->createToken($iTokenId);
                    }
                    if ($sToken) {
                        $surveylink = App()->createAbsoluteUrl("/survey/index/sid/{$iSurveyId}", array('token' => $sToken));
                        header('Location: ' . $surveylink);
                    }
                } else {
                    $aReplacementFields = array();
                    $aReplacementFields["{ADMINNAME}"] = $aSurveyInfo['adminname'];
                    $aReplacementFields["{ADMINEMAIL}"] = $aSurveyInfo['adminemail'];
                    $sLanguage = Yii::app()->request->getParam('lang', '');
                    if ($sLanguage == "") {
                        $sLanguage = Survey::model()->findByPk($iSurveyId)->language;
                    }
                    $aSurveyInfo = getSurveyInfo($iSurveyId, $sLanguage);
                    $sTemplatePath = $aData['templatedir'] = getTemplatePath($aSurveyInfo['template']);
                    $sAttributesRequired = '';
                    $sAttributesReceived = '';
                    foreach ($aSurveyIdpAttributes as $key => $value) {
                        $sAttributesRequired .= "<li>{$key} = \"{$value}\"</li>";
                    }
                    foreach (array_intersect_key($this->attributes, $aSurveyIdpAttributes) as $key => $value) {
                        $sAttributesReceived .= "<li>{$key} = \"{$value[0]}\"</li>";
                    }
                    $sReturnHtml = "<div id='wrapper' class='message tokenmessage'>"
                            . "<h3>Acesso ao questionário não permitido!</h3>\n"
                            . "<p>Informações de usuário necessárias:</p>\n"
                            . "<ul>$sAttributesRequired</ul><br />"
                            . "<p>Informações de usuário recebidas:</p>\n"
                            . "<ul>$sAttributesReceived</ul><br />"
                            . "<p>Entre em contato com o administrador do questionário: {ADMINNAME} ({ADMINEMAIL})</p>"
                            . "</div>\n";
                    $sReturnHtml = ReplaceFields($sReturnHtml, $aReplacementFields);
                    ob_start(function($buffer, $phase) {
                        App()->getClientScript()->render($buffer);
                        App()->getClientScript()->reset();
                        return $buffer;
                    });
                    ob_implicit_flush(false);
                    sendCacheHeaders();
                    doHeader();
                    $aData['thissurvey'] = $aSurveyInfo;
                    $aData['thissurvey'] = $aSurveyInfo;
                    echo templatereplace(file_get_contents($sTemplatePath . '/startpage.pstpl'), array(), $aData);
                    echo templatereplace(file_get_contents($sTemplatePath . '/survey.pstpl'), array(), $aData);
                    echo $sReturnHtml;
                    echo templatereplace(file_get_contents($sTemplatePath . '/endpage.pstpl'), array(), $aData);
                    doFooter();
                    ob_flush();
                    App()->end();
                }
            } else {// Asks idp authentication
                header('Location: ' . $this->ssp->getLoginURL());
            }
        }
    }
    /**
     * 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();
    }
        public function beforeSurveyPage()
        {
            $oEvent = $this->event;
            $iSurveyId = $oEvent->get('surveyId');

            self::__init();
            $bUse=$this->get('bUse', 'Survey', $iSurveyId);
            if(is_null($bUse))
                $bUse=$this->bUse;
            if(!$bUse)
                return;

            $sToken= Yii::app()->request->getParam('token');
            if($iSurveyId && !$sToken)// Test invalid token ?
            {
                // Get the survey model
                $oSurvey=Survey::model()->find("sid=:sid",array(':sid'=>$iSurveyId));
                if($oSurvey && $oSurvey->active=="Y" && $oSurvey->allowregister=="Y" && tableExists("tokens_{$iSurveyId}"))
                {
                    // Fill parameters
                    $bShowTokenForm=$this->get('bShowTokenForm', 'Survey', $iSurveyId);
                    if(is_null($bShowTokenForm))
                        $bShowTokenForm=$this->bShowTokenForm;
                    $bShowTokenForm=$this->get('use', 'Survey', $iSurveyId);
                    if(is_null($bShowTokenForm))
                        $bShowTokenForm=$this->bUse;
                    Yii::app()->getClientScript()->registerCssFile(Yii::app()->getConfig('publicurl')."plugins/replaceRegister/css/register.css");
                    // We can go
                    $sLanguage = Yii::app()->request->getParam('lang','');
                    if ($sLanguage=="" )
                    {
                        $sLanguage = Survey::model()->findByPk($iSurveyId)->language;
                    }
                    $aSurveyInfo=getSurveyInfo($iSurveyId,$sLanguage);
                    $sAction= Yii::app()->request->getParam('action','view') ;
                    $sHtmlRegistererror="";
                    $sHtmlRegistermessage1=gT("You must be registered to complete this survey");;
                    $sHtmlRegistermessage2=gT("You may register for this survey if you wish to take part.")."<br />\n".gT("Enter your details below, and an email containing the link to participate in this survey will be sent immediately.");
                    $sHtmlRegisterform="";
                    $sHtml="";
                    $bShowForm=true;
                    $bValidMail=false;
                    $bTokenCreate=true;
                    $aExtraParams=array();
                    $aRegisterError=array();
                    $sR_email= Yii::app()->request->getPost('register_email');
                    $sR_firstname= sanitize_xss_string(Yii::app()->request->getPost('register_firstname',""));
                    $sR_lastname= sanitize_xss_string(Yii::app()->request->getPost('register_lastname',""));
                    $sR_lastname= sanitize_xss_string(Yii::app()->request->getPost('register_lastname',""));
                    $aR_attribute=array();
                    $aR_attributeGet=array();
                    $aExtraParams=array();
                    $aMail=array();
                    foreach ($aSurveyInfo['attributedescriptions'] as $field => $aAttribute)
                    {
                        if (!empty($aAttribute['show_register']) && $aAttribute['show_register'] == 'Y')
                        {
                            $aR_attribute[$field]= sanitize_xss_string(Yii::app()->request->getPost('register_'.$field),"");// Need to be filtered ?
                        }
                        elseif($aAttribute['description']==sanitize_paranoid_string($aAttribute['description']) && trim(Yii::app()->request->getQuery($aAttribute['description'],"")) )
                        {
                            $aR_attributeGet[$field]= sanitize_xss_string(trim(Yii::app()->request->getQuery($aAttribute['description'],"")));// Allow prefill with URL (TODO: add an option)
                            $aExtraParams[$aAttribute['description']]=sanitize_xss_string(trim(Yii::app()->request->getParam($aAttribute['description'],"")));
                        }
                    }
                    if($sAction=='register' && !is_null($sR_email) && Yii::app()->request->getPost('changelang')!='changelang')
                    {
                        $bShowForm=false;
                        // captcha
                        $sLoadsecurity=Yii::app()->request->getPost('loadsecurity');
                        $sSecAnswer=(isset($_SESSION['survey_'.$iSurveyId]['secanswer']))?$_SESSION['survey_'.$iSurveyId]['secanswer']:"";
                        $bShowForm=false;
                        $bNoError=true;
                        // Copy paste RegisterController
                        if($sR_email)
                        {
                            //Check that the email is a valid style addressattribute_2
                            if (!validateEmailAddress($sR_email))
                            {
                                $aRegisterError[]= gT("The email you used is not valid. Please try again.");
                            }
                        }
                        else
                        {
                            $aRegisterError[]= gT("The email you used is not valid. Please try again.");// Empty email
                        }
                        // Fill and validate mandatory extra attribute
                        foreach ($aSurveyInfo['attributedescriptions'] as $field => $aAttribute)
                        {
                            if (!empty($aAttribute['show_register']) && $aAttribute['show_register'] == 'Y' && $aAttribute['mandatory'] == 'Y' && ($aR_attribute[$field]=="" || is_null($aR_attribute[$field])) )
                            {
                                $aRegisterError[]= sprintf(gT("%s cannot be left empty").".", $aSurveyInfo['attributecaptions'][$field]);
                            }
                        }
                        // Check the security question's answer : at end because the security question is the last one
                        if (function_exists("ImageCreate") && isCaptchaEnabled('registrationscreen',$aSurveyInfo['usecaptcha']) )
                        {
                            if (!$sLoadsecurity || !$sSecAnswer || $sLoadsecurity != $sSecAnswer)
                            {
                                $aRegisterError[]= gT("The answer to the security question is incorrect.");
                            }
                        }
                        if(count($aRegisterError)==0)
                        {
                            //Check if this email already exists in token database
                            $oToken=TokenDynamic::model($iSurveyId)->find('email=:email',array(':email'=>$sR_email));
                            if ($oToken)
                            {
                                if($oToken->usesleft<1 && $aSurveyInfo['alloweditaftercompletion']!='Y')
                                {
                                    $aRegisterError="The e-mail address you have entered is already registered an the questionnaire has been completed.";
                                }
                                elseif(strtolower(substr(trim($oToken->emailstatus),0,6))==="optout")// And global blacklisting ?
                                {
                                    $aRegisterError="This email address is already registered but someone ask to don't receive new email again.";
                                }
                                elseif(!$oToken->emailstatus && $oToken->emailstatus!="OK")
                                {
                                    $aRegisterError="This email address is already registered but the email adress was bounced.";
                                }
                                else
                                {
                                    $iTokenId=$oToken->tid;
                                    $aMail['subject']=$aSurveyInfo['email_register_subj'];
                                    $aMail['message']=$aSurveyInfo['email_register'];
                                    $aMail['information']="The address you have entered is already registered. An email has been sent to this address with a link that gives you access to the survey.";
                                    // Did we update the token ? Setting ?
                                }
                            }
                            else
                            {
                                $oToken= Token::create($iSurveyId);
                                $oToken->firstname = $sR_firstname;
                                $oToken->lastname = $sR_lastname;
                                $oToken->email = $sR_email;
                                $oToken->emailstatus = 'OK';
                                $oToken->language = $sLanguage;
                                $oToken->setAttributes($aR_attribute);
                                $oToken->setAttributes($aR_attributeGet);// Need an option
                                if ($aSurveyInfo['startdate'])
                                {
                                    $oToken->validfrom = $aSurveyInfo['startdate'];
                                }
                                if ($aSurveyInfo['expires'])
                                {
                                    $oToken->validuntil = $aSurveyInfo['expires'];
                                }
                                $oToken->save();
                                $iTokenId=$oToken->tid;
                                TokenDynamic::model($iSurveyId)->createToken($iTokenId);// Review if really create a token
                                $aMail['subject']=$aSurveyInfo['email_register_subj'];
                                $aMail['message']=$aSurveyInfo['email_register'];
                                $aMail['information']=gT("An email has been sent to the address you provided with access details for this survey. Please follow the link in that email to proceed.");
                            }
                        }
                    }
                    if($aMail && $oToken)
                    {
                        $aReplacementFields=array();
                        $aReplacementFields["{ADMINNAME}"]=$aSurveyInfo['adminname'];
                        $aReplacementFields["{ADMINEMAIL}"]=$aSurveyInfo['adminemail'];
                        $aReplacementFields["{SURVEYNAME}"]=$aSurveyInfo['name'];
                        $aReplacementFields["{SURVEYDESCRIPTION}"]=$aSurveyInfo['description'];
                        $aReplacementFields["{EXPIRY}"]=$aSurveyInfo["expiry"];
                        $oToken=TokenDynamic::model($iSurveyId)->findByPk($iTokenId);
                        foreach($oToken->attributes as $attribute=>$value){
                            $aReplacementFields["{".strtoupper($attribute)."}"]=$value;
                        }
                        $sToken=$oToken->token;
                        $aMail['subject']=preg_replace("/{TOKEN:([A-Z0-9_]+)}/","{"."$1"."}",$aMail['subject']);
                        $aMail['message']=preg_replace("/{TOKEN:([A-Z0-9_]+)}/","{"."$1"."}",$aMail['message']);
                        $surveylink = App()->createAbsoluteUrl("/survey/index/sid/{$iSurveyId}",array('lang'=>$sLanguage,'token'=>$sToken));
                        $optoutlink = App()->createAbsoluteUrl("/optout/tokens/surveyid/{$iSurveyId}",array('langcode'=>$sLanguage,'token'=>$sToken));
                        $optinlink = App()->createAbsoluteUrl("/optin/tokens/surveyid/{$iSurveyId}",array('langcode'=>$sLanguage,'token'=>$sToken));
                        if (getEmailFormat($iSurveyId) == 'html')
                        {
                            $useHtmlEmail = true;
                            $aReplacementFields["{SURVEYURL}"]="<a href='$surveylink'>".$surveylink."</a>";
                            $aReplacementFields["{OPTOUTURL}"]="<a href='$optoutlink'>".$optoutlink."</a>";
                            $aReplacementFields["{OPTINURL}"]="<a href='$optinlink'>".$optinlink."</a>";
                        }
                        else
                        {
                            $useHtmlEmail = false;
                            $aReplacementFields["{SURVEYURL}"]= $surveylink;
                            $aReplacementFields["{OPTOUTURL}"]= $optoutlink;
                            $aReplacementFields["{OPTINURL}"]= $optinlink;
                        }
                        // Allow barebone link for all URL
                        $aMail['message'] = str_replace("@@SURVEYURL@@", $surveylink, $aMail['message']);
                        $aMail['message'] = str_replace("@@OPTOUTURL@@", $optoutlink, $aMail['message']);
                        $aMail['message'] = str_replace("@@OPTINURL@@", $optinlink, $aMail['message']);
                        // Replace the fields
                        $aMail['subject']=ReplaceFields($aMail['subject'], $aReplacementFields);
                        $aMail['message']=ReplaceFields($aMail['message'], $aReplacementFields);
                        
                        // We have it, then try to send the mail.
                        $from = "{$aSurveyInfo['adminname']} <{$aSurveyInfo['adminemail']}>";
                        $sitename =  Yii::app()->getConfig('sitename');
                        if (SendEmailMessage($aMail['message'], $aMail['subject'], $sR_email, $from, $sitename,$useHtmlEmail,getBounceEmail($iSurveyId)))
                        {
                            // TLR change to put date into sent
                            $today = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i", Yii::app()->getConfig('timeadjust'));
                            $oToken->sent=$today;
                            $oToken->save();
                            $sReturnHtml="<div id='wrapper' class='message tokenmessage'>"
                                . "<p>".gT("Thank you for registering to participate in this survey.")."</p>\n"
                                . "<p>".$aMail['information']."</p>\n"
                                . "<p>".gT("Survey administrator")." {ADMINNAME} ({ADMINEMAIL})</p>"
                                . "</div>\n";

                        }
                        else
                        {
                            $sReturnHtml="<div id='wrapper' class='message tokenmessage'>"
                                . "<p>".gT("Thank you for registering to participate in this survey.")."</p>\n"
                                . "<p>"."We can not sent you an email actually, please contact the survey administrator"."</p>\n"
                                . "<p>".gT("Survey administrator")." {ADMINNAME} ({ADMINEMAIL})</p>"
                                . "</div>\n";
                        
                        }
                        $sReturnHtml=ReplaceFields($sReturnHtml, $aReplacementFields);
                        $sTemplatePath=$aData['templatedir'] = getTemplatePath($aSurveyInfo['template']);
                        ob_start(function($buffer, $phase) {
                            App()->getClientScript()->render($buffer);
                            App()->getClientScript()->reset();
                            return $buffer;
                        });
                        ob_implicit_flush(false);
                        sendCacheHeaders();
                        doHeader();
                        $aData['thissurvey'] = $aSurveyInfo;
                        $aData['thissurvey'] = $aSurveyInfo;
                        echo templatereplace(file_get_contents($sTemplatePath.'/startpage.pstpl'),array(), $aData);
                        echo templatereplace(file_get_contents($sTemplatePath.'/survey.pstpl'),array(), $aData);
                        echo $sReturnHtml;
                        echo templatereplace(file_get_contents($sTemplatePath.'/endpage.pstpl'),array(), $aData);
                        doFooter();
                        ob_flush();
                        App()->end();
                    }
                    if($bShowForm || count($aRegisterError))
                    {
                        // Language ?
                        if(count($aRegisterError)==1){
                            $sHtmlRegistererror="<p class='error error-register'><strong>{$aRegisterError[0]}</strong></p>";
                        }elseif(count($aRegisterError)>1){
                            $sHtmlRegistererror="<ul class='error error-register error-list'>";
                            foreach ($aRegisterError as $sRegisterError)
                                $sHtmlRegistererror.="<li><strong>{$sRegisterError}</strong></li>";
                            $sHtmlRegistererror.="</ul>";
                        }
                        $aExtraParams['action']='register';
                        $aExtraParams['lang']=$sLanguage;
                        $sHtmlRegisterform = CHtml::form(Yii::app()->createUrl("/survey/index/sid/{$iSurveyId}",$aExtraParams), 'post');
                        $sHtmlRegisterform.="<table class='register'><tbody>\n";
                        $sHtmlRegisterform.=  "<tr><th><label for='register_firstname'>".gT("First name") . "</label></th><td>".CHtml::textField('register_firstname',htmlentities($sR_firstname, ENT_QUOTES, 'UTF-8'),array('class'=>'text'))."</td></tr>\n";
                        $sHtmlRegisterform.=  "<tr><th><label for='register_lastname'>".gT("Last name") . "</label></th><td>".CHtml::textField('register_lastname',htmlentities($sR_lastname, ENT_QUOTES, 'UTF-8'),array('class'=>'text'))."</td></tr>\n";
                        $sHtmlRegisterform.=  "<tr class='mandatory'><th><label for='register_email'>".gT("Email address") . "</label></th><td>".CHtml::textField('register_email',htmlentities($sR_email, ENT_QUOTES, 'UTF-8'),array('class'=>'text'))."</td></tr>\n";
                        // Extra attribute
                        foreach ($aSurveyInfo['attributedescriptions'] as $field => $aAttribute)
                        {
                            if (!empty($aAttribute['show_register']) && $aAttribute['show_register'] == 'Y')
                            {
                                $sHtmlRegisterform.=  "<tr".($aAttribute['mandatory'] == 'Y' ? " class='mandatory'" : '')."><th><label for='register_{$field}'>".$aSurveyInfo['attributecaptions'][$field].($aAttribute['mandatory'] == 'Y' ? ' *' : '')."</label></th><td>".CHtml::textField('register_'.$field,htmlentities($aR_attribute[$field], ENT_QUOTES, 'UTF-8'),array('class'=>'text'))."</td></tr>\n";
                            }
                        }
                        if (function_exists("ImageCreate") && isCaptchaEnabled('registrationscreen', $aSurveyInfo['usecaptcha']))
                            $sHtmlRegisterform.= "<tr><th><label for='loadsecurity'>" . gT("Security question") . "</label></th><td><img src='".Yii::app()->getController()->createUrl("/verification/image/sid/{$iSurveyId}")."' alt='' /><input type='text' size='5' maxlength='3' name='loadsecurity' id='loadsecurity' value='' /></td></tr>\n";
                        $sHtmlRegisterform.= "<tr><td></td><td>".CHtml::submitButton(gT("Continue"))."</td></tr>";
                        $sHtmlRegisterform.= "</tbody></table>\n";
                        $sHtmlRegisterform.= makeLanguageChangerSurvey($sLanguage);// Need to be inside the form
                        $sHtmlRegisterform.= CHtml::endForm();
                    }
                    $sTemplatePath=$aData['templatedir'] = getTemplatePath($aSurveyInfo['template']);
                    ob_start(function($buffer, $phase) {
                        App()->getClientScript()->render($buffer);
                        App()->getClientScript()->reset();
                        return $buffer;
                    });
                    ob_implicit_flush(false);
                    sendCacheHeaders();
                    doHeader();
                    // Get the register.pstpl file content, but remplace default by own string
                    $sHtmlRegister=file_get_contents($sTemplatePath.'/register.pstpl');
                    $sHtmlRegister= str_replace("{REGISTERERROR}",$sHtmlRegistererror,$sHtmlRegister);
                    $sHtmlRegister= str_replace("{REGISTERMESSAGE1}",$sHtmlRegistermessage1,$sHtmlRegister);
                    $sHtmlRegister= str_replace("{REGISTERMESSAGE2}",$sHtmlRegistermessage2,$sHtmlRegister);
                    $sHtmlRegister= str_replace("{REGISTERFORM}",$sHtmlRegisterform,$sHtmlRegister);

                    $aData['thissurvey'] = $aSurveyInfo;
                    echo templatereplace(file_get_contents($sTemplatePath.'/startpage.pstpl'),array(), $aData);
                    echo templatereplace(file_get_contents($sTemplatePath.'/survey.pstpl'),array(), $aData);
                    echo templatereplace($sHtmlRegister);
                    echo templatereplace(file_get_contents($sTemplatePath.'/endpage.pstpl'),array(), $aData);
                    doFooter();
                    ob_flush();
                    App()->end();
                }
            }
        }
/**
* Shows the welcome page, used in group by group and question by question mode
*/
function display_first_page()
{
    global $token, $surveyid, $thissurvey, $navigator;
    $totalquestions = $_SESSION['survey_' . $surveyid]['totalquestions'];
    // Fill some necessary var for template
    $aNavigator = surveymover();
    $moveprevbutton = $aNavigator['sMovePrevButton'];
    $movenextbutton = $aNavigator['sMoveNextButton'];
    $navigator = $moveprevbutton . ' ' . $movenextbutton;
    $sitename = Yii::app()->getConfig('sitename');
    $languagechanger = makeLanguageChangerSurvey(App()->language);
    sendCacheHeaders();
    doHeader();
    LimeExpressionManager::StartProcessingPage();
    LimeExpressionManager::StartProcessingGroup(-1, false, $surveyid);
    // start on welcome page
    $redata = compact(array_keys(get_defined_vars()));
    $oTemplate = Template::model()->getInstance('', $surveyid);
    $sTemplatePath = $oTemplate->path;
    $sTemplateViewPath = $oTemplate->viewPath;
    echo templatereplace(file_get_contents($sTemplateViewPath . "startpage.pstpl"), array(), $redata, 'frontend_helper[2757]');
    echo CHtml::form(array("/survey/index", "sid" => $surveyid), 'post', array('id' => 'limesurvey', 'name' => 'limesurvey', 'autocomplete' => 'off', 'class' => 'frontend_helper'));
    echo templatereplace(file_get_contents($sTemplateViewPath . "welcome.pstpl"), array(), $redata, 'frontend_helper[2762]') . "\n";
    if ($thissurvey['anonymized'] == "Y") {
        echo templatereplace(file_get_contents($sTemplateViewPath . "/privacy.pstpl"), array(), $redata, 'frontend_helper[2765]') . "\n";
    }
    echo templatereplace(file_get_contents($sTemplateViewPath . "navigator.pstpl"), array(), $redata, 'frontend_helper[2767]');
    echo "\n<input type='hidden' name='sid' value='{$surveyid}' id='sid' />\n";
    if (isset($token) && !empty($token)) {
        echo "\n<input type='hidden' name='token' value='{$token}' id='token' />\n";
    }
    echo "\n<input type='hidden' name='lastgroupname' value='_WELCOME_SCREEN_' id='lastgroupname' />\n";
    //This is to ensure consistency with mandatory checks, and new group test
    $loadsecurity = returnGlobal('loadsecurity', true);
    if (isset($loadsecurity)) {
        echo "\n<input type='hidden' name='loadsecurity' value='{$loadsecurity}' id='loadsecurity' />\n";
    }
    $_SESSION['survey_' . $surveyid]['LEMpostKey'] = mt_rand();
    echo "<input type='hidden' name='LEMpostKey' value='{$_SESSION['survey_' . $surveyid]['LEMpostKey']}' id='LEMpostKey' />\n";
    echo "<input type='hidden' name='thisstep' id='thisstep' value='0' />\n";
    echo "<!--frontendhelper --></form>";
    echo templatereplace(file_get_contents($sTemplateViewPath . "endpage.pstpl"), array(), $redata, 'frontend_helper[2782]');
    echo LimeExpressionManager::GetRelevanceAndTailoringJavaScript();
    LimeExpressionManager::FinishProcessingPage();
    doFooter();
    echo "<!-- end of frontend_helper /  display_first_page -->";
}
 /**
  * printanswers::view()
  * View answers at the end of a survey in one place. To export as pdf, set 'usepdfexport' = 1 in lsconfig.php and $printableexport='pdf'.
  * @param mixed $surveyid
  * @param bool $printableexport
  * @return
  */
 function actionView($surveyid, $printableexport = FALSE)
 {
     Yii::app()->loadHelper("frontend");
     Yii::import('application.libraries.admin.pdf');
     $iSurveyID = (int) $surveyid;
     $sExportType = $printableexport;
     Yii::app()->loadHelper('database');
     if (isset($_SESSION['survey_' . $iSurveyID]['sid'])) {
         $iSurveyID = $_SESSION['survey_' . $iSurveyID]['sid'];
     } else {
         //die('Invalid survey/session');
     }
     // Get the survey inforamtion
     // Set the language for dispay
     if (isset($_SESSION['survey_' . $iSurveyID]['s_lang'])) {
         $sLanguage = $_SESSION['survey_' . $iSurveyID]['s_lang'];
     } elseif (Survey::model()->findByPk($iSurveyID)) {
         $sLanguage = Survey::model()->findByPk($iSurveyID)->language;
     } else {
         $iSurveyID = 0;
         $sLanguage = Yii::app()->getConfig("defaultlang");
     }
     SetSurveyLanguage($iSurveyID, $sLanguage);
     $aSurveyInfo = getSurveyInfo($iSurveyID, $sLanguage);
     $oTemplate = Template::model()->getInstance(null, $iSurveyID);
     //Survey is not finished or don't exist
     if (!isset($_SESSION['survey_' . $iSurveyID]['finished']) || !isset($_SESSION['survey_' . $iSurveyID]['srid'])) {
         sendCacheHeaders();
         doHeader();
         /// $oTemplate is a global variable defined in controller/survey/index
         echo templatereplace(file_get_contents($oTemplate->viewPath . '/startpage.pstpl'), array());
         echo "<center><br />\n" . "\t<font color='RED'><strong>" . gT("Error") . "</strong></font><br />\n" . "\t" . gT("We are sorry but your session has expired.") . "<br />" . gT("Either you have been inactive for too long, you have cookies disabled for your browser, or there were problems with your connection.") . "<br />\n" . "\t" . sprintf(gT("Please contact %s ( %s ) for further assistance."), Yii::app()->getConfig("siteadminname"), Yii::app()->getConfig("siteadminemail")) . "\n" . "</center><br />\n";
         echo templatereplace(file_get_contents($oTemplate->viewPath . '/endpage.pstpl'), array());
         doFooter();
         exit;
     }
     //Fin session time out
     $sSRID = $_SESSION['survey_' . $iSurveyID]['srid'];
     //I want to see the answers with this id
     //Ensure script is not run directly, avoid path disclosure
     //if (!isset($rootdir) || isset($_REQUEST['$rootdir'])) {die( "browse - Cannot run this script directly");}
     //Ensure Participants printAnswer setting is set to true or that the logged user have read permissions over the responses.
     if ($aSurveyInfo['printanswers'] == 'N' && !Permission::model()->hasSurveyPermission($iSurveyID, 'responses', 'read')) {
         throw new CHttpException(401, 'You are not allowed to print answers.');
     }
     //CHECK IF SURVEY IS ACTIVATED AND EXISTS
     $sSurveyName = $aSurveyInfo['surveyls_title'];
     $sAnonymized = $aSurveyInfo['anonymized'];
     //OK. IF WE GOT THIS FAR, THEN THE SURVEY EXISTS AND IT IS ACTIVE, SO LETS GET TO WORK.
     //SHOW HEADER
     if ($sExportType != 'pdf') {
         $sOutput = CHtml::form(array("printanswers/view/surveyid/{$iSurveyID}/printableexport/pdf"), 'post') . "<center><input class='btn btn-default' type='submit' value='" . gT("PDF export") . "'id=\"exportbutton\"/><input type='hidden' name='printableexport' /></center></form>";
         $sOutput .= "\t<div class='printouttitle'><strong>" . gT("Survey name (ID):") . "</strong> {$sSurveyName} ({$iSurveyID})</div><p>&nbsp;\n";
         LimeExpressionManager::StartProcessingPage(true);
         // means that all variables are on the same page
         // Since all data are loaded, and don't need JavaScript, pretend all from Group 1
         LimeExpressionManager::StartProcessingGroup(1, $aSurveyInfo['anonymized'] != "N", $iSurveyID);
         $printanswershonorsconditions = Yii::app()->getConfig('printanswershonorsconditions');
         $aFullResponseTable = getFullResponseTable($iSurveyID, $sSRID, $sLanguage, $printanswershonorsconditions);
         //Get the fieldmap @TODO: do we need to filter out some fields?
         if ($aSurveyInfo['datestamp'] != "Y" || $sAnonymized == 'Y') {
             unset($aFullResponseTable['submitdate']);
         } else {
             unset($aFullResponseTable['id']);
         }
         unset($aFullResponseTable['token']);
         unset($aFullResponseTable['lastpage']);
         unset($aFullResponseTable['startlanguage']);
         unset($aFullResponseTable['datestamp']);
         unset($aFullResponseTable['startdate']);
         $sOutput .= "<table class='printouttable' >\n";
         foreach ($aFullResponseTable as $sFieldname => $fname) {
             if (substr($sFieldname, 0, 4) == 'gid_') {
                 $sOutput .= "\t<tr class='printanswersgroup'><td colspan='2'>{$fname[0]}</td></tr>\n";
                 $sOutput .= "\t<tr class='printanswersgroupdesc'><td colspan='2'>{$fname[1]}</td></tr>\n";
             } elseif ($sFieldname == 'submitdate') {
                 if ($sAnonymized != 'Y') {
                     $sOutput .= "\t<tr class='printanswersquestion'><td>{$fname[0]} {$fname[1]} {$sFieldname}</td><td class='printanswersanswertext'>{$fname[2]}</td></tr>";
                 }
             } elseif (substr($sFieldname, 0, 4) != 'qid_') {
                 $sOutput .= "\t<tr class='printanswersquestion'><td>{$fname[0]} {$fname[1]}</td><td class='printanswersanswertext'>" . flattenText($fname[2]) . "</td></tr>";
             }
         }
         $sOutput .= "</table>\n";
         $sData['thissurvey'] = $aSurveyInfo;
         $sOutput = templatereplace($sOutput, array(), $sData, '', $aSurveyInfo['anonymized'] == "Y", NULL, array(), true);
         // Do a static replacement
         ob_start(function ($buffer, $phase) {
             App()->getClientScript()->render($buffer);
             App()->getClientScript()->reset();
             return $buffer;
         });
         ob_implicit_flush(false);
         sendCacheHeaders();
         doHeader();
         echo templatereplace(file_get_contents($oTemplate->viewPath . '/startpage.pstpl'), array(), $sData);
         echo templatereplace(file_get_contents($oTemplate->viewPath . '/printanswers.pstpl'), array('ANSWERTABLE' => $sOutput), $sData);
         echo templatereplace(file_get_contents($oTemplate->viewPath . '/endpage.pstpl'), array(), $sData);
         echo "</body></html>";
         ob_flush();
     }
     if ($sExportType == 'pdf') {
         // Get images for TCPDF from template directory
         define('K_PATH_IMAGES', getTemplatePath($aSurveyInfo['template']) . DIRECTORY_SEPARATOR);
         Yii::import('application.libraries.admin.pdf', true);
         Yii::import('application.helpers.pdfHelper');
         $aPdfLanguageSettings = pdfHelper::getPdfLanguageSettings(App()->language);
         $oPDF = new pdf();
         $sDefaultHeaderString = $sSurveyName . " (" . gT("ID", 'unescaped') . ":" . $iSurveyID . ")";
         $oPDF->initAnswerPDF($aSurveyInfo, $aPdfLanguageSettings, Yii::app()->getConfig('sitename'), $sSurveyName, $sDefaultHeaderString);
         LimeExpressionManager::StartProcessingPage(true);
         // means that all variables are on the same page
         // Since all data are loaded, and don't need JavaScript, pretend all from Group 1
         LimeExpressionManager::StartProcessingGroup(1, $aSurveyInfo['anonymized'] != "N", $iSurveyID);
         $printanswershonorsconditions = Yii::app()->getConfig('printanswershonorsconditions');
         $aFullResponseTable = getFullResponseTable($iSurveyID, $sSRID, $sLanguage, $printanswershonorsconditions);
         //Get the fieldmap @TODO: do we need to filter out some fields?
         if ($aSurveyInfo['datestamp'] != "Y" || $sAnonymized == 'Y') {
             unset($aFullResponseTable['submitdate']);
         } else {
             unset($aFullResponseTable['id']);
         }
         unset($aFullResponseTable['token']);
         unset($aFullResponseTable['lastpage']);
         unset($aFullResponseTable['startlanguage']);
         unset($aFullResponseTable['datestamp']);
         unset($aFullResponseTable['startdate']);
         foreach ($aFullResponseTable as $sFieldname => $fname) {
             if (substr($sFieldname, 0, 4) == 'gid_') {
                 $oPDF->addGidAnswer($fname[0], $fname[1]);
             } elseif ($sFieldname == 'submitdate') {
                 if ($sAnonymized != 'Y') {
                     $oPDF->addAnswer($fname[0] . " " . $fname[1], $fname[2]);
                 }
             } elseif (substr($sFieldname, 0, 4) != 'qid_') {
                 $oPDF->addAnswer($fname[0] . " " . $fname[1], $fname[2]);
             }
         }
         header("Pragma: public");
         header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
         $sExportFileName = sanitize_filename($sSurveyName);
         $oPDF->Output($sExportFileName . "-" . $iSurveyID . ".pdf", "D");
     }
     LimeExpressionManager::FinishProcessingGroup();
     LimeExpressionManager::FinishProcessingPage();
 }
Example #22
0
/>
  	 No: <input type="radio" name="cbActive" value="0"<?php 
    if (!$defaults['cbActive']) {
        print " checked=checked";
    }
    ?>
/>
  </td>
  </tr>
  <tr>
    <td colspan=2 align="center"><input name="isPostback" type="hidden" id="isPostback" value="1">
      <input name="btSubmit" type="submit" id="btSubmit" value="Save Edits?"></td>
    <td>&nbsp;</td>
  </tr>
  <tr>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
  </tr>
  <tr>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
  </tr>
</table></form>
<?php 
}
// end of editUserForm
?>
<p>&nbsp;</p>
<?php 
doFooter();
Example #23
0
 function _niceExit(&$redata, $iDebugLine, $sTemplateDir = null, $asMessage = array())
 {
     $sTemplateDir = getTemplatePath($sTemplateDir);
     sendCacheHeaders();
     doHeader();
     $this->_printTemplateContent($sTemplateDir . '/startpage.pstpl', $redata, $iDebugLine);
     $this->_printMessage($asMessage);
     $this->_printTemplateContent($sTemplateDir . '/endpage.pstpl', $redata, $iDebugLine);
     doFooter();
     exit;
 }
 /**
  * register::index()
  * Process register form data and take appropriate action
  * @return
  */
 function actionIndex($surveyid = null)
 {
     Yii::app()->loadHelper('database');
     Yii::app()->loadHelper('replacements');
     $postlang = Yii::app()->request->getPost('lang');
     if ($surveyid == null) {
         $surveyid = Yii::app()->request->getPost('sid');
     }
     if (!$surveyid) {
         Yii::app()->request->redirect(Yii::app()->baseUrl);
     }
     // Get passed language from form, so that we dont loose this!
     if (!isset($postlang) || $postlang == "" || !$postlang) {
         $baselang = Survey::model()->findByPk($surveyid)->language;
         Yii::import('application.libraries.Limesurvey_lang');
         Yii::app()->lang = new Limesurvey_lang($baselang);
         $clang = Yii::app()->lang;
     } else {
         Yii::import('application.libraries.Limesurvey_lang');
         Yii::app()->lang = new Limesurvey_lang($postlang);
         $clang = Yii::app()->lang;
         $baselang = $postlang;
     }
     $thissurvey = getSurveyInfo($surveyid, $baselang);
     $register_errormsg = "";
     // Check the security question's answer
     if (function_exists("ImageCreate") && isCaptchaEnabled('registrationscreen', $thissurvey['usecaptcha'])) {
         if (!isset($_POST['loadsecurity']) || !isset($_SESSION['survey_' . $surveyid]['secanswer']) || Yii::app()->request->getPost('loadsecurity') != $_SESSION['survey_' . $surveyid]['secanswer']) {
             $register_errormsg .= $clang->gT("The answer to the security question is incorrect.") . "<br />\n";
         }
     }
     //Check that the email is a valid style address
     if (!validateEmailAddress(Yii::app()->request->getPost('register_email'))) {
         $register_errormsg .= $clang->gT("The email you used is not valid. Please try again.");
     }
     // Check for additional fields
     $attributeinsertdata = array();
     foreach (GetParticipantAttributes($surveyid) as $field => $data) {
         if (empty($data['show_register']) || $data['show_register'] != 'Y') {
             continue;
         }
         $value = sanitize_xss_string(Yii::app()->request->getPost('register_' . $field));
         if (trim($value) == '' && $data['mandatory'] == 'Y') {
             $register_errormsg .= sprintf($clang->gT("%s cannot be left empty"), $thissurvey['attributecaptions'][$field]);
         }
         $attributeinsertdata[$field] = $value;
     }
     if ($register_errormsg != "") {
         $_SESSION['survey_' . $surveyid]['register_errormsg'] = $register_errormsg;
         Yii::app()->request->redirect(Yii::app()->createUrl('survey/index/sid/' . $surveyid));
     }
     //Check if this email already exists in token database
     $query = "SELECT email FROM {{tokens_{$surveyid}}}\n" . "WHERE email = '" . sanitize_email(Yii::app()->request->getPost('register_email')) . "'";
     $usrow = Yii::app()->db->createCommand($query)->queryRow();
     if ($usrow) {
         $register_errormsg = $clang->gT("The email you used has already been registered.");
         $_SESSION['survey_' . $surveyid]['register_errormsg'] = $register_errormsg;
         Yii::app()->request->redirect(Yii::app()->createUrl('survey/index/sid/' . $surveyid));
         //include "index.php";
         //exit;
     }
     $mayinsert = false;
     // Get the survey settings for token length
     //$this->load->model("surveys_model");
     $tlresult = Survey::model()->findAllByAttributes(array("sid" => $surveyid));
     if (isset($tlresult[0])) {
         $tlrow = $tlresult[0];
     } else {
         $tlrow = $tlresult;
     }
     $tokenlength = $tlrow['tokenlength'];
     //if tokenlength is not set or there are other problems use the default value (15)
     if (!isset($tokenlength) || $tokenlength == '') {
         $tokenlength = 15;
     }
     while ($mayinsert != true) {
         $newtoken = randomChars($tokenlength);
         $ntquery = "SELECT * FROM {{tokens_{$surveyid}}} WHERE token='{$newtoken}'";
         $usrow = Yii::app()->db->createCommand($ntquery)->queryRow();
         if (!$usrow) {
             $mayinsert = true;
         }
     }
     $postfirstname = sanitize_xss_string(strip_tags(Yii::app()->request->getPost('register_firstname')));
     $postlastname = sanitize_xss_string(strip_tags(Yii::app()->request->getPost('register_lastname')));
     $starttime = sanitize_xss_string(Yii::app()->request->getPost('startdate'));
     $endtime = sanitize_xss_string(Yii::app()->request->getPost('enddate'));
     /*$postattribute1=sanitize_xss_string(strip_tags(returnGlobal('register_attribute1')));
       $postattribute2=sanitize_xss_string(strip_tags(returnGlobal('register_attribute2')));   */
     // Insert new entry into tokens db
     Tokens_dynamic::sid($thissurvey['sid']);
     $token = new Tokens_dynamic();
     $token->firstname = $postfirstname;
     $token->lastname = $postlastname;
     $token->email = Yii::app()->request->getPost('register_email');
     $token->emailstatus = 'OK';
     $token->token = $newtoken;
     if ($starttime && $endtime) {
         $token->validfrom = $starttime;
         $token->validuntil = $endtime;
     }
     foreach ($attributeinsertdata as $k => $v) {
         $token->{$k} = $v;
     }
     $result = $token->save();
     /**
     $result = $connect->Execute($query, array($postfirstname,
     $postlastname,
     returnGlobal('register_email'),
     'OK',
     $newtoken)
     
     //                             $postattribute1,   $postattribute2)
     ) or safeDie ($query."<br />".$connect->ErrorMsg());  //Checked - According to adodb docs the bound variables are quoted automatically
     */
     $tid = getLastInsertID($token->tableName());
     $fieldsarray["{ADMINNAME}"] = $thissurvey['adminname'];
     $fieldsarray["{ADMINEMAIL}"] = $thissurvey['adminemail'];
     $fieldsarray["{SURVEYNAME}"] = $thissurvey['name'];
     $fieldsarray["{SURVEYDESCRIPTION}"] = $thissurvey['description'];
     $fieldsarray["{FIRSTNAME}"] = $postfirstname;
     $fieldsarray["{LASTNAME}"] = $postlastname;
     $fieldsarray["{EXPIRY}"] = $thissurvey["expiry"];
     $message = $thissurvey['email_register'];
     $subject = $thissurvey['email_register_subj'];
     $from = "{$thissurvey['adminname']} <{$thissurvey['adminemail']}>";
     if (getEmailFormat($surveyid) == 'html') {
         $useHtmlEmail = true;
         $surveylink = $this->createAbsoluteUrl($surveyid . '/lang-' . $baselang . '/tk-' . $newtoken);
         $optoutlink = $this->createAbsoluteUrl('optout/local/' . $surveyid . '/' . $baselang . '/' . $newtoken);
         $optinlink = $this->createAbsoluteUrl('optin/local/' . $surveyid . '/' . $baselang . '/' . $newtoken);
         $fieldsarray["{SURVEYURL}"] = "<a href='{$surveylink}'>" . $surveylink . "</a>";
         $fieldsarray["{OPTOUTURL}"] = "<a href='{$optoutlink}'>" . $optoutlink . "</a>";
         $fieldsarray["{OPTINURL}"] = "<a href='{$optinlink}'>" . $optinlink . "</a>";
     } else {
         $useHtmlEmail = false;
         $fieldsarray["{SURVEYURL}"] = $this->createAbsoluteUrl('' . $surveyid . '/lang-' . $baselang . '/tk-' . $newtoken);
         $fieldsarray["{OPTOUTURL}"] = $this->createAbsoluteUrl('optout/local/' . $surveyid . '/' . $baselang . '/' . $newtoken);
         $fieldsarray["{OPTINURL}"] = $this->createAbsoluteUrl('optin/local/' . $surveyid . '/' . $baselang . '/' . $newtoken);
     }
     $message = ReplaceFields($message, $fieldsarray);
     $subject = ReplaceFields($subject, $fieldsarray);
     $html = "";
     //Set variable
     $sitename = Yii::app()->getConfig('sitename');
     if (SendEmailMessage($message, $subject, Yii::app()->request->getPost('register_email'), $from, $sitename, $useHtmlEmail, getBounceEmail($surveyid))) {
         // TLR change to put date into sent
         $today = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i", Yii::app()->getConfig('timeadjust'));
         $query = "UPDATE {{tokens_{$surveyid}}}\n" . "SET sent='{$today}' WHERE tid={$tid}";
         $result = dbExecuteAssoc($query) or show_error("Unable to execute this query : {$query}<br />");
         //Checked
         $html = "<center>" . $clang->gT("Thank you for registering to participate in this survey.") . "<br /><br />\n" . $clang->gT("An email has been sent to the address you provided with access details for this survey. Please follow the link in that email to proceed.") . "<br /><br />\n" . $clang->gT("Survey administrator") . " {ADMINNAME} ({ADMINEMAIL})";
         $html = ReplaceFields($html, $fieldsarray);
         $html .= "<br /><br /></center>\n";
     } else {
         $html = "Email Error";
     }
     //PRINT COMPLETED PAGE
     if (!$thissurvey['template']) {
         $thistpl = getTemplatePath(validateTemplateDir('default'));
     } else {
         $thistpl = getTemplatePath(validateTemplateDir($thissurvey['template']));
     }
     sendCacheHeaders();
     doHeader();
     Yii::app()->lang = $clang;
     // fetch the defined variables and pass it to the header footer templates.
     $redata = compact(array_keys(get_defined_vars()));
     $this->_printTemplateContent($thistpl . '/startpage.pstpl', $redata, __LINE__);
     $this->_printTemplateContent($thistpl . '/survey.pstpl', $redata, __LINE__);
     echo $html;
     $this->_printTemplateContent($thistpl . '/endpage.pstpl', $redata, __LINE__);
     doFooter();
 }
Example #25
0
 /**
  * Render stuff
  *
  * @param string $html
  * @param array $aSurveyInfo
  * @param int $iSurveyID
  * @return void
  */
 private function _renderHtml($html, $aSurveyInfo, $iSurveyID)
 {
     sendCacheHeaders();
     doHeader();
     $aSupportData = array('thissurvey' => $aSurveyInfo);
     $oTemplate = Template::model()->getInstance(null, $iSurveyID);
     if ($oTemplate->cssFramework == 'bootstrap') {
         App()->bootstrap->register();
     }
     $thistpl = $oTemplate->viewPath;
     echo templatereplace(file_get_contents($thistpl . 'startpage.pstpl'), array(), $aSupportData);
     $aData['html'] = $html;
     $aData['thistpl'] = $thistpl;
     $this->render('/opt_view', $aData);
     echo templatereplace(file_get_contents($thistpl . 'endpage.pstpl'), array(), $aSupportData);
     doFooter();
 }
 /**
  * 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();
 }
Example #27
0
function display_first_page()
{
    global $clang, $thistpl, $token, $surveyid, $thissurvey, $navigator, $publicurl;
    sendcacheheaders();
    doHeader();
    echo templatereplace(file_get_contents("{$thistpl}/startpage.pstpl"));
    echo "\n<form method='post' action='{$publicurl}/index.php' id='limesurvey' name='limesurvey' autocomplete='off'>\n";
    echo "\n\n<!-- START THE SURVEY -->\n";
    echo templatereplace(file_get_contents("{$thistpl}/welcome.pstpl")) . "\n";
    if ($thissurvey['private'] == "Y") {
        echo templatereplace(file_get_contents("{$thistpl}/privacy.pstpl")) . "\n";
    }
    $navigator = surveymover();
    echo templatereplace(file_get_contents("{$thistpl}/navigator.pstpl"));
    if ($thissurvey['active'] != "Y") {
        echo "<center><font color='red' size='2'>" . $clang->gT("This survey is not currently active. You will not be able to save your responses.") . "</font></center>\n";
    }
    echo "\n<input type='hidden' name='sid' value='{$surveyid}' id='sid' />\n";
    echo "\n<input type='hidden' name='token' value='{$token}' id='token' />\n";
    echo "\n<input type='hidden' name='lastgroupname' value='_WELCOME_SCREEN_' id='lastgroupname' />\n";
    //This is to ensure consistency with mandatory checks, and new group test
    echo "\n</form>\n";
    echo templatereplace(file_get_contents("{$thistpl}/endpage.pstpl"));
    doFooter();
}