public function index()
 {
     $surveyid = intval(App()->request->getQuery('surveyid'));
     $gid = intval(App()->request->getQuery('gid'));
     $qid = intval(App()->request->getQuery('qid'));
     $fieldtype = sanitize_xss_string(App()->request->getQuery('fieldtype'));
     $action = sanitize_xss_string(App()->request->getQuery('action'));
     if (!Yii::app()->session['loginID']) {
         throw new CHttpException(401);
     }
     list($replacementFields, $isInstertAnswerEnabled) = $this->_getReplacementFields($fieldtype, $surveyid);
     if ($isInstertAnswerEnabled === true) {
         //2: Get all other questions that occur before this question that are pre-determined answer types
         $fieldmap = createFieldMap($surveyid, 'full', false, false, getBaseLanguageFromSurveyID($surveyid));
         $surveyInfo = getSurveyInfo($surveyid);
         $surveyformat = $surveyInfo['format'];
         // S, G, A
         //Go through each question until we reach the current one
         //error_log(print_r($qrows,true));
         $questionlist = $this->_getQuestionList($action, $gid, $qid, $fieldmap, $fieldtype, $surveyformat);
         $childQuestions = $this->_getChildQuestions($questionlist);
     }
     $data['countfields'] = count($replacementFields);
     $data['replFields'] = $replacementFields;
     if (isset($childQuestions)) {
         $data['cquestions'] = $childQuestions;
     }
     if (isset($surveyformat)) {
         $data['surveyformat'] = $surveyformat;
     }
     $this->getController()->render('/admin/limeReplacementFields_view', $data);
 }
Пример #2
0
 function index()
 {
     Yii::app()->loadHelper('admin/htmleditor');
     $aData = array('ckLanguage' => sTranslateLangCode2CK(Yii::app()->session['adminlang']), 'sFieldName' => sanitize_xss_string(App()->request->getQuery('name')), 'sFieldText' => sanitize_xss_string(App()->request->getQuery('text')), 'sFieldType' => sanitize_xss_string(App()->request->getQuery('type')), 'sAction' => sanitize_paranoid_string(App()->request->getQuery('action')), 'iSurveyId' => sanitize_int(App()->request->getQuery('sid', 0)), 'iGroupId' => sanitize_int(App()->request->getQuery('gid', 0)), 'iQuestionId' => sanitize_int(App()->request->getQuery('qid', 0)));
     if (!$aData['sFieldName']) {
         $this->getController()->render('/admin/htmleditor/pop_nofields_view', $aData);
     } else {
         $aData['sControlIdEna'] = $aData['sFieldName'] . '_popupctrlena';
         $aData['sControlIdDis'] = $aData['sFieldName'] . '_popupctrldis';
         $aData['toolbarname'] = 'popup';
         $aData['htmlformatoption'] = '';
         if (in_array($aData['sFieldType'], array('email-inv', 'email-reg', 'email-conf', 'email-rem'))) {
             $aData['htmlformatoption'] = ',fullPage:true';
         }
         $this->getController()->render('/admin/htmleditor/pop_editor_view', $aData);
     }
 }
Пример #3
0
    $register_errormsg=$clang->gT("The email you used has already been registered.");
    include "index.php";
    exit;
}

$mayinsert = false;
while ($mayinsert != true)
{
    $newtoken = sRandomChars(15);
    $ntquery = "SELECT * FROM {$dbprefix}tokens_$surveyid WHERE token='$newtoken'";
    $ntresult = $connect->Execute($ntquery); //Checked
    if (!$ntresult->RecordCount()) {$mayinsert = true;}
}

$postfirstname=sanitize_xss_string(strip_tags(returnglobal('register_firstname')));
$postlastname=sanitize_xss_string(strip_tags(returnglobal('register_lastname')));
/*$postattribute1=sanitize_xss_string(strip_tags(returnglobal('register_attribute1')));
 $postattribute2=sanitize_xss_string(strip_tags(returnglobal('register_attribute2')));   */

//Insert new entry into tokens db
$query = "INSERT INTO {$dbprefix}tokens_$surveyid\n"
. "(firstname, lastname, email, emailstatus, token)\n"
. "VALUES (?, ?, ?, ?, ?)";
$result = $connect->Execute($query, array($postfirstname,
$postlastname,
returnglobal('register_email'),
                                          'OK', 
$newtoken)
//                             $postattribute1,   $postattribute2)
) or safe_die ($query."<br />".$connect->ErrorMsg());  //Checked - According to adodb docs the bound variables are quoted automatically
$tid=$connect->Insert_ID("{$dbprefix}tokens_$surveyid","tid");
Пример #4
0
 /**
  * surveypermission::delete()
  * Function responsible to delete a user/usergroup.
  * @param mixed $surveyid
  * @return void
  */
 function delete($surveyid)
 {
     $aData['surveyid'] = $surveyid = sanitize_int($surveyid);
     $aViewUrls = array();
     $action = $_POST['action'];
     $clang = Yii::app()->lang;
     $imageurl = Yii::app()->getConfig('imageurl');
     $postuserid = !empty($_POST['uid']) ? $_POST['uid'] : false;
     $postusergroupid = !empty($_POST['gid']) ? $_POST['gid'] : false;
     if ($action == "delsurveysecurity") {
         $addsummary = "<div class=\"header\">" . $clang->gT("Deleting User") . "</div>\n";
         $addsummary .= "<div class=\"messagebox\">\n";
         $result = Survey::model()->findAll('sid = :sid AND owner_id = :owner_id AND owner_id != :postuserid', array(':sid' => $surveyid, ':owner_id' => Yii::app()->session['loginID'], ':postuserid' => $postuserid));
         if (count($result) > 0 || Yii::app()->session['USER_RIGHT_SUPERADMIN'] == 1) {
             if (isset($postuserid)) {
                 $dbresult = Survey_permissions::model()->deleteAll('uid = :uid AND sid = :sid', array(':uid' => $postuserid, ':sid' => $surveyid));
                 $addsummary .= "<br />" . $clang->gT("Username") . ": " . sanitize_xss_string($_POST['user']) . "<br /><br />\n";
                 $addsummary .= "<div class=\"successheader\">" . $clang->gT("Success!") . "</div>\n";
             } else {
                 $addsummary .= "<div class=\"warningheader\">" . $clang->gT("Could not delete user. User was not supplied.") . "</div>\n";
             }
             $addsummary .= "<br/><input type=\"submit\" onclick=\"window.open('" . $this->getController()->createUrl('admin/surveypermission/sa/view/surveyid/' . $surveyid) . "', '_top')\" value=\"" . $clang->gT("Continue") . "\"/>\n";
         } else {
             accessDenied();
         }
         $addsummary .= "</div>\n";
         $aViewUrls['output'] = $addsummary;
     }
     $this->_renderWrappedTemplate('authentication', $aViewUrls, $aData);
 }
Пример #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
 /**
  * surveypermission::delete()
  * Function responsible to delete a user/usergroup.
  * @param mixed $surveyid
  * @return void
  */
 function delete($surveyid)
 {
     $aData['surveyid'] = $surveyid = sanitize_int($surveyid);
     $aViewUrls = array();
     $action = App()->getRequest()->getParam('action');
     $imageurl = Yii::app()->getConfig('imageurl');
     $uid = App()->getRequest()->getParam('uid');
     $gid = App()->getRequest()->getParam('gid');
     $postuserid = !empty($uid) ? $uid : false;
     $postusergroupid = !empty($gid) ? $gid : false;
     // Not used
     $userList = getUserList('onlyuidarray');
     if ($postuserid && !in_array($postuserid, $userList)) {
         $this->getController()->error('Access denied');
     } elseif ($postusergroupid && !in_array($postusergroupid, $userList)) {
         $this->getController()->error('Access denied');
     }
     if ($action == "delsurveysecurity") {
         $addsummary = "<div id='edit-permission' class='side-body " . getSideBodyClass(false) . "'>";
         $addsummary .= '<div class="row"><div class="col-lg-12 content-right">';
         $addsummary .= "<div class=\"jumbotron message-box\">\n";
         $addsummary .= "<h2>" . gT("Deleting User") . "</h2>\n";
         if (Permission::model()->hasSurveyPermission($surveyid, 'surveysecurity', 'delete')) {
             if (isset($postuserid)) {
                 $dbresult = Permission::model()->deleteAll("uid = :uid AND entity_id = :sid AND entity = 'survey'", array(':uid' => $postuserid, ':sid' => $surveyid));
                 $addsummary .= "<br />" . gT("Username") . ": " . sanitize_xss_string(App()->getRequest()->getParam('user')) . "<br /><br />\n";
                 $addsummary .= "<div class=\"successheader\">" . gT("Success!") . "</div>\n";
             } else {
                 $addsummary .= "<div class=\"warningheader\">" . gT("Could not delete user. User was not supplied.") . "</div>\n";
             }
             $addsummary .= "<br/><input class='btn btn-default'  type=\"submit\" onclick=\"window.open('" . $this->getController()->createUrl('admin/surveypermission/sa/view/surveyid/' . $surveyid) . "', '_top')\" value=\"" . gT("Continue") . "\"/>\n";
         } else {
             $this->getController()->error('Access denied');
         }
         $addsummary .= "</div></div></div>\n";
         $aViewUrls['output'] = $addsummary;
     }
     $aData['sidemenu']['state'] = false;
     $surveyinfo = Survey::model()->findByPk($surveyid)->surveyinfo;
     $aData['title_bar']['title'] = $surveyinfo['surveyls_title'] . "(" . gT("ID") . ":" . $surveyid . ")";
     //$aData['surveybar']['savebutton']['form'] = 'frmeditgroup';
     //$aData['surveybar']['closebutton']['url'] = 'admin/survey/sa/view/surveyid/'.$surveyid;
     $this->_renderWrappedTemplate('authentication', $aViewUrls, $aData);
 }
Пример #7
0
 /**
  * surveypermission::delete()
  * Function responsible to delete a user/usergroup.
  * @param mixed $surveyid
  * @return void
  */
 function delete($surveyid)
 {
     $aData['surveyid'] = $surveyid = sanitize_int($surveyid);
     $aViewUrls = array();
     $action = $_POST['action'];
     $imageurl = Yii::app()->getConfig('imageurl');
     $postuserid = !empty($_POST['uid']) ? $_POST['uid'] : false;
     $postusergroupid = !empty($_POST['gid']) ? $_POST['gid'] : false;
     // Not used
     if ($postuserid && !in_array($postuserid, getUserList('onlyuidarray'))) {
         $this->getController()->error('Access denied');
     } elseif ($postusergroupid && !in_array($postusergroupid, getUserList('onlyuidarray'))) {
         $this->getController()->error('Access denied');
     }
     if ($action == "delsurveysecurity") {
         $addsummary = "<div class=\"header\">" . gT("Deleting User") . "</div>\n";
         $addsummary .= "<div class=\"messagebox\">\n";
         if (Permission::model()->hasSurveyPermission($surveyid, 'surveysecurity', 'delete')) {
             if (isset($postuserid)) {
                 $dbresult = Permission::model()->deleteAll("uid = :uid AND entity_id = :sid AND entity = 'survey'", array(':uid' => $postuserid, ':sid' => $surveyid));
                 $addsummary .= "<br />" . gT("Username") . ": " . sanitize_xss_string($_POST['user']) . "<br /><br />\n";
                 $addsummary .= "<div class=\"successheader\">" . gT("Success!") . "</div>\n";
             } else {
                 $addsummary .= "<div class=\"warningheader\">" . gT("Could not delete user. User was not supplied.") . "</div>\n";
             }
             $addsummary .= "<br/><input type=\"submit\" onclick=\"window.open('" . $this->getController()->createUrl('admin/surveypermission/sa/view/surveyid/' . $surveyid) . "', '_top')\" value=\"" . gT("Continue") . "\"/>\n";
         } else {
             $this->getController()->error('Access denied');
         }
         $addsummary .= "</div>\n";
         $aViewUrls['output'] = $addsummary;
     }
     $this->_renderWrappedTemplate('authentication', $aViewUrls, $aData);
 }
 /**
  * register::index()
  * Process register form data and take appropriate action
  * @return
  */
 function actionIndex($iSurveyID = null)
 {
     Yii::app()->loadHelper('database');
     Yii::app()->loadHelper('replacements');
     $sLanguage = Yii::app()->request->getParam('lang', '');
     if ($iSurveyID == null) {
         $iSurveyID = Yii::app()->request->getPost('sid');
     }
     if (!$iSurveyID) {
         $this->redirect(Yii::app()->baseUrl);
     }
     if ($sLanguage == "") {
         $sBaseLanguage = Survey::model()->findByPk($iSurveyID)->language;
     } else {
         $sBaseLanguage = $sLanguage;
     }
     Yii::import('application.libraries.Limesurvey_lang');
     Yii::app()->lang = new Limesurvey_lang($sBaseLanguage);
     $clang = Yii::app()->lang;
     $thissurvey = getSurveyInfo($iSurveyID, $sBaseLanguage);
     $register_errormsg = "";
     // Check the security question's answer
     if (function_exists("ImageCreate") && isCaptchaEnabled('registrationscreen', $thissurvey['usecaptcha'])) {
         if (!isset($_POST['loadsecurity']) || !isset($_SESSION['survey_' . $iSurveyID]['secanswer']) || Yii::app()->request->getPost('loadsecurity') != $_SESSION['survey_' . $iSurveyID]['secanswer']) {
             $register_errormsg .= $clang->gT("The answer to the security question is incorrect.") . "<br />\n";
         }
     }
     //Check that the email is a valid style address
     if (!validateEmailAddress(Yii::app()->request->getPost('register_email'))) {
         $register_errormsg .= $clang->gT("The email you used is not valid. Please try again.");
     }
     // Check for additional fields
     $attributeinsertdata = array();
     foreach (GetParticipantAttributes($iSurveyID) as $field => $data) {
         if (empty($data['show_register']) || $data['show_register'] != 'Y') {
             continue;
         }
         $value = sanitize_xss_string(Yii::app()->request->getPost('register_' . $field));
         if (trim($value) == '' && $data['mandatory'] == 'Y') {
             $register_errormsg .= sprintf($clang->gT("%s cannot be left empty"), $thissurvey['attributecaptions'][$field]);
         }
         $attributeinsertdata[$field] = $value;
     }
     if ($register_errormsg != "") {
         $_SESSION['survey_' . $iSurveyID]['register_errormsg'] = $register_errormsg;
         $this->redirect($this->createUrl("survey/index/sid/{$iSurveyID}", array('lang' => $sBaseLanguage)));
     }
     //Check if this email already exists in token database
     $oToken = TokenDynamic::model($iSurveyID)->find('email=:email', array(':email' => Yii::app()->request->getPost('register_email')));
     if ($oToken) {
         $register_errormsg = $clang->gT("The email you used has already been registered.");
         $_SESSION['survey_' . $iSurveyID]['register_errormsg'] = $register_errormsg;
         $this->redirect($this->createUrl("survey/index/sid/{$iSurveyID}", array('lang' => $sBaseLanguage)));
         //include "index.php";
         //exit;
     }
     $mayinsert = false;
     // Get the survey settings for token length
     $tokenlength = $thissurvey['tokenlength'];
     //if tokenlength is not set or there are other problems use the default value (15)
     if (!isset($tokenlength) || $tokenlength == '') {
         $tokenlength = 15;
     }
     while ($mayinsert != true) {
         $newtoken = randomChars($tokenlength);
         $oTokenExist = TokenDynamic::model($iSurveyID)->find('token=:token', array(':token' => $newtoken));
         if (!$oTokenExist) {
             $mayinsert = true;
         }
     }
     $postfirstname = sanitize_xss_string(strip_tags(Yii::app()->request->getPost('register_firstname')));
     $postlastname = sanitize_xss_string(strip_tags(Yii::app()->request->getPost('register_lastname')));
     $starttime = sanitize_xss_string(Yii::app()->request->getPost('startdate'));
     $endtime = sanitize_xss_string(Yii::app()->request->getPost('enddate'));
     /*$postattribute1=sanitize_xss_string(strip_tags(returnGlobal('register_attribute1')));
       $postattribute2=sanitize_xss_string(strip_tags(returnGlobal('register_attribute2')));   */
     // Insert new entry into tokens db
     $oToken = Token::create($thissurvey['sid']);
     $oToken->firstname = $postfirstname;
     $oToken->lastname = $postlastname;
     $oToken->email = Yii::app()->request->getPost('register_email');
     $oToken->emailstatus = 'OK';
     $oToken->token = $newtoken;
     if ($starttime && $endtime) {
         $oToken->validfrom = $starttime;
         $oToken->validuntil = $endtime;
     }
     $oToken->setAttributes($attributeinsertdata, false);
     $result = $oToken->save();
     //$tid = $oToken->tid;// Not needed any more
     $fieldsarray["{ADMINNAME}"] = $thissurvey['adminname'];
     $fieldsarray["{ADMINEMAIL}"] = $thissurvey['adminemail'];
     $fieldsarray["{SURVEYNAME}"] = $thissurvey['name'];
     $fieldsarray["{SURVEYDESCRIPTION}"] = $thissurvey['description'];
     $fieldsarray["{FIRSTNAME}"] = $postfirstname;
     $fieldsarray["{LASTNAME}"] = $postlastname;
     $fieldsarray["{EXPIRY}"] = $thissurvey["expiry"];
     $fieldsarray["{TOKEN}"] = $oToken->token;
     $fieldsarray["{EMAIL}"] = $oToken->email;
     $token = $oToken->token;
     $message = $thissurvey['email_register'];
     $subject = $thissurvey['email_register_subj'];
     $from = "{$thissurvey['adminname']} <{$thissurvey['adminemail']}>";
     $surveylink = $this->createAbsoluteUrl("/survey/index/sid/{$iSurveyID}", array('lang' => $sBaseLanguage, 'token' => $newtoken));
     $optoutlink = $this->createAbsoluteUrl("/optout/tokens/surveyid/{$iSurveyID}", array('langcode' => $sBaseLanguage, 'token' => $newtoken));
     $optinlink = $this->createAbsoluteUrl("/optin/tokens/surveyid/{$iSurveyID}", array('langcode' => $sBaseLanguage, 'token' => $newtoken));
     if (getEmailFormat($iSurveyID) == 'html') {
         $useHtmlEmail = true;
         $fieldsarray["{SURVEYURL}"] = "<a href='{$surveylink}'>" . $surveylink . "</a>";
         $fieldsarray["{OPTOUTURL}"] = "<a href='{$optoutlink}'>" . $optoutlink . "</a>";
         $fieldsarray["{OPTINURL}"] = "<a href='{$optinlink}'>" . $optinlink . "</a>";
     } else {
         $useHtmlEmail = false;
         $fieldsarray["{SURVEYURL}"] = $surveylink;
         $fieldsarray["{OPTOUTURL}"] = $optoutlink;
         $fieldsarray["{OPTINURL}"] = $optinlink;
     }
     $message = ReplaceFields($message, $fieldsarray);
     $subject = ReplaceFields($subject, $fieldsarray);
     $html = "";
     //Set variable
     $sitename = Yii::app()->getConfig('sitename');
     if (SendEmailMessage($message, $subject, Yii::app()->request->getPost('register_email'), $from, $sitename, $useHtmlEmail, getBounceEmail($iSurveyID))) {
         // TLR change to put date into sent
         $today = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i", Yii::app()->getConfig('timeadjust'));
         $oToken->sent = $today;
         $oToken->save();
         $html = "<div id='wrapper' class='message tokenmessage'>" . "<p>" . $clang->gT("Thank you for registering to participate in this survey.") . "</p>\n" . "<p>" . $clang->gT("An email has been sent to the address you provided with access details for this survey. Please follow the link in that email to proceed.") . "</p>\n" . "<p>" . $clang->gT("Survey administrator") . " {ADMINNAME} ({ADMINEMAIL})</p>" . "</div>\n";
         $html = ReplaceFields($html, $fieldsarray);
     } else {
         $html = "Email Error";
     }
     //PRINT COMPLETED PAGE
     if (!$thissurvey['template']) {
         $thistpl = getTemplatePath(validateTemplateDir('default'));
     } else {
         $thistpl = getTemplatePath(validateTemplateDir($thissurvey['template']));
     }
     // Same fix than http://bugs.limesurvey.org/view.php?id=8441
     ob_start(function ($buffer, $phase) {
         App()->getClientScript()->render($buffer);
         App()->getClientScript()->reset();
         return $buffer;
     });
     ob_implicit_flush(false);
     sendCacheHeaders();
     doHeader();
     Yii::app()->lang = $clang;
     // fetch the defined variables and pass it to the header footer templates.
     $redata = compact(array_keys(get_defined_vars()));
     $this->_printTemplateContent($thistpl . '/startpage.pstpl', $redata, __LINE__);
     $this->_printTemplateContent($thistpl . '/survey.pstpl', $redata, __LINE__);
     echo $html;
     $this->_printTemplateContent($thistpl . '/endpage.pstpl', $redata, __LINE__);
     doFooter();
     ob_flush();
 }
Пример #9
0
 /**
  * register::index()
  * Process register form data and take appropriate action
  * @return
  */
 function actionIndex($surveyid = null)
 {
     Yii::app()->loadHelper('database');
     Yii::app()->loadHelper('replacements');
     $postlang = Yii::app()->request->getPost('lang');
     if ($surveyid == null) {
         $surveyid = Yii::app()->request->getPost('sid');
     }
     if (!$surveyid) {
         Yii::app()->request->redirect(Yii::app()->baseUrl);
     }
     // Get passed language from form, so that we dont loose this!
     if (!isset($postlang) || $postlang == "" || !$postlang) {
         $baselang = Survey::model()->findByPk($surveyid)->language;
         Yii::import('application.libraries.Limesurvey_lang');
         Yii::app()->lang = new Limesurvey_lang($baselang);
         $clang = Yii::app()->lang;
     } else {
         Yii::import('application.libraries.Limesurvey_lang');
         Yii::app()->lang = new Limesurvey_lang($postlang);
         $clang = Yii::app()->lang;
         $baselang = $postlang;
     }
     $thissurvey = getSurveyInfo($surveyid, $baselang);
     $register_errormsg = "";
     // Check the security question's answer
     if (function_exists("ImageCreate") && isCaptchaEnabled('registrationscreen', $thissurvey['usecaptcha'])) {
         if (!isset($_POST['loadsecurity']) || !isset($_SESSION['survey_' . $surveyid]['secanswer']) || Yii::app()->request->getPost('loadsecurity') != $_SESSION['survey_' . $surveyid]['secanswer']) {
             $register_errormsg .= $clang->gT("The answer to the security question is incorrect.") . "<br />\n";
         }
     }
     //Check that the email is a valid style address
     if (!validateEmailAddress(Yii::app()->request->getPost('register_email'))) {
         $register_errormsg .= $clang->gT("The email you used is not valid. Please try again.");
     }
     // Check for additional fields
     $attributeinsertdata = array();
     foreach (GetParticipantAttributes($surveyid) as $field => $data) {
         if (empty($data['show_register']) || $data['show_register'] != 'Y') {
             continue;
         }
         $value = sanitize_xss_string(Yii::app()->request->getPost('register_' . $field));
         if (trim($value) == '' && $data['mandatory'] == 'Y') {
             $register_errormsg .= sprintf($clang->gT("%s cannot be left empty"), $thissurvey['attributecaptions'][$field]);
         }
         $attributeinsertdata[$field] = $value;
     }
     if ($register_errormsg != "") {
         $_SESSION['survey_' . $surveyid]['register_errormsg'] = $register_errormsg;
         Yii::app()->request->redirect(Yii::app()->createUrl('survey/index/sid/' . $surveyid));
     }
     //Check if this email already exists in token database
     $query = "SELECT email FROM {{tokens_{$surveyid}}}\n" . "WHERE email = '" . sanitize_email(Yii::app()->request->getPost('register_email')) . "'";
     $usrow = Yii::app()->db->createCommand($query)->queryRow();
     if ($usrow) {
         $register_errormsg = $clang->gT("The email you used has already been registered.");
         $_SESSION['survey_' . $surveyid]['register_errormsg'] = $register_errormsg;
         Yii::app()->request->redirect(Yii::app()->createUrl('survey/index/sid/' . $surveyid));
         //include "index.php";
         //exit;
     }
     $mayinsert = false;
     // Get the survey settings for token length
     //$this->load->model("surveys_model");
     $tlresult = Survey::model()->findAllByAttributes(array("sid" => $surveyid));
     if (isset($tlresult[0])) {
         $tlrow = $tlresult[0];
     } else {
         $tlrow = $tlresult;
     }
     $tokenlength = $tlrow['tokenlength'];
     //if tokenlength is not set or there are other problems use the default value (15)
     if (!isset($tokenlength) || $tokenlength == '') {
         $tokenlength = 15;
     }
     while ($mayinsert != true) {
         $newtoken = randomChars($tokenlength);
         $ntquery = "SELECT * FROM {{tokens_{$surveyid}}} WHERE token='{$newtoken}'";
         $usrow = Yii::app()->db->createCommand($ntquery)->queryRow();
         if (!$usrow) {
             $mayinsert = true;
         }
     }
     $postfirstname = sanitize_xss_string(strip_tags(Yii::app()->request->getPost('register_firstname')));
     $postlastname = sanitize_xss_string(strip_tags(Yii::app()->request->getPost('register_lastname')));
     $starttime = sanitize_xss_string(Yii::app()->request->getPost('startdate'));
     $endtime = sanitize_xss_string(Yii::app()->request->getPost('enddate'));
     /*$postattribute1=sanitize_xss_string(strip_tags(returnGlobal('register_attribute1')));
       $postattribute2=sanitize_xss_string(strip_tags(returnGlobal('register_attribute2')));   */
     // Insert new entry into tokens db
     Tokens_dynamic::sid($thissurvey['sid']);
     $token = new Tokens_dynamic();
     $token->firstname = $postfirstname;
     $token->lastname = $postlastname;
     $token->email = Yii::app()->request->getPost('register_email');
     $token->emailstatus = 'OK';
     $token->token = $newtoken;
     if ($starttime && $endtime) {
         $token->validfrom = $starttime;
         $token->validuntil = $endtime;
     }
     foreach ($attributeinsertdata as $k => $v) {
         $token->{$k} = $v;
     }
     $result = $token->save();
     /**
     $result = $connect->Execute($query, array($postfirstname,
     $postlastname,
     returnGlobal('register_email'),
     'OK',
     $newtoken)
     
     //                             $postattribute1,   $postattribute2)
     ) or safeDie ($query."<br />".$connect->ErrorMsg());  //Checked - According to adodb docs the bound variables are quoted automatically
     */
     $tid = getLastInsertID($token->tableName());
     $fieldsarray["{ADMINNAME}"] = $thissurvey['adminname'];
     $fieldsarray["{ADMINEMAIL}"] = $thissurvey['adminemail'];
     $fieldsarray["{SURVEYNAME}"] = $thissurvey['name'];
     $fieldsarray["{SURVEYDESCRIPTION}"] = $thissurvey['description'];
     $fieldsarray["{FIRSTNAME}"] = $postfirstname;
     $fieldsarray["{LASTNAME}"] = $postlastname;
     $fieldsarray["{EXPIRY}"] = $thissurvey["expiry"];
     $message = $thissurvey['email_register'];
     $subject = $thissurvey['email_register_subj'];
     $from = "{$thissurvey['adminname']} <{$thissurvey['adminemail']}>";
     if (getEmailFormat($surveyid) == 'html') {
         $useHtmlEmail = true;
         $surveylink = $this->createAbsoluteUrl($surveyid . '/lang-' . $baselang . '/tk-' . $newtoken);
         $optoutlink = $this->createAbsoluteUrl('optout/local/' . $surveyid . '/' . $baselang . '/' . $newtoken);
         $optinlink = $this->createAbsoluteUrl('optin/local/' . $surveyid . '/' . $baselang . '/' . $newtoken);
         $fieldsarray["{SURVEYURL}"] = "<a href='{$surveylink}'>" . $surveylink . "</a>";
         $fieldsarray["{OPTOUTURL}"] = "<a href='{$optoutlink}'>" . $optoutlink . "</a>";
         $fieldsarray["{OPTINURL}"] = "<a href='{$optinlink}'>" . $optinlink . "</a>";
     } else {
         $useHtmlEmail = false;
         $fieldsarray["{SURVEYURL}"] = $this->createAbsoluteUrl('' . $surveyid . '/lang-' . $baselang . '/tk-' . $newtoken);
         $fieldsarray["{OPTOUTURL}"] = $this->createAbsoluteUrl('optout/local/' . $surveyid . '/' . $baselang . '/' . $newtoken);
         $fieldsarray["{OPTINURL}"] = $this->createAbsoluteUrl('optin/local/' . $surveyid . '/' . $baselang . '/' . $newtoken);
     }
     $message = ReplaceFields($message, $fieldsarray);
     $subject = ReplaceFields($subject, $fieldsarray);
     $html = "";
     //Set variable
     $sitename = Yii::app()->getConfig('sitename');
     if (SendEmailMessage($message, $subject, Yii::app()->request->getPost('register_email'), $from, $sitename, $useHtmlEmail, getBounceEmail($surveyid))) {
         // TLR change to put date into sent
         $today = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i", Yii::app()->getConfig('timeadjust'));
         $query = "UPDATE {{tokens_{$surveyid}}}\n" . "SET sent='{$today}' WHERE tid={$tid}";
         $result = dbExecuteAssoc($query) or show_error("Unable to execute this query : {$query}<br />");
         //Checked
         $html = "<center>" . $clang->gT("Thank you for registering to participate in this survey.") . "<br /><br />\n" . $clang->gT("An email has been sent to the address you provided with access details for this survey. Please follow the link in that email to proceed.") . "<br /><br />\n" . $clang->gT("Survey administrator") . " {ADMINNAME} ({ADMINEMAIL})";
         $html = ReplaceFields($html, $fieldsarray);
         $html .= "<br /><br /></center>\n";
     } else {
         $html = "Email Error";
     }
     //PRINT COMPLETED PAGE
     if (!$thissurvey['template']) {
         $thistpl = getTemplatePath(validateTemplateDir('default'));
     } else {
         $thistpl = getTemplatePath(validateTemplateDir($thissurvey['template']));
     }
     sendCacheHeaders();
     doHeader();
     Yii::app()->lang = $clang;
     // fetch the defined variables and pass it to the header footer templates.
     $redata = compact(array_keys(get_defined_vars()));
     $this->_printTemplateContent($thistpl . '/startpage.pstpl', $redata, __LINE__);
     $this->_printTemplateContent($thistpl . '/survey.pstpl', $redata, __LINE__);
     echo $html;
     $this->_printTemplateContent($thistpl . '/endpage.pstpl', $redata, __LINE__);
     doFooter();
 }
Пример #10
0
/**
* This function builds all the required session variables when a survey is first started and
* it loads any answer defaults from command line or from the table defaultvalues
* It is called from the related format script (group.php, question.php, survey.php)
* if the survey has just started.
*
* @returns  $totalquestions Total number of questions in the survey
*
*/
function buildsurveysession()
{
    global $thissurvey, $secerror, $clienttoken;
    global $tokensexist, $thistpl;
    global $surveyid, $dbprefix, $connect;
    global $register_errormsg, $clang;
    global $totalBoilerplatequestions;
    global $templang, $move, $rooturl, $publicurl;
    if (!isset($templang) || $templang == '') {
        $templang = $thissurvey['language'];
    }
    $totalBoilerplatequestions = 0;
    // NO TOKEN REQUIRED BUT CAPTCHA ENABLED FOR SURVEY ACCESS
    if ($tokensexist == 0 && captcha_enabled('surveyaccessscreen', $thissurvey['usecaptcha'])) {
        // IF CAPTCHA ANSWER IS NOT CORRECT OR NOT SET
        if (!isset($_GET['loadsecurity']) || !isset($_SESSION['secanswer']) || $_GET['loadsecurity'] != $_SESSION['secanswer']) {
            sendcacheheaders();
            doHeader();
            // No or bad answer to required security question
            echo templatereplace(file_get_contents("{$thistpl}/startpage.pstpl"));
            //echo makedropdownlist();
            echo templatereplace(file_get_contents("{$thistpl}/survey.pstpl"));
            if (isset($_GET['loadsecurity'])) {
                // was a bad answer
                echo "<font color='#FF0000'>" . $clang->gT("The answer to the security question is incorrect.") . "</font><br />";
            }
            echo "<p class='captcha'>" . $clang->gT("Please confirm access to survey by answering the security question below and click continue.") . "</p>\n\t\t\t        <form class='captcha' method='get' action='{$publicurl}/index.php'>\n\t\t\t        <table align='center'>\n\t\t\t\t        <tr>\n\t\t\t\t\t        <td align='right' valign='middle'>\n\t\t\t\t\t        <input type='hidden' name='sid' value='" . $surveyid . "' id='sid' />\n\t\t\t\t\t        <input type='hidden' name='lang' value='" . $templang . "' id='lang' />";
            // In case we this is a direct Reload previous answers URL, then add hidden fields
            if (isset($_GET['loadall']) && isset($_GET['scid']) && isset($_GET['loadname']) && isset($_GET['loadpass'])) {
                echo "\n\t\t\t\t\t\t<input type='hidden' name='loadall' value='" . htmlspecialchars($_GET['loadall']) . "' id='loadall' />\n\t\t\t\t\t\t<input type='hidden' name='scid' value='" . returnglobal('scid') . "' id='scid' />\n\t\t\t\t\t\t<input type='hidden' name='loadname' value='" . htmlspecialchars($_GET['loadname']) . "' id='loadname' />\n\t\t\t\t\t\t<input type='hidden' name='loadpass' value='" . htmlspecialchars($_GET['loadpass']) . "' id='loadpass' />";
            }
            echo "\n\t\t\t\t        </td>\n\t\t\t        </tr>";
            if (function_exists("ImageCreate") && captcha_enabled('surveyaccessscreen', $thissurvey['usecaptcha'])) {
                echo "<tr>\n\t\t\t\t                <td align='center' valign='middle'><label for='captcha'>" . $clang->gT("Security question:") . "</label></td><td align='left' valign='middle'><table><tr><td valign='middle'><img src='{$rooturl}/verification.php?sid={$surveyid}' alt='captcha' /></td>\n                                <td valign='middle'><input id='captcha' type='text' size='5' maxlength='3' name='loadsecurity' value='' /></td></tr></table>\n\t\t\t\t                </td>\n\t\t\t                </tr>";
            }
            echo "<tr><td colspan='2' align='center'><input class='submit' type='submit' value='" . $clang->gT("Continue") . "' /></td></tr>\n\t\t        </table>\n\t\t        </form>";
            echo templatereplace(file_get_contents("{$thistpl}/endpage.pstpl"));
            doFooter();
            exit;
        }
    }
    //BEFORE BUILDING A NEW SESSION FOR THIS SURVEY, LET'S CHECK TO MAKE SURE THE SURVEY SHOULD PROCEED!
    // TOKEN REQUIRED BUT NO TOKEN PROVIDED
    if ($tokensexist == 1 && !returnglobal('token')) {
        // DISPLAY REGISTER-PAGE if needed
        // DISPLAY CAPTCHA if needed
        sendcacheheaders();
        doHeader();
        echo templatereplace(file_get_contents("{$thistpl}/startpage.pstpl"));
        //echo makedropdownlist();
        echo templatereplace(file_get_contents("{$thistpl}/survey.pstpl"));
        if (isset($thissurvey) && $thissurvey['allowregister'] == "Y") {
            echo templatereplace(file_get_contents("{$thistpl}/register.pstpl"));
        } else {
            if (isset($secerror)) {
                echo "<span class='error'>" . $secerror . "</span><br />";
            }
            echo '<div id="wrapper"><p id="tokenmessage">' . $clang->gT("This is a controlled survey. You need a valid token to participate.") . "<br />";
            echo $clang->gT("If you have been issued a token, please enter it in the box below and click continue.") . "</p>\n            <script type='text/javascript'>var focus_element='#token';</script>\n\t        <form id='tokenform' method='get' action='{$publicurl}/index.php'>\n\n                <ul>\n                <li>\n                    <label for='token'>" . $clang->gT("Token") . "</label><input class='text' id='token' type='text' name='token' />\n                <input type='hidden' name='sid' value='" . $surveyid . "' id='sid' />\n\t\t\t\t<input type='hidden' name='lang' value='" . $templang . "' id='lang' />";
            if (isset($_GET['newtest']) && ($_GET['newtest'] = "Y")) {
                echo "  <input type='hidden' name='newtest' value='Y' id='newtest' />";
            }
            // If this is a direct Reload previous answers URL, then add hidden fields
            if (isset($_GET['loadall']) && isset($_GET['scid']) && isset($_GET['loadname']) && isset($_GET['loadpass'])) {
                echo "\n\t\t\t\t\t<input type='hidden' name='loadall' value='" . htmlspecialchars($_GET['loadall']) . "' id='loadall' />\n\t\t\t\t\t<input type='hidden' name='scid' value='" . returnglobal('scid') . "' id='scid' />\n\t\t\t\t\t<input type='hidden' name='loadname' value='" . htmlspecialchars($_GET['loadname']) . "' id='loadname' />\n\t\t\t\t\t<input type='hidden' name='loadpass' value='" . htmlspecialchars($_GET['loadpass']) . "' id='loadpass' />";
            }
            echo "</li>";
            if (function_exists("ImageCreate") && captcha_enabled('surveyaccessscreen', $thissurvey['usecaptcha'])) {
                echo "<li>\n\t\t\t                <label for='captchaimage'>" . $clang->gT("Security Question") . "</label><img id='captchaimage' src='{$rooturl}/verification.php?sid={$surveyid}' alt='captcha' /><input type='text' size='5' maxlength='3' name='loadsecurity' value='' />\n\t\t                  </li>";
            }
            echo "<li>\n                        <input class='submit' type='submit' value='" . $clang->gT("Continue") . "' />\n                      </li>\n            </ul>\n\t        </form></div>";
        }
        echo templatereplace(file_get_contents("{$thistpl}/endpage.pstpl"));
        doFooter();
        exit;
    } elseif ($tokensexist == 1 && returnglobal('token') && !captcha_enabled('surveyaccessscreen', $thissurvey['usecaptcha'])) {
        //check if token actually does exist
        $tkquery = "SELECT COUNT(*) FROM " . db_table_name('tokens_' . $surveyid) . " WHERE token='" . db_quote(trim(strip_tags(returnglobal('token')))) . "' AND (completed = 'N' or completed='')";
        $tkresult = db_execute_num($tkquery);
        //Checked
        list($tkexist) = $tkresult->FetchRow();
        if (!$tkexist) {
            //TOKEN DOESN'T EXIST OR HAS ALREADY BEEN USED. EXPLAIN PROBLEM AND EXIT
            killSession();
            sendcacheheaders();
            doHeader();
            echo templatereplace(file_get_contents("{$thistpl}/startpage.pstpl"));
            echo templatereplace(file_get_contents("{$thistpl}/survey.pstpl"));
            echo '<div id="wrapper"><p id="tokenmessage">' . $clang->gT("This is a controlled survey. You need a valid token to participate.") . "<br /><br />\n" . "\t" . $clang->gT("The token you have provided is either not valid, or has already been used.") . "<br />\n" . "\t" . sprintf($clang->gT("For further information contact %s"), $thissurvey['adminname']) . " (<a href='mailto:{$thissurvey['adminemail']}'>" . "{$thissurvey['adminemail']}</a>)</p></div>\n";
            echo templatereplace(file_get_contents("{$thistpl}/endpage.pstpl"));
            doFooter();
            exit;
        }
    } elseif ($tokensexist == 1 && returnglobal('token') && captcha_enabled('surveyaccessscreen', $thissurvey['usecaptcha'])) {
        // IF CAPTCHA ANSWER IS CORRECT
        if (isset($_GET['loadsecurity']) && isset($_SESSION['secanswer']) && $_GET['loadsecurity'] == $_SESSION['secanswer']) {
            //check if token actually does exist
            $tkquery = "SELECT COUNT(*) FROM " . db_table_name('tokens_' . $surveyid) . " WHERE token='" . db_quote(trim(sanitize_xss_string(strip_tags(returnglobal('token'))))) . "' AND (completed = 'N' or completed='')";
            $tkresult = db_execute_num($tkquery);
            //Checked
            list($tkexist) = $tkresult->FetchRow();
            if (!$tkexist) {
                sendcacheheaders();
                doHeader();
                //TOKEN DOESN'T EXIST OR HAS ALREADY BEEN USED. EXPLAIN PROBLEM AND EXIT
                echo templatereplace(file_get_contents("{$thistpl}/startpage.pstpl"));
                echo templatereplace(file_get_contents("{$thistpl}/survey.pstpl"));
                echo "\t<center><br />\n" . "\t" . $clang->gT("This is a controlled survey. You need a valid token to participate.") . "<br /><br />\n" . "\t" . $clang->gT("The token you have provided is either not valid, or has already been used.") . "<br/>\n" . "\t" . sprintf($clang->gT("For further information contact %s"), $thissurvey['adminname']) . " (<a href='mailto:{$thissurvey['adminemail']}'>" . "{$thissurvey['adminemail']}</a>)<br /><br />\n";
                echo templatereplace(file_get_contents("{$thistpl}/endpage.pstpl"));
                doFooter();
                exit;
            }
        } else {
            if (!isset($move) || is_null($move)) {
                $gettoken = $clienttoken;
                sendcacheheaders();
                doHeader();
                // No or bad answer to required security question
                echo templatereplace(file_get_contents("{$thistpl}/startpage.pstpl"));
                echo templatereplace(file_get_contents("{$thistpl}/survey.pstpl"));
                // If token wasn't provided and public registration
                // is enabled then show registration form
                if (!isset($gettoken) && isset($thissurvey) && $thissurvey['allowregister'] == "Y") {
                    echo templatereplace(file_get_contents("{$thistpl}/register.pstpl"));
                } else {
                    // only show CAPTCHA
                    echo '<div id="wrapper"><p id="tokenmessage">';
                    if (isset($_GET['loadsecurity'])) {
                        // was a bad answer
                        echo "<span class='error'>" . $clang->gT("The answer to the security question is incorrect.") . "</span><br />";
                    }
                    echo $clang->gT("This is a controlled survey. You need a valid token to participate.") . "<br /><br />";
                    // IF TOKEN HAS BEEN GIVEN THEN AUTOFILL IT
                    // AND HIDE ENTRY FIELD
                    if (!isset($gettoken)) {
                        echo $clang->gT("If you have been issued with a token, please enter it in the box below and click continue.") . "</p>\n\t\t\t            <form id='tokenform' method='get' action='{$publicurl}/index.php'>\n                        <ul>\n                        <li>\n\t\t\t\t\t        <input type='hidden' name='sid' value='" . $surveyid . "' id='sid' />\n\t\t\t\t\t\t    <input type='hidden' name='lang' value='" . $templang . "' id='lang' />";
                        if (isset($_GET['loadall']) && isset($_GET['scid']) && isset($_GET['loadname']) && isset($_GET['loadpass'])) {
                            echo "<input type='hidden' name='loadall' value='" . htmlspecialchars($_GET['loadall']) . "' id='loadall' />\n\t\t\t\t\t\t        <input type='hidden' name='scid' value='" . returnglobal('scid') . "' id='scid' />\n\t\t\t\t\t\t        <input type='hidden' name='loadname' value='" . htmlspecialchars($_GET['loadname']) . "' id='loadname' />\n\t\t\t\t\t\t        <input type='hidden' name='loadpass' value='" . htmlspecialchars($_GET['loadpass']) . "' id='loadpass' />";
                        }
                        echo '<label for="token">' . $clang->gT("Token") . "</label><input class='text' type='text' id=token name='token'></li>";
                    } else {
                        echo $clang->gT("Please confirm the token by answering the security question below and click continue.") . "</p>\n\t\t\t            <form id='tokenform' method='get' action='{$publicurl}/index.php'>\n                        <ul>\n\t\t\t            <li>\n\t\t\t\t\t            <input type='hidden' name='sid' value='" . $surveyid . "' id='sid' />\n\t\t\t\t\t\t        <input type='hidden' name='lang' value='" . $templang . "' id='lang' />";
                        if (isset($_GET['loadall']) && isset($_GET['scid']) && isset($_GET['loadname']) && isset($_GET['loadpass'])) {
                            echo "<input type='hidden' name='loadall' value='" . htmlspecialchars($_GET['loadall']) . "' id='loadall' />\n                              <input type='hidden' name='scid' value='" . returnglobal('scid') . "' id='scid' />\n                              <input type='hidden' name='loadname' value='" . htmlspecialchars($_GET['loadname']) . "' id='loadname' />\n                              <input type='hidden' name='loadpass' value='" . htmlspecialchars($_GET['loadpass']) . "' id='loadpass' />";
                        }
                        echo '<label for="token">' . $clang->gT("Token:") . "</label><span id=token>{$gettoken}</span>" . "<input type='hidden' name='token' value='{$gettoken}'></li>";
                    }
                    if (function_exists("ImageCreate") && captcha_enabled('surveyaccessscreen', $thissurvey['usecaptcha'])) {
                        echo "<li>\n                            <label for='captchaimage'>" . $clang->gT("Security Question") . "</label><img id='captchaimage' src='{$rooturl}/verification.php?sid={$surveyid}' alt='captcha' /><input type='text' size='5' maxlength='3' name='loadsecurity' value='' />\n                          </li>";
                    }
                    echo "<li><input class='submit' type='submit' value='" . $clang->gT("Continue") . "' /></li>\n\t\t                </ul>\n\t\t                </form>\n\t\t                </id>";
                }
                echo '</div>' . templatereplace(file_get_contents("{$thistpl}/endpage.pstpl"));
                doFooter();
                exit;
            }
        }
    }
    //RESET ALL THE SESSION VARIABLES AND START AGAIN
    unset($_SESSION['grouplist']);
    unset($_SESSION['fieldarray']);
    unset($_SESSION['insertarray']);
    unset($_SESSION['thistoken']);
    unset($_SESSION['fieldnamesInfo']);
    $_SESSION['fieldnamesInfo'] = array();
    //RL: multilingual support
    if (isset($_GET['token']) && db_tables_exist($dbprefix . 'tokens_' . $surveyid)) {
        //get language from token (if one exists)
        $tkquery2 = "SELECT * FROM " . db_table_name('tokens_' . $surveyid) . " WHERE token='" . db_quote($clienttoken) . "' AND (completed = 'N' or completed='')";
        //echo $tkquery2;
        $result = db_execute_assoc($tkquery2) or safe_die("Couldn't get tokens<br />{$tkquery}<br />" . $connect->ErrorMsg());
        //Checked
        while ($rw = $result->FetchRow()) {
            $tklanguage = $rw['language'];
        }
    }
    if (returnglobal('lang')) {
        $language_to_set = returnglobal('lang');
    } elseif (isset($tklanguage)) {
        $language_to_set = $tklanguage;
    } else {
        $language_to_set = $thissurvey['language'];
    }
    if (!isset($_SESSION['s_lang'])) {
        SetSurveyLanguage($surveyid, $language_to_set);
    }
    UpdateSessionGroupList($_SESSION['s_lang']);
    // Optimized Query
    // Change query to use sub-select to see if conditions exist.
    $query = "SELECT " . db_table_name('questions') . ".*, " . db_table_name('groups') . ".*,\n" . " (SELECT count(1) FROM " . db_table_name('conditions') . "\n" . " WHERE " . db_table_name('questions') . ".qid = " . db_table_name('conditions') . ".qid) AS hasconditions,\n" . " (SELECT count(1) FROM " . db_table_name('conditions') . "\n" . " WHERE " . db_table_name('questions') . ".qid = " . db_table_name('conditions') . ".cqid) AS usedinconditions\n" . " FROM " . db_table_name('groups') . " INNER JOIN " . db_table_name('questions') . " ON " . db_table_name('groups') . ".gid = " . db_table_name('questions') . ".gid\n" . " WHERE " . db_table_name('questions') . ".sid=" . $surveyid . "\n" . " AND " . db_table_name('groups') . ".language='" . $_SESSION['s_lang'] . "'\n" . " AND " . db_table_name('questions') . ".language='" . $_SESSION['s_lang'] . "'\n" . " AND " . db_table_name('questions') . ".parent_qid=0\n" . " ORDER BY " . db_table_name('groups') . ".group_order," . db_table_name('questions') . ".question_order";
    //var_dump($_SESSION);
    $result = db_execute_assoc($query);
    //Checked
    $arows = $result->GetRows();
    $totalquestions = $result->RecordCount();
    //2. SESSION VARIABLE: totalsteps
    //The number of "pages" that will be presented in this survey
    //The number of pages to be presented will differ depending on the survey format
    switch ($thissurvey['format']) {
        case "A":
            $_SESSION['totalsteps'] = 1;
            break;
        case "G":
            if (isset($_SESSION['grouplist'])) {
                $_SESSION['totalsteps'] = count($_SESSION['grouplist']);
            }
            break;
        case "S":
            $_SESSION['totalsteps'] = $totalquestions;
    }
    if ($totalquestions == "0") {
        sendcacheheaders();
        doHeader();
        echo templatereplace(file_get_contents("{$thistpl}/startpage.pstpl"));
        echo templatereplace(file_get_contents("{$thistpl}/survey.pstpl"));
        echo "\t<center><br />\n" . "\t" . $clang->gT("This survey does not yet have any questions and cannot be tested or completed.") . "<br /><br />\n" . "\t" . sprintf($clang->gT("For further information contact %s"), $thissurvey['adminname']) . " (<a href='mailto:{$thissurvey['adminemail']}'>" . "{$thissurvey['adminemail']}</a>)<br /><br />\n";
        echo templatereplace(file_get_contents("{$thistpl}/endpage.pstpl"));
        doFooter();
        exit;
    }
    //Perform a case insensitive natural sort on group name then question title of a multidimensional array
    //	usort($arows, 'GroupOrderThenQuestionOrder');
    //3. SESSION VARIABLE - insertarray
    //An array containing information about used to insert the data into the db at the submit stage
    //4. SESSION VARIABLE - fieldarray
    //See rem at end..
    $_SESSION['token'] = $clienttoken;
    if ($thissurvey['private'] == "N") {
        $_SESSION['insertarray'][] = "token";
    }
    if ($tokensexist == 1 && $thissurvey['private'] == "N" && db_tables_exist($dbprefix . 'tokens_' . $surveyid)) {
        //Gather survey data for "non anonymous" surveys, for use in presenting questions
        $_SESSION['thistoken'] = getTokenData($surveyid, $clienttoken);
    }
    $qtypes = getqtypelist('', 'array');
    $fieldmap = createFieldMap($surveyid, 'full', false, false, $_SESSION['s_lang']);
    $_SESSION['fieldmap'] = $fieldmap;
    foreach ($fieldmap as $field) {
        if ($field['qid'] != '') {
            $_SESSION['fieldnamesInfo'][$field['fieldname']] = $field['sid'] . 'X' . $field['gid'] . 'X' . $field['qid'];
            $_SESSION['insertarray'][] = $field['fieldname'];
            //fieldarray ARRAY CONTENTS -
            //            [0]=questions.qid,
            //			[1]=fieldname,
            //			[2]=questions.title,
            //			[3]=questions.question
            //                 	[4]=questions.type,
            //			[5]=questions.gid,
            //			[6]=questions.mandatory,
            //			[7]=conditionsexist,
            //			[8]=usedinconditions
            if (!isset($_SESSION['fieldarray'][$field['sid'] . 'X' . $field['gid'] . 'X' . $field['qid']])) {
                $_SESSION['fieldarray'][$field['sid'] . 'X' . $field['gid'] . 'X' . $field['qid']] = array($field['qid'], $field['sid'] . 'X' . $field['gid'] . 'X' . $field['qid'], $field['title'], $field['question'], $field['type'], $field['gid'], $field['mandatory'], $field['hasconditions'], $field['usedinconditions']);
            }
        }
    }
    // Prefill question/answer from defaultvalues
    foreach ($fieldmap as $field) {
        if (isset($field['defaultvalue'])) {
            $_SESSION[$field['fieldname']] = $field['defaultvalue'];
        }
    }
    // Prefill questions/answers from command line params
    if (isset($_SESSION['insertarray'])) {
        foreach ($_SESSION['insertarray'] as $field) {
            if (isset($_GET[$field]) && $field != 'token') {
                $_SESSION[$field] = $_GET[$field];
            }
        }
    }
    $_SESSION['fieldarray'] = array_values($_SESSION['fieldarray']);
    // Check if the current survey language is set - if not set it
    // this way it can be changed later (for example by a special question type)
    //Check if a passthru label and value have been included in the query url
    if (isset($_GET['passthru']) && $_GET['passthru'] != "") {
        if (isset($_GET[$_GET['passthru']]) && $_GET[$_GET['passthru']] != "") {
            $_SESSION['passthrulabel'] = $_GET['passthru'];
            $_SESSION['passthruvalue'] = $_GET[$_GET['passthru']];
        }
    }
    return $totalquestions;
}
Пример #11
0
    $usersummary = "<div class=\"header\">".$clang->gT("Delete User")."</div>\n";
    $usersummary .= "<div class=\"messagebox\">\n";

    if ($_SESSION['USER_RIGHT_SUPERADMIN'] == 1)
    {
        $ugid = $postusergroupid;
        $uid = $postuserid;

        $query = "SELECT ugid, owner_id FROM ".db_table_name('user_groups')." WHERE ugid = ".$ugid." AND ((owner_id = ".$_SESSION['loginID']." AND owner_id != ".$uid.") OR (owner_id != ".$_SESSION['loginID']." AND $uid = ".$_SESSION['loginID']."))";
        $result = db_execute_assoc($query); //Checked
        if($result->RecordCount() > 0)
        {
            $remquery = "DELETE FROM ".db_table_name('user_in_groups')." WHERE ugid = {$ugid} AND uid = {$uid}";
            if($connect->Execute($remquery)) //Checked
            {
                $usersummary .= "<br />".$clang->gT("Username").": ".sanitize_xss_string(strip_tags($_POST['user']))."<br /><br />\n";
                $usersummary .= "<div class=\"successheader\">".$clang->gT("Success!")."</div>\n";
            }
            else
            {
                $usersummary .= "<div class=\"warningheader\">".$clang->gT("Could not delete user. User was not supplied.")."</div>\n";
            }
        }
        else
        {
            include("access_denied.php");
        }
        if($_SESSION['loginID'] != $postuserid)
        {
            $usersummary .= "<br/><input type=\"submit\" onclick=\"window.location='$scriptname?action=editusergroups&amp;ugid=$ugid'\" value=\"".$clang->gT("Continue")."\"/>\n";
        }
/**
* This function builds all the required session variables when a survey is first started and
* it loads any answer defaults from command line or from the table defaultvalues
* It is called from the related format script (group.php, question.php, survey.php)
* if the survey has just started.
*
* @returns  $totalquestions Total number of questions in the survey
*
*/
function buildsurveysession()
{
    global $thissurvey, $secerror, $clienttoken, $databasetype;
    global $tokensexist, $thistpl;
    global $surveyid, $dbprefix, $connect;
    global $register_errormsg, $clang;
    global $totalBoilerplatequestions;
    global $templang, $move, $rooturl, $publicurl;
    if (!isset($templang) || $templang == '') {
        $templang = $thissurvey['language'];
    }
    $totalBoilerplatequestions = 0;
    $loadsecurity = returnglobal('loadsecurity');
    // NO TOKEN REQUIRED BUT CAPTCHA ENABLED FOR SURVEY ACCESS
    if ($tokensexist == 0 && captcha_enabled('surveyaccessscreen', $thissurvey['usecaptcha'])) {
        // IF CAPTCHA ANSWER IS NOT CORRECT OR NOT SET
        if (!isset($loadsecurity) || !isset($_SESSION['secanswer']) || $loadsecurity != $_SESSION['secanswer']) {
            sendcacheheaders();
            doHeader();
            // No or bad answer to required security question
            echo templatereplace(file_get_contents("{$thistpl}/startpage.pstpl"));
            //echo makedropdownlist();
            echo templatereplace(file_get_contents("{$thistpl}/survey.pstpl"));
            if (isset($loadsecurity)) {
                // was a bad answer
                echo "<font color='#FF0000'>" . $clang->gT("The answer to the security question is incorrect.") . "</font><br />";
            }
            echo "<p class='captcha'>" . $clang->gT("Please confirm access to survey by answering the security question below and click continue.") . "</p>\n\t\t\t        <form class='captcha' method='get' action='{$publicurl}/index.php'>\n\t\t\t        <table align='center'>\n\t\t\t\t        <tr>\n\t\t\t\t\t        <td align='right' valign='middle'>\n\t\t\t\t\t        <input type='hidden' name='sid' value='" . $surveyid . "' id='sid' />\n\t\t\t\t\t        <input type='hidden' name='lang' value='" . $templang . "' id='lang' />";
            // In case we this is a direct Reload previous answers URL, then add hidden fields
            if (isset($_GET['loadall']) && isset($_GET['scid']) && isset($_GET['loadname']) && isset($_GET['loadpass'])) {
                echo "\n\t\t\t\t\t\t<input type='hidden' name='loadall' value='" . htmlspecialchars($_GET['loadall']) . "' id='loadall' />\n\t\t\t\t\t\t<input type='hidden' name='scid' value='" . returnglobal('scid') . "' id='scid' />\n\t\t\t\t\t\t<input type='hidden' name='loadname' value='" . htmlspecialchars($_GET['loadname']) . "' id='loadname' />\n\t\t\t\t\t\t<input type='hidden' name='loadpass' value='" . htmlspecialchars($_GET['loadpass']) . "' id='loadpass' />";
            }
            echo "\n\t\t\t\t        </td>\n\t\t\t        </tr>";
            if (function_exists("ImageCreate") && captcha_enabled('surveyaccessscreen', $thissurvey['usecaptcha'])) {
                echo "<tr>\n\t\t\t\t                <td align='center' valign='middle'><label for='captcha'>" . $clang->gT("Security question:") . "</label></td><td align='left' valign='middle'><table><tr><td valign='middle'><img src='{$rooturl}/verification.php?sid={$surveyid}' alt='captcha' /></td>\n                                <td valign='middle'><input id='captcha' type='text' size='5' maxlength='3' name='loadsecurity' value='' /></td></tr></table>\n\t\t\t\t                </td>\n\t\t\t                </tr>";
            }
            echo "<tr><td colspan='2' align='center'><input class='submit' type='submit' value='" . $clang->gT("Continue") . "' /></td></tr>\n\t\t        </table>\n\t\t        </form>";
            echo templatereplace(file_get_contents("{$thistpl}/endpage.pstpl"));
            doFooter();
            exit;
        }
    }
    //BEFORE BUILDING A NEW SESSION FOR THIS SURVEY, LET'S CHECK TO MAKE SURE THE SURVEY SHOULD PROCEED!
    // TOKEN REQUIRED BUT NO TOKEN PROVIDED
    if ($tokensexist == 1 && !returnglobal('token')) {
        if ($thissurvey['nokeyboard'] == 'Y') {
            vIncludeKeypad();
            $kpclass = "text-keypad";
        } else {
            $kpclass = "";
        }
        // DISPLAY REGISTER-PAGE if needed
        // DISPLAY CAPTCHA if needed
        sendcacheheaders();
        doHeader();
        echo templatereplace(file_get_contents("{$thistpl}/startpage.pstpl"));
        //echo makedropdownlist();
        echo templatereplace(file_get_contents("{$thistpl}/survey.pstpl"));
        if (isset($thissurvey) && $thissurvey['allowregister'] == "Y") {
            echo templatereplace(file_get_contents("{$thistpl}/register.pstpl"));
        } else {
            if (isset($secerror)) {
                echo "<span class='error'>" . $secerror . "</span><br />";
            }
            echo '<div id="wrapper"><p id="tokenmessage">' . $clang->gT("This is a controlled survey. You need a valid token to participate.") . "<br />";
            echo $clang->gT("If you have been issued a token, please enter it in the box below and click continue.") . "</p>\n            <script type='text/javascript'>var focus_element='#token';</script>\n\t        <form id='tokenform' method='get' action='{$publicurl}/index.php'>\n                <ul>\n                <li>\n            <label for='token'>" . $clang->gT("Token") . "</label><input class='text {$kpclass}' id='token' type='text' name='token' />";
            echo "<input type='hidden' name='sid' value='" . $surveyid . "' id='sid' />\n\t\t\t\t<input type='hidden' name='lang' value='" . $templang . "' id='lang' />";
            if (isset($_GET['newtest']) && $_GET['newtest'] == "Y") {
                echo "  <input type='hidden' name='newtest' value='Y' id='newtest' />";
            }
            // If this is a direct Reload previous answers URL, then add hidden fields
            if (isset($_GET['loadall']) && isset($_GET['scid']) && isset($_GET['loadname']) && isset($_GET['loadpass'])) {
                echo "\n\t\t\t\t\t<input type='hidden' name='loadall' value='" . htmlspecialchars($_GET['loadall']) . "' id='loadall' />\n\t\t\t\t\t<input type='hidden' name='scid' value='" . returnglobal('scid') . "' id='scid' />\n\t\t\t\t\t<input type='hidden' name='loadname' value='" . htmlspecialchars($_GET['loadname']) . "' id='loadname' />\n\t\t\t\t\t<input type='hidden' name='loadpass' value='" . htmlspecialchars($_GET['loadpass']) . "' id='loadpass' />";
            }
            echo "</li>";
            if (function_exists("ImageCreate") && captcha_enabled('surveyaccessscreen', $thissurvey['usecaptcha'])) {
                echo "<li>\n\t\t\t                <label for='captchaimage'>" . $clang->gT("Security Question") . "</label><img id='captchaimage' src='{$rooturl}/verification.php?sid={$surveyid}' alt='captcha' /><input type='text' size='5' maxlength='3' name='loadsecurity' value='' />\n\t\t                  </li>";
            }
            echo "<li>\n                        <input class='submit' type='submit' value='" . $clang->gT("Continue") . "' />\n                      </li>\n            </ul>\n\t        </form></div>";
        }
        echo templatereplace(file_get_contents("{$thistpl}/endpage.pstpl"));
        doFooter();
        exit;
    } elseif ($tokensexist == 1 && returnglobal('token') && !captcha_enabled('surveyaccessscreen', $thissurvey['usecaptcha'])) {
        //check if tokens actually haven't been already used
        $areTokensUsed = usedTokens(db_quote(trim(strip_tags(returnglobal('token')))));
        //check if token actually does exist
        // check also if it is allowed to change survey after completion
        if ($thissurvey['alloweditaftercompletion'] == 'Y') {
            $tkquery = "SELECT COUNT(*) FROM " . db_table_name('tokens_' . $surveyid) . " WHERE token='" . db_quote(trim(strip_tags(returnglobal('token')))) . "' ";
        } else {
            $tkquery = "SELECT COUNT(*) FROM " . db_table_name('tokens_' . $surveyid) . " WHERE token='" . db_quote(trim(strip_tags(returnglobal('token')))) . "' AND (completed = 'N' or completed='')";
        }
        $tkresult = db_execute_num($tkquery);
        //Checked
        list($tkexist) = $tkresult->FetchRow();
        if (!$tkexist || $areTokensUsed && $thissurvey['alloweditaftercompletion'] != 'Y') {
            //TOKEN DOESN'T EXIST OR HAS ALREADY BEEN USED. EXPLAIN PROBLEM AND EXIT
            killSession();
            sendcacheheaders();
            doHeader();
            echo templatereplace(file_get_contents("{$thistpl}/startpage.pstpl"));
            echo templatereplace(file_get_contents("{$thistpl}/survey.pstpl"));
            echo '<div id="wrapper"><p id="tokenmessage">' . $clang->gT("This is a controlled survey. You need a valid token to participate.") . "<br /><br />\n" . "\t" . $clang->gT("The token you have provided is either not valid, or has already been used.") . "<br />\n" . "\t" . sprintf($clang->gT("For further information please contact %s"), $thissurvey['adminname']) . " (<a href='mailto:{$thissurvey['adminemail']}'>" . "{$thissurvey['adminemail']}</a>)</p></div>\n";
            echo templatereplace(file_get_contents("{$thistpl}/endpage.pstpl"));
            doFooter();
            exit;
        }
    } elseif ($tokensexist == 1 && returnglobal('token') && captcha_enabled('surveyaccessscreen', $thissurvey['usecaptcha'])) {
        // IF CAPTCHA ANSWER IS CORRECT
        if (isset($loadsecurity) && isset($_SESSION['secanswer']) && $loadsecurity == $_SESSION['secanswer']) {
            //check if tokens actually haven't been already used
            $areTokensUsed = usedTokens(db_quote(trim(strip_tags(returnglobal('token')))));
            //check if token actually does exist
            if ($thissurvey['alloweditaftercompletion'] == 'Y') {
                $tkquery = "SELECT COUNT(*) FROM " . db_table_name('tokens_' . $surveyid) . " WHERE token='" . db_quote(trim(sanitize_xss_string(strip_tags(returnglobal('token'))))) . "'";
            } else {
                $tkquery = "SELECT COUNT(*) FROM " . db_table_name('tokens_' . $surveyid) . " WHERE token='" . db_quote(trim(sanitize_xss_string(strip_tags(returnglobal('token'))))) . "' AND (completed = 'N' or completed='')";
            }
            $tkresult = db_execute_num($tkquery);
            //Checked
            list($tkexist) = $tkresult->FetchRow();
            if (!$tkexist || $areTokensUsed && $thissurvey['alloweditaftercompletion'] != 'Y') {
                sendcacheheaders();
                doHeader();
                //TOKEN DOESN'T EXIST OR HAS ALREADY BEEN USED. EXPLAIN PROBLEM AND EXIT
                echo templatereplace(file_get_contents("{$thistpl}/startpage.pstpl"));
                echo templatereplace(file_get_contents("{$thistpl}/survey.pstpl"));
                echo "\t<div id='wrapper'>\n" . "\t<p id='tokenmessage'>\n" . "\t" . $clang->gT("This is a controlled survey. You need a valid token to participate.") . "<br /><br />\n" . "\t" . $clang->gT("The token you have provided is either not valid, or has already been used.") . "<br/>\n" . "\t" . sprintf($clang->gT("For further information please contact %s"), $thissurvey['adminname']) . " (<a href='mailto:{$thissurvey['adminemail']}'>" . "{$thissurvey['adminemail']}</a>)\n" . "\t</p>\n" . "\t</div>\n";
                echo templatereplace(file_get_contents("{$thistpl}/endpage.pstpl"));
                doFooter();
                exit;
            }
        } else {
            if (!isset($move) || is_null($move)) {
                $gettoken = $clienttoken;
                sendcacheheaders();
                doHeader();
                // No or bad answer to required security question
                echo templatereplace(file_get_contents("{$thistpl}/startpage.pstpl"));
                echo templatereplace(file_get_contents("{$thistpl}/survey.pstpl"));
                // If token wasn't provided and public registration
                // is enabled then show registration form
                if (!isset($gettoken) && isset($thissurvey) && $thissurvey['allowregister'] == "Y") {
                    echo templatereplace(file_get_contents("{$thistpl}/register.pstpl"));
                } else {
                    // only show CAPTCHA
                    echo '<div id="wrapper"><p id="tokenmessage">';
                    if (isset($loadsecurity)) {
                        // was a bad answer
                        echo "<span class='error'>" . $clang->gT("The answer to the security question is incorrect.") . "</span><br />";
                    }
                    echo $clang->gT("This is a controlled survey. You need a valid token to participate.") . "<br /><br />";
                    // IF TOKEN HAS BEEN GIVEN THEN AUTOFILL IT
                    // AND HIDE ENTRY FIELD
                    if (!isset($gettoken)) {
                        echo $clang->gT("If you have been issued a token, please enter it in the box below and click continue.") . "</p>\n\t\t\t            <form id='tokenform' method='get' action='{$publicurl}/index.php'>\n                        <ul>\n                        <li>\n\t\t\t\t\t        <input type='hidden' name='sid' value='" . $surveyid . "' id='sid' />\n\t\t\t\t\t\t    <input type='hidden' name='lang' value='" . $templang . "' id='lang' />";
                        if (isset($_GET['loadall']) && isset($_GET['scid']) && isset($_GET['loadname']) && isset($_GET['loadpass'])) {
                            echo "<input type='hidden' name='loadall' value='" . htmlspecialchars($_GET['loadall']) . "' id='loadall' />\n\t\t\t\t\t\t        <input type='hidden' name='scid' value='" . returnglobal('scid') . "' id='scid' />\n\t\t\t\t\t\t        <input type='hidden' name='loadname' value='" . htmlspecialchars($_GET['loadname']) . "' id='loadname' />\n\t\t\t\t\t\t        <input type='hidden' name='loadpass' value='" . htmlspecialchars($_GET['loadpass']) . "' id='loadpass' />";
                        }
                        echo '<label for="token">' . $clang->gT("Token") . "</label><input class='text' type='text' id='token' name='token'></li>";
                    } else {
                        echo $clang->gT("Please confirm the token by answering the security question below and click continue.") . "</p>\n\t\t\t            <form id='tokenform' method='get' action='{$publicurl}/index.php'>\n                        <ul>\n\t\t\t            <li>\n\t\t\t\t\t            <input type='hidden' name='sid' value='" . $surveyid . "' id='sid' />\n\t\t\t\t\t\t        <input type='hidden' name='lang' value='" . $templang . "' id='lang' />";
                        if (isset($_GET['loadall']) && isset($_GET['scid']) && isset($_GET['loadname']) && isset($_GET['loadpass'])) {
                            echo "<input type='hidden' name='loadall' value='" . htmlspecialchars($_GET['loadall']) . "' id='loadall' />\n                              <input type='hidden' name='scid' value='" . returnglobal('scid') . "' id='scid' />\n                              <input type='hidden' name='loadname' value='" . htmlspecialchars($_GET['loadname']) . "' id='loadname' />\n                              <input type='hidden' name='loadpass' value='" . htmlspecialchars($_GET['loadpass']) . "' id='loadpass' />";
                        }
                        echo '<label for="token">' . $clang->gT("Token:") . "</label><span id='token'>{$gettoken}</span>" . "<input type='hidden' name='token' value='{$gettoken}'></li>";
                    }
                    if (function_exists("ImageCreate") && captcha_enabled('surveyaccessscreen', $thissurvey['usecaptcha'])) {
                        echo "<li>\n                            <label for='captchaimage'>" . $clang->gT("Security Question") . "</label><img id='captchaimage' src='{$rooturl}/verification.php?sid={$surveyid}' alt='captcha' /><input type='text' size='5' maxlength='3' name='loadsecurity' value='' />\n                          </li>";
                    }
                    echo "<li><input class='submit' type='submit' value='" . $clang->gT("Continue") . "' /></li>\n\t\t                </ul>\n\t\t                </form>\n\t\t                </id>";
                }
                echo '</div>' . templatereplace(file_get_contents("{$thistpl}/endpage.pstpl"));
                doFooter();
                unset($_SESSION['srid']);
                exit;
            }
        }
    }
    //RESET ALL THE SESSION VARIABLES AND START AGAIN
    unset($_SESSION['grouplist']);
    unset($_SESSION['fieldarray']);
    unset($_SESSION['insertarray']);
    unset($_SESSION['thistoken']);
    unset($_SESSION['fieldnamesInfo']);
    $_SESSION['fieldnamesInfo'] = array();
    //RL: multilingual support
    if (isset($_GET['token']) && db_tables_exist($dbprefix . 'tokens_' . $surveyid)) {
        //get language from token (if one exists)
        $tkquery2 = "SELECT * FROM " . db_table_name('tokens_' . $surveyid) . " WHERE token='" . db_quote($clienttoken) . "' AND (completed = 'N' or completed='')";
        //echo $tkquery2;
        $result = db_execute_assoc($tkquery2) or safe_die("Couldn't get tokens<br />{$tkquery}<br />" . $connect->ErrorMsg());
        //Checked
        while ($rw = $result->FetchRow()) {
            $tklanguage = $rw['language'];
        }
    }
    if (returnglobal('lang')) {
        $language_to_set = returnglobal('lang');
    } elseif (isset($tklanguage)) {
        $language_to_set = $tklanguage;
    } else {
        $language_to_set = $thissurvey['language'];
    }
    if (!isset($_SESSION['s_lang'])) {
        SetSurveyLanguage($surveyid, $language_to_set);
    }
    UpdateSessionGroupList($_SESSION['s_lang']);
    // Optimized Query
    // Change query to use sub-select to see if conditions exist.
    $query = "SELECT " . db_table_name('questions') . ".*, " . db_table_name('groups') . ".*,\n" . " (SELECT count(1) FROM " . db_table_name('conditions') . "\n" . " WHERE " . db_table_name('questions') . ".qid = " . db_table_name('conditions') . ".qid) AS hasconditions,\n" . " (SELECT count(1) FROM " . db_table_name('conditions') . "\n" . " WHERE " . db_table_name('questions') . ".qid = " . db_table_name('conditions') . ".cqid) AS usedinconditions\n" . " FROM " . db_table_name('groups') . " INNER JOIN " . db_table_name('questions') . " ON " . db_table_name('groups') . ".gid = " . db_table_name('questions') . ".gid\n" . " WHERE " . db_table_name('questions') . ".sid=" . $surveyid . "\n" . " AND " . db_table_name('groups') . ".language='" . $_SESSION['s_lang'] . "'\n" . " AND " . db_table_name('questions') . ".language='" . $_SESSION['s_lang'] . "'\n" . " AND " . db_table_name('questions') . ".parent_qid=0\n" . " ORDER BY " . db_table_name('groups') . ".group_order," . db_table_name('questions') . ".question_order";
    //var_dump($_SESSION);
    $result = db_execute_assoc($query);
    //Checked
    $arows = $result->GetRows();
    $totalquestions = $result->RecordCount();
    //2. SESSION VARIABLE: totalsteps
    //The number of "pages" that will be presented in this survey
    //The number of pages to be presented will differ depending on the survey format
    switch ($thissurvey['format']) {
        case "A":
            $_SESSION['totalsteps'] = 1;
            break;
        case "G":
            if (isset($_SESSION['grouplist'])) {
                $_SESSION['totalsteps'] = count($_SESSION['grouplist']);
            }
            break;
        case "S":
            $_SESSION['totalsteps'] = $totalquestions;
    }
    if ($totalquestions == "0") {
        sendcacheheaders();
        doHeader();
        echo templatereplace(file_get_contents("{$thistpl}/startpage.pstpl"));
        echo templatereplace(file_get_contents("{$thistpl}/survey.pstpl"));
        echo "\t<div id='wrapper'>\n" . "\t<p id='tokenmessage'>\n" . "\t" . $clang->gT("This survey does not yet have any questions and cannot be tested or completed.") . "<br /><br />\n" . "\t" . sprintf($clang->gT("For further information please contact %s"), $thissurvey['adminname']) . " (<a href='mailto:{$thissurvey['adminemail']}'>" . "{$thissurvey['adminemail']}</a>)<br /><br />\n" . "\t</p>\n" . "\t</div>\n";
        echo templatereplace(file_get_contents("{$thistpl}/endpage.pstpl"));
        doFooter();
        exit;
    }
    //Perform a case insensitive natural sort on group name then question title of a multidimensional array
    //	usort($arows, 'GroupOrderThenQuestionOrder');
    //3. SESSION VARIABLE - insertarray
    //An array containing information about used to insert the data into the db at the submit stage
    //4. SESSION VARIABLE - fieldarray
    //See rem at end..
    $_SESSION['token'] = $clienttoken;
    if ($thissurvey['anonymized'] == "N") {
        $_SESSION['insertarray'][] = "token";
    }
    if ($tokensexist == 1 && $thissurvey['anonymized'] == "N" && db_tables_exist($dbprefix . 'tokens_' . $surveyid)) {
        //Gather survey data for "non anonymous" surveys, for use in presenting questions
        $_SESSION['thistoken'] = getTokenData($surveyid, $clienttoken);
    }
    $qtypes = getqtypelist('', 'array');
    $fieldmap = createFieldMap($surveyid, 'full', false, false, $_SESSION['s_lang']);
    // Randomization Groups
    // Find all defined randomization groups through question attribute values
    $randomGroups = array();
    if ($databasetype == 'odbc_mssql' || $databasetype == 'odbtp' || $databasetype == 'mssql_n' || $databasetype == 'mssqlnative') {
        $rgquery = "SELECT attr.qid, CAST(value as varchar(255)) FROM " . db_table_name('question_attributes') . " as attr right join " . db_table_name('questions') . " as quests on attr.qid=quests.qid WHERE attribute='random_group' and CAST(value as varchar(255)) <> '' and sid={$surveyid} GROUP BY attr.qid, CAST(value as varchar(255))";
    } else {
        $rgquery = "SELECT attr.qid, value FROM " . db_table_name('question_attributes') . " as attr right join " . db_table_name('questions') . " as quests on attr.qid=quests.qid WHERE attribute='random_group' and value <> '' and sid={$surveyid} GROUP BY attr.qid, value";
    }
    $rgresult = db_execute_assoc($rgquery);
    while ($rgrow = $rgresult->FetchRow()) {
        // Get the question IDs for each randomization group
        $randomGroups[$rgrow['value']][] = $rgrow['qid'];
    }
    // If we have randomization groups set, then lets cycle through each group and
    // replace questions in the group with a randomly chosen one from the same group
    if (count($randomGroups) > 0) {
        $copyFieldMap = array();
        $oldQuestOrder = array();
        $newQuestOrder = array();
        $randGroupNames = array();
        foreach ($randomGroups as $key => $value) {
            $oldQuestOrder[$key] = $randomGroups[$key];
            $newQuestOrder[$key] = $oldQuestOrder[$key];
            // We shuffle the question list to get a random key->qid which will be used to swap from the old key
            shuffle($newQuestOrder[$key]);
            $randGroupNames[] = $key;
        }
        // Loop through the fieldmap and swap each question as they come up
        while (list($fieldkey, $fieldval) = each($fieldmap)) {
            $found = 0;
            foreach ($randomGroups as $gkey => $gval) {
                // We found a qid that is in the randomization group
                if (isset($fieldval['qid']) && in_array($fieldval['qid'], $oldQuestOrder[$gkey])) {
                    // Get the swapped question
                    $oldQuestFlip = array_flip($oldQuestOrder[$gkey]);
                    $qfieldmap = createFieldMap($surveyid, 'full', true, $newQuestOrder[$gkey][$oldQuestFlip[$fieldval['qid']]], $_SESSION['s_lang']);
                    unset($qfieldmap['id']);
                    unset($qfieldmap['submitdate']);
                    unset($qfieldmap['lastpage']);
                    unset($qfieldmap['lastpage']);
                    unset($qfieldmap['token']);
                    foreach ($qfieldmap as $tkey => $tval) {
                        // Assign the swapped question (Might be more than one field)
                        $tval['random_gid'] = $fieldval['gid'];
                        //$tval['gid'] = $fieldval['gid'];
                        $copyFieldMap[$tkey] = $tval;
                    }
                    $found = 1;
                    break;
                } else {
                    $found = 2;
                }
            }
            if ($found == 2) {
                $copyFieldMap[$fieldkey] = $fieldval;
            }
            reset($randomGroups);
        }
        $fieldmap = $copyFieldMap;
    }
    //die(print_r($fieldmap));
    $_SESSION['fieldmap'] = $fieldmap;
    foreach ($fieldmap as $field) {
        if (isset($field['qid']) && $field['qid'] != '') {
            $_SESSION['fieldnamesInfo'][$field['fieldname']] = $field['sid'] . 'X' . $field['gid'] . 'X' . $field['qid'];
            $_SESSION['insertarray'][] = $field['fieldname'];
            //fieldarray ARRAY CONTENTS -
            //            [0]=questions.qid,
            //			[1]=fieldname,
            //			[2]=questions.title,
            //			[3]=questions.question
            //                 	[4]=questions.type,
            //			[5]=questions.gid,
            //			[6]=questions.mandatory,
            //			[7]=conditionsexist,
            //			[8]=usedinconditions
            //			[8]=usedinconditions
            //			[9]=used in group.php for question count
            //			[10]=new group id for question in randomization group (GroupbyGroup Mode)
            if (!isset($_SESSION['fieldarray'][$field['sid'] . 'X' . $field['gid'] . 'X' . $field['qid']])) {
                $_SESSION['fieldarray'][$field['sid'] . 'X' . $field['gid'] . 'X' . $field['qid']] = array($field['qid'], $field['sid'] . 'X' . $field['gid'] . 'X' . $field['qid'], $field['title'], $field['question'], $field['type'], $field['gid'], $field['mandatory'], $field['hasconditions'], $field['usedinconditions']);
            }
            if (isset($field['random_gid'])) {
                $_SESSION['fieldarray'][$field['sid'] . 'X' . $field['gid'] . 'X' . $field['qid']][10] = $field['random_gid'];
            }
        }
    }
    // Prefill question/answer from defaultvalues
    foreach ($fieldmap as $field) {
        if (isset($field['defaultvalue'])) {
            $_SESSION[$field['fieldname']] = $field['defaultvalue'];
        }
    }
    // Prefill questions/answers from command line params
    if (isset($_SESSION['insertarray'])) {
        foreach ($_SESSION['insertarray'] as $field) {
            if (isset($_GET[$field]) && $field != 'token') {
                $_SESSION[$field] = $_GET[$field];
            }
        }
    }
    if (isset($_SESSION['fieldarray'])) {
        $_SESSION['fieldarray'] = array_values($_SESSION['fieldarray']);
    }
    // Check if the current survey language is set - if not set it
    // this way it can be changed later (for example by a special question type)
    //Check if a passthru label and value have been included in the query url
    if (isset($_GET['passthru']) && $_GET['passthru'] != "") {
        if (isset($_GET[$_GET['passthru']]) && $_GET[$_GET['passthru']] != "") {
            $_SESSION['passthrulabel'] = $_GET['passthru'];
            $_SESSION['passthruvalue'] = $_GET[$_GET['passthru']];
        }
    } elseif (isset($_SERVER['QUERY_STRING'])) {
        $_SESSION['ls_initialquerystr'] = $_SERVER['QUERY_STRING'];
    }
    // END NEW
    // Fix totalquestions by substracting Test Display questions
    $sNoOfTextDisplayQuestions = (int) $connect->GetOne("SELECT count(*)\n" . " FROM " . db_table_name('questions') . " WHERE type='X'\n" . " AND sid={$surveyid}" . " AND language='" . $_SESSION['s_lang'] . "'" . " AND parent_qid=0");
    $_SESSION['therearexquestions'] = $totalquestions - $sNoOfTextDisplayQuestions;
    // must be global for THEREAREXQUESTIONS replacement field to work
    return $totalquestions - $sNoOfTextDisplayQuestions;
}
Пример #13
0
 /**
  * Get the token id according to filled values
  * @param $iSurveyId
  * @return integer : the token id created
  */
 public function getTokenId($iSurveyId)
 {
     $sLanguage = App()->language;
     $aSurveyInfo = getSurveyInfo($iSurveyId, $sLanguage);
     $aFieldValue = $this->getFieldValue($iSurveyId);
     // Now construct the text returned
     $oToken = Token::model($iSurveyId)->findByAttributes(array('email' => $aFieldValue['sEmail']));
     if ($oToken) {
         if ($oToken->usesleft < 1 && $aSurveyInfo['alloweditaftercompletion'] != 'Y') {
             $this->aRegisterErrors[] = gT("The email address you have entered is already registered and the survey has been completed.");
         } elseif (strtolower(substr(trim($oToken->emailstatus), 0, 6)) === "optout") {
             $this->aRegisterErrors[] = gT("This email address cannot be used because it was opted out of this survey.");
         } elseif (!$oToken->emailstatus && $oToken->emailstatus != "OK") {
             $this->aRegisterErrors[] = gT("This email address is already registered but the email adress was bounced.");
         } else {
             $this->sMailMessage = gT("The address you have entered is already registered. An email has been sent to this address with a link that gives you access to the survey.");
             return $oToken->tid;
         }
     } else {
         // TODO : move xss filtering in model
         $oToken = Token::create($iSurveyId);
         $oToken->firstname = sanitize_xss_string($aFieldValue['sFirstName']);
         $oToken->lastname = sanitize_xss_string($aFieldValue['sLastName']);
         $oToken->email = $aFieldValue['sEmail'];
         $oToken->emailstatus = 'OK';
         $oToken->language = $sLanguage;
         $aFieldValue['aAttribute'] = array_map('sanitize_xss_string', $aFieldValue['aAttribute']);
         $oToken->setAttributes($aFieldValue['aAttribute']);
         if ($aSurveyInfo['startdate']) {
             $oToken->validfrom = $aSurveyInfo['startdate'];
         }
         if ($aSurveyInfo['expires']) {
             $oToken->validuntil = $aSurveyInfo['expires'];
         }
         $oToken->generateToken();
         $oToken->save();
         $this->sMailMessage = gT("An email has been sent to the address you provided with access details for this survey. Please follow the link in that email to proceed.");
         return $oToken->tid;
     }
 }
Пример #14
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, $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;
}
Пример #15
0
 public function ajaxSets()
 {
     $lid = Yii::app()->getRequest()->getPost('lid');
     $answers = Yii::app()->getRequest()->getPost('answers');
     $code = Yii::app()->getRequest()->getPost('code');
     //Create new label set
     $language = "";
     foreach ($answers as $lang => $answer) {
         $language .= $lang . " ";
     }
     $language = trim($language);
     if ($lid == 0) {
         $lset = new Labelsets();
         $lset->label_name = sanitize_xss_string(Yii::app()->getRequest()->getPost('laname'));
         $lset->languages = sanitize_xss_string($language);
         $lset->save();
         $lid = getLastInsertID($lset->tableName());
     } else {
         Label::model()->deleteAll('lid = :lid', array(':lid' => $lid));
     }
     $res = 'ok';
     //optimistic
     foreach ($answers as $lang => $answer) {
         foreach ($answer as $key => $ans) {
             $label = new Label();
             $label->lid = $lid;
             $label->code = $code[$key];
             $label->title = $ans;
             $label->sortorder = $key;
             $label->language = $lang;
             if (!$label->save()) {
                 $res = 'fail';
             }
         }
     }
     echo ls_json_encode($res);
 }
Пример #16
0
    }
    $addsummary .= "</div>\n";
}
if ($action == "delsurveysecurity") {
    $addsummary = "<div class=\"header\">" . $clang->gT("Deleting User") . "</div>\n";
    $addsummary .= "<div class=\"messagebox\">\n";
    $query = "SELECT sid, owner_id FROM " . db_table_name('surveys') . " WHERE sid = {$surveyid} AND owner_id = " . $_SESSION['loginID'] . " AND owner_id != " . $postuserid;
    $result = db_execute_assoc($query);
    //Checked
    if ($result->RecordCount() > 0 || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {
        if (isset($postuserid)) {
            $dquery = "DELETE FROM" . db_table_name('survey_permissions') . " WHERE uid={$postuserid} AND sid={$surveyid}";
            //	added by Dennis
            $dresult = $connect->Execute($dquery);
            //Checked
            $addsummary .= "<br />" . $clang->gT("Username") . ": " . sanitize_xss_string($_POST['user']) . "<br /><br />\n";
            $addsummary .= "<div class=\"successheader\">" . $clang->gT("Success!") . "</div>\n";
        } else {
            $addsummary .= "<div class=\"warningheader\">" . $clang->gT("Could not delete user. User was not supplied.") . "</div>\n";
        }
        $addsummary .= "<br/><input type=\"submit\" onclick=\"window.open('{$scriptname}?sid={$surveyid}&amp;action=surveysecurity', '_top')\" value=\"" . $clang->gT("Continue") . "\"/>\n";
    } else {
        include "access_denied.php";
    }
    $addsummary .= "</div>\n";
}
if ($action == "setsurveysecurity" || $action == "setusergroupsurveysecurity") {
    $query = "SELECT sid, owner_id FROM " . db_table_name('surveys') . " WHERE sid = {$surveyid} AND owner_id = " . $_SESSION['loginID'];
    if ($action == "setsurveysecurity") {
        $query .= " AND owner_id != " . $postuserid;
    }
Пример #17
0
        public function beforeSurveyPage()
        {
            $oEvent = $this->event;
            $iSurveyId = $oEvent->get('surveyId');

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

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

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

                    $aData['thissurvey'] = $aSurveyInfo;
                    echo templatereplace(file_get_contents($sTemplatePath.'/startpage.pstpl'),array(), $aData);
                    echo templatereplace(file_get_contents($sTemplatePath.'/survey.pstpl'),array(), $aData);
                    echo templatereplace($sHtmlRegister);
                    echo templatereplace(file_get_contents($sTemplatePath.'/endpage.pstpl'),array(), $aData);
                    doFooter();
                    ob_flush();
                    App()->end();
                }
            }
        }
Пример #18
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;
}
Пример #19
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;
}