コード例 #1
0
/**
* This function replaces keywords in a text and is mainly intended for templates
* If you use this functions put your replacement strings into the $replacements variable
* instead of using global variables
* NOTE - Don't do any embedded replacements in this function.  Create the array of replacement values and
* they will be done in batch at the end
*
* @param mixed $line Text to search in
* @param mixed $replacements Array of replacements:  Array( <stringtosearch>=><stringtoreplacewith>
* @param boolean $anonymized Determines if token data is being used or just replaced with blanks
* @param questionNum - needed to support dynamic JavaScript-based tailoring within questions
* @return string  Text with replaced strings
*/
function templatereplace($line, $replacements = array(), &$redata = array(), $debugSrc = 'Unspecified', $anonymized = false, $questionNum = NULL, $registerdata = array())
{
    /*
    global $clienttoken,$token,$sitename,$move,$showxquestions,$showqnumcode,$questioncode,$register_errormsg;
    global $s_lang,$errormsg,$saved_id, $relativeurl, $languagechanger,$captchapath,$loadname;
    */
    /*
    $allowedvars = array('surveylist', 'sitename', 'clienttoken', 'rooturl', 'thissurvey', 'imageurl', 'defaulttemplate',
    'percentcomplete', 'move', 'groupname', 'groupdescription', 'question', 'showxquestions',
    'showgroupinfo', 'showqnumcode', 'questioncode', 'answer', 'navigator', 'help', 'totalquestions',
    'surveyformat', 'completed', 'register_errormsg', 'notanswered', 'privacy', 'surveyid', 'publicurl',
    'templatedir', 'token', 'assessments', 's_lang', 'errormsg', 'clang', 'saved_id', 'usertemplaterootdir',
    'relativeurl', 'languagechanger', 'printoutput', 'captchapath', 'loadname');
    */
    $allowedvars = array('answer', 'assessments', 'captchapath', 'clienttoken', 'completed', 'errormsg', 'groupdescription', 'groupname', 'help', 'imageurl', 'languagechanger', 'loadname', 'move', 'navigator', 'percentcomplete', 'privacy', 'question', 'register_errormsg', 'relativeurl', 's_lang', 'saved_id', 'showgroupinfo', 'showqnumcode', 'showxquestions', 'sitename', 'surveylist', 'templatedir', 'thissurvey', 'token', 'totalBoilerplatequestions', 'totalquestions');
    $varsPassed = array();
    foreach ($allowedvars as $var) {
        if (isset($redata[$var])) {
            ${$var} = $redata[$var];
            $varsPassed[] = $var;
        }
    }
    //    if (count($varsPassed) > 0) {
    //        log_message('debug', 'templatereplace() called from ' . $debugSrc . ' contains: ' . implode(', ', $varsPassed));
    //    }
    //    if (isset($redata['question'])) {
    //        LimeExpressionManager::ShowStackTrace('has QID and/or SGA',$allowedvars);
    //    }
    //    extract($redata);   // creates variables for each of the keys in the array
    // Local over-rides in case not set above
    if (!isset($showgroupinfo)) {
        $showgroupinfo = Yii::app()->getConfig('showgroupinfo');
    }
    if (!isset($showqnumcode)) {
        $showqnumcode = Yii::app()->getConfig('showqnumcode');
    }
    $_surveyid = Yii::app()->getConfig('surveyID');
    if (!isset($showxquestions)) {
        $showxquestions = Yii::app()->getConfig('showxquestions');
    }
    if (!isset($s_lang)) {
        $s_lang = isset(Yii::app()->session['survey_' . $_surveyid]['s_lang']) ? Yii::app()->session['survey_' . $_surveyid]['s_lang'] : 'en';
    }
    if (!isset($captchapath)) {
        $captchapath = '';
    }
    $clang = Yii::app()->lang;
    Yii::app()->loadHelper('surveytranslator');
    $questiondetails = array('sid' => 0, 'gid' => 0, 'qid' => 0, 'aid' => 0);
    if (isset($question) && isset($question['sgq'])) {
        $questiondetails = getSIDGIDQIDAIDType($question['sgq']);
    }
    //Gets an array containing SID, GID, QID, AID and Question Type)
    if (isset($thissurvey['sid'])) {
        $surveyid = $thissurvey['sid'];
    }
    // lets sanitize the survey template
    if (isset($thissurvey['templatedir'])) {
        $templatename = $thissurvey['templatedir'];
    } else {
        $templatename = Yii::app()->getConfig('defaulttemplate');
    }
    if (!isset($templatedir)) {
        $templatedir = getTemplatePath($templatename);
    }
    if (!isset($templateurl)) {
        $templateurl = getTemplateURL($templatename) . "/";
    }
    // TEMPLATECSS and TEMPLATEJS
    $_templatecss = "";
    $_templatejs = "";
    if (stripos($line, "{TEMPLATECSS}")) {
        $css_header_includes = Yii::app()->getConfig("css_header_includes");
        if (file_exists($templatedir . DIRECTORY_SEPARATOR . 'jquery-ui-custom.css')) {
            $template_jqueryui_css = "<link rel='stylesheet' type='text/css' media='all' href='{$templateurl}jquery-ui-custom.css' />\n";
        } elseif (file_exists($templatedir . DIRECTORY_SEPARATOR . 'jquery-ui.css')) {
            $template_jqueryui_css = "<link rel='stylesheet' type='text/css' media='all' href='{$templateurl}jquery-ui.css' />\n";
        } else {
            $_templatecss .= "<link rel='stylesheet' type='text/css' media='all' href='" . Yii::app()->getConfig('publicstyleurl') . "jquery-ui.css' />\n";
            // Remove it after corrected slider
            $template_jqueryui_css = "";
        }
        if ($css_header_includes) {
            foreach ($css_header_includes as $cssinclude) {
                if (substr($cssinclude, 0, 4) == 'http' || substr($cssinclude, 0, strlen(Yii::app()->getConfig('publicurl'))) == Yii::app()->getConfig('publicurl')) {
                    $_templatecss .= "<link rel='stylesheet' type='text/css' media='all' href='" . $cssinclude . "' />\n";
                } else {
                    if (file_exists($templatedir . DIRECTORY_SEPARATOR . $cssinclude)) {
                        $_templatecss .= "<link rel='stylesheet' type='text/css' media='all' href='{$templateurl}{$cssinclude}' />\n";
                    } else {
                        $_templatecss .= "<link rel='stylesheet' type='text/css' media='all' href='" . Yii::app()->getConfig('publicstyleurl') . $cssinclude . "' />\n";
                    }
                }
            }
        }
        $_templatecss .= $template_jqueryui_css;
        // Template jquery ui after default css
        $_templatecss .= "<link rel='stylesheet' type='text/css' media='all' href='{$templateurl}template.css' />\n";
        if (getLanguageRTL($clang->langcode)) {
            $_templatecss .= "<link rel='stylesheet' type='text/css' media='all' href='{$templateurl}template-rtl.css' />\n";
        }
    }
    if (stripos($line, "{TEMPLATEJS}")) {
        $js_header_includes = header_includes(false, 'js');
        $_jqueryuijsurl = Yii::app()->getConfig('generalscripts') . "jquery/jquery-ui.js";
        $_templatejs .= "<script type='text/javascript' src='" . Yii::app()->getConfig('generalscripts') . "jquery/jquery.js'></script>\n";
        $_templatejs .= "<script type='text/javascript' src='{$_jqueryuijsurl}'></script>\n";
        $_templatejs .= "<script type='text/javascript' src='" . Yii::app()->getConfig('generalscripts') . "jquery/jquery.ui.touch-punch.min.js'></script>\n";
        if ($js_header_includes) {
            foreach ($js_header_includes as $jsinclude) {
                if (substr($jsinclude, 0, 4) == 'http' || substr($jsinclude, 0, strlen(Yii::app()->getConfig('publicurl'))) == Yii::app()->getConfig('publicurl')) {
                    $_templatejs .= "<script type='text/javascript' src='{$jsinclude}'></script>\n";
                } else {
                    $_templatejs .= "<script type='text/javascript' src='" . Yii::app()->getConfig('generalscripts') . $jsinclude . "'></script>\n";
                }
            }
        }
        $_templatejs .= "<script type='text/javascript' src='" . Yii::app()->getConfig('generalscripts') . "survey_runtime.js'></script>\n";
        $_templatejs .= "<script type='text/javascript' src='{$templateurl}template.js'></script>\n";
        $_templatejs .= useFirebug();
    }
    // surveyformat
    if (isset($thissurvey['format'])) {
        $surveyformat = str_replace(array("A", "S", "G"), array("allinone", "questionbyquestion", "groupbygroup"), $thissurvey['format']);
    } else {
        $surveyformat = "";
    }
    if (isset(Yii::app()->session['step']) && Yii::app()->session['step'] % 2 && $surveyformat != "allinone") {
        $surveyformat .= " page-odd";
    }
    if (isset($thissurvey['allowjumps']) && $thissurvey['allowjumps'] == "Y" && $surveyformat != "allinone" && (isset(Yii::app()->session['step']) && Yii::app()->session['step'] > 0)) {
        $surveyformat .= " withindex";
    }
    if (isset($thissurvey['showprogress']) && $thissurvey['showprogress'] == "Y") {
        $surveyformat .= " showprogress";
    }
    if (isset($thissurvey['showqnumcode'])) {
        $surveyformat .= " showqnumcode-" . $thissurvey['showqnumcode'];
    }
    // real survey contact
    if (isset($surveylist) && isset($surveylist['contact'])) {
        $surveycontact = $surveylist['contact'];
    } elseif (isset($surveylist) && isset($thissurvey['admin']) && $thissurvey['admin'] != "") {
        $surveycontact = sprintf($clang->gT("Please contact %s ( %s ) for further assistance."), $thissurvey['admin'], $thissurvey['adminemail']);
    } else {
        $surveycontact = "";
    }
    // If there are non-bracketed replacements to be made do so above this line.
    // Only continue in this routine if there are bracketed items to replace {}
    if (strpos($line, "{") === false) {
        // process string anyway so that it can be pretty-printed
        return LimeExpressionManager::ProcessString($line, $questionNum, NULL, false, 1, 1, true);
    }
    if ($showgroupinfo == 'both' || $showgroupinfo == 'name' || $showgroupinfo == 'choose' && !isset($thissurvey['showgroupinfo']) || $showgroupinfo == 'choose' && $thissurvey['showgroupinfo'] == 'B' || $showgroupinfo == 'choose' && $thissurvey['showgroupinfo'] == 'N') {
        $_groupname = isset($groupname) ? $groupname : '';
    } else {
        $_groupname = '';
    }
    if ($showgroupinfo == 'both' || $showgroupinfo == 'description' || $showgroupinfo == 'choose' && !isset($thissurvey['showgroupinfo']) || $showgroupinfo == 'choose' && $thissurvey['showgroupinfo'] == 'B' || $showgroupinfo == 'choose' && $thissurvey['showgroupinfo'] == 'D') {
        $_groupdescription = isset($groupdescription) ? $groupdescription : '';
    } else {
        $_groupdescription = '';
    }
    if (isset($question) && is_array($question)) {
        $_question = $question['all'];
        $_question_text = $question['text'];
        $_question_help = $question['help'];
        $_question_mandatory = $question['mandatory'];
        $_question_man_message = $question['man_message'];
        $_question_valid_message = $question['valid_message'];
        $_question_file_valid_message = $question['file_valid_message'];
        $_question_sgq = isset($question['sgq']) ? $question['sgq'] : '';
        $_question_essentials = $question['essentials'];
        $_getQuestionClass = $question['class'];
        $_question_man_class = $question['man_class'];
        $_question_input_error_class = $question['input_error_class'];
        $_question_number = $question['number'];
        $_question_code = $question['code'];
        $_question_type = $question['type'];
    } else {
        $_question = isset($question) ? $question : '';
        $_question_text = '';
        $_question_help = '';
        $_question_mandatory = '';
        $_question_man_message = '';
        $_question_valid_message = '';
        $_question_file_valid_message = '';
        $_question_sgq = '';
        $_question_essentials = '';
        $_getQuestionClass = '';
        $_question_man_class = '';
        $_question_input_error_class = '';
        $_question_number = '';
        $_question_code = '';
        $_question_type = '';
    }
    if ($_question_type == '*') {
        $_question_text = '<div class="em_equation">' . $_question_text . '</div>';
    }
    if (!($showqnumcode == 'both' || $showqnumcode == 'number' || $showqnumcode == 'choose' && !isset($thissurvey['showqnumcode']) || $showqnumcode == 'choose' && $thissurvey['showqnumcode'] == 'B' || $showqnumcode == 'choose' && $thissurvey['showqnumcode'] == 'N')) {
        $_question_number = '';
    }
    if (!($showqnumcode == 'both' || $showqnumcode == 'code' || $showqnumcode == 'choose' && !isset($thissurvey['showqnumcode']) || $showqnumcode == 'choose' && $thissurvey['showqnumcode'] == 'B' || $showqnumcode == 'choose' && $thissurvey['showqnumcode'] == 'C')) {
        $_question_code = '';
    }
    if (!isset($totalquestions)) {
        $totalquestions = 0;
    }
    $_totalquestionsAsked = $totalquestions;
    if ($showxquestions == 'show' || $showxquestions == 'choose' && !isset($thissurvey['showxquestions']) || $showxquestions == 'choose' && $thissurvey['showxquestions'] == 'Y') {
        if ($_totalquestionsAsked < 1) {
            $_therearexquestions = $clang->gT("There are no questions in this survey");
            // Singular
        } elseif ($_totalquestionsAsked == 1) {
            $_therearexquestions = $clang->gT("There is 1 question in this survey");
            //Singular
        } else {
            $_therearexquestions = $clang->gT("There are {NUMBEROFQUESTIONS} questions in this survey.");
            //Note this line MUST be before {NUMBEROFQUESTIONS}
        }
    } else {
        $_therearexquestions = '';
    }
    if (isset($token)) {
        $_token = $token;
    } elseif (isset($clienttoken)) {
        $_token = htmlentities($clienttoken, ENT_QUOTES, 'UTF-8');
        // or should it be URL-encoded?
    } else {
        $_token = '';
    }
    // Expiry
    if (isset($thissurvey['expiry'])) {
        $dateformatdetails = getDateFormatData($thissurvey['surveyls_dateformat']);
        Yii::import('application.libraries.Date_Time_Converter', true);
        $datetimeobj = new Date_Time_Converter($thissurvey['expiry'], "Y-m-d");
        $_dateoutput = $datetimeobj->convert($dateformatdetails['phpdate']);
    } else {
        $_dateoutput = '-';
    }
    $_submitbutton = "<input class='submit' type='submit' value=' " . $clang->gT("Submit") . " ' name='move2' onclick=\"javascript:document.limesurvey.move.value = 'movesubmit';\" />";
    if (isset($thissurvey['surveyls_url']) and $thissurvey['surveyls_url'] != "") {
        if (trim($thissurvey['surveyls_urldescription']) != '') {
            $_linkreplace = "<a href='{$thissurvey['surveyls_url']}'>{$thissurvey['surveyls_urldescription']}</a>";
        } else {
            $_linkreplace = "<a href='{$thissurvey['surveyls_url']}'>{$thissurvey['surveyls_url']}</a>";
        }
    } else {
        $_linkreplace = '';
    }
    if (isset($thissurvey['sid']) && isset($_SESSION['survey_' . $thissurvey['sid']]['srid']) && $thissurvey['active'] == 'Y') {
        $iscompleted = Survey_dynamic::model($surveyid)->isCompleted($_SESSION['survey_' . $thissurvey['sid']]['srid']);
    } else {
        $iscompleted = false;
    }
    if (isset($surveyid) && !$iscompleted) {
        $_clearall = "<input type='button' name='clearallbtn' value='" . $clang->gT("Exit and clear survey") . "' class='clearall' " . "onclick=\"if (confirm('" . $clang->gT("Are you sure you want to clear all your responses?", 'js') . "')) {\nwindow.open('" . Yii::app()->getController()->createUrl("survey/index/sid/{$surveyid}", array('move' => 'clearall', 'lang' => $s_lang), '&amp;');
        if (returnGlobal('token')) {
            $_clearall .= "&amp;token=" . urlencode(trim(sanitize_token(strip_tags(returnGlobal('token')))));
        }
        $_clearall .= "', '_self')}\" />";
    } else {
        $_clearall = "";
    }
    if (isset(Yii::app()->session['datestamp'])) {
        $_datestamp = Yii::app()->session['datestamp'];
    } else {
        $_datestamp = '-';
    }
    if (isset($thissurvey['allowsave']) and $thissurvey['allowsave'] == "Y") {
        // Find out if the user has any saved data
        if ($thissurvey['format'] == 'A') {
            if ($thissurvey['tokenanswerspersistence'] != 'Y' || !isset($surveyid) || !tableExists('tokens_' . $surveyid)) {
                $_saveall = "\t\t\t<input type='button' name='loadall' value='" . $clang->gT("Load unfinished survey") . "' class='saveall' onclick=\"javascript:addHiddenField(document.getElementById('limesurvey'),'loadall',this.value);document.getElementById('limesurvey').submit();\" " . ($thissurvey['active'] != "Y" ? "disabled='disabled'" : "") . "/>" . "\n\t\t\t<input type='button' name='saveallbtn' value='" . $clang->gT("Resume later") . "' class='saveall' onclick=\"javascript:document.limesurvey.move.value = this.value;addHiddenField(document.getElementById('limesurvey'),'saveall',this.value);document.getElementById('limesurvey').submit();\" " . ($thissurvey['active'] != "Y" ? "disabled='disabled'" : "") . "/>";
                // Show Save So Far button
            } else {
                $_saveall = "\t\t\t<input type='button' name='saveallbtn' value='" . $clang->gT("Resume later") . "' class='saveall' onclick=\"javascript:document.limesurvey.move.value = this.value;addHiddenField(document.getElementById('limesurvey'),'saveall',this.value);document.getElementById('limesurvey').submit();\" " . ($thissurvey['active'] != "Y" ? "disabled='disabled'" : "") . "/>";
                // Show Save So Far button
            }
        } elseif (isset($surveyid) && (!isset($_SESSION['survey_' . $surveyid]['step']) || !$_SESSION['survey_' . $surveyid]['step'])) {
            //First page, show LOAD
            if ($thissurvey['tokenanswerspersistence'] != 'Y' || !isset($surveyid) || !tableExists('tokens_' . $surveyid)) {
                $_saveall = "\t\t\t<input type='button' name='loadall' value='" . $clang->gT("Load unfinished survey") . "' class='saveall' onclick=\"javascript:addHiddenField(document.getElementById('limesurvey'),'loadall',this.value);document.getElementById('limesurvey').submit();\" " . ($thissurvey['active'] != "Y" ? "disabled='disabled'" : "") . "/>";
            } else {
                $_saveall = '';
            }
        } elseif (isset(Yii::app()->session['scid']) && (isset($move) && $move == "movelast")) {
            //Already saved and on Submit Page, dont show Save So Far button
            $_saveall = '';
        } else {
            $_saveall = "<input type='button' name='saveallbtn' value='" . $clang->gT("Resume later") . "' class='saveall' onclick=\"javascript:document.limesurvey.move.value = this.value;addHiddenField(document.getElementById('limesurvey'),'saveall',this.value);document.getElementById('limesurvey').submit();\" " . ($thissurvey['active'] != "Y" ? "disabled='disabled'" : "") . "/>";
            // Show Save So Far button
        }
    } else {
        $_saveall = "";
    }
    if (!isset($help)) {
        $help = "";
    }
    if (flattenText($help, true, true) != '') {
        if (!isset($helpicon)) {
            if (file_exists($templatedir . '/help.gif')) {
                $helpicon = $templateurl . 'help.gif';
            } elseif (file_exists($templatedir . '/help.png')) {
                $helpicon = $templateurl . 'help.png';
            } else {
                $helpicon = Yii::app()->getConfig('imageurl') . "/help.gif";
            }
        }
        $_questionhelp = "<img src='{$helpicon}' alt='Help' align='left' />" . $help;
    } else {
        $_questionhelp = $help;
    }
    if (isset($thissurvey['allowprev']) && $thissurvey['allowprev'] == "N") {
        $_strreview = "";
    } else {
        $_strreview = $clang->gT("If you want to check any of the answers you have made, and/or change them, you can do that now by clicking on the [<< prev] button and browsing through your responses.");
    }
    if (isset($thissurvey['active']) and $thissurvey['active'] == "N") {
        $_restart = "<a href='" . Yii::app()->getController()->createUrl("survey/index/sid/{$surveyid}/newtest/Y");
        if (isset($s_lang) && $s_lang != '') {
            $_restart .= "/lang/" . $s_lang;
        }
        $_restart .= "'>" . $clang->gT("Restart this survey") . "</a>";
    } else {
        if (isset($surveyid)) {
            $restart_extra = "";
            $restart_token = returnGlobal('token');
            if (!empty($restart_token)) {
                $restart_extra .= "/token/" . urlencode($restart_token);
            } else {
                $restart_extra = "/newtest/Y";
            }
            if (!empty($_GET['lang'])) {
                $restart_extra .= "/lang/" . returnGlobal('lang');
            }
            $_restart = "<a href='" . Yii::app()->getController()->createUrl("survey/index/sid/{$surveyid}{$restart_extra}") . "'>" . $clang->gT("Restart this Survey") . "</a>";
        } else {
            $_restart = "";
        }
    }
    if (isset($thissurvey['anonymized']) && $thissurvey['anonymized'] == 'Y') {
        $_savealert = $clang->gT("To remain anonymous please use a pseudonym as your username, also an email address is not required.");
    } else {
        $_savealert = "";
    }
    if (isset($surveyid)) {
        $_return_to_survey = "<a href=" . Yii::app()->getController()->createUrl("survey/index/sid/{$surveyid}");
        if (returnGlobal('token')) {
            $_return_to_survey .= "?amp;token=" . urlencode(trim(sanitize_xss_string(strip_tags(returnGlobal('token')))));
        }
        $_return_to_survey .= "'>" . $clang->gT("Return to survey") . "</a>";
    } else {
        $_return_to_survey = "";
    }
    // Save Form
    $_saveform = "<table><tr><td align='right'>" . $clang->gT("Name") . ":</td><td><input type='text' name='savename' value='";
    if (isset($_POST['savename'])) {
        $_saveform .= HTMLEscape(autoUnescape($_POST['savename']));
    }
    $_saveform .= "' /></td></tr>\n" . "<tr><td align='right'>" . $clang->gT("Password") . ":</td><td><input type='password' name='savepass' value='";
    if (isset($_POST['savepass'])) {
        $_saveform .= HTMLEscape(autoUnescape($_POST['savepass']));
    }
    $_saveform .= "' /></td></tr>\n" . "<tr><td align='right'>" . $clang->gT("Repeat password") . ":</td><td><input type='password' name='savepass2' value='";
    if (isset($_POST['savepass2'])) {
        $_saveform .= HTMLEscape(autoUnescape($_POST['savepass2']));
    }
    $_saveform .= "' /></td></tr>\n" . "<tr><td align='right'>" . $clang->gT("Your email address") . ":</td><td><input type='text' name='saveemail' value='";
    if (isset($_POST['saveemail'])) {
        $_saveform .= HTMLEscape(autoUnescape($_POST['saveemail']));
    }
    $_saveform .= "' /></td></tr>\n";
    if (isset($thissurvey['usecaptcha']) && function_exists("ImageCreate") && isCaptchaEnabled('saveandloadscreen', $thissurvey['usecaptcha'])) {
        $_saveform .= "<tr><td align='right'>" . $clang->gT("Security question") . ":</td><td><table><tr><td valign='middle'><img src='" . Yii::app()->getController()->createUrl('/verification/image/sid/' . (isset($surveyid) ? $surveyid : '')) . "' alt6='' /></td><td valign='middle' style='text-align:left'><input type='text' size='5' maxlength='3' name='loadsecurity' value='' /></td></tr></table></td></tr>\n";
    }
    $_saveform .= "<tr><td align='right'></td><td></td></tr>\n" . "<tr><td></td><td><input type='submit'  id='savebutton' name='savesubmit' value='" . $clang->gT("Save Now") . "' /></td></tr>\n" . "</table>";
    // Load Form
    $_loadform = "<table><tr><td align='right'>" . $clang->gT("Saved name") . ":</td><td><input type='text' name='loadname' value='";
    if (isset($loadname)) {
        $_loadform .= HTMLEscape(autoUnescape($loadname));
    }
    $_loadform .= "' /></td></tr>\n" . "<tr><td align='right'>" . $clang->gT("Password") . ":</td><td><input type='password' name='loadpass' value='";
    if (isset($loadpass)) {
        $_loadform .= HTMLEscape(autoUnescape($loadpass));
    }
    $_loadform .= "' /></td></tr>\n";
    if (isset($thissurvey['usecaptcha']) && function_exists("ImageCreate") && isCaptchaEnabled('saveandloadscreen', $thissurvey['usecaptcha'])) {
        $_loadform .= "<tr><td align='right'>" . $clang->gT("Security question") . ":</td><td><table><tr><td valign='middle'><img src='" . Yii::app()->getController()->createUrl('/verification/image/sid/' . $surveyid) . "' alt='' /></td><td valign='middle'><input type='text' size='5' maxlength='3' name='loadsecurity' value='' alt=''/></td></tr></table></td></tr>\n";
    }
    $_loadform .= "<tr><td align='right'></td><td></td></tr>\n" . "<tr><td></td><td><input type='submit' id='loadbutton' value='" . $clang->gT("Load now") . "' /></td></tr></table>\n";
    // Registration Form
    if (isset($surveyid) || isset($registerdata) && $debugSrc == 'register.php') {
        if (isset($surveyid)) {
            $tokensid = $surveyid;
        } else {
            $tokensid = $registerdata['sid'];
        }
        $_registerform = "<form method='post' action='" . Yii::app()->getController()->createUrl('/register/index/surveyid/' . $tokensid) . "'>\n";
        if (!isset($_REQUEST['lang'])) {
            $_reglang = Survey::model()->findByPk($tokensid)->language;
        } else {
            $_reglang = returnGlobal('lang');
        }
        $_registerform .= "<input type='hidden' name='lang' value='" . $_reglang . "' />\n";
        $_registerform .= "<input type='hidden' name='sid' value='{$tokensid}' id='sid' />\n";
        $_registerform .= "<table class='register' summary='Registrationform'>\n" . "<tr><td align='right'>" . $clang->gT("First name") . ":</td>" . "<td align='left'><input class='text' type='text' name='register_firstname'";
        if (isset($_POST['register_firstname'])) {
            $_registerform .= " value='" . htmlentities(returnGlobal('register_firstname'), ENT_QUOTES, 'UTF-8') . "'";
        }
        $_registerform .= " /></td></tr>" . "<tr><td align='right'>" . $clang->gT("Last name") . ":</td>\n" . "<td align='left'><input class='text' type='text' name='register_lastname'";
        if (isset($_POST['register_lastname'])) {
            $_registerform .= " value='" . htmlentities(returnGlobal('register_lastname'), ENT_QUOTES, 'UTF-8') . "'";
        }
        $_registerform .= " /></td></tr>\n" . "<tr><td align='right'>" . $clang->gT("Email address") . ":</td>\n" . "<td align='left'><input class='text' type='text' name='register_email'";
        if (isset($_POST['register_email'])) {
            $_registerform .= " value='" . htmlentities(returnGlobal('register_email'), ENT_QUOTES, 'UTF-8') . "'";
        }
        $_registerform .= " /></td></tr>\n";
        foreach ($thissurvey['attributedescriptions'] as $field => $attribute) {
            if (empty($attribute['show_register']) || $attribute['show_register'] != 'Y') {
                continue;
            }
            $_registerform .= '
            <tr>
            <td align="right">' . $thissurvey['attributecaptions'][$field] . ($attribute['mandatory'] == 'Y' ? '*' : '') . ':</td>
            <td align="left"><input class="text" type="text" name="register_' . $field . '" /></td>
            </tr>';
        }
        if ((count($registerdata) > 1 || isset($thissurvey['usecaptcha'])) && function_exists("ImageCreate") && isCaptchaEnabled('registrationscreen', $thissurvey['usecaptcha'])) {
            $_registerform .= "<tr><td align='right'>" . $clang->gT("Security Question") . ":</td><td><table><tr><td valign='middle'><img src='" . Yii::app()->getController()->createUrl('/verification/image/sid/' . $surveyid) . "' alt='' /></td><td valign='middle'><input type='text' size='5' maxlength='3' name='loadsecurity' value='' /></td></tr></table></td></tr>\n";
        }
        $_registerform .= "<tr><td></td><td><input id='registercontinue' class='submit' type='submit' value='" . $clang->gT("Continue") . "' />" . "</td></tr>\n" . "</table>\n";
        if (count($registerdata) > 1 && $registerdata['sid'] != NULL && $debugSrc == 'register.php') {
            $_registerform .= "<input name='startdate' type ='hidden' value='" . $registerdata['startdate'] . "' />";
            $_registerform .= "<input name='enddate' type ='hidden' value='" . $registerdata['enddate'] . "' />";
        }
        $_registerform .= "</form>\n";
    } else {
        $_registerform = "";
    }
    // Assessments
    $assessmenthtml = "";
    if (isset($surveyid) && !is_null($surveyid) && function_exists('doAssessment')) {
        $assessmentdata = doAssessment($surveyid, true);
        $_assessment_current_total = $assessmentdata['total'];
        if (stripos($line, "{ASSESSMENTS}")) {
            $assessmenthtml = doAssessment($surveyid, false);
        }
    } else {
        $_assessment_current_total = '';
    }
    if (isset($thissurvey['googleanalyticsapikey']) && trim($thissurvey['googleanalyticsapikey']) != '') {
        $_googleAnalyticsAPIKey = trim($thissurvey['googleanalyticsapikey']);
    } else {
        $_googleAnalyticsAPIKey = trim(getGlobalSetting('googleanalyticsapikey'));
    }
    $_googleAnalyticsStyle = isset($thissurvey['googleanalyticsstyle']) ? $thissurvey['googleanalyticsstyle'] : '0';
    $_googleAnalyticsJavaScript = '';
    if ($_googleAnalyticsStyle != '' && $_googleAnalyticsStyle != 0 && $_googleAnalyticsAPIKey != '') {
        switch ($_googleAnalyticsStyle) {
            case '1':
                // Default Google Tracking
                $_googleAnalyticsJavaScript = <<<EOD
<script type="text/javascript">
  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', '{$_googleAnalyticsAPIKey}']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();
</script>
EOD;
                break;
            case '2':
                // SurveyName-[SID]/[GSEQ]-GroupName - create custom GSEQ based upon page step
                $moveInfo = LimeExpressionManager::GetLastMoveResult();
                if (is_null($moveInfo)) {
                    $gseq = 'welcome';
                } else {
                    if ($moveInfo['finished']) {
                        $gseq = 'finished';
                    } else {
                        if (isset($moveInfo['at_start']) && $moveInfo['at_start']) {
                            $gseq = 'welcome';
                        } else {
                            if (is_null($_groupname)) {
                                $gseq = 'printanswers';
                            } else {
                                $gseq = $moveInfo['gseq'] + 1;
                            }
                        }
                    }
                }
                $_trackURL = htmlspecialchars($thissurvey['name'] . '-[' . $surveyid . ']/[' . $gseq . ']-' . $_groupname);
                $_googleAnalyticsJavaScript = <<<EOD
<script type="text/javascript">
  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', '{$_googleAnalyticsAPIKey}']);
  _gaq.push(['_trackPageview','{$_trackURL}']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();
</script>
EOD;
                break;
        }
    }
    $_endtext = '';
    if (isset($thissurvey['surveyls_endtext']) && trim($thissurvey['surveyls_endtext']) != '') {
        $_endtext = $thissurvey['surveyls_endtext'];
    }
    // Set the array of replacement variables here - don't include curly braces
    $coreReplacements = array();
    $coreReplacements['ACTIVE'] = isset($thissurvey['active']) && !($thissurvey['active'] != "Y");
    $coreReplacements['AID'] = isset($questiondetails['aid']) ? $questiondetails['aid'] : '';
    $coreReplacements['ANSWER'] = isset($answer) ? $answer : '';
    // global
    $coreReplacements['ANSWERSCLEARED'] = $clang->gT("Answers cleared");
    $coreReplacements['ASSESSMENTS'] = $assessmenthtml;
    $coreReplacements['ASSESSMENT_CURRENT_TOTAL'] = $_assessment_current_total;
    $coreReplacements['ASSESSMENT_HEADING'] = $clang->gT("Your assessment");
    $coreReplacements['CHECKJAVASCRIPT'] = "<noscript><span class='warningjs'>" . $clang->gT("Caution: JavaScript execution is disabled in your browser. You may not be able to answer all questions in this survey. Please, verify your browser parameters.") . "</span></noscript>";
    $coreReplacements['CLEARALL'] = $_clearall;
    $coreReplacements['CLOSEWINDOW'] = "<a href='javascript:%20self.close()'>" . $clang->gT("Close this window") . "</a>";
    $coreReplacements['COMPLETED'] = isset($redata['completed']) ? $redata['completed'] : '';
    // global
    $coreReplacements['DATESTAMP'] = $_datestamp;
    $coreReplacements['ENDTEXT'] = $_endtext;
    $coreReplacements['EXPIRY'] = $_dateoutput;
    $coreReplacements['GID'] = isset($questiondetails['gid']) ? $questiondetails['gid'] : '';
    $coreReplacements['GOOGLE_ANALYTICS_API_KEY'] = $_googleAnalyticsAPIKey;
    $coreReplacements['GOOGLE_ANALYTICS_JAVASCRIPT'] = $_googleAnalyticsJavaScript;
    $coreReplacements['GROUPDESCRIPTION'] = $_groupdescription;
    $coreReplacements['GROUPNAME'] = $_groupname;
    $coreReplacements['LANG'] = $clang->getlangcode();
    $coreReplacements['LANGUAGECHANGER'] = isset($languagechanger) ? $languagechanger : '';
    // global
    $coreReplacements['LOADERROR'] = isset($errormsg) ? $errormsg : '';
    // global
    $coreReplacements['LOADFORM'] = $_loadform;
    $coreReplacements['LOADHEADING'] = $clang->gT("Load a previously saved survey");
    $coreReplacements['LOADMESSAGE'] = $clang->gT("You can load a survey that you have previously saved from this screen.") . "<br />" . $clang->gT("Type in the 'name' you used to save the survey, and the password.") . "<br />";
    $coreReplacements['NAVIGATOR'] = isset($navigator) ? $navigator : '';
    // global
    $coreReplacements['NOSURVEYID'] = isset($surveylist) ? $surveylist['nosid'] : '';
    $coreReplacements['NUMBEROFQUESTIONS'] = $_totalquestionsAsked;
    $coreReplacements['PERCENTCOMPLETE'] = isset($percentcomplete) ? $percentcomplete : '';
    // global
    $coreReplacements['PRIVACY'] = isset($privacy) ? $privacy : '';
    // global
    $coreReplacements['PRIVACYMESSAGE'] = "<span style='font-weight:bold; font-style: italic;'>" . $clang->gT("A Note On Privacy") . "</span><br />" . $clang->gT("This survey is anonymous.") . "<br />" . $clang->gT("The record kept of your survey responses does not contain any identifying information about you unless a specific question in the survey has asked for this. If you have responded to a survey that used an identifying token to allow you to access the survey, you can rest assured that the identifying token is not kept with your responses. It is managed in a separate database, and will only be updated to indicate that you have (or haven't) completed this survey. There is no way of matching identification tokens with survey responses in this survey.");
    $coreReplacements['QID'] = isset($questiondetails['qid']) ? $questiondetails['qid'] : '';
    $coreReplacements['QUESTION'] = $_question;
    $coreReplacements['QUESTIONHELP'] = $_questionhelp;
    $coreReplacements['QUESTIONHELPPLAINTEXT'] = strip_tags(addslashes($help));
    // global
    $coreReplacements['QUESTION_CLASS'] = $_getQuestionClass;
    $coreReplacements['QUESTION_CODE'] = $_question_code;
    $coreReplacements['QUESTION_ESSENTIALS'] = $_question_essentials;
    $coreReplacements['QUESTION_FILE_VALID_MESSAGE'] = $_question_file_valid_message;
    $coreReplacements['QUESTION_HELP'] = $_question_help;
    $coreReplacements['QUESTION_INPUT_ERROR_CLASS'] = $_question_input_error_class;
    $coreReplacements['QUESTION_MANDATORY'] = $_question_mandatory;
    $coreReplacements['QUESTION_MAN_CLASS'] = $_question_man_class;
    $coreReplacements['QUESTION_MAN_MESSAGE'] = $_question_man_message;
    $coreReplacements['QUESTION_NUMBER'] = $_question_number;
    $coreReplacements['QUESTION_TEXT'] = $_question_text;
    $coreReplacements['QUESTION_VALID_MESSAGE'] = $_question_valid_message;
    $coreReplacements['REGISTERERROR'] = isset($register_errormsg) ? $register_errormsg : '';
    // global
    $coreReplacements['REGISTERFORM'] = $_registerform;
    $coreReplacements['REGISTERMESSAGE1'] = $clang->gT("You must be registered to complete this survey");
    $coreReplacements['REGISTERMESSAGE2'] = $clang->gT("You may register for this survey if you wish to take part.") . "<br />\n" . $clang->gT("Enter your details below, and an email containing the link to participate in this survey will be sent immediately.");
    $coreReplacements['RESTART'] = $_restart;
    $coreReplacements['RETURNTOSURVEY'] = $_return_to_survey;
    $coreReplacements['SAVE'] = $_saveall;
    $coreReplacements['SAVEALERT'] = $_savealert;
    $coreReplacements['SAVEDID'] = isset($saved_id) ? $saved_id : '';
    // global
    $coreReplacements['SAVEERROR'] = isset($errormsg) ? $errormsg : '';
    // global - same as LOADERROR
    $coreReplacements['SAVEFORM'] = $_saveform;
    $coreReplacements['SAVEHEADING'] = $clang->gT("Save your unfinished survey");
    $coreReplacements['SAVEMESSAGE'] = $clang->gT("Enter a name and password for this survey and click save below.") . "<br />\n" . $clang->gT("Your survey will be saved using that name and password, and can be completed later by logging in with the same name and password.") . "<br /><br />\n" . $clang->gT("If you give an email address, an email containing the details will be sent to you.") . "<br /><br />\n" . $clang->gT("After having clicked the save button you can either close this browser window or continue filling out the survey.");
    $coreReplacements['SGQ'] = $_question_sgq;
    $coreReplacements['SID'] = isset($surveyid) ? $surveyid : (isset($questiondetails['sid']) ? $questiondetails['sid'] : '');
    $coreReplacements['SITENAME'] = isset($sitename) ? $sitename : '';
    // global
    $coreReplacements['SUBMITBUTTON'] = $_submitbutton;
    $coreReplacements['SUBMITCOMPLETE'] = "<strong>" . $clang->gT("Thank you!") . "<br /><br />" . $clang->gT("You have completed answering the questions in this survey.") . "</strong><br /><br />" . $clang->gT("Click on 'Submit' now to complete the process and save your answers.");
    $coreReplacements['SUBMITREVIEW'] = $_strreview;
    $coreReplacements['SURVEYCONTACT'] = $surveycontact;
    $coreReplacements['SURVEYDESCRIPTION'] = isset($thissurvey['description']) ? $thissurvey['description'] : '';
    $coreReplacements['SURVEYFORMAT'] = isset($surveyformat) ? $surveyformat : '';
    // global
    $coreReplacements['SURVEYLANGAGE'] = $clang->langcode;
    $coreReplacements['SURVEYLANGUAGE'] = $clang->langcode;
    $coreReplacements['SURVEYLIST'] = isset($surveylist) ? $surveylist['list'] : '';
    $coreReplacements['SURVEYLISTHEADING'] = isset($surveylist) ? $surveylist['listheading'] : '';
    $coreReplacements['SURVEYNAME'] = isset($thissurvey['name']) ? $thissurvey['name'] : '';
    $coreReplacements['TEMPLATECSS'] = $_templatecss;
    $coreReplacements['TEMPLATEJS'] = $_templatejs;
    $coreReplacements['TEMPLATEURL'] = $templateurl;
    $coreReplacements['THEREAREXQUESTIONS'] = $_therearexquestions;
    if (!$anonymized) {
        $coreReplacements['TOKEN'] = $_token;
    }
    $coreReplacements['URL'] = $_linkreplace;
    $coreReplacements['WELCOME'] = isset($thissurvey['welcome']) ? $thissurvey['welcome'] : '';
    if (!is_null($replacements) && is_array($replacements)) {
        $doTheseReplacements = array_merge($coreReplacements, $replacements);
        // so $replacements overrides core values
    } else {
        $doTheseReplacements = $coreReplacements;
    }
    // Now do all of the replacements - In rare cases, need to do 3 deep recursion, that that is default
    $line = LimeExpressionManager::ProcessString($line, $questionNum, $doTheseReplacements, false, 3, 1);
    return $line;
}
コード例 #2
0
 /**
  * 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();
 }
コード例 #3
0
/**
* This function replaces keywords in a text and is mainly intended for templates
* If you use this functions put your replacement strings into the $replacements variable
* instead of using global variables
* NOTE - Don't do any embedded replacements in this function.  Create the array of replacement values and
* they will be done in batch at the end
*
* @param mixed $line Text to search in
* @param mixed $replacements Array of replacements:  Array( <stringtosearch>=><stringtoreplacewith>
* @param boolean $anonymized Determines if token data is being used or just replaced with blanks
* @param questionNum - needed to support dynamic JavaScript-based tailoring within questions
* @param bStaticReplacement - Default off, forces non-dynamic replacements without <SPAN> tags (e.g. for the Completed page)
* @return string  Text with replaced strings
*/
function templatereplace($line, $replacements = array(), &$redata = array(), $debugSrc = 'Unspecified', $anonymized = false, $questionNum = NULL, $registerdata = array(), $bStaticReplacement = false, $oTemplate = '')
{
    /*
    global $clienttoken,$token,$sitename,$move,$showxquestions,$showqnumcode,$questioncode;
    global $s_lang,$errormsg,$saved_id, $languagechanger,$captchapath,$loadname;
    */
    /*
    $allowedvars = array('surveylist', 'sitename', 'clienttoken', 'rooturl', 'thissurvey', 'imageurl', 'defaulttemplate',
    'percentcomplete', 'move', 'groupname', 'groupdescription', 'question', 'showxquestions',
    'showgroupinfo', 'showqnumcode', 'questioncode', 'answer', 'navigator', 'help', 'totalquestions',
    'surveyformat', 'completed', 'notanswered', 'privacy', 'surveyid', 'publicurl',
    'templatedir', 'token', 'assessments', 's_lang', 'errormsg', 'saved_id', 'usertemplaterootdir',
    'languagechanger', 'printoutput', 'captchapath', 'loadname');
    */
    $allowedvars = array('assessments', 'captchapath', 'clienttoken', 'completed', 'errormsg', 'groupdescription', 'groupname', 'imageurl', 'languagechanger', 'loadname', 'move', 'navigator', 'moveprevbutton', 'movenextbutton', 'percentcomplete', 'privacy', 's_lang', 'saved_id', 'showgroupinfo', 'showqnumcode', 'showxquestions', 'sitename', 'sitelogo', 'surveylist', 'templatedir', 'thissurvey', 'token', 'totalBoilerplatequestions', 'totalquestions', 'questionindex', 'questionindexmenu');
    $varsPassed = array();
    foreach ($allowedvars as $var) {
        if (isset($redata[$var])) {
            ${$var} = $redata[$var];
            $varsPassed[] = $var;
        }
    }
    //    if (count($varsPassed) > 0) {
    //        log_message('debug', 'templatereplace() called from ' . $debugSrc . ' contains: ' . implode(', ', $varsPassed));
    //    }
    //    if (isset($redata['question'])) {
    //        LimeExpressionManager::ShowStackTrace('has QID and/or SGA',$allowedvars);
    //    }
    //    extract($redata);   // creates variables for each of the keys in the array
    // Local over-rides in case not set above
    if (!isset($showgroupinfo)) {
        $showgroupinfo = Yii::app()->getConfig('showgroupinfo');
    }
    if (!isset($showqnumcode)) {
        $showqnumcode = Yii::app()->getConfig('showqnumcode');
    }
    $_surveyid = Yii::app()->getConfig('surveyID');
    if (!isset($showxquestions)) {
        $showxquestions = Yii::app()->getConfig('showxquestions');
    }
    if (!isset($s_lang)) {
        $s_lang = isset(Yii::app()->session['survey_' . $_surveyid]['s_lang']) ? Yii::app()->session['survey_' . $_surveyid]['s_lang'] : 'en';
    }
    if ($_surveyid && !isset($thissurvey)) {
        $thissurvey = getSurveyInfo($_surveyid, $s_lang);
    }
    if (!isset($captchapath)) {
        $captchapath = '';
    }
    if (!isset($sitename)) {
        $sitename = Yii::app()->getConfig('sitename');
    }
    if (!isset($saved_id) && isset(Yii::app()->session['survey_' . $_surveyid]['srid'])) {
        $saved_id = Yii::app()->session['survey_' . $_surveyid]['srid'];
    }
    Yii::app()->loadHelper('surveytranslator');
    if (isset($thissurvey['sid'])) {
        $surveyid = $thissurvey['sid'];
    }
    // lets sanitize the survey template
    if (isset($thissurvey['templatedir'])) {
        $templatename = $thissurvey['templatedir'];
    } else {
        $templatename = Yii::app()->getConfig('defaulttemplate');
    }
    if (!isset($templatedir)) {
        $templatedir = getTemplatePath($templatename);
    }
    if (!isset($templateurl)) {
        $templateurl = getTemplateURL($templatename) . "/";
    }
    if (!$anonymized && isset($thissurvey['anonymized'])) {
        $anonymized = $thissurvey['anonymized'] == "Y";
    }
    // TEMPLATECSS
    $_templatecss = "";
    $_templatejs = "";
    /**
     * Template css/js files from the template config files are loaded.
     * It use the asset manager (so user never need to empty the cache, even if template is updated)
     * If debug mode is on, no asset manager is used.
     *
     * oTemplate is defined in controller/survey/index
     *
     * If templatereplace is called from the template editor, a $oTemplate is provided.
     */
    $oTemplate = Template::model()->getInstance($templatename);
    $aCssFiles = $oTemplate->config->files->css->filename;
    $aJsFiles = $oTemplate->config->files->js->filename;
    $aOtherFiles = $oTemplate->otherFiles;
    //var_dump($aOtherFiles); die();
    if (stripos($line, "{TEMPLATECSS}")) {
        // If the template has files for css, we can't publish the files one by one, but we must publish them as a whole directory
        // TODO : extend asset manager so it check for file modification even in directory mode
        if (!YII_DEBUG || count($aOtherFiles) < 0) {
            foreach ($aCssFiles as $sCssFile) {
                if (file_exists($oTemplate->path . DIRECTORY_SEPARATOR . $sCssFile)) {
                    Yii::app()->getClientScript()->registerCssFile(App()->getAssetManager()->publish($oTemplate->path . DIRECTORY_SEPARATOR . $sCssFile), $sCssFile['media']);
                }
            }
        } else {
            foreach ($aCssFiles as $sCssFile) {
                if (file_exists($oTemplate->path . DIRECTORY_SEPARATOR . $sCssFile)) {
                    Yii::app()->getClientScript()->registerCssFile("{$templateurl}{$sCssFile}", $sCssFile['media']);
                }
            }
        }
        /* RTL CSS */
        if (getLanguageRTL(App()->language)) {
            $aCssFiles = (array) $oTemplate->config->files->rtl->css->filename;
            if (!YII_DEBUG) {
                foreach ($aCssFiles as $sCssFile) {
                    if (file_exists($oTemplate->path . DIRECTORY_SEPARATOR . $sCssFile)) {
                        Yii::app()->getClientScript()->registerCssFile(App()->getAssetManager()->publish($oTemplate->path . DIRECTORY_SEPARATOR . $sCssFile), $sCssFile['media']);
                    }
                }
            } else {
                foreach ($aCssFiles as $sCssFile) {
                    if (file_exists($oTemplate->path . DIRECTORY_SEPARATOR . $sCssFile)) {
                        Yii::app()->getClientScript()->registerCssFile("{$templateurl}{$sCssFile}", $sCssFile['media']);
                    }
                }
            }
        }
    }
    if (stripos($line, "{TEMPLATEJS}")) {
        if (!YII_DEBUG) {
            foreach ($aJsFiles as $sJsFile) {
                if (file_exists($oTemplate->path . DIRECTORY_SEPARATOR . $sJsFile)) {
                    App()->getClientScript()->registerScriptFile(App()->getAssetManager()->publish($oTemplate->path . DIRECTORY_SEPARATOR . $sJsFile));
                }
            }
        } else {
            foreach ($aJsFiles as $sJsFile) {
                if (file_exists($oTemplate->path . DIRECTORY_SEPARATOR . $sJsFile)) {
                    Yii::app()->getClientScript()->registerScriptFile("{$templateurl}{$sJsFile}");
                }
            }
        }
        /* RTL JS */
        if (getLanguageRTL(App()->language)) {
            $aJsFiles = (array) $oTemplate->config->files->rtl->js->filename;
            if (!YII_DEBUG) {
                foreach ($aJsFiles as $aJsFile) {
                    if (file_exists($oTemplate->path . DIRECTORY_SEPARATOR . $aJsFile)) {
                        App()->getClientScript()->registerScriptFile(App()->getAssetManager()->publish($oTemplate->path . DIRECTORY_SEPARATOR . $aJsFile));
                    }
                }
            } else {
                foreach ($aJsFiles as $sJsFile) {
                    if (file_exists($oTemplate->path . DIRECTORY_SEPARATOR . $sJsFile)) {
                        Yii::app()->getClientScript()->registerScriptFile("{$templateurl}{$sJsFile}");
                    }
                }
            }
        }
    }
    // surveyformat
    if (isset($thissurvey['format'])) {
        $surveyformat = str_replace(array("A", "S", "G"), array("allinone", "questionbyquestion", "groupbygroup"), $thissurvey['format']);
    } else {
        $surveyformat = "";
    }
    if ($oTemplate->config->engine->cssframework) {
        $surveyformat .= " " . $oTemplate->config->engine->cssframework . "-engine ";
    }
    if (isset(Yii::app()->session['step']) && Yii::app()->session['step'] % 2 && $surveyformat != "allinone") {
        $surveyformat .= " page-odd";
    }
    if (isset($thissurvey['questionindex']) && $thissurvey['questionindex'] > 0 && $surveyformat != "allinone" && (isset(Yii::app()->session['step']) && Yii::app()->session['step'] > 0)) {
        $surveyformat .= " withindex";
    }
    if (isset($thissurvey['showprogress']) && $thissurvey['showprogress'] == "Y") {
        $surveyformat .= " showprogress";
    }
    if (isset($thissurvey['showqnumcode'])) {
        $surveyformat .= " showqnumcode-" . $thissurvey['showqnumcode'];
    }
    // real survey contact
    if (isset($surveylist) && isset($surveylist['contact'])) {
        $surveycontact = $surveylist['contact'];
    } elseif (isset($surveylist) && isset($thissurvey['admin']) && $thissurvey['admin'] != "") {
        $surveycontact = sprintf(gT("Please contact %s ( %s ) for further assistance."), $thissurvey['admin'], $thissurvey['adminemail']);
    } else {
        $surveycontact = "";
    }
    // If there are non-bracketed replacements to be made do so above this line.
    // Only continue in this routine if there are bracketed items to replace {}
    if (strpos($line, "{") === false) {
        // process string anyway so that it can be pretty-printed
        return LimeExpressionManager::ProcessString($line, $questionNum, NULL, false, 1, 1, true);
    }
    if ($showgroupinfo == 'both' || $showgroupinfo == 'name' || $showgroupinfo == 'choose' && !isset($thissurvey['showgroupinfo']) || $showgroupinfo == 'choose' && $thissurvey['showgroupinfo'] == 'B' || $showgroupinfo == 'choose' && $thissurvey['showgroupinfo'] == 'N') {
        $_groupname = isset($groupname) ? $groupname : '';
    } else {
        $_groupname = '';
    }
    if ($showgroupinfo == 'both' || $showgroupinfo == 'description' || $showgroupinfo == 'choose' && !isset($thissurvey['showgroupinfo']) || $showgroupinfo == 'choose' && $thissurvey['showgroupinfo'] == 'B' || $showgroupinfo == 'choose' && $thissurvey['showgroupinfo'] == 'D') {
        $_groupdescription = isset($groupdescription) ? $groupdescription : '';
    } else {
        $_groupdescription = '';
    }
    if (!isset($totalquestions)) {
        $totalquestions = 0;
    }
    $_totalquestionsAsked = $totalquestions;
    if ($showxquestions == 'show' || $showxquestions == 'choose' && !isset($thissurvey['showxquestions']) || $showxquestions == 'choose' && $thissurvey['showxquestions'] == 'Y') {
        if ($_totalquestionsAsked < 1) {
            $_therearexquestions = gT("There are no questions in this survey");
            // Singular
        } elseif ($_totalquestionsAsked == 1) {
            $_therearexquestions = gT("There is 1 question in this survey");
            //Singular
        } else {
            $_therearexquestions = gT("There are {NUMBEROFQUESTIONS} questions in this survey.");
            //Note this line MUST be before {NUMBEROFQUESTIONS}
        }
    } else {
        $_therearexquestions = '';
    }
    if (isset($token)) {
        $_token = $token;
    } elseif (isset($clienttoken)) {
        $_token = htmlentities($clienttoken, ENT_QUOTES, 'UTF-8');
        // or should it be URL-encoded?
    } else {
        $_token = '';
    }
    // Expiry
    if (isset($thissurvey['expiry'])) {
        $dateformatdetails = getDateFormatData($thissurvey['surveyls_dateformat']);
        Yii::import('application.libraries.Date_Time_Converter', true);
        $datetimeobj = new Date_Time_Converter($thissurvey['expiry'], "Y-m-d");
        $_dateoutput = $datetimeobj->convert($dateformatdetails['phpdate']);
    } else {
        $_dateoutput = '-';
    }
    $_submitbutton = "<input class='submit btn btn-default' type='submit' value=' " . gT("Submit") . " ' name='move2' onclick=\"javascript:document.limesurvey.move.value = 'movesubmit';\" />";
    if (isset($thissurvey['surveyls_url']) and $thissurvey['surveyls_url'] != "") {
        if (trim($thissurvey['surveyls_urldescription']) != '') {
            $_linkreplace = "<a href='{$thissurvey['surveyls_url']}'>{$thissurvey['surveyls_urldescription']}</a>";
        } else {
            $_linkreplace = "<a href='{$thissurvey['surveyls_url']}'>{$thissurvey['surveyls_url']}</a>";
        }
    } else {
        $_linkreplace = '';
    }
    if (isset($thissurvey['sid']) && isset($_SESSION['survey_' . $thissurvey['sid']]['srid']) && $thissurvey['active'] == 'Y') {
        $iscompleted = SurveyDynamic::model($surveyid)->isCompleted($_SESSION['survey_' . $thissurvey['sid']]['srid']);
    } else {
        $iscompleted = false;
    }
    if (isset($surveyid) && !$iscompleted) {
        $_clearall = CHtml::htmlButton(gT("Exit and clear survey"), array('type' => 'submit', 'id' => "clearall", 'value' => 'clearall', 'name' => 'clearall', 'class' => 'clearall button  btn btn-default btn-lg  col-xs-4 hidden', 'data-confirmedby' => 'confirm-clearall', 'title' => gT("This action need confirmation.")));
        $_clearall .= CHtml::checkBox("confirm-clearall", false, array('id' => 'confirm-clearall', 'value' => 'confirm', 'class' => 'hide jshide  btn btn-default btn-lg  col-xs-4'));
        $_clearall .= CHtml::label(gT("Are you sure you want to clear all your responses?"), 'confirm-clearall', array('class' => 'hide jshide  btn btn-default btn-lg  col-xs-4'));
        $_clearalllinks = '<li><a href="#" id="clearallbtnlink">' . gT("Exit and clear survey") . '</a></li>';
    } else {
        $_clearall = "";
        $_clearalllinks = '';
    }
    if (isset(Yii::app()->session['datestamp'])) {
        $_datestamp = Yii::app()->session['datestamp'];
    } else {
        $_datestamp = '-';
    }
    if (isset($thissurvey['allowsave']) and $thissurvey['allowsave'] == "Y") {
        $_saveall = doHtmlSaveAll(isset($move) ? $move : NULL);
        $_savelinks = doHtmlSaveLinks(isset($move) ? $move : NULL);
    } else {
        $_saveall = "";
        $_savelinks = "";
    }
    if (isset($thissurvey['allowprev']) && $thissurvey['allowprev'] == "N") {
        $_strreview = "";
    } else {
        $_strreview = gT("If you want to check any of the answers you have made, and/or change them, you can do that now by clicking on the [<< prev] button and browsing through your responses.");
    }
    if (isset($surveyid)) {
        $restartparam = array();
        if ($_token) {
            $restartparam['token'] = sanitize_token($_token);
        }
        // urlencode with needed with sanitize_token
        if (Yii::app()->request->getQuery('lang')) {
            $restartparam['lang'] = sanitize_languagecode(Yii::app()->request->getQuery('lang'));
        } elseif ($s_lang) {
            $restartparam['lang'] = $s_lang;
        }
        $restartparam['newtest'] = "Y";
        $restarturl = Yii::app()->getController()->createUrl("survey/index/sid/{$surveyid}", $restartparam);
        $_restart = "<a href='{$restarturl}'>" . gT("Restart this Survey") . "</a>";
    } else {
        $_restart = "";
    }
    if (isset($thissurvey['anonymized']) && $thissurvey['anonymized'] == 'Y') {
        $_savealert = gT("To remain anonymous please use a pseudonym as your username, also an email address is not required.");
    } else {
        $_savealert = "";
    }
    if (isset($surveyid)) {
        if ($_token) {
            $returnlink = Yii::app()->getController()->createUrl("survey/index/sid/{$surveyid}", array('token' => Token::sanitizeToken($_token)));
        } else {
            $returnlink = Yii::app()->getController()->createUrl("survey/index/sid/{$surveyid}");
        }
        $_return_to_survey = "<a href='{$returnlink}'>" . gT("Return to survey") . "</a>";
    } else {
        $_return_to_survey = "";
    }
    // Save Form
    $_saveform = "<table class='save-survey-form'><tr class='save-survey-row save-survey-name'><td class='save-survey-label label-cell' align='right'><label for='savename'>" . gT("Name") . "</label>:</td><td class='save-survey-input input-cell'><input type='text' name='savename' id='savename' value='";
    if (isset($_POST['savename'])) {
        $_saveform .= HTMLEscape(autoUnescape($_POST['savename']));
    }
    $_saveform .= "' /></td></tr>\n" . "<tr class='save-survey-row save-survey-password-1'><td class='save-survey-label label-cell' align='right'><label for='savepass'>" . gT("Password") . "</label>:</td><td class='save-survey-input input-cell'><input type='password' id='savepass' name='savepass' value='";
    if (isset($_POST['savepass'])) {
        $_saveform .= HTMLEscape(autoUnescape($_POST['savepass']));
    }
    $_saveform .= "' /></td></tr>\n" . "<tr class='save-survey-row save-survey-password-2'><td class='save-survey-label label-cell' align='right'><label for='savepass2'>" . gT("Repeat password") . "</label>:</td><td class='save-survey-input input-cell'><input type='password' id='savepass2' name='savepass2' value='";
    if (isset($_POST['savepass2'])) {
        $_saveform .= HTMLEscape(autoUnescape($_POST['savepass2']));
    }
    $_saveform .= "' /></td></tr>\n" . "<tr class='save-survey-row save-survey-email'><td class='save-survey-label label-cell' align='right'><label for='saveemail'>" . gT("Your email address") . "</label>:</td><td class='save-survey-input input-cell'><input type='text' id='saveemail' name='saveemail' value='";
    if (isset($_POST['saveemail'])) {
        $_saveform .= HTMLEscape(autoUnescape($_POST['saveemail']));
    }
    $_saveform .= "' /></td></tr>\n";
    if (isset($thissurvey['usecaptcha']) && function_exists("ImageCreate") && isCaptchaEnabled('saveandloadscreen', $thissurvey['usecaptcha'])) {
        $_saveform .= "<tr class='save-survey-row save-survey-captcha'><td class='save-survey-label label-cell' align='right'><label for='loadsecurity'>" . gT("Security question") . "</label>:</td><td class='save-survey-input input-cell'><table class='captcha-table'><tr><td class='captcha-image' valign='middle'><img alt='' src='" . Yii::app()->getController()->createUrl('/verification/image/sid/' . (isset($surveyid) ? $surveyid : '')) . "' /></td><td class='captcha-input' valign='middle' style='text-align:left'><input type='text' size='5' maxlength='3' id='loadsecurity' name='loadsecurity' value='' /></td></tr></table></td></tr>\n";
    }
    $_saveform .= "<tr><td align='right'></td><td></td></tr>\n" . "<tr class='save-survey-row save-survey-submit'><td class='save-survey-label label-cell'><label class='hide jshide' for='savebutton'>" . gT("Save Now") . "</label></td><td class='save-survey-input input-cell'><input type='submit' id='savebutton' name='savesubmit' class='button' value='" . gT("Save Now") . "' /></td></tr>\n" . "</table>";
    // Load Form
    $_loadform = "<table class='load-survey-form'><tr class='load-survey-row load-survey-name'><td class='load-survey-label label-cell' align='right'><label for='loadname'>" . gT("Saved name") . "</label>:</td><td class='load-survey-input input-cell'><input type='text' id='loadname' name='loadname' value='";
    if (isset($loadname)) {
        $_loadform .= HTMLEscape(autoUnescape($loadname));
    }
    $_loadform .= "' /></td></tr>\n" . "<tr class='load-survey-row load-survey-password'><td class='load-survey-label label-cell' align='right'><label for='loadpass'>" . gT("Password") . "</label>:</td><td class='load-survey-input input-cell'><input type='password' id='loadpass' name='loadpass' value='";
    if (isset($loadpass)) {
        $_loadform .= HTMLEscape(autoUnescape($loadpass));
    }
    $_loadform .= "' /></td></tr>\n";
    if (isset($thissurvey['usecaptcha']) && function_exists("ImageCreate") && isCaptchaEnabled('saveandloadscreen', $thissurvey['usecaptcha'])) {
        $_loadform .= "<tr class='load-survey-row load-survey-captcha'><td class='load-survey-label label-cell' align='right'><label for='loadsecurity'>" . gT("Security question") . "</label>:</td><td class='load-survey-input input-cell'><table class='captcha-table'><tr><td class='captcha-image' valign='middle'><img src='" . Yii::app()->getController()->createUrl('/verification/image/sid/' . (isset($surveyid) ? $surveyid : '')) . "' alt='' /></td><td class='captcha-input' valign='middle'><input type='text' size='5' maxlength='3' id='loadsecurity' name='loadsecurity' value='' alt=''/></td></tr></table></td></tr>\n";
    }
    $_loadform .= "<tr class='load-survey-row load-survey-submit'><td class='load-survey-label label-cell'><label class='hide jshide' for='loadbutton'>" . gT("Load now") . "</label></td><td class='load-survey-input input-cell'><input type='submit' id='loadbutton' class='button' value='" . gT("Load now") . "' /></td></tr></table>\n";
    // Assessments
    $assessmenthtml = "";
    if (isset($surveyid) && !is_null($surveyid) && function_exists('doAssessment')) {
        $assessmentdata = doAssessment($surveyid, true);
        $_assessment_current_total = $assessmentdata['total'];
        if (stripos($line, "{ASSESSMENTS}")) {
            $assessmenthtml = doAssessment($surveyid, false);
        }
    } else {
        $_assessment_current_total = '';
    }
    if (isset($thissurvey['googleanalyticsapikey']) && trim($thissurvey['googleanalyticsapikey']) != '') {
        $_googleAnalyticsAPIKey = trim($thissurvey['googleanalyticsapikey']);
    } else {
        $_googleAnalyticsAPIKey = trim(getGlobalSetting('googleanalyticsapikey'));
    }
    $_googleAnalyticsStyle = isset($thissurvey['googleanalyticsstyle']) ? $thissurvey['googleanalyticsstyle'] : '0';
    $_googleAnalyticsJavaScript = '';
    if ($_googleAnalyticsStyle != '' && $_googleAnalyticsStyle != 0 && $_googleAnalyticsAPIKey != '') {
        switch ($_googleAnalyticsStyle) {
            case '1':
                // Default Google Tracking
                $_googleAnalyticsJavaScript = <<<EOD
<script>
(function(i,s,o,g,r,a,m){ i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments) },i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');

ga('create', '{$_googleAnalyticsAPIKey}', 'auto');  // Replace with your property ID.
ga('send', 'pageview');

</script>

EOD;
                break;
            case '2':
                // SurveyName-[SID]/[GSEQ]-GroupName - create custom GSEQ based upon page step
                $moveInfo = LimeExpressionManager::GetLastMoveResult();
                if (is_null($moveInfo)) {
                    $gseq = 'welcome';
                } else {
                    if ($moveInfo['finished']) {
                        $gseq = 'finished';
                    } else {
                        if (isset($moveInfo['at_start']) && $moveInfo['at_start']) {
                            $gseq = 'welcome';
                        } else {
                            if (is_null($_groupname)) {
                                $gseq = 'printanswers';
                            } else {
                                $gseq = $moveInfo['gseq'] + 1;
                            }
                        }
                    }
                }
                $_trackURL = htmlspecialchars($thissurvey['name'] . '-[' . $surveyid . ']/[' . $gseq . ']-' . $_groupname);
                $_googleAnalyticsJavaScript = <<<EOD
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');

ga('create', '{$_googleAnalyticsAPIKey}', 'auto');  // Replace with your property ID.
ga('send', 'pageview');
ga('send', 'pageview', '{$_trackURL}');

</script>
EOD;
                break;
        }
    }
    $_endtext = '';
    if (isset($thissurvey['surveyls_endtext']) && trim($thissurvey['surveyls_endtext']) != '') {
        $_endtext = $thissurvey['surveyls_endtext'];
    }
    $sitelogo = !empty($oTemplate->siteLogo) ? '<img src="' . App()->getAssetManager()->publish($oTemplate->path . '/' . $oTemplate->siteLogo) . '"/>' : '';
    // Set the array of replacement variables here - don't include curly braces
    $coreReplacements = array();
    $coreReplacements['ACTIVE'] = isset($thissurvey['active']) && !($thissurvey['active'] != "Y");
    $coreReplacements['ANSWERSCLEARED'] = gT("Answers cleared");
    $coreReplacements['ASSESSMENTS'] = $assessmenthtml;
    $coreReplacements['ASSESSMENT_CURRENT_TOTAL'] = $_assessment_current_total;
    $coreReplacements['ASSESSMENT_HEADING'] = gT("Your assessment");
    $coreReplacements['CHECKJAVASCRIPT'] = "<noscript><span class='warningjs'>" . gT("Caution: JavaScript execution is disabled in your browser. You may not be able to answer all questions in this survey. Please, verify your browser parameters.") . "</span></noscript>";
    $coreReplacements['CLEARALL'] = $_clearall;
    $coreReplacements['CLEARALL_LINKS'] = $_clearalllinks;
    $coreReplacements['CLOSEWINDOW'] = '';
    // Obsolete tag - keep this line for compatibility reaons
    $coreReplacements['COMPLETED'] = isset($redata['completed']) ? $redata['completed'] : '';
    // global
    $coreReplacements['DATESTAMP'] = $_datestamp;
    $coreReplacements['ENDTEXT'] = $_endtext;
    $coreReplacements['EXPIRY'] = $_dateoutput;
    $coreReplacements['ADMINNAME'] = isset($thissurvey['admin']) ? $thissurvey['admin'] : '';
    $coreReplacements['ADMINEMAIL'] = isset($thissurvey['adminemail']) ? $thissurvey['adminemail'] : '';
    $coreReplacements['GID'] = Yii::app()->getConfig('gid', '');
    // Use the gid of the question, except if we are not in question (Randomization group name)
    $coreReplacements['GOOGLE_ANALYTICS_API_KEY'] = $_googleAnalyticsAPIKey;
    $coreReplacements['GOOGLE_ANALYTICS_JAVASCRIPT'] = $_googleAnalyticsJavaScript;
    $coreReplacements['GROUPDESCRIPTION'] = $_groupdescription;
    $coreReplacements['GROUPNAME'] = $_groupname;
    $coreReplacements['LANG'] = App()->language;
    $coreReplacements['LANGUAGECHANGER'] = isset($languagechanger) ? $languagechanger : '';
    // global
    $coreReplacements['LOADERROR'] = isset($errormsg) ? $errormsg : '';
    // global
    $coreReplacements['LOADFORM'] = $_loadform;
    $coreReplacements['LOADHEADING'] = gT("Load a previously saved survey");
    $coreReplacements['LOADMESSAGE'] = gT("You can load a survey that you have previously saved from this screen.") . "<br />" . gT("Type in the 'name' you used to save the survey, and the password.") . "<br />";
    $coreReplacements['NAVIGATOR'] = isset($navigator) ? $navigator : '';
    // global
    $coreReplacements['MOVEPREVBUTTON'] = isset($moveprevbutton) ? $moveprevbutton : '';
    // global
    $coreReplacements['MOVENEXTBUTTON'] = isset($movenextbutton) ? $movenextbutton : '';
    // global
    $coreReplacements['NOSURVEYID'] = isset($surveylist) ? $surveylist['nosid'] : '';
    $coreReplacements['NUMBEROFQUESTIONS'] = $_totalquestionsAsked;
    $coreReplacements['PERCENTCOMPLETE'] = isset($percentcomplete) ? $percentcomplete : '';
    // global
    $coreReplacements['PRIVACY'] = isset($privacy) ? $privacy : '';
    // global
    $coreReplacements['PRIVACYMESSAGE'] = "<span style='font-weight:bold; font-style: italic;'>" . gT("A Note On Privacy") . "</span><br />" . gT("This survey is anonymous.") . "<br />" . gT("The record of your survey responses does not contain any identifying information about you, unless a specific survey question explicitly asked for it.") . ' ' . gT("If you used an identifying token to access this survey, please rest assured that this token will not be stored together with your responses. It is managed in a separate database and will only be updated to indicate whether you did (or did not) complete this survey. There is no way of matching identification tokens with survey responses.");
    $coreReplacements['QUESTION_INDEX'] = isset($questionindex) ? $questionindex : '';
    $coreReplacements['QUESTION_INDEX_MENU'] = isset($questionindexmenu) ? $questionindexmenu : '';
    $coreReplacements['RESTART'] = $_restart;
    $coreReplacements['RETURNTOSURVEY'] = $_return_to_survey;
    $coreReplacements['SAVE_LINKS'] = $_savelinks;
    $coreReplacements['SAVE'] = $_saveall;
    $coreReplacements['SAVEALERT'] = $_savealert;
    $coreReplacements['SAVEDID'] = isset($saved_id) ? $saved_id : '';
    // global
    $coreReplacements['SAVEERROR'] = isset($errormsg) ? $errormsg : '';
    // global - same as LOADERROR
    $coreReplacements['SAVEFORM'] = $_saveform;
    $coreReplacements['SAVEHEADING'] = gT("Save your unfinished survey");
    $coreReplacements['SAVEMESSAGE'] = gT("Enter a name and password for this survey and click save below.") . "<br />\n" . gT("Your survey will be saved using that name and password, and can be completed later by logging in with the same name and password.") . "<br /><br />\n<span class='emailoptional'>" . gT("If you give an email address, an email containing the details will be sent to you.") . "</span><br /><br />\n" . gT("After having clicked the save button you can either close this browser window or continue filling out the survey.");
    $coreReplacements['SID'] = Yii::app()->getConfig('surveyID', '');
    // Allways use surveyID from config
    $coreReplacements['SITENAME'] = isset($sitename) ? $sitename : '';
    // global
    $coreReplacements['SITELOGO'] = $sitelogo;
    $coreReplacements['SUBMITBUTTON'] = $_submitbutton;
    $coreReplacements['SUBMITCOMPLETE'] = "<strong>" . gT("Thank you!") . "<br /><br />" . gT("You have completed answering the questions in this survey.") . "</strong><br /><br />" . gT("Click on 'Submit' now to complete the process and save your answers.");
    $coreReplacements['SUBMITREVIEW'] = $_strreview;
    $coreReplacements['SURVEYCONTACT'] = $surveycontact;
    $coreReplacements['SURVEYDESCRIPTION'] = isset($thissurvey['description']) ? $thissurvey['description'] : '';
    $coreReplacements['SURVEYFORMAT'] = isset($surveyformat) ? $surveyformat : '';
    // global
    $coreReplacements['SURVEYLANGUAGE'] = App()->language;
    $coreReplacements['SURVEYLIST'] = isset($surveylist) ? $surveylist['list'] : '';
    $coreReplacements['SURVEYLISTHEADING'] = isset($surveylist) ? $surveylist['listheading'] : '';
    $coreReplacements['SURVEYNAME'] = isset($thissurvey['name']) ? $thissurvey['name'] : '';
    $coreReplacements['SURVEYRESOURCESURL'] = isset($thissurvey['sid']) ? Yii::app()->getConfig("uploadurl") . '/surveys/' . $thissurvey['sid'] . '/' : '';
    $coreReplacements['TEMPLATECSS'] = $_templatecss;
    $coreReplacements['TEMPLATEJS'] = $_templatejs;
    $coreReplacements['TEMPLATEURL'] = $templateurl;
    $coreReplacements['THEREAREXQUESTIONS'] = $_therearexquestions;
    $coreReplacements['TOKEN'] = !$anonymized ? $_token : '';
    // Silently replace TOKEN by empty string
    $coreReplacements['URL'] = $_linkreplace;
    $coreReplacements['WELCOME'] = isset($thissurvey['welcome']) ? $thissurvey['welcome'] : '';
    if (!isset($replacements['QID'])) {
        Yii::import('application.helpers.SurveyRuntimeHelper');
        $coreReplacements = array_merge($coreReplacements, SurveyRuntimeHelper::getQuestionReplacement(null));
        // so $replacements overrides core values
    }
    if (!is_null($replacements) && is_array($replacements)) {
        $doTheseReplacements = array_merge($coreReplacements, $replacements);
        // so $replacements overrides core values
    } else {
        $doTheseReplacements = $coreReplacements;
    }
    // Now do all of the replacements - In rare cases, need to do 3 deep recursion, that that is default
    $line = LimeExpressionManager::ProcessString($line, $questionNum, $doTheseReplacements, false, 3, 1, false, true, $bStaticReplacement);
    return $line;
}
コード例 #4
0
    /**
     * 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();
    }
コード例 #5
0
/**
 * This function replaces keywords in a text and is mainly intended for templates
 * If you use this functions put your replacement strings into the $replacements variable
 * instead of using global variables
 * NOTE - Don't do any embedded replacements in this function.  Create the array of replacement values and
 * they will be done in batch at the end
 *
 * @param string $line Text to search in
 * @param array $replacements Array of replacements:  Array( <stringtosearch>=><stringtoreplacewith>, where <stringtosearch> is NOT surrounded with curly braces
 * @param boolean $anonymized Determines if token data is being used or just replaced with blanks
 * @return string  Text with replaced strings
 */
function templatereplace($line, $replacements=array(), $anonymized=false)
{
    global $surveylist, $sitename, $clienttoken, $rooturl;
    global $thissurvey, $imageurl, $defaulttemplate;
    global $percentcomplete, $move;
    global $groupname, $groupdescription;
    global $question;
    global $showXquestions, $showgroupinfo, $showqnumcode;
    global $answer, $navigator;
    global $help, $surveyformat;
    global $completed, $register_errormsg;
    global $privacy, $surveyid;
    global $publicurl, $templatedir, $token;
    global $assessments, $s_lang;
    global $errormsg, $clang;
    global $saved_id;
    global $totalBoilerplatequestions, $relativeurl;
    global $languagechanger;
    global $captchapath, $loadname;

    // lets sanitize the survey template
    if (isset($thissurvey['templatedir']))
    {
        $_templatename = $thissurvey['templatedir'];
    }
    else
    {
        $_templatename = $defaulttemplate;
    }
    $_templatename = validate_templatedir($_templatename);

    // create absolute template URL and template dir vars
    $_templateurl = sGetTemplateURL($_templatename) . '/';
    $templatedir = sgetTemplatePath($_templatename);

    if (stripos($line, "</head>"))
    {
        $line = str_ireplace("</head>",
            "<script type=\"text/javascript\" src=\"$rooturl/scripts/survey_runtime.js\"></script>\n"
                        . use_firebug()
                        . "\t</head>", $line);
    }
    // Get some vars : move elsewhere ?
    // surveyformat
    if (isset($thissurvey['format']))
    {
        $surveyformat = str_replace(array("A", "S", "G"), array("allinone", "questionbyquestion", "groupbygroup"), $thissurvey['format']);
    }
    else
    {
        $surveyformat = "";
    }
    // real survey contact
    if (isset($surveylist['contact']))
    {
        $_surveycontact = $surveylist['contact'];
    }
    elseif (isset($thissurvey['admin']) && $thissurvey['admin'] != "")
    {
        $_surveycontact = sprintf($clang->gT("Please contact %s ( %s ) for further assistance."), $thissurvey['admin'], $thissurvey['adminemail']);
    }
    else
    {
        $_surveycontact = "";
    }

    // If there are non-bracketed replacements to be made do so above this line.
    // Only continue in this routine if there are bracketed items to replace {}
    if (strpos($line, "{") === false)
    {
        return $line;
    }

    if (
        $showgroupinfo == 'both' ||
	    $showgroupinfo == 'name' ||
	    ($showgroupinfo == 'choose' && !isset($thissurvey['showgroupinfo'])) ||
	    ($showgroupinfo == 'choose' && $thissurvey['showgroupinfo'] == 'B') ||
	    ($showgroupinfo == 'choose' && $thissurvey['showgroupinfo'] == 'N')
    )
    {
        $_groupname = $groupname;
    }
    else
    {
        $_groupname = '';
    };
    if (
        $showgroupinfo == 'both' ||
	    $showgroupinfo == 'description' ||
	    ($showgroupinfo == 'choose' && !isset($thissurvey['showgroupinfo'])) ||
	    ($showgroupinfo == 'choose' && $thissurvey['showgroupinfo'] == 'B') ||
	    ($showgroupinfo == 'choose' && $thissurvey['showgroupinfo'] == 'D')
    )
    {
        $_groupdescription = $groupdescription;
    }
    else
    {
        $_groupdescription = '';
    };

    if (is_array($question))
    {
        $_question = $question['all'];
        $_question_text = $question['text'];
        $_question_help = $question['help'];
        $_question_mandatory = $question['mandatory'];
        $_question_man_message = $question['man_message'];
        $_question_valid_message = $question['valid_message'];
        $_question_file_valid_message = $question['file_valid_message'];
        $_question_sgq = (isset($question['sgq']) ? $question['sgq'] : '');
        $_question_essentials = $question['essentials'];
        $_question_class = $question['class'];
        $_question_man_class = $question['man_class'];
        $_question_input_error_class = $question['input_error_class'];
        }
        else
        {
        $_question = $question;
        $_question_text = '';
        $_question_help = '';
        $_question_mandatory = '';
        $_question_man_message = '';
        $_question_valid_message = '';
        $_question_file_valid_message = '';
        $_question_sgq = '';
        $_question_essentials = '';
        $_question_class = '';
        $_question_man_class = '';
        $_question_input_error_class = '';
    };

    if (
        $showqnumcode == 'both' ||
	    $showqnumcode == 'number' ||
	    ($showqnumcode == 'choose' && !isset($thissurvey['showqnumcode'])) ||
	    ($showqnumcode == 'choose' && $thissurvey['showqnumcode'] == 'B') ||
	    ($showqnumcode == 'choose' && $thissurvey['showqnumcode'] == 'N')
    )
    {
        $_question_number = $question['number'];
    }
    else
    {
        $_question_number = '';
    };
    if (
        $showqnumcode == 'both' ||
	    $showqnumcode == 'code' ||
	    ($showqnumcode == 'choose' && !isset($thissurvey['showqnumcode'])) ||
	    ($showqnumcode == 'choose' && $thissurvey['showqnumcode'] == 'B') ||
	    ($showqnumcode == 'choose' && $thissurvey['showqnumcode'] == 'C')
    )
    {
        $_question_code = $question['code'];
    }
    else
    {
        $_question_code = '';
    }

    if (isset($_SESSION['therearexquestions']))
    {
        $_totalquestionsAsked = $_SESSION['therearexquestions'] - $totalBoilerplatequestions;
    }
    else {
        $_totalquestionsAsked = 0;
    }
    if (
      $showXquestions == 'show' ||
      ($showXquestions == 'choose' && !isset($thissurvey['showXquestions'])) ||
      ($showXquestions == 'choose' && $thissurvey['showXquestions'] == 'Y')
    )
    {
        if ($_totalquestionsAsked < 1)
        {
            $_therearexquestions = $clang->gT("There are no questions in this survey"); // Singular
        }
        elseif ($_totalquestionsAsked == 1)
        {
            $_therearexquestions = $clang->gT("There is 1 question in this survey"); //Singular
        }
        else
        {
            $_therearexquestions = $clang->gT("There are {NUMBEROFQUESTIONS} questions in this survey.");    //Note this line MUST be before {NUMBEROFQUESTIONS}
	};
    }
    else
    {
        $_therearexquestions = '';
    };

    if (isset($token))
    {
        $_token = $token;
        }
    elseif (isset($clienttoken))
    {
        $_token = htmlentities($clienttoken, ENT_QUOTES, 'UTF-8');
        }
    else
    {
        $_token = '';
    }

    if (isset($thissurvey['surveyls_dateformat']))
    {
        $dateformatdetails = getDateFormatData($thissurvey['surveyls_dateformat']);
    }
    else {
        $dateformatdetails = getDateFormatData();
    }
    if (isset($thissurvey['expiry']))
    {
        $_datetimeobj = new Date_Time_Converter($thissurvey['expiry'], "Y-m-d");
        $_dateoutput = $_datetimeobj->convert($dateformatdetails['phpdate']);
            }
    else
    {
        $_dateoutput = '-';
            }
    $_submitbutton = "<input class='submit' type='submit' value=' " . $clang->gT("Submit") . " ' name='move2' onclick=\"javascript:document.limesurvey.move.value = 'movesubmit';\" />";
    if (isset($thissurvey['surveyls_url']) and $thissurvey['surveyls_url'] != "")
    {
        if (trim($thissurvey['surveyls_urldescription']) != '')
        {
            $_linkreplace = "<a href='{$thissurvey['surveyls_url']}'>{$thissurvey['surveyls_urldescription']}</a>";
        }
        else
        {
            $_linkreplace = "<a href='{$thissurvey['surveyls_url']}'>{$thissurvey['surveyls_url']}</a>";
    }
    }
    else
    {
        $_linkreplace='';
    }

    if (isset($clienttoken))
    {
        $token = $clienttoken;
    }
    else
    {
        $token = '';
    }

    if (!isset($_SESSION['s_lang']))
    {
        $_s_lang = 'en';
    }
    else
    {
        $_s_lang = $_SESSION['s_lang'];
    }

    $_clearall = "<input type='button' name='clearallbtn' value='" . $clang->gT("Exit and Clear Survey") . "' class='clearall' "
            . "onclick=\"if (confirm('" . $clang->gT("Are you sure you want to clear all your responses?", 'js') . "')) {window.open('{$publicurl}/index.php?sid=$surveyid&amp;move=clearall&amp;lang=" . $_s_lang;
        if (returnglobal('token'))
        {
        $_clearall .= "&amp;token=" . urlencode(trim(sanitize_xss_string(strip_tags(returnglobal('token')))));
        }
        $_clearall .= "', '_self')}\" />";

    if (isset($_SESSION['datestamp']))
    {
        $_datestamp = $_SESSION['datestamp'];
    }
    else
    {
        $_datestamp = '-';
        }
        //Set up save/load feature
    if (isset($thissurvey['allowsave']) and $thissurvey['allowsave'] == "Y")
        {
            // Find out if the user has any saved data

        if ($thissurvey['format'] == 'A')
            {
            if ($thissurvey['tokenanswerspersistence'] != 'Y')
                {
                $_saveall = "\t\t\t<input type='submit' name='loadall' value='" . $clang->gT("Load Unfinished Survey") . "' class='saveall' " . (($thissurvey['active'] != "Y") ? "disabled='disabled'" : "") . "/>"
                        . "\n\t\t\t<input type='button' name='saveallbtn' value='" . $clang->gT("Resume Later") . "' class='saveall' onclick=\"javascript:document.limesurvey.move.value = this.value;addHiddenField(document.getElementById('limesurvey'),'saveall',this.value);document.getElementById('limesurvey').submit();\" " . (($thissurvey['active'] != "Y") ? "disabled='disabled'" : "") . "/>";  // Show Save So Far button
                }
                else
                {
                $_saveall = "\t\t\t<input type='button' name='saveallbtn' value='" . $clang->gT("Resume Later") . "' class='saveall' onclick=\"javascript:document.limesurvey.move.value = this.value;addHiddenField(document.getElementById('limesurvey'),'saveall',this.value);document.getElementById('limesurvey').submit();\" " . (($thissurvey['active'] != "Y") ? "disabled='disabled'" : "") . "/>";  // Show Save So Far button
        	};
            }
        elseif (!isset($_SESSION['step']) || !$_SESSION['step'])
        {  //First page, show LOAD
            if ($thissurvey['tokenanswerspersistence'] != 'Y')
            {
                $_saveall = "\t\t\t<input type='submit' name='loadall' value='" . $clang->gT("Load Unfinished Survey") . "' class='saveall' " . (($thissurvey['active'] != "Y") ? "disabled='disabled'" : "") . "/>";
                }
		else
		{
                    $_saveall = '';
		};
            }
        elseif (isset($_SESSION['scid']) && (isset($move) && $move == "movelast"))
        {  //Already saved and on Submit Page, dont show Save So Far button
            $_saveall = '';
            }
            else
            {
            $_saveall = "<input type='button' name='saveallbtn' value='" . $clang->gT("Resume Later") . "' class='saveall' onclick=\"javascript:document.limesurvey.move.value = this.value;addHiddenField(document.getElementById('limesurvey'),'saveall',this.value);document.getElementById('limesurvey').submit();\" " . (($thissurvey['active'] != "Y") ? "disabled='disabled'" : "") . "/>";  // Show Save So Far button
            }
        }
        else
        {
        $_saveall = "";
        }

    $_templatecss = "<link rel='stylesheet' type='text/css' href='{$_templateurl}template.css' />\n";
        if (getLanguageRTL($clang->langcode))
        {
            $_templatecss.="<link rel='stylesheet' type='text/css' href='{$_templateurl}template-rtl.css' />\n";
        }

    if (FlattenText($help, true) != '')
        {
            If (!isset($helpicon))
            {
            if (file_exists($templatedir . '/help.gif'))
                {

                $helpicon = $_templateurl . 'help.gif';
                }
            elseif (file_exists($templatedir . '/help.png'))
                {

                $helpicon = $_templateurl . 'help.png';
                }
                else
                {
                $helpicon = $imageurl . "/help.gif";
                }
            }
            $_questionhelp =  "<img src='{$helpicon}' alt='Help' align='left' />".$help;
        }
    else
    {
        $_questionhelp = $help;
    }

    if (isset($thissurvey['allowprev']) && $thissurvey['allowprev'] == "N")
    {
            $_strreview = "";
        }
    else
    {
        $_strreview = $clang->gT("If you want to check any of the answers you have made, and/or change them, you can do that now by clicking on the [<< prev] button and browsing through your responses.");
        }

    if (isset($thissurvey['active']) and $thissurvey['active'] == "N")
    {
        $_restart = "<a href='{$publicurl}/index.php?sid=$surveyid&amp;newtest=Y";
        if (isset($s_lang) && $s_lang != '') {
            $_restart.="&amp;lang=" . $s_lang;
        }
        $_restart.="'>" . $clang->gT("Restart this Survey") . "</a>";
    } else
        {
            $restart_extra = "";
            $restart_token = returnglobal('token');
        if (!empty($restart_token))
            $restart_extra .= "&amp;token=" . urlencode($restart_token);
        else
            $restart_extra = "&amp;newtest=Y";
        if (!empty($_GET['lang']))
            $restart_extra .= "&amp;lang=" . returnglobal('lang');
        $_restart = "<a href='{$publicurl}/index.php?sid=$surveyid" . $restart_extra . "'>" . $clang->gT("Restart this Survey") . "</a>";
        }
    if (isset($thissurvey['anonymized']) && $thissurvey['anonymized'] == 'Y')
    {
        $_savealert = $clang->gT("To remain anonymous please use a pseudonym as your username, also an email address is not required.");
        }
        else
        {
        $_savealert = "";
        }

        $_return_to_survey = "<a href='$relativeurl/index.php?sid=$surveyid";
        if (returnglobal('token'))
        {
        $_return_to_survey.= "&amp;token=" . urlencode(trim(sanitize_xss_string(strip_tags(returnglobal('token')))));
        }
    $_return_to_survey .= "'>" . $clang->gT("Return To Survey") . "</a>";

    $_saveform = "<table><tr><td align='right'>" . $clang->gT("Name") . ":</td><td><input type='text' name='savename' value='";
    if (isset($_POST['savename']))
    {
        $_saveform .= html_escape(auto_unescape($_POST['savename']));
    }
        $_saveform .= "' /></td></tr>\n"
            . "<tr><td align='right'>" . $clang->gT("Password") . ":</td><td><input type='password' name='savepass' value='";
    if (isset($_POST['savepass']))
    {
        $_saveform .= html_escape(auto_unescape($_POST['savepass']));
    }
        $_saveform .= "' /></td></tr>\n"
            . "<tr><td align='right'>" . $clang->gT("Repeat Password") . ":</td><td><input type='password' name='savepass2' value='";
    if (isset($_POST['savepass2']))
    {
        $_saveform .= html_escape(auto_unescape($_POST['savepass2']));
    }
        $_saveform .= "' /></td></tr>\n"
            . "<tr><td align='right'>" . $clang->gT("Your Email") . ":</td><td><input type='text' name='saveemail' value='";
    if (isset($_POST['saveemail']))
    {
        $_saveform .= html_escape(auto_unescape($_POST['saveemail']));
    }
        $_saveform .= "' /></td></tr>\n";
    if (isset($thissurvey['usecaptcha']) && function_exists("ImageCreate") && captcha_enabled('saveandloadscreen', $thissurvey['usecaptcha']))
        {
        $_saveform .="<tr><td align='right'>" . $clang->gT("Security Question") . ":</td><td><table><tr><td valign='middle'><img src='{$captchapath}verification.php?sid=$surveyid' alt='' /></td><td valign='middle' style='text-align:left'><input type='text' size='5' maxlength='3' name='loadsecurity' value='' /></td></tr></table></td></tr>\n";
        }
        $_saveform .= "<tr><td align='right'></td><td></td></tr>\n"
            . "<tr><td></td><td><input type='submit'  id='savebutton' name='savesubmit' value='" . $clang->gT("Save Now") . "' /></td></tr>\n"
        . "</table>";

    $_loadform = "<table><tr><td align='right'>" . $clang->gT("Saved name") . ":</td><td><input type='text' name='loadname' value='";
    if ($loadname)
    {
        $_loadform .= html_escape(auto_unescape($loadname));
    }
        $_loadform .= "' /></td></tr>\n"
            . "<tr><td align='right'>" . $clang->gT("Password") . ":</td><td><input type='password' name='loadpass' value='";
    if (isset($loadpass))
    {
        $_loadform .= html_escape(auto_unescape($loadpass));
    }
        $_loadform .= "' /></td></tr>\n";
    if (isset($thissurvey['usecaptcha']) && function_exists("ImageCreate") && captcha_enabled('saveandloadscreen', $thissurvey['usecaptcha']))
        {
        $_loadform .="<tr><td align='right'>" . $clang->gT("Security Question") . ":</td><td><table><tr><td valign='middle'><img src='{$captchapath}verification.php?sid=$surveyid' alt='' /></td><td valign='middle'><input type='text' size='5' maxlength='3' name='loadsecurity' value='' alt=''/></td></tr></table></td></tr>\n";
        }

        $_loadform .="<tr><td align='right'></td><td></td></tr>\n"
            . "<tr><td></td><td><input type='submit' id='loadbutton' value='" . $clang->gT("Load Now") . "' /></td></tr></table>\n";

    $_registerform = "<form method='post' action='{$publicurl}/register.php'>\n";
        if (!isset($_REQUEST['lang']))
        {
            $_reglang = GetBaseLanguageFromSurveyID($surveyid);
        }
        else
        {
            $_reglang = returnglobal('lang');
        }
    $_registerform .= "<input type='hidden' name='lang' value='" . $_reglang . "' />\n";
        $_registerform .= "<input type='hidden' name='sid' value='$surveyid' id='sid' />\n";

        $_registerform.="<table class='register' summary='Registrationform'>\n"
            . "<tr><td align='right'>"
            . $clang->gT("First name") . ":</td>"
            . "<td align='left'><input class='text' type='text' name='register_firstname'";
        if (isset($_POST['register_firstname']))
        {
        $_registerform .= " value='" . htmlentities(returnglobal('register_firstname'), ENT_QUOTES, 'UTF-8') . "'";
        }
        $_registerform .= " /></td></tr>"
            . "<tr><td align='right'>" . $clang->gT("Last name") . ":</td>\n"
            . "<td align='left'><input class='text' type='text' name='register_lastname'";
        if (isset($_POST['register_lastname']))
        {
        $_registerform .= " value='" . htmlentities(returnglobal('register_lastname'), ENT_QUOTES, 'UTF-8') . "'";
        }
        $_registerform .= " /></td></tr>\n"
            . "<tr><td align='right'>" . $clang->gT("Email address") . ":</td>\n"
            . "<td align='left'><input class='text' type='text' name='register_email'";
        if (isset($_POST['register_email']))
        {
        $_registerform .= " value='" . htmlentities(returnglobal('register_email'), ENT_QUOTES, 'UTF-8') . "'";
        }
        $_registerform .= " /></td></tr>\n";


    if (isset($thissurvey['usecaptcha']) && function_exists("ImageCreate") && captcha_enabled('registrationscreen', $thissurvey['usecaptcha']))
        {
        $_registerform .="<tr><td align='right'>" . $clang->gT("Security Question") . ":</td><td><table><tr><td valign='middle'><img src='{$captchapath}verification.php?sid=$surveyid' alt='' /></td><td valign='middle'><input type='text' size='5' maxlength='3' name='loadsecurity' value='' /></td></tr></table></td></tr>\n";
        }


        /*      if(isset($thissurvey['attribute1']) && $thissurvey['attribute1'])
         {
         $_registerform .= "<tr><td align='right'>".$thissurvey['attribute1'].":</td>\n"
         ."<td align='left'><input class='text' type='text' name='register_attribute1'";
         if (isset($_POST['register_attribute1']))
         {
         $_registerform .= " value='".htmlentities(returnglobal('register_attribute1'),ENT_QUOTES,'UTF-8')."'";
         }
         $_registerform .= " /></td></tr>\n";
         }
         if(isset($thissurvey['attribute2']) && $thissurvey['attribute2'])
         {
         $_registerform .= "<tr><td align='right'>".$thissurvey['attribute2'].":</td>\n"
         ."<td align='left'><input class='text' type='text' name='register_attribute2'";
         if (isset($_POST['register_attribute2']))
         {
         $_registerform .= " value='".htmlentities(returnglobal('register_attribute2'),ENT_QUOTES,'UTF-8')."'";
         }
         $_registerform .= " /></td></tr>\n";
      } */
    $_registerform .= "<tr><td></td><td><input id='registercontinue' class='submit' type='submit' value='" . $clang->gT("Continue") . "' />"
            . "</td></tr>\n"
            . "</table>\n"
            . "</form>\n";

    if (!is_null($surveyid) && function_exists('doAssessment'))
    {
        $assessmentdata = doAssessment($surveyid, true);
        $_assessment_current_total = $assessmentdata['total'];
    }
    else
    {
        $_assessment_current_total = '';
    }

    // Set the array of replacement variables here - don't include curly braces
	$corecoreReplacements = array();
	$coreReplacements['ANSWER'] = $answer;  // global
	$coreReplacements['ANSWERSCLEARED'] = $clang->gT("Answers Cleared");
	$coreReplacements['ASSESSMENTS'] = $assessments;    // global
	$coreReplacements['ASSESSMENT_CURRENT_TOTAL'] = $_assessment_current_total;
	$coreReplacements['ASSESSMENT_HEADING'] = $clang->gT("Your Assessment");
	$coreReplacements['CHECKJAVASCRIPT'] = "<noscript><span class='warningjs'>".$clang->gT("Caution: JavaScript execution is disabled in your browser. You may not be able to answer all questions in this survey. Please, verify your browser parameters.")."</span></noscript>";
	$coreReplacements['CLEARALL'] = $_clearall;
	$coreReplacements['CLOSEWINDOW']  =  "<a href='javascript:%20self.close()'>".$clang->gT("Close this window")."</a>";
	$coreReplacements['COMPLETED'] = $completed;    // global
	$coreReplacements['DATESTAMP'] = $_datestamp;
	$coreReplacements['EXPIRY'] = $_dateoutput;
	$coreReplacements['GROUPDESCRIPTION'] = $_groupdescription;
	$coreReplacements['GROUPNAME'] = $_groupname;
	$coreReplacements['LANG'] = $clang->getlangcode();
	$coreReplacements['LANGUAGECHANGER'] = $languagechanger;    // global
	$coreReplacements['LOADERROR'] = $errormsg; // global
	$coreReplacements['LOADFORM'] = $_loadform;
	$coreReplacements['LOADHEADING'] = $clang->gT("Load A Previously Saved Survey");
	$coreReplacements['LOADMESSAGE'] = $clang->gT("You can load a survey that you have previously saved from this screen.")."<br />".$clang->gT("Type in the 'name' you used to save the survey, and the password.")."<br />";
	$coreReplacements['NAVIGATOR'] = $navigator;    // global
	$coreReplacements['NOSURVEYID'] = $surveylist['nosid']; // global
	$coreReplacements['NUMBEROFQUESTIONS'] = $_totalquestionsAsked;
	$coreReplacements['PERCENTCOMPLETE'] = $percentcomplete;    // global
	$coreReplacements['PRIVACY'] = $privacy;    // global
	$coreReplacements['PRIVACYMESSAGE'] = "<span style='font-weight:bold; font-style: italic;'>".$clang->gT("A Note On Privacy")."</span><br />".$clang->gT("This survey is anonymous.")."<br />".$clang->gT("The record kept of your survey responses does not contain any identifying information about you unless a specific question in the survey has asked for this. If you have responded to a survey that used an identifying token to allow you to access the survey, you can rest assured that the identifying token is not kept with your responses. It is managed in a separate database, and will only be updated to indicate that you have (or haven't) completed this survey. There is no way of matching identification tokens with survey responses in this survey.");
	$coreReplacements['QUESTION'] = $_question;
	$coreReplacements['QUESTIONHELP'] = $_questionhelp;
	$coreReplacements['QUESTIONHELPPLAINTEXT'] = strip_tags(addslashes($help)); // global
	$coreReplacements['QUESTION_CLASS'] = $_question_class;
	$coreReplacements['QUESTION_CODE'] = $_question_code;
	$coreReplacements['QUESTION_ESSENTIALS'] = $_question_essentials;
	$coreReplacements['QUESTION_FILE_VALID_MESSAGE'] = $_question_file_valid_message;
	$coreReplacements['QUESTION_HELP'] = $_question_help;
	$coreReplacements['QUESTION_INPUT_ERROR_CLASS'] = $_question_input_error_class;
	$coreReplacements['QUESTION_MANDATORY'] = $_question_mandatory;
	$coreReplacements['QUESTION_MAN_CLASS'] = $_question_man_class;
	$coreReplacements['QUESTION_MAN_MESSAGE'] = $_question_man_message;
	$coreReplacements['QUESTION_NUMBER'] = $_question_number;
	$coreReplacements['QUESTION_TEXT'] = $_question_text;
	$coreReplacements['QUESTION_VALID_MESSAGE'] = $_question_valid_message;
	$coreReplacements['REGISTERERROR'] = $register_errormsg;    // global
	$coreReplacements['REGISTERFORM'] = $_registerform;
	$coreReplacements['REGISTERMESSAGE1'] = $clang->gT("You must be registered to complete this survey");
	$coreReplacements['REGISTERMESSAGE2'] = $clang->gT("You may register for this survey if you wish to take part.")."<br />\n".$clang->gT("Enter your details below, and an email containing the link to participate in this survey will be sent immediately.");
	$coreReplacements['RESTART'] = $_restart;
	$coreReplacements['RETURNTOSURVEY'] = $_return_to_survey;
	$coreReplacements['SAVE'] = $_saveall;
	$coreReplacements['SAVEALERT'] = $_savealert;
	$coreReplacements['SAVEDID'] = $saved_id;   // global
	$coreReplacements['SAVEERROR'] = $errormsg; // global - same as LOADERROR
	$coreReplacements['SAVEFORM'] = $_saveform;
	$coreReplacements['SAVEHEADING'] = $clang->gT("Save Your Unfinished Survey");
	$coreReplacements['SAVEMESSAGE'] = $clang->gT("Enter a name and password for this survey and click save below.")."<br />\n".$clang->gT("Your survey will be saved using that name and password, and can be completed later by logging in with the same name and password.")."<br /><br />\n".$clang->gT("If you give an email address, an email containing the details will be sent to you.")."<br /><br />\n".$clang->gT("After having clicked the save button you can either close this browser window or continue filling out the survey.");
	$coreReplacements['SGQ'] = $_question_sgq;
	$coreReplacements['SID'] = $surveyid;   // global
	$coreReplacements['SITENAME'] = $sitename;  // global
	$coreReplacements['SUBMITBUTTON'] = $_submitbutton;
	$coreReplacements['SUBMITCOMPLETE'] = "<strong>".$clang->gT("Thank you!")."<br /><br />".$clang->gT("You have completed answering the questions in this survey.")."</strong><br /><br />".$clang->gT("Click on 'Submit' now to complete the process and save your answers.");
	$coreReplacements['SUBMITREVIEW'] = $_strreview;
	$coreReplacements['SURVEYCONTACT'] = $_surveycontact;
	$coreReplacements['SURVEYDESCRIPTION'] = (isset($thissurvey['description']) ? $thissurvey['description'] : '');
	$coreReplacements['SURVEYFORMAT'] = $surveyformat;  // global
	$coreReplacements['SURVEYLANGAGE'] = $clang->langcode;
	$coreReplacements['SURVEYLIST'] = $surveylist['list'];  // global
	$coreReplacements['SURVEYLISTHEADING'] =  $surveylist['listheading'];   // global
	$coreReplacements['SURVEYNAME'] = $thissurvey['name'];  // global
	$coreReplacements['TEMPLATECSS'] = $_templatecss;
	$coreReplacements['TEMPLATEURL'] = $_templateurl;
	$coreReplacements['THEREAREXQUESTIONS'] = $_therearexquestions;
	if (!$anonymized) $coreReplacements['TOKEN'] = $_token;
	$coreReplacements['URL'] = $_linkreplace;
	$coreReplacements['WELCOME'] = (isset($thissurvey['welcome']) ? $thissurvey['welcome'] : '');

    $tokenAndAnswerMap = getAnswerAndTokenMappings(false,$anonymized);
    $doTheseReplacements = array_merge($coreReplacements, $tokenAndAnswerMap, $replacements);   // so $replacements overrides core values

    $line = doReplacements($line,$doTheseReplacements);
    // Do replacements twice since some reference others
    $line = doReplacements($line,$doTheseReplacements);

    return $line;
}
コード例 #6
0
ファイル: survey.php プロジェクト: nmklong/limesurvey-cdio3
        if ($thissurvey['usecookie'] == "Y" && $tokensexist != 1) //don't use cookies if tokens are being used
        {
            $cookiename="PHPSID".returnglobal('sid')."STATUS";
            setcookie("$cookiename", "COMPLETE", time() + 31536000); //Cookie will expire in 365 days
        }

        //Before doing the "templatereplace()" function, check the $thissurvey['url']
        //field for limereplace stuff, and do transformations!
        $thissurvey['surveyls_url']=dTexts::run($thissurvey['surveyls_url']);
        $thissurvey['surveyls_url']=passthruReplace($thissurvey['surveyls_url'], $thissurvey);

        $content='';
        $content .= templatereplace(file_get_contents("$thistpl/startpage.pstpl"));

        //Check for assessments
        $assessments = doAssessment($surveyid);
        if ($assessments)
        {
            $content .= templatereplace(file_get_contents("$thistpl/assessment.pstpl"));
        }

        // Unsetting $postedfieldnames tells the createinsertquery() function only to set the sbumit date, nothing else
        unset($postedfieldnames);

        // only update submitdate if the user did not already visit the submit page
        if (!isset($_SESSION['finished']))
        {
            //            $subquery = createinsertquery();
            //            $connect->Execute($subquery);   // Checked
            submitanswer();
        }
コード例 #7
0
ファイル: replacements.php プロジェクト: ddrmoscow/queXS
/**
 * This function replaces keywords in a text and is mainly intended for templates
 * If you use this functions put your replacement strings into the $replacements variable
 * instead of using global variables
 * NOTE - Don't do any embedded replacements in this function.  Create the array of replacement values and
 * they will be done in batch at the end
 *
 * @param string $line Text to search in
 * @param array $replacements Array of replacements:  Array( <stringtosearch>=><stringtoreplacewith>, where <stringtosearch> is NOT surrounded with curly braces
 * @param boolean $anonymized Determines if token data is being used or just replaced with blanks
 * @return string  Text with replaced strings
 */
function templatereplace($line, $replacements = array(), $anonymized = false, $questionNum = NULL)
{
    global $surveylist, $sitename, $clienttoken, $rooturl;
    global $thissurvey, $imageurl, $defaulttemplate;
    global $percentcomplete, $move;
    global $groupname, $groupdescription;
    global $question;
    global $showxquestions, $showgroupinfo, $showqnumcode;
    global $answer, $navigator;
    global $help, $surveyformat;
    global $completed, $register_errormsg;
    global $privacy, $surveyid;
    global $publicurl, $templatedir, $token;
    global $assessments, $s_lang;
    global $errormsg, $clang;
    global $saved_id;
    global $totalBoilerplatequestions, $relativeurl;
    global $languagechanger;
    global $captchapath, $loadname;
    // lets sanitize the survey template
    if (isset($thissurvey['templatedir'])) {
        $_templatename = $thissurvey['templatedir'];
    } else {
        $_templatename = $defaulttemplate;
    }
    #    $_templatename = validate_templatedir($_templatename); // Not needed: sGetTemplateURL and sgetTemplatePath do validation
    // create absolute template URL and template dir vars
    $_templateurl = sGetTemplateURL($_templatename) . '/';
    $templatedir = sgetTemplatePath($_templatename);
    $interviewer = returnglobal('interviewer');
    if (!empty($interviewer) || isset($_SESSION['interviewer']) && $_SESSION['interviewer'] == true) {
        $interviewer = true;
        $_SESSION['interviewer'] = true;
    } else {
        $interviewer = false;
    }
    if (stripos($line, "</head>")) {
        //queXS Addition
        $textfocus = "";
        if ($interviewer) {
            $textfocus = '<script type="text/javascript">
		$(document).ready(function()
		{
	        	$(".text").focus();
		        $(".textarea").focus();
		});
		</script>';
        }
        $line = str_ireplace("</head>", "<script type=\"text/javascript\" src=\"{$rooturl}/scripts/survey_runtime.js\"></script>\n" . "{$textfocus}\n" . use_firebug() . "\t</head>", $line);
    }
    // Get some vars : move elsewhere ?
    // surveyformat
    if (isset($thissurvey['format'])) {
        $surveyformat = str_replace(array("A", "S", "G"), array("allinone", "questionbyquestion", "groupbygroup"), $thissurvey['format']);
    } else {
        $surveyformat = "";
    }
    /*if (isset($thissurvey['allowjumps']) && $thissurvey['allowjumps']=="Y" && $surveyformat!="allinone" && (isset($_SESSION['step']) && $_SESSION['step']>0)){
          $surveyformat .= " withindex";
      }*/
    if (isset($thissurvey['showprogress']) && $thissurvey['showprogress'] == "Y") {
        $surveyformat .= " showprogress";
    }
    if (isset($thissurvey['showqnumcode'])) {
        $surveyformat .= " showqnumcode-" . $thissurvey['showqnumcode'];
    }
    // real survey contact
    if (isset($surveylist['contact'])) {
        $_surveycontact = $surveylist['contact'];
    } elseif (isset($thissurvey['admin']) && $thissurvey['admin'] != "") {
        $_surveycontact = sprintf($clang->gT("Please contact %s ( %s ) for further assistance."), $thissurvey['admin'], $thissurvey['adminemail']);
    } else {
        $_surveycontact = "";
    }
    // If there are non-bracketed replacements to be made do so above this line.
    // Only continue in this routine if there are bracketed items to replace {}
    if (strpos($line, "{") === false) {
        return LimeExpressionManager::ProcessString($line, $questionNum, NULL, false, 1, 1, true);
    }
    if ($showgroupinfo == 'both' || $showgroupinfo == 'name' || $showgroupinfo == 'choose' && !isset($thissurvey['showgroupinfo']) || $showgroupinfo == 'choose' && $thissurvey['showgroupinfo'] == 'B' || $showgroupinfo == 'choose' && $thissurvey['showgroupinfo'] == 'N') {
        $_groupname = $groupname;
    } else {
        $_groupname = '';
    }
    if ($showgroupinfo == 'both' || $showgroupinfo == 'description' || $showgroupinfo == 'choose' && !isset($thissurvey['showgroupinfo']) || $showgroupinfo == 'choose' && $thissurvey['showgroupinfo'] == 'B' || $showgroupinfo == 'choose' && $thissurvey['showgroupinfo'] == 'D') {
        $_groupdescription = $groupdescription;
    } else {
        $_groupdescription = '';
    }
    if (is_array($question)) {
        $_question = $question['all'];
        $_question_text = $question['text'];
        $_question_help = $question['help'];
        $_question_mandatory = $question['mandatory'];
        $_question_man_message = $question['man_message'];
        $_question_valid_message = $question['valid_message'];
        $_question_file_valid_message = $question['file_valid_message'];
        if (isset($question['sgq'])) {
            $_question_sgq = $question['sgq'];
            $_parts = explode('X', $_question_sgq);
            $_question_gid = $_parts[1];
        } else {
            $_question_sgq = '';
            $_question_gid = '';
        }
        $_question_essentials = $question['essentials'];
        $_question_class = $question['class'];
        $_question_man_class = $question['man_class'];
        $_question_input_error_class = $question['input_error_class'];
        $_aid = isset($question['aid']) ? $question['aid'] : '';
        $_sqid = isset($question['sqid']) ? $question['sqid'] : '';
        $_question_type = isset($question['type']) ? $question['type'] : '';
    } else {
        $_question = $question;
        $_question_text = '';
        $_question_help = '';
        $_question_mandatory = '';
        $_question_man_message = '';
        $_question_valid_message = '';
        $_question_file_valid_message = '';
        $_question_gid = '';
        $_question_sgq = '';
        $_question_essentials = '';
        $_question_class = '';
        $_question_man_class = '';
        $_question_input_error_class = '';
        $_aid = '';
        $_sqid = '';
        $_question_type = '';
    }
    global $answer_id;
    if ($_question_type == '*') {
        $_question_text = '<div class="em_equation">' . $_question_text . '</div>';
    }
    if ($showqnumcode == 'both' || $showqnumcode == 'number' || $showqnumcode == 'choose' && !isset($thissurvey['showqnumcode']) || $showqnumcode == 'choose' && $thissurvey['showqnumcode'] == 'B' || $showqnumcode == 'choose' && $thissurvey['showqnumcode'] == 'N') {
        $_question_number = $question['number'];
    } else {
        $_question_number = '';
    }
    if ($showqnumcode == 'both' || $showqnumcode == 'code' || $showqnumcode == 'choose' && !isset($thissurvey['showqnumcode']) || $showqnumcode == 'choose' && $thissurvey['showqnumcode'] == 'B' || $showqnumcode == 'choose' && $thissurvey['showqnumcode'] == 'C') {
        $_question_code = $question['code'];
    } else {
        $_question_code = '';
    }
    if (isset($_SESSION['therearexquestions'])) {
        $_totalquestionsAsked = $_SESSION['therearexquestions'] - $totalBoilerplatequestions;
    } else {
        $_totalquestionsAsked = 0;
    }
    if ($showxquestions == 'show' || $showxquestions == 'choose' && !isset($thissurvey['showxquestions']) || $showxquestions == 'choose' && $thissurvey['showxquestions'] == 'Y') {
        if ($_totalquestionsAsked < 1) {
            $_therearexquestions = $clang->gT("There are no questions in this survey");
            // Singular
        } elseif ($_totalquestionsAsked == 1) {
            $_therearexquestions = $clang->gT("There is 1 question in this survey");
            //Singular
        } else {
            $_therearexquestions = $clang->gT("There are {NUMBEROFQUESTIONS} questions in this survey.");
            //Note this line MUST be before {NUMBEROFQUESTIONS}
        }
    } else {
        $_therearexquestions = '';
    }
    if (isset($token)) {
        $_token = $token;
    } elseif (isset($clienttoken)) {
        $_token = htmlentities($clienttoken, ENT_QUOTES, 'UTF-8');
    } else {
        $_token = '';
    }
    if (isset($thissurvey['surveyls_dateformat'])) {
        $dateformatdetails = getDateFormatData($thissurvey['surveyls_dateformat']);
    } else {
        $dateformatdetails = getDateFormatData();
    }
    if (isset($thissurvey['expiry'])) {
        $_datetimeobj = new Date_Time_Converter($thissurvey['expiry'], "Y-m-d");
        $_dateoutput = $_datetimeobj->convert($dateformatdetails['phpdate']);
    } else {
        $_dateoutput = '-';
    }
    $_submitbutton = "<input class='submit' type='submit' value=' " . $clang->gT("Submit") . " ' name='move2' onclick=\"javascript:document.limesurvey.move.value = 'movesubmit';\" />";
    if (isset($thissurvey['surveyls_url']) and $thissurvey['surveyls_url'] != "") {
        if (trim($thissurvey['surveyls_urldescription']) != '') {
            $_linkreplace = "<a href='{$thissurvey['surveyls_url']}'>{$thissurvey['surveyls_urldescription']}</a>";
        } else {
            $_linkreplace = "<a href='{$thissurvey['surveyls_url']}'>{$thissurvey['surveyls_url']}</a>";
        }
    } else {
        $_linkreplace = '';
    }
    if (isset($clienttoken)) {
        $token = $clienttoken;
    } else {
        $token = '';
    }
    if (!isset($_SESSION['s_lang'])) {
        $_s_lang = 'en';
    } else {
        $_s_lang = $_SESSION['s_lang'];
    }
    // CLEARALL
    if ($surveyid && !isCompleted($surveyid, $saved_id)) {
        $_clearall = "<input type='button' name='clearallbtn' value='" . $clang->gT("Exit and Clear Survey") . "' class='clearall' " . "onclick=\"if (confirm('" . $clang->gT("Are you sure you want to clear all your responses?", 'js') . "')) {\nwindow.open('{$publicurl}/index.php?sid={$surveyid}&amp;move=clearall&amp;lang=" . $_s_lang;
        if (returnglobal('token')) {
            $_clearall .= "&amp;token={$_token}";
        }
        $_clearall .= "', '_self')}\" />";
    } else {
        $_clearall = "";
        // This survey are already completed or surveyid not set, then don't have access to clearallbtn
    }
    if (isset($_SESSION['datestamp'])) {
        $_datestamp = $_SESSION['datestamp'];
    } else {
        $_datestamp = '-';
    }
    //Set up save/load feature
    if (isset($thissurvey['allowsave']) and $thissurvey['allowsave'] == "Y") {
        // Find out if the user has any saved data
        if ($thissurvey['format'] == 'A') {
            if ($thissurvey['tokenanswerspersistence'] != 'Y' || !tableExists('tokens_' . $surveyid)) {
                $_saveall = "\t\t\t<input type='button' name='loadall' value='" . $clang->gT("Load Unfinished Survey") . "' class='saveall' onclick=\"javascript:addHiddenField(document.getElementById('limesurvey'),'loadall',this.value);document.getElementById('limesurvey').submit();\" " . ($thissurvey['active'] != "Y" ? "disabled='disabled'" : "") . "/>" . "\n\t\t\t<input type='button' name='saveallbtn' value='" . $clang->gT("Resume Later") . "' class='saveall' onclick=\"javascript:document.limesurvey.move.value = this.value;addHiddenField(document.getElementById('limesurvey'),'saveall',this.value);document.getElementById('limesurvey').submit();\" " . ($thissurvey['active'] != "Y" ? "disabled='disabled'" : "") . "/>";
                // Show Save So Far button
            } else {
                $_saveall = "\t\t\t<input type='button' name='saveallbtn' value='" . $clang->gT("Resume Later") . "' class='saveall' onclick=\"javascript:document.limesurvey.move.value = this.value;addHiddenField(document.getElementById('limesurvey'),'saveall',this.value);document.getElementById('limesurvey').submit();\" " . ($thissurvey['active'] != "Y" ? "disabled='disabled'" : "") . "/>";
                // Show Save So Far button
            }
        } elseif (!isset($_SESSION['step']) || !$_SESSION['step']) {
            //First page, show LOAD
            if ($thissurvey['tokenanswerspersistence'] != 'Y' || !tableExists('tokens_' . $surveyid)) {
                $_saveall = "\t\t\t<input type='button' name='loadall' value='" . $clang->gT("Load Unfinished Survey") . "' class='saveall' onclick=\"javascript:addHiddenField(document.getElementById('limesurvey'),'loadall',this.value);document.getElementById('limesurvey').submit();\" " . ($thissurvey['active'] != "Y" ? "disabled='disabled'" : "") . "/>";
            } else {
                $_saveall = '';
            }
        } elseif (isset($_SESSION['scid']) && (isset($move) && $move == "movelast")) {
            //Already saved and on Submit Page, dont show Save So Far button
            $_saveall = '';
        } else {
            $_saveall = "<input type='button' name='saveallbtn' value='" . $clang->gT("Resume Later") . "' class='saveall' onclick=\"javascript:document.limesurvey.move.value = this.value;addHiddenField(document.getElementById('limesurvey'),'saveall',this.value);document.getElementById('limesurvey').submit();\" " . ($thissurvey['active'] != "Y" ? "disabled='disabled'" : "") . "/>";
            // Show Save So Far button
        }
    } else {
        $_saveall = "";
    }
    $_templatecss = "<link rel='stylesheet' type='text/css' href='{$_templateurl}template.css' />\n";
    if (getLanguageRTL($clang->langcode)) {
        $_templatecss .= "<link rel='stylesheet' type='text/css' href='{$_templateurl}template-rtl.css' />\n";
    }
    if (FlattenText($help, true) != '') {
        if (!isset($helpicon)) {
            if (file_exists($templatedir . '/help.gif')) {
                $helpicon = $_templateurl . 'help.gif';
            } elseif (file_exists($templatedir . '/help.png')) {
                $helpicon = $_templateurl . 'help.png';
            } else {
                $helpicon = $imageurl . "/help.gif";
            }
        }
        $_questionhelp = "<img src='{$helpicon}' alt='Help' align='left' />" . $help;
    } else {
        $_questionhelp = $help;
    }
    if (isset($thissurvey['allowprev']) && $thissurvey['allowprev'] == "N") {
        $_strreview = "";
    } else {
        $_strreview = $clang->gT("If you want to check any of the answers you have made, and/or change them, you can do that now by clicking on the [<< prev] button and browsing through your responses.");
    }
    if (isset($thissurvey['active']) and $thissurvey['active'] == "N") {
        $_restart = "<a href='{$publicurl}/index.php?sid={$surveyid}&amp;newtest=Y";
        if (isset($s_lang) && $s_lang != '') {
            $_restart .= "&amp;lang=" . $s_lang;
        }
        $_restart .= "'>" . $clang->gT("Restart this Survey") . "</a>";
    } else {
        $restart_extra = "";
        $restart_token = returnglobal('token');
        if (!empty($restart_token)) {
            $restart_extra .= "&amp;token=" . urlencode($restart_token);
        } else {
            $restart_extra = "&amp;newtest=Y";
        }
        if (!empty($_GET['lang'])) {
            $restart_extra .= "&amp;lang=" . returnglobal('lang');
        }
        $_restart = "<a href='{$publicurl}/index.php?sid={$surveyid}" . $restart_extra . "'>" . $clang->gT("Restart this Survey") . "</a>";
    }
    if (isset($thissurvey['anonymized']) && $thissurvey['anonymized'] == 'Y') {
        $_savealert = $clang->gT("To remain anonymous please use a pseudonym as your username, also an email address is not required.");
    } else {
        $_savealert = "";
    }
    $_return_to_survey = "<a href='{$relativeurl}/index.php?sid={$surveyid}";
    if (returnglobal('token')) {
        $_return_to_survey .= "&amp;token=" . urlencode(trim(sanitize_xss_string(strip_tags(returnglobal('token')))));
    }
    $_return_to_survey .= "'>" . $clang->gT("Return To Survey") . "</a>";
    $_saveform = "<table><tr><td align='right'>" . $clang->gT("Name") . ":</td><td><input type='text' name='savename' value='";
    if (isset($_POST['savename'])) {
        $_saveform .= html_escape(auto_unescape($_POST['savename']));
    }
    $_saveform .= "' /></td></tr>\n" . "<tr><td align='right'>" . $clang->gT("Password") . ":</td><td><input type='password' name='savepass' value='";
    if (isset($_POST['savepass'])) {
        $_saveform .= html_escape(auto_unescape($_POST['savepass']));
    }
    $_saveform .= "' /></td></tr>\n" . "<tr><td align='right'>" . $clang->gT("Repeat Password") . ":</td><td><input type='password' name='savepass2' value='";
    if (isset($_POST['savepass2'])) {
        $_saveform .= html_escape(auto_unescape($_POST['savepass2']));
    }
    $_saveform .= "' /></td></tr>\n" . "<tr><td align='right'>" . $clang->gT("Your Email") . ":</td><td><input type='text' name='saveemail' value='";
    if (isset($_POST['saveemail'])) {
        $_saveform .= html_escape(auto_unescape($_POST['saveemail']));
    }
    $_saveform .= "' /></td></tr>\n";
    if (isset($thissurvey['usecaptcha']) && function_exists("ImageCreate") && captcha_enabled('saveandloadscreen', $thissurvey['usecaptcha'])) {
        $_saveform .= "<tr><td align='right'>" . $clang->gT("Security Question") . ":</td><td><table><tr><td valign='middle'><img src='{$captchapath}verification.php?sid={$surveyid}' alt='' /></td><td valign='middle' style='text-align:left'><input type='text' size='5' maxlength='3' name='loadsecurity' value='' /></td></tr></table></td></tr>\n";
    }
    $_saveform .= "<tr><td align='right'></td><td></td></tr>\n" . "<tr><td></td><td><input type='submit'  id='savebutton' name='savesubmit' value='" . $clang->gT("Save Now") . "' /></td></tr>\n" . "</table>";
    $_loadform = "<table><tr><td align='right'>" . $clang->gT("Saved name") . ":</td><td><input type='text' name='loadname' value='";
    if ($loadname) {
        $_loadform .= html_escape(auto_unescape($loadname));
    }
    $_loadform .= "' /></td></tr>\n" . "<tr><td align='right'>" . $clang->gT("Password") . ":</td><td><input type='password' name='loadpass' value='";
    if (isset($loadpass)) {
        $_loadform .= html_escape(auto_unescape($loadpass));
    }
    $_loadform .= "' /></td></tr>\n";
    if (isset($thissurvey['usecaptcha']) && function_exists("ImageCreate") && captcha_enabled('saveandloadscreen', $thissurvey['usecaptcha'])) {
        $_loadform .= "<tr><td align='right'>" . $clang->gT("Security Question") . ":</td><td><table><tr><td valign='middle'><img src='{$captchapath}verification.php?sid={$surveyid}' alt='' /></td><td valign='middle'><input type='text' size='5' maxlength='3' name='loadsecurity' value='' alt=''/></td></tr></table></td></tr>\n";
    }
    $_loadform .= "<tr><td align='right'></td><td></td></tr>\n" . "<tr><td></td><td><input type='submit' id='loadbutton' value='" . $clang->gT("Load Now") . "' /></td></tr></table>\n";
    $_registerform = "<form method='post' action='{$publicurl}/register.php'>\n";
    if (!isset($_REQUEST['lang'])) {
        $_reglang = GetBaseLanguageFromSurveyID($surveyid);
    } else {
        $_reglang = returnglobal('lang');
    }
    $_registerform .= "<input type='hidden' name='lang' value='" . $_reglang . "' />\n";
    $_registerform .= "<input type='hidden' name='sid' value='{$surveyid}' id='sid' />\n";
    $_registerform .= "<table class='register' summary='Registrationform'>\n" . "<tr><td align='right'>" . $clang->gT("First name") . ":</td>" . "<td align='left'><input class='text' type='text' name='register_firstname'";
    if (isset($_POST['register_firstname'])) {
        $_registerform .= " value='" . htmlentities(returnglobal('register_firstname'), ENT_QUOTES, 'UTF-8') . "'";
    }
    $_registerform .= " /></td></tr>" . "<tr><td align='right'>" . $clang->gT("Last name") . ":</td>\n" . "<td align='left'><input class='text' type='text' name='register_lastname'";
    if (isset($_POST['register_lastname'])) {
        $_registerform .= " value='" . htmlentities(returnglobal('register_lastname'), ENT_QUOTES, 'UTF-8') . "'";
    }
    $_registerform .= " /></td></tr>\n" . "<tr><td align='right'>" . $clang->gT("Email address") . ":</td>\n" . "<td align='left'><input class='text' type='text' name='register_email'";
    if (isset($_POST['register_email'])) {
        $_registerform .= " value='" . htmlentities(returnglobal('register_email'), ENT_QUOTES, 'UTF-8') . "'";
    }
    $_registerform .= " /></td></tr>\n";
    if (isset($thissurvey['usecaptcha']) && function_exists("ImageCreate") && captcha_enabled('registrationscreen', $thissurvey['usecaptcha'])) {
        $_registerform .= "<tr><td align='right'>" . $clang->gT("Security Question") . ":</td><td><table><tr><td valign='middle'><img src='{$captchapath}verification.php?sid={$surveyid}' alt='' /></td><td valign='middle'><input type='text' size='5' maxlength='3' name='loadsecurity' value='' /></td></tr></table></td></tr>\n";
    }
    /*      if(isset($thissurvey['attribute1']) && $thissurvey['attribute1'])
             {
             $_registerform .= "<tr><td align='right'>".$thissurvey['attribute1'].":</td>\n"
             ."<td align='left'><input class='text' type='text' name='register_attribute1'";
             if (isset($_POST['register_attribute1']))
             {
             $_registerform .= " value='".htmlentities(returnglobal('register_attribute1'),ENT_QUOTES,'UTF-8')."'";
             }
             $_registerform .= " /></td></tr>\n";
             }
             if(isset($thissurvey['attribute2']) && $thissurvey['attribute2'])
             {
             $_registerform .= "<tr><td align='right'>".$thissurvey['attribute2'].":</td>\n"
             ."<td align='left'><input class='text' type='text' name='register_attribute2'";
             if (isset($_POST['register_attribute2']))
             {
             $_registerform .= " value='".htmlentities(returnglobal('register_attribute2'),ENT_QUOTES,'UTF-8')."'";
             }
             $_registerform .= " /></td></tr>\n";
          } */
    $_registerform .= "<tr><td></td><td><input id='registercontinue' class='submit' type='submit' value='" . $clang->gT("Continue") . "' />" . "</td></tr>\n" . "</table>\n" . "</form>\n";
    if (!is_null($surveyid) && function_exists('doAssessment')) {
        $assessmentdata = doAssessment($surveyid, true);
        $_assessment_current_total = $assessmentdata['total'];
    } else {
        $_assessment_current_total = '';
    }
    if (isset($thissurvey['googleanalyticsapikey']) && trim($thissurvey['googleanalyticsapikey']) != '') {
        $_googleAnalyticsAPIKey = trim($thissurvey['googleanalyticsapikey']);
    } else {
        $_googleAnalyticsAPIKey = trim(getGlobalSetting('googleanalyticsapikey'));
    }
    $_googleAnalyticsStyle = isset($thissurvey['googleanalyticsstyle']) ? $thissurvey['googleanalyticsstyle'] : '0';
    $_googleAnalyticsJavaScript = '';
    if ($_googleAnalyticsStyle != '' && $_googleAnalyticsStyle != 0 && $_googleAnalyticsAPIKey != '') {
        switch ($_googleAnalyticsStyle) {
            case '1':
                // Default Google Tracking
                $_googleAnalyticsJavaScript = <<<EOD
<script type="text/javascript">
  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', '{$_googleAnalyticsAPIKey}']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();
</script>
EOD;
                break;
            case '2':
                // SurveyName-[SID]/[GSEQ]-GroupName - create custom GSEQ based upon page step
                $moveInfo = LimeExpressionManager::GetLastMoveResult();
                if (is_null($moveInfo)) {
                    $gseq = 'welcome';
                } else {
                    if ($moveInfo['finished']) {
                        $gseq = 'finished';
                    } else {
                        if (isset($moveInfo['at_start']) && $moveInfo['at_start']) {
                            $gseq = 'welcome';
                        } else {
                            if (is_null($_groupname)) {
                                $gseq = 'printanswers';
                            } else {
                                $gseq = $moveInfo['gseq'] + 1;
                            }
                        }
                    }
                }
                $_trackURL = htmlentities($thissurvey['name'] . '-[' . $surveyid . ']/[' . $gseq . ']-' . $_groupname, ENT_QUOTES);
                $_googleAnalyticsJavaScript = <<<EOD
<script type="text/javascript">
  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', '{$_googleAnalyticsAPIKey}']);
  _gaq.push(['_trackPageview','{$_trackURL}']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();
</script>
EOD;
                break;
        }
    }
    $_endtext = '';
    if (isset($thissurvey['surveyls_endtext']) && trim($thissurvey['surveyls_endtext']) != '') {
        $_endtext = $thissurvey['surveyls_endtext'];
    }
    // Set the array of replacement variables here - don't include curly braces
    // Please put any conditional logic above this section.  Here below should just be an alphabetical list of replacement values with no embedded logic.
    $coreReplacements = array();
    $coreReplacements['ACTIVE'] = isset($thissurvey['active']) && !($thissurvey['active'] != "Y");
    $coreReplacements['AID'] = $_aid;
    // global
    $coreReplacements['ANSWER'] = $answer;
    // global
    $coreReplacements['ANSWERSCLEARED'] = $clang->gT("Answers Cleared");
    $coreReplacements['ASSESSMENTS'] = $assessments;
    // global
    $coreReplacements['ASSESSMENT_CURRENT_TOTAL'] = $_assessment_current_total;
    $coreReplacements['ASSESSMENT_HEADING'] = $clang->gT("Your Assessment");
    $coreReplacements['CHECKJAVASCRIPT'] = "<noscript><span class='warningjs'>" . $clang->gT("Caution: JavaScript execution is disabled in your browser. You may not be able to answer all questions in this survey. Please, verify your browser parameters.") . "</span></noscript>";
    $coreReplacements['CLEARALL'] = $_clearall;
    $coreReplacements['CLOSEWINDOW'] = "<a href='javascript:%20self.close()'>" . $clang->gT("Close this window") . "</a>";
    $coreReplacements['COMPLETED'] = $completed;
    // global
    $coreReplacements['DATESTAMP'] = $_datestamp;
    $coreReplacements['ENDTEXT'] = $_endtext;
    $coreReplacements['EXPIRY'] = $_dateoutput;
    $coreReplacements['GID'] = $_question_gid;
    $coreReplacements['GOOGLE_ANALYTICS_API_KEY'] = $_googleAnalyticsAPIKey;
    $coreReplacements['GOOGLE_ANALYTICS_JAVASCRIPT'] = $_googleAnalyticsJavaScript;
    $coreReplacements['GROUPDESCRIPTION'] = $_groupdescription;
    $coreReplacements['GROUPNAME'] = $_groupname;
    $coreReplacements['LANG'] = $clang->getlangcode();
    $coreReplacements['LANGUAGECHANGER'] = $languagechanger;
    // global
    $coreReplacements['LOADERROR'] = $errormsg;
    // global
    $coreReplacements['LOADFORM'] = $_loadform;
    $coreReplacements['LOADHEADING'] = $clang->gT("Load A Previously Saved Survey");
    $coreReplacements['LOADMESSAGE'] = $clang->gT("You can load a survey that you have previously saved from this screen.") . "<br />" . $clang->gT("Type in the 'name' you used to save the survey, and the password.") . "<br />";
    $coreReplacements['NAVIGATOR'] = $navigator;
    // global
    $coreReplacements['NOSURVEYID'] = $surveylist['nosid'];
    // global
    $coreReplacements['NUMBEROFQUESTIONS'] = $_totalquestionsAsked;
    $coreReplacements['PASSTHRULABEL'] = '';
    $coreReplacements['PASSTHRUVALUE'] = '';
    $coreReplacements['PERCENTCOMPLETE'] = $percentcomplete;
    // global
    $coreReplacements['PRIVACY'] = $privacy;
    // global
    $coreReplacements['PRIVACYMESSAGE'] = "<span style='font-weight:bold; font-style: italic;'>" . $clang->gT("A Note On Privacy") . "</span><br />" . $clang->gT("This survey is anonymous.") . "<br />" . $clang->gT("The record kept of your survey responses does not contain any identifying information about you unless a specific question in the survey has asked for this. If you have responded to a survey that used an identifying token to allow you to access the survey, you can rest assured that the identifying token is not kept with your responses. It is managed in a separate database, and will only be updated to indicate that you have (or haven't) completed this survey. There is no way of matching identification tokens with survey responses in this survey.");
    $coreReplacements['QID'] = isset($questionNum) ? $questionNum : '';
    $coreReplacements['QUESTION'] = $_question;
    $coreReplacements['QUESTIONHELP'] = $_questionhelp;
    $coreReplacements['QUESTIONHELPPLAINTEXT'] = strip_tags(addslashes($help));
    // global
    $coreReplacements['QUESTION_CLASS'] = $_question_class;
    $coreReplacements['QUESTION_CODE'] = $_question_code;
    $coreReplacements['QUESTION_ESSENTIALS'] = $_question_essentials;
    $coreReplacements['QUESTION_FILE_VALID_MESSAGE'] = $_question_file_valid_message;
    $coreReplacements['QUESTION_HELP'] = $_question_help;
    $coreReplacements['QUESTION_INPUT_ERROR_CLASS'] = $_question_input_error_class;
    $coreReplacements['QUESTION_MANDATORY'] = $_question_mandatory;
    $coreReplacements['QUESTION_MAN_CLASS'] = $_question_man_class;
    $coreReplacements['QUESTION_MAN_MESSAGE'] = $_question_man_message;
    $coreReplacements['QUESTION_NUMBER'] = $_question_number;
    $coreReplacements['QUESTION_TEXT'] = $_question_text;
    $coreReplacements['QUESTION_VALID_MESSAGE'] = $_question_valid_message;
    $coreReplacements['REGISTERERROR'] = $register_errormsg;
    // global
    $coreReplacements['REGISTERFORM'] = $_registerform;
    $coreReplacements['REGISTERMESSAGE1'] = $clang->gT("You must be registered to complete this survey");
    $coreReplacements['REGISTERMESSAGE2'] = $clang->gT("You may register for this survey if you wish to take part.") . "<br />\n" . $clang->gT("Enter your details below, and an email containing the link to participate in this survey will be sent immediately.");
    $coreReplacements['RESTART'] = $_restart;
    $coreReplacements['RETURNTOSURVEY'] = $_return_to_survey;
    $coreReplacements['SAVE'] = $_saveall;
    $coreReplacements['SAVEALERT'] = $_savealert;
    $coreReplacements['SAVEDID'] = $saved_id;
    // global
    $coreReplacements['SAVEERROR'] = $errormsg;
    // global - same as LOADERROR
    $coreReplacements['SAVEFORM'] = $_saveform;
    $coreReplacements['SAVEHEADING'] = $clang->gT("Save Your Unfinished Survey");
    $coreReplacements['SAVEMESSAGE'] = $clang->gT("Enter a name and password for this survey and click save below.") . "<br />\n" . $clang->gT("Your survey will be saved using that name and password, and can be completed later by logging in with the same name and password.") . "<br /><br />\n" . $clang->gT("If you give an email address, an email containing the details will be sent to you.") . "<br /><br />\n" . $clang->gT("After having clicked the save button you can either close this browser window or continue filling out the survey.");
    $coreReplacements['SGQ'] = $_question_sgq;
    $coreReplacements['SID'] = $surveyid;
    // global
    $coreReplacements['SITENAME'] = $sitename;
    // global
    $coreReplacements['SQID'] = $_sqid;
    // global
    $coreReplacements['SUBMITBUTTON'] = $_submitbutton;
    $coreReplacements['SUBMITCOMPLETE'] = "<strong>" . $clang->gT("Thank you!") . "<br /><br />" . $clang->gT("You have completed answering the questions in this survey.") . "</strong><br /><br />" . $clang->gT("Click on 'Submit' now to complete the process and save your answers.");
    $coreReplacements['SUBMITREVIEW'] = $_strreview;
    $coreReplacements['SURVEYCONTACT'] = $_surveycontact;
    $coreReplacements['SURVEYDESCRIPTION'] = isset($thissurvey['description']) ? $thissurvey['description'] : '';
    $coreReplacements['SURVEYFORMAT'] = $surveyformat;
    // global
    $coreReplacements['SURVEYLANGAGE'] = $clang->langcode;
    // this misspelling is kept for legacy reasons
    $coreReplacements['SURVEYLANGUAGE'] = $clang->langcode;
    $coreReplacements['SURVEYLIST'] = $surveylist['list'];
    // global
    $coreReplacements['SURVEYLISTHEADING'] = $surveylist['listheading'];
    // global
    $coreReplacements['SURVEYNAME'] = $thissurvey['name'];
    // global
    $coreReplacements['TEMPLATECSS'] = $_templatecss;
    $coreReplacements['TEMPLATEURL'] = $_templateurl;
    $coreReplacements['THEREAREXQUESTIONS'] = $_therearexquestions;
    if (!$anonymized) {
        $coreReplacements['TOKEN'] = $_token;
    }
    $coreReplacements['URL'] = $_linkreplace;
    $coreReplacements['WELCOME'] = isset($thissurvey['welcome']) ? $thissurvey['welcome'] : '';
    //queXS Addition
    include_once "quexs.php";
    $coreReplacements['IS_INTERVIEWER'] = $interviewer;
    $coreReplacements = array_merge($coreReplacements, quexs_core_replace());
    if (!is_null($replacements) && is_array($replacements)) {
        $doTheseReplacements = array_merge($coreReplacements, $replacements);
        // so $replacements overrides core values
    } else {
        $doTheseReplacements = $coreReplacements;
    }
    // Now do all of the replacements - In rare cases, need to do 3 deep recursion, that that is default
    $line = LimeExpressionManager::ProcessString($line, $questionNum, $doTheseReplacements, false, 3, 1);
    return $line;
}
コード例 #8
0
/**
 * This function replaces keywords in a text and is mainly intended for templates
 * If you use this functions put your replacement strings into the $replacements variable
 * instead of using global variables
 *
 * @param mixed $line Text to search in
 * @param mixed $replacements Array of replacements:  Array( <stringtosearch>=><stringtoreplacewith>
 * @return string  Text with replaced strings
 */
function templatereplace($line, $replacements = array())
{
    global $surveylist, $sitename, $clienttoken, $rooturl;
    global $thissurvey, $imagefiles, $defaulttemplate;
    global $percentcomplete, $move;
    global $groupname, $groupdescription;
    global $question;
    global $answer, $navigator;
    global $help, $totalquestions, $surveyformat;
    global $completed, $register_errormsg;
    global $notanswered, $privacy, $surveyid;
    global $publicurl, $templatedir, $token;
    global $assessments, $s_lang;
    global $errormsg, $clang;
    global $saved_id, $usertemplaterootdir;
    global $totalBoilerplatequestions, $relativeurl;
    global $languagechanger;
    global $printoutput, $captchapath, $loadname;
    // lets sanitize the survey template
    if (isset($thissurvey['templatedir'])) {
        $templatename = $thissurvey['templatedir'];
    } else {
        $templatename = $defaulttemplate;
    }
    $templatename = validate_templatedir($templatename);
    // create absolute template URL and template dir vars
    $templateurl = sGetTemplateURL($templatename) . '/';
    $templatedir = sgetTemplatePath($templatename);
    if (stripos($line, "</head>")) {
        $line = str_ireplace("</head>", "<script type=\"text/javascript\" src=\"{$rooturl}/scripts/survey_runtime.js\"></script>\n" . use_firebug() . "\t</head>", $line);
    }
    // If there are non-bracketed replacements to be made do so above this line.
    // Only continue in this routine if there are bracketed items to replace {}
    if (strpos($line, "{") === false) {
        return $line;
    }
    foreach ($replacements as $replacementkey => $replacementvalue) {
        if (strpos($line, '{' . $replacementkey . '}') !== false) {
            $line = str_replace('{' . $replacementkey . '}', $replacementvalue, $line);
        }
    }
    if (strpos($line, "{SURVEYLISTHEADING}") !== false) {
        $line = str_replace("{SURVEYLISTHEADING}", $surveylist['listheading'], $line);
    }
    if (strpos($line, "{SURVEYLIST}") !== false) {
        $line = str_replace("{SURVEYLIST}", $surveylist['list'], $line);
    }
    if (strpos($line, "{NOSURVEYID}") !== false) {
        $line = str_replace("{NOSURVEYID}", $surveylist['nosid'], $line);
    }
    if (strpos($line, "{SURVEYCONTACT}") !== false) {
        $line = str_replace("{SURVEYCONTACT}", $surveylist['contact'], $line);
    }
    if (strpos($line, "{SITENAME}") !== false) {
        $line = str_replace("{SITENAME}", $sitename, $line);
    }
    if (strpos($line, "{SURVEYLIST}") !== false) {
        $line = str_replace("{SURVEYLIST}", $surveylist, $line);
    }
    if (strpos($line, "{CHECKJAVASCRIPT}") !== false) {
        $line = str_replace("{CHECKJAVASCRIPT}", "<noscript><span class='warningjs'>" . $clang->gT("Caution: JavaScript execution is disabled in your browser. You may not be able to answer all questions in this survey. Please, verify your browser parameters.") . "</span></noscript>", $line);
    }
    if (strpos($line, "{ANSWERTABLE}") !== false) {
        $line = str_replace("{ANSWERTABLE}", $printoutput, $line);
    }
    if (strpos($line, "{SURVEYNAME}") !== false) {
        $line = str_replace("{SURVEYNAME}", $thissurvey['name'], $line);
    }
    if (strpos($line, "{SURVEYDESCRIPTION}") !== false) {
        $line = str_replace("{SURVEYDESCRIPTION}", $thissurvey['description'], $line);
    }
    if (strpos($line, "{WELCOME}") !== false) {
        $line = str_replace("{WELCOME}", $thissurvey['welcome'], $line);
    }
    if (strpos($line, "{LANGUAGECHANGER}") !== false) {
        $line = str_replace("{LANGUAGECHANGER}", $languagechanger, $line);
    }
    if (strpos($line, "{PERCENTCOMPLETE}") !== false) {
        $line = str_replace("{PERCENTCOMPLETE}", $percentcomplete, $line);
    }
    if (strpos($line, "{GROUPNAME}") !== false) {
        $line = str_replace("{GROUPNAME}", $groupname, $line);
    }
    if (strpos($line, "{GROUPDESCRIPTION}") !== false) {
        $line = str_replace("{GROUPDESCRIPTION}", $groupdescription, $line);
    }
    if (is_array($question)) {
        if (strpos($line, "{QUESTION}") !== false) {
            $line = str_replace("{QUESTION}", $question['all'], $line);
        } else {
            if (strpos($line, "{QUESTION_TEXT}") !== false) {
                $line = str_replace("{QUESTION_TEXT}", $question['text'], $line);
            }
            if (strpos($line, "{QUESTION_HELP}") !== false) {
                $line = str_replace("{QUESTION_HELP}", $question['help'], $line);
            }
            if (strpos($line, "{QUESTION_MANDATORY}") !== false) {
                $line = str_replace("{QUESTION_MANDATORY}", $question['mandatory'], $line);
            }
            if (strpos($line, "{QUESTION_MAN_MESSAGE}") !== false) {
                $line = str_replace("{QUESTION_MAN_MESSAGE}", $question['man_message'], $line);
            }
            if (strpos($line, "{QUESTION_VALID_MESSAGE}") !== false) {
                $line = str_replace("{QUESTION_VALID_MESSAGE}", $question['valid_message'], $line);
            }
        }
    } else {
        if (strpos($line, "{QUESTION}") !== false) {
            $line = str_replace("{QUESTION}", $question, $line);
        }
    }
    if (strpos($line, '{QUESTION_ESSENTIALS}') !== false) {
        $line = str_replace('{QUESTION_ESSENTIALS}', $question['essentials'], $line);
    }
    if (strpos($line, '{QUESTION_CLASS}') !== false) {
        $line = str_replace('{QUESTION_CLASS}', $question['class'], $line);
    }
    if (strpos($line, '{QUESTION_MAN_CLASS}') !== false) {
        $line = str_replace('{QUESTION_MAN_CLASS}', $question['man_class'], $line);
    }
    if (strpos($line, "{QUESTION_INPUT_ERROR_CLASS}") !== false) {
        $line = str_replace("{QUESTION_INPUT_ERROR_CLASS}", $question['input_error_class'], $line);
    }
    if (strpos($line, "{QUESTION_CODE}") !== false) {
        $line = str_replace("{QUESTION_CODE}", $question['code'], $line);
    }
    if (strpos($line, "{ANSWER}") !== false) {
        $line = str_replace("{ANSWER}", $answer, $line);
    }
    $totalquestionsAsked = $totalquestions - $totalBoilerplatequestions;
    if ($totalquestionsAsked < 1) {
        if (strpos($line, "{THEREAREXQUESTIONS}") !== false) {
            $line = str_replace("{THEREAREXQUESTIONS}", $clang->gT("There are no questions in this survey"), $line);
        }
        //Singular
    }
    if ($totalquestionsAsked == 1) {
        if (strpos($line, "{THEREAREXQUESTIONS}") !== false) {
            $line = str_replace("{THEREAREXQUESTIONS}", $clang->gT("There is 1 question in this survey"), $line);
        }
        //Singular
    } else {
        if (strpos($line, "{THEREAREXQUESTIONS}") !== false) {
            $line = str_replace("{THEREAREXQUESTIONS}", $clang->gT("There are {NUMBEROFQUESTIONS} questions in this survey."), $line);
        }
        //Note this line MUST be before {NUMBEROFQUESTIONS}
    }
    if (strpos($line, "{NUMBEROFQUESTIONS}") !== false) {
        $line = str_replace("{NUMBEROFQUESTIONS}", $totalquestionsAsked, $line);
    }
    if (strpos($line, "{TOKEN}") !== false) {
        if (isset($token)) {
            $line = str_replace("{TOKEN}", $token, $line);
        } elseif (isset($clienttoken)) {
            $line = str_replace("{TOKEN}", htmlentities($clienttoken, ENT_QUOTES, 'UTF-8'), $line);
        } else {
            $line = str_replace("{TOKEN}", '', $line);
        }
    }
    if (strpos($line, "{SID}") !== false) {
        $line = str_replace("{SID}", $surveyid, $line);
    }
    if (strpos($line, "{EXPIRY}") !== false) {
        $line = str_replace("{EXPIRY}", $thissurvey['expiry'], $line);
    }
    if (strpos($line, "{EXPIRY-DMY}") !== false) {
        $line = str_replace("{EXPIRY-DMY}", date("d-m-Y", strtotime($thissurvey["expiry"])), $line);
    }
    if (strpos($line, "{EXPIRY-MDY}") !== false) {
        $line = str_replace("{EXPIRY-MDY}", date("m-d-Y", strtotime($thissurvey["expiry"])), $line);
    }
    if (strpos($line, "{NAVIGATOR}") !== false) {
        $line = str_replace("{NAVIGATOR}", $navigator, $line);
    }
    if (strpos($line, "{SUBMITBUTTON}") !== false) {
        $submitbutton = "          <input class='submit' type='submit' value=' " . $clang->gT("Submit") . " ' name='move2' onclick=\"javascript:document.limesurvey.move.value = 'movesubmit';\" />";
        $line = str_replace("{SUBMITBUTTON}", $submitbutton, $line);
    }
    if (strpos($line, "{COMPLETED}") !== false) {
        $line = str_replace("{COMPLETED}", $completed, $line);
    }
    if (strpos($line, "{URL}") !== false) {
        if ($thissurvey['surveyls_url'] != "") {
            if (trim($thissurvey['surveyls_urldescription']) != '') {
                $linkreplace = "<a href='{$thissurvey['surveyls_url']}'>{$thissurvey['surveyls_urldescription']}</a>";
            } else {
                $linkreplace = "<a href='{$thissurvey['surveyls_url']}'>{$thissurvey['surveyls_url']}</a>";
            }
        } else {
            $linkreplace = '';
        }
        $line = str_replace("{URL}", $linkreplace, $line);
        $line = str_replace("{SAVEDID}", $saved_id, $line);
        // to activate the SAVEDID in the END URL
        if (isset($clienttoken)) {
            $token = $clienttoken;
        } else {
            $token = '';
        }
        $line = str_replace("{TOKEN}", urlencode($token), $line);
        // to activate the TOKEN in the END URL
        $line = str_replace("{SID}", $surveyid, $line);
        // to activate the SID in the RND URL
    }
    if (strpos($line, "{PRIVACY}") !== false) {
        $line = str_replace("{PRIVACY}", $privacy, $line);
    }
    if (strpos($line, "{PRIVACYMESSAGE}") !== false) {
        $line = str_replace("{PRIVACYMESSAGE}", "<span style='font-weight:bold; font-style: italic;'>" . $clang->gT("A Note On Privacy") . "</span><br />" . $clang->gT("This survey is anonymous.") . "<br />" . $clang->gT("The record kept of your survey responses does not contain any identifying information about you unless a specific question in the survey has asked for this."), $line);
        // If you have responded to a survey that used an identifying token to allow you to access the survey, you can rest assured that the identifying token is not kept with your responses. It is managed in a separate database, and will only be updated to indicate that you have (or haven't) completed this survey. There is no way of matching identification tokens with survey responses in this survey.
    }
    if (strpos($line, "{CLEARALL}") !== false) {
        $clearall = "          <input type='button' name='clearallbtn' value='" . $clang->gT("Exit and Clear Survey") . "' class='clearall' " . "onclick=\"if (confirm('" . $clang->gT("Are you sure you want to clear all your responses?", 'js') . "')) {window.open('{$publicurl}/index.php?sid={$surveyid}&amp;move=clearall&amp;lang=" . $_SESSION['s_lang'];
        if (returnglobal('token')) {
            $clearall .= "&amp;token=" . urlencode(trim(sanitize_xss_string(strip_tags(returnglobal('token')))));
        }
        $clearall .= "', '_top')}\" />";
        $line = str_replace("{CLEARALL}", $clearall, $line);
    }
    // --> START NEW FEATURE - SAVE
    if (strpos($line, "{DATESTAMP}") !== false) {
        if (isset($_SESSION['datestamp'])) {
            $line = str_replace("{DATESTAMP}", $_SESSION['datestamp'], $line);
        } else {
            $line = str_replace("{DATESTAMP}", "-", $line);
        }
    }
    // <-- END NEW FEATURE - SAVE
    if (strpos($line, "{SAVE}") !== false) {
        //Set up save/load feature
        if ($thissurvey['allowsave'] == "Y") {
            // Find out if the user has any saved data
            if ($thissurvey['format'] == 'A') {
                $saveall = "          <input type='submit' name='loadall' value='" . $clang->gT("Load Unfinished Survey") . "' class='saveall' " . ($thissurvey['active'] != "Y" ? "disabled='disabled'" : "") . "/>" . "          <input type='button' name='saveallbtn' value='" . $clang->gT("Resume Later") . "' class='saveall' onclick=\"javascript:document.limesurvey.move.value = this.value;addHiddenField(document.getElementById('limesurvey'),'saveall',this.value);document.getElementById('limesurvey').submit();\" " . ($thissurvey['active'] != "Y" ? "disabled='disabled'" : "") . "/>";
                // Show Save So Far button
            } elseif (!isset($_SESSION['step']) || !$_SESSION['step']) {
                $saveall = "          <input type='submit' name='loadall' value='" . $clang->gT("Load Unfinished Survey") . "' class='saveall' " . ($thissurvey['active'] != "Y" ? "disabled='disabled'" : "") . "/>";
            } elseif (isset($_SESSION['scid']) && (isset($move) && $move == "movelast")) {
                $saveall = "";
            } else {
                $saveall = "          <input type='button' name='saveallbtn' value='" . $clang->gT("Resume Later") . "' class='saveall' onclick=\"javascript:document.limesurvey.move.value = this.value;addHiddenField(document.getElementById('limesurvey'),'saveall',this.value);document.getElementById('limesurvey').submit();\" " . ($thissurvey['active'] != "Y" ? "disabled='disabled'" : "") . "/>";
                // Show Save So Far button
            }
        } else {
            $saveall = "";
        }
        $line = str_replace("{SAVE}", $saveall, $line);
    }
    if (strpos($line, "{TEMPLATEURL}") !== false) {
        $line = str_replace("{TEMPLATEURL}", $templateurl, $line);
    }
    if (strpos($line, "{TEMPLATECSS}") !== false) {
        $templatecss = "<link rel='stylesheet' type='text/css' href='{$templateurl}template.css' />\n";
        if (getLanguageRTL($clang->langcode)) {
            $templatecss .= "<link rel='stylesheet' type='text/css' href='{$templateurl}template-rtl.css' />\n";
        }
        $line = str_replace("{TEMPLATECSS}", $templatecss, $line);
    }
    if (FlattenText($help, true) != '') {
        if (strpos($line, "{QUESTIONHELP}") !== false) {
            if (!isset($helpicon)) {
                if (file_exists($templatedir . '/help.gif')) {
                    $helpicon = $templateurl . 'help.gif';
                } elseif (file_exists($templatedir . '/help.png')) {
                    $helpicon = $templateurl . 'help.png';
                } else {
                    $helpicon = $imagefiles . "/help.gif";
                }
            }
            $line = str_replace("{QUESTIONHELP}", "<img src='{$helpicon}' alt='Help' align='left' />" . $help, $line);
        }
        if (strpos($line, "{QUESTIONHELPPLAINTEXT}") !== false) {
            $line = str_replace("{QUESTIONHELPPLAINTEXT}", strip_tags(addslashes($help)), $line);
        }
    } else {
        if (strpos($line, "{QUESTIONHELP}") !== false) {
            $line = str_replace("{QUESTIONHELP}", $help, $line);
        }
        if (strpos($line, "{QUESTIONHELPPLAINTEXT}") !== false) {
            $line = str_replace("{QUESTIONHELPPLAINTEXT}", strip_tags(addslashes($help)), $line);
        }
    }
    $line = insertansReplace($line);
    if (strpos($line, "{SUBMITCOMPLETE}") !== false) {
        $line = str_replace("{SUBMITCOMPLETE}", "<strong>" . $clang->gT("Thank You!") . "<br /><br />" . $clang->gT("You have completed answering the questions in this survey.") . "</strong><br /><br />" . $clang->gT("Click on 'Submit' now to complete the process and save your answers."), $line);
    }
    if (strpos($line, "{SUBMITREVIEW}") !== false) {
        if (isset($thissurvey['allowprev']) && $thissurvey['allowprev'] == "N") {
            $strreview = "";
        } else {
            $strreview = $clang->gT("If you want to check any of the answers you have made, and/or change them, you can do that now by clicking on the [<< prev] button and browsing through your responses.");
        }
        $line = str_replace("{SUBMITREVIEW}", $strreview, $line);
    }
    $line = tokenReplace($line);
    if (strpos($line, "{ANSWERSCLEARED}") !== false) {
        $line = str_replace("{ANSWERSCLEARED}", $clang->gT("Answers Cleared"), $line);
    }
    if (strpos($line, "{RESTART}") !== false) {
        if ($thissurvey['active'] == "N") {
            $replacetext = "<a href='{$publicurl}/index.php?sid={$surveyid}&amp;newtest=Y";
            if (isset($s_lang) && $s_lang != '') {
                $replacetext .= "&amp;lang=" . $s_lang;
            }
            $replacetext .= "'>" . $clang->gT("Restart this Survey") . "</a>";
            $line = str_replace("{RESTART}", $replacetext, $line);
        } else {
            $restart_extra = "";
            $restart_token = returnglobal('token');
            if (!empty($restart_token)) {
                $restart_extra .= "&amp;token=" . urlencode($restart_token);
            } else {
                $restart_extra = "&amp;newtest=Y";
            }
            if (!empty($_GET['lang'])) {
                $restart_extra .= "&amp;lang=" . returnglobal('lang');
            }
            $line = str_replace("{RESTART}", "<a href='{$publicurl}/index.php?sid={$surveyid}" . $restart_extra . "'>" . $clang->gT("Restart this Survey") . "</a>", $line);
        }
    }
    if (strpos($line, "{CLOSEWINDOW}") !== false) {
        $line = str_replace("{CLOSEWINDOW}", "<a href='javascript:%20self.close()'>" . $clang->gT("Close this Window") . "</a>", $line);
    }
    if (strpos($line, "{SAVEERROR}") !== false) {
        $line = str_replace("{SAVEERROR}", $errormsg, $line);
    }
    if (strpos($line, "{SAVEHEADING}") !== false) {
        $line = str_replace("{SAVEHEADING}", $clang->gT("Save Your Unfinished Survey"), $line);
    }
    if (strpos($line, "{SAVEMESSAGE}") !== false) {
        $line = str_replace("{SAVEMESSAGE}", $clang->gT("Enter a name and password for this survey and click save below.") . "<br />\n" . $clang->gT("Your survey will be saved using that name and password, and can be completed later by logging in with the same name and password.") . "<br /><br />\n" . $clang->gT("If you give an email address, an email containing the details will be sent to you."), $line);
    }
    if (strpos($line, "{RETURNTOSURVEY}") !== false) {
        $savereturn = "<a href='{$relativeurl}/index.php?sid={$surveyid}";
        if (returnglobal('token')) {
            $savereturn .= "&amp;token=" . urlencode(trim(sanitize_xss_string(strip_tags(returnglobal('token')))));
        }
        $savereturn .= "'>" . $clang->gT("Return To Survey") . "</a>";
        $line = str_replace("{RETURNTOSURVEY}", $savereturn, $line);
    }
    if (strpos($line, "{SAVEFORM}") !== false) {
        //SAVE SURVEY DETAILS
        $saveform = "<table><tr><td align='right'>" . $clang->gT("Name") . ":</td><td><input type='text' name='savename' value='";
        if (isset($_POST['savename'])) {
            $saveform .= html_escape(auto_unescape($_POST['savename']));
        }
        $saveform .= "' /></td></tr>\n" . "<tr><td align='right'>" . $clang->gT("Password") . ":</td><td><input type='password' name='savepass' value='";
        if (isset($_POST['savepass'])) {
            $saveform .= html_escape(auto_unescape($_POST['savepass']));
        }
        $saveform .= "' /></td></tr>\n" . "<tr><td align='right'>" . $clang->gT("Repeat Password") . ":</td><td><input type='password' name='savepass2' value='";
        if (isset($_POST['savepass2'])) {
            $saveform .= html_escape(auto_unescape($_POST['savepass2']));
        }
        $saveform .= "' /></td></tr>\n" . "<tr><td align='right'>" . $clang->gT("Your Email") . ":</td><td><input type='text' name='saveemail' value='";
        if (isset($_POST['saveemail'])) {
            $saveform .= html_escape(auto_unescape($_POST['saveemail']));
        }
        $saveform .= "' /></td></tr>\n";
        if (function_exists("ImageCreate") && captcha_enabled('saveandloadscreen', $thissurvey['usecaptcha'])) {
            $saveform .= "<tr><td align='right'>" . $clang->gT("Security Question") . ":</td><td><table><tr><td valign='middle'><img src='{$captchapath}verification.php?sid={$surveyid}' alt='' /></td><td valign='middle' style='text-align:left'><input type='text' size='5' maxlength='3' name='loadsecurity' value='' /></td></tr></table></td></tr>\n";
        }
        $saveform .= "<tr><td align='right'></td><td></td></tr>\n" . "<tr><td></td><td><input type='submit'  id='savebutton' name='savesubmit' value='" . $clang->gT("Save Now") . "' /></td></tr>\n" . "</table>";
        $line = str_replace("{SAVEFORM}", $saveform, $line);
    }
    if (strpos($line, "{LOADERROR}") !== false) {
        $line = str_replace("{LOADERROR}", $errormsg, $line);
    }
    if (strpos($line, "{LOADHEADING}") !== false) {
        $line = str_replace("{LOADHEADING}", $clang->gT("Load A Previously Saved Survey"), $line);
    }
    if (strpos($line, "{LOADMESSAGE}") !== false) {
        $line = str_replace("{LOADMESSAGE}", $clang->gT("You can load a survey that you have previously saved from this screen.") . "<br />" . $clang->gT("Type in the 'name' you used to save the survey, and the password.") . "<br />", $line);
    }
    if (strpos($line, "{LOADFORM}") !== false) {
        //LOAD SURVEY DETAILS
        $loadform = "<table><tr><td align='right'>" . $clang->gT("Saved name") . ":</td><td><input type='text' name='loadname' value='";
        if ($loadname) {
            $loadform .= html_escape(auto_unescape($loadname));
        }
        $loadform .= "' /></td></tr>\n" . "<tr><td align='right'>" . $clang->gT("Password") . ":</td><td><input type='password' name='loadpass' value='";
        if (isset($loadpass)) {
            $loadform .= html_escape(auto_unescape($loadpass));
        }
        $loadform .= "' /></td></tr>\n";
        if (function_exists("ImageCreate") && captcha_enabled('saveandloadscreen', $thissurvey['usecaptcha'])) {
            $loadform .= "<tr><td align='right'>" . $clang->gT("Security Question") . ":</td><td><table><tr><td valign='middle'><img src='{$captchapath}verification.php?sid={$surveyid}' alt='' /></td><td valign='middle'><input type='text' size='5' maxlength='3' name='loadsecurity' value='' alt=''/></td></tr></table></td></tr>\n";
        }
        $loadform .= "<tr><td align='right'></td><td></td></tr>\n" . "<tr><td></td><td><input type='submit' id='loadbutton' value='" . $clang->gT("Load Now") . "' /></td></tr></table>\n";
        $line = str_replace("{LOADFORM}", $loadform, $line);
    }
    //REGISTER SURVEY DETAILS
    if (strpos($line, "{REGISTERERROR}") !== false) {
        $line = str_replace("{REGISTERERROR}", $register_errormsg, $line);
    }
    if (strpos($line, "{REGISTERMESSAGE1}") !== false) {
        $line = str_replace("{REGISTERMESSAGE1}", $clang->gT("You must be registered to complete this survey"), $line);
    }
    if (strpos($line, "{REGISTERMESSAGE2}") !== false) {
        $line = str_replace("{REGISTERMESSAGE2}", $clang->gT("You may register for this survey if you wish to take part.") . "<br />\n" . $clang->gT("Enter your details below, and an email containing the link to participate in this survey will be sent immediately."), $line);
    }
    if (strpos($line, "{REGISTERFORM}") !== false) {
        $registerform = "<form method='post' action='{$publicurl}/register.php'>\n" . "<table class='register' summary='Registrationform'>\n" . "<tr><td align='right'>" . "<input type='hidden' name='sid' value='{$surveyid}' id='sid' />\n" . $clang->gT("First Name") . ":</td>" . "<td align='left'><input class='text' type='text' name='register_firstname'";
        if (isset($_POST['register_firstname'])) {
            $registerform .= " value='" . htmlentities(returnglobal('register_firstname'), ENT_QUOTES, 'UTF-8') . "'";
        }
        $registerform .= " /></td></tr>" . "<tr><td align='right'>" . $clang->gT("Last Name") . ":</td>\n" . "<td align='left'><input class='text' type='text' name='register_lastname'";
        if (isset($_POST['register_lastname'])) {
            $registerform .= " value='" . htmlentities(returnglobal('register_lastname'), ENT_QUOTES, 'UTF-8') . "'";
        }
        $registerform .= " /></td></tr>\n" . "<tr><td align='right'>" . $clang->gT("Email Address") . ":</td>\n" . "<td align='left'><input class='text' type='text' name='register_email'";
        if (isset($_POST['register_email'])) {
            $registerform .= " value='" . htmlentities(returnglobal('register_email'), ENT_QUOTES, 'UTF-8') . "'";
        }
        $registerform .= " /></td></tr>\n";
        if (!isset($_REQUEST['lang'])) {
            $reglang = GetBaseLanguageFromSurveyID($surveyid);
        } else {
            $reglang = returnglobal('lang');
        }
        if (function_exists("ImageCreate") && captcha_enabled('registrationscreen', $thissurvey['usecaptcha'])) {
            $registerform .= "<tr><td align='right'>" . $clang->gT("Security Question") . ":</td><td><table><tr><td valign='middle'><img src='{$captchapath}verification.php?sid={$surveyid}' alt='' /></td><td valign='middle'><input type='text' size='5' maxlength='3' name='loadsecurity' value='' /></td></tr></table></td></tr>\n";
        }
        $registerform .= "<tr><td align='right'><input type='hidden' name='lang' value='" . $reglang . "' /></td><td></td></tr>\n";
        /*      if(isset($thissurvey['attribute1']) && $thissurvey['attribute1'])
                {
                $registerform .= "<tr><td align='right'>".$thissurvey['attribute1'].":</td>\n"
                ."<td align='left'><input class='text' type='text' name='register_attribute1'";
                if (isset($_POST['register_attribute1']))
                {
                $registerform .= " value='".htmlentities(returnglobal('register_attribute1'),ENT_QUOTES,'UTF-8')."'";
                }
                $registerform .= " /></td></tr>\n";
                }
                if(isset($thissurvey['attribute2']) && $thissurvey['attribute2'])
                {
                $registerform .= "<tr><td align='right'>".$thissurvey['attribute2'].":</td>\n"
                ."<td align='left'><input class='text' type='text' name='register_attribute2'";
                if (isset($_POST['register_attribute2']))
                {
                $registerform .= " value='".htmlentities(returnglobal('register_attribute2'),ENT_QUOTES,'UTF-8')."'";
                }
                $registerform .= " /></td></tr>\n";
                }        */
        $registerform .= "<tr><td></td><td><input id='registercontinue' class='submit' type='submit' value='" . $clang->gT("Continue") . "' />" . "</td></tr>\n" . "</table>\n" . "</form>\n";
        $line = str_replace("{REGISTERFORM}", $registerform, $line);
    }
    if (strpos($line, "{ASSESSMENT_CURRENT_TOTAL}") !== false && function_exists('doAssessment')) {
        $assessmentdata = doAssessment($surveyid, true);
        $line = str_replace("{ASSESSMENT_CURRENT_TOTAL}", $assessmentdata['total'], $line);
    }
    if (strpos($line, "{ASSESSMENTS}") !== false) {
        $line = str_replace("{ASSESSMENTS}", $assessments, $line);
    }
    if (strpos($line, "{ASSESSMENT_HEADING}") !== false) {
        $line = str_replace("{ASSESSMENT_HEADING}", $clang->gT("Your Assessment"), $line);
    }
    return $line;
}