Example #1
0
    $html=ReplaceFields($html, $fieldsarray);
    $html .= "<br /><br /></center>\n";
}
else
{
    $html="Email Error";
}

//PRINT COMPLETED PAGE
if (!$thissurvey['template'])
{
    $thistpl=sGetTemplatePath(validate_templatedir('default'));
} 
else 
{
    $thistpl=sGetTemplatePath(validate_templatedir($thissurvey['template']));
}

sendcacheheaders();
doHeader();

foreach(file("$thistpl/startpage.pstpl") as $op)
{
    echo templatereplace($op);
}
foreach(file("$thistpl/survey.pstpl") as $op)
{
    echo "\t".templatereplace($op);
}
echo $html;
foreach(file("$thistpl/endpage.pstpl") as $op)
/**
* This function imports the old CSV data from 1.50 to 1.87 or older. Starting with 1.90 (DBVersion 143) there is an XML format instead
*
* @param array $sFullFilepath
* @returns array Information of imported questions/answers/etc.
*/
function CSVImportSurvey($sFullFilepath,$iDesiredSurveyId=NULL)
{
    global $dbprefix, $connect, $timeadjust, $clang;

    $handle = fopen($sFullFilepath, "r");
    while (!feof($handle))
    {

        $buffer = fgets($handle);
        $bigarray[] = $buffer;
    }
    fclose($handle);

    $aIgnoredAnswers=array();
    $aSQIDReplacements=array();
    $aLIDReplacements=array();
    $aGIDReplacements=array();
    $substitutions=array();
    $aQuotaReplacements=array();
    $importresults['error']=false;
    $importresults['importwarnings']=array();
    $importresults['question_attributes']=0;

    if (isset($bigarray[0])) $bigarray[0]=removeBOM($bigarray[0]);

    // Now we try to determine the dataformat of the survey file.
    $importversion=0;
    if (isset($bigarray[1]) && isset($bigarray[4])&& (substr($bigarray[1], 0, 22) == "# SURVEYOR SURVEY DUMP"))
    {
        $importversion = 100;  // Version 0.99 or  1.0 file
    }
    elseif
    (substr($bigarray[0], 0, 24) == "# LimeSurvey Survey Dump" || substr($bigarray[0], 0, 25) == "# PHPSurveyor Survey Dump")
    {  // Seems to be a >1.0 version file - these files carry the version information to read in line two
        $importversion=substr($bigarray[1], 12, 3);
    }
    else    // unknown file - show error message
    {
        $importresults['error'] = $clang->gT("This file is not a LimeSurvey survey file. Import failed.")."\n";
        return $importresults;
    }

    if  ((int)$importversion<112)
    {
        $importresults['error'] = $clang->gT("This file is too old. Only files from LimeSurvey version 1.50 (DBVersion 112) and newer are supported.");
        return $importresults;
    }

    // okay.. now lets drop the first 9 lines and get to the data
    // This works for all versions
    for ($i=0; $i<9; $i++)
    {
        unset($bigarray[$i]);
    }
    $bigarray = array_values($bigarray);


    //SURVEYS
    if (array_search("# GROUPS TABLE\n", $bigarray))
    {
        $stoppoint = array_search("# GROUPS TABLE\n", $bigarray);
    }
    elseif (array_search("# GROUPS TABLE\r\n", $bigarray))
    {
        $stoppoint = array_search("# GROUPS TABLE\r\n", $bigarray);
    }
    for ($i=0; $i<=$stoppoint+1; $i++)
    {
        if ($i<$stoppoint-2) {$surveyarray[] = $bigarray[$i];}
        unset($bigarray[$i]);
    }
    $bigarray = array_values($bigarray);

    //GROUPS
    if (array_search("# QUESTIONS TABLE\n", $bigarray))
    {
        $stoppoint = array_search("# QUESTIONS TABLE\n", $bigarray);
    }
    elseif (array_search("# QUESTIONS TABLE\r\n", $bigarray))
    {
        $stoppoint = array_search("# QUESTIONS TABLE\r\n", $bigarray);
    }
    else
    {
        $stoppoint = count($bigarray)-1;
    }
    for ($i=0; $i<=$stoppoint+1; $i++)
    {
        if ($i<$stoppoint-2) {$grouparray[] = $bigarray[$i];}
        unset($bigarray[$i]);
    }
    $bigarray = array_values($bigarray);

    //QUESTIONS
    if (array_search("# ANSWERS TABLE\n", $bigarray))
    {
        $stoppoint = array_search("# ANSWERS TABLE\n", $bigarray);
    }
    elseif (array_search("# ANSWERS TABLE\r\n", $bigarray))
    {
        $stoppoint = array_search("# ANSWERS TABLE\r\n", $bigarray);
    }
    else
    {
        $stoppoint = count($bigarray)-1;
    }
    for ($i=0; $i<=$stoppoint+1; $i++)
    {
        if ($i<$stoppoint-2)
        {
            $questionarray[] = $bigarray[$i];
        }
        unset($bigarray[$i]);
    }
    $bigarray = array_values($bigarray);

    //ANSWERS
    if (array_search("# CONDITIONS TABLE\n", $bigarray))
    {
        $stoppoint = array_search("# CONDITIONS TABLE\n", $bigarray);
    }
    elseif (array_search("# CONDITIONS TABLE\r\n", $bigarray))
    {
        $stoppoint = array_search("# CONDITIONS TABLE\r\n", $bigarray);
    }
    else
    {
        $stoppoint = count($bigarray)-1;
    }
    for ($i=0; $i<=$stoppoint+1; $i++)
    {
        if ($i<$stoppoint-2)
        {
            $answerarray[] = str_replace("`default`", "`default_value`", $bigarray[$i]);
        }
        unset($bigarray[$i]);
    }
    $bigarray = array_values($bigarray);

    //CONDITIONS
    if (array_search("# LABELSETS TABLE\n", $bigarray))
    {
        $stoppoint = array_search("# LABELSETS TABLE\n", $bigarray);
    }
    elseif (array_search("# LABELSETS TABLE\r\n", $bigarray))
    {
        $stoppoint = array_search("# LABELSETS TABLE\r\n", $bigarray);
    }
    for ($i=0; $i<=$stoppoint+1; $i++)
    {
        if ($i<$stoppoint-2) {$conditionsarray[] = $bigarray[$i];}
        unset($bigarray[$i]);
    }
    $bigarray = array_values($bigarray);

    //LABELSETS
    if (array_search("# LABELS TABLE\n", $bigarray))
    {
        $stoppoint = array_search("# LABELS TABLE\n", $bigarray);
    }
    elseif (array_search("# LABELS TABLE\r\n", $bigarray))
    {
        $stoppoint = array_search("# LABELS TABLE\r\n", $bigarray);
    }
    else
    {
        $stoppoint = count($bigarray)-1;
    }
    for ($i=0; $i<=$stoppoint+1; $i++)
    {
        if ($i<$stoppoint-2) {$labelsetsarray[] = $bigarray[$i];}
        unset($bigarray[$i]);
    }
    $bigarray = array_values($bigarray);

    //LABELS
    if (array_search("# QUESTION_ATTRIBUTES TABLE\n", $bigarray))
    {
        $stoppoint = array_search("# QUESTION_ATTRIBUTES TABLE\n", $bigarray);
    }
    elseif (array_search("# QUESTION_ATTRIBUTES TABLE\r\n", $bigarray))
    {
        $stoppoint = array_search("# QUESTION_ATTRIBUTES TABLE\r\n", $bigarray);
    }
    else
    {
        $stoppoint = count($bigarray)-1;
    }

    for ($i=0; $i<=$stoppoint+1; $i++)
    {
        if ($i<$stoppoint-2) {$labelsarray[] = $bigarray[$i];}
        unset($bigarray[$i]);
    }
    $bigarray = array_values($bigarray);

    //Question attributes
    if (array_search("# ASSESSMENTS TABLE\n", $bigarray))
    {
        $stoppoint = array_search("# ASSESSMENTS TABLE\n", $bigarray);
    }
    elseif (array_search("# ASSESSMENTS TABLE\r\n", $bigarray))
    {
        $stoppoint = array_search("# ASSESSMENTS TABLE\r\n", $bigarray);
    }
    else
    {
        $stoppoint = count($bigarray)-1;
    }
    for ($i=0; $i<=$stoppoint+1; $i++)
    {
        if ($i<$stoppoint-2) {$question_attributesarray[] = $bigarray[$i];}
        unset($bigarray[$i]);
    }
    $bigarray = array_values($bigarray);


    //ASSESSMENTS
    if (array_search("# SURVEYS_LANGUAGESETTINGS TABLE\n", $bigarray))
    {
        $stoppoint = array_search("# SURVEYS_LANGUAGESETTINGS TABLE\n", $bigarray);
    }
    elseif (array_search("# SURVEYS_LANGUAGESETTINGS TABLE\r\n", $bigarray))
    {
        $stoppoint = array_search("# SURVEYS_LANGUAGESETTINGS TABLE\r\n", $bigarray);
    }
    else
    {
        $stoppoint = count($bigarray)-1;
    }
    for ($i=0; $i<=$stoppoint+1; $i++)
    {
        //    if ($i<$stoppoint-2 || $i==count($bigarray)-1)
        if ($i<$stoppoint-2)
        {
            $assessmentsarray[] = $bigarray[$i];
        }
        unset($bigarray[$i]);
    }
    $bigarray = array_values($bigarray);

    //LANGAUGE SETTINGS
    if (array_search("# QUOTA TABLE\n", $bigarray))
    {
        $stoppoint = array_search("# QUOTA TABLE\n", $bigarray);
    }
    elseif (array_search("# QUOTA TABLE\r\n", $bigarray))
    {
        $stoppoint = array_search("# QUOTA TABLE\r\n", $bigarray);
    }
    else
    {
        $stoppoint = count($bigarray)-1;
    }
    for ($i=0; $i<=$stoppoint+1; $i++)
    {
        //    if ($i<$stoppoint-2 || $i==count($bigarray)-1)
        //$bigarray[$i]=        trim($bigarray[$i]);
        if (isset($bigarray[$i]) && (trim($bigarray[$i])!=''))
        {
            if (strpos($bigarray[$i],"#")===0)
            {
                unset($bigarray[$i]);
                unset($bigarray[$i+1]);
                unset($bigarray[$i+2]);
                break ;
            }
            else
            {
                $surveylsarray[] = $bigarray[$i];
            }
        }
        unset($bigarray[$i]);
    }
    $bigarray = array_values($bigarray);

    //QUOTA
    if (array_search("# QUOTA_MEMBERS TABLE\n", $bigarray))
    {
        $stoppoint = array_search("# QUOTA_MEMBERS TABLE\n", $bigarray);
    }
    elseif (array_search("# QUOTA_MEMBERS TABLE\r\n", $bigarray))
    {
        $stoppoint = array_search("# QUOTA_MEMBERS TABLE\r\n", $bigarray);
    }
    else
    {
        $stoppoint = count($bigarray)-1;
    }
    for ($i=0; $i<=$stoppoint+1; $i++)
    {
        //    if ($i<$stoppoint-2 || $i==count($bigarray)-1)
        if ($i<$stoppoint-2)
        {
            $quotaarray[] = $bigarray[$i];
        }
        unset($bigarray[$i]);
    }
    $bigarray = array_values($bigarray);

    //QUOTA MEMBERS
    if (array_search("# QUOTA_LANGUAGESETTINGS TABLE\n", $bigarray))
    {
        $stoppoint = array_search("# QUOTA_LANGUAGESETTINGS TABLE\n", $bigarray);
    }
    elseif (array_search("# QUOTA_LANGUAGESETTINGS TABLE\r\n", $bigarray))
    {
        $stoppoint = array_search("# QUOTA_LANGUAGESETTINGS TABLE\r\n", $bigarray);
    }
    else
    {
        $stoppoint = count($bigarray)-1;
    }
    for ($i=0; $i<=$stoppoint+1; $i++)
    {
        //    if ($i<$stoppoint-2 || $i==count($bigarray)-1)
        if ($i<$stoppoint-2)
        {
            $quotamembersarray[] = $bigarray[$i];
        }
        unset($bigarray[$i]);
    }
    $bigarray = array_values($bigarray);


    //Whatever is the last table - currently
    //QUOTA LANGUAGE SETTINGS
    $stoppoint = count($bigarray)-1;
    for ($i=0; $i<$stoppoint-1; $i++)
    {
        if ($i<=$stoppoint) {$quotalsarray[] = $bigarray[$i];}
        unset($bigarray[$i]);
    }
    $bigarray = array_values($bigarray);

    if (isset($surveyarray)) {$importresults['surveys'] = count($surveyarray);} else {$importresults['surveys'] = 0;}
    if (isset($surveylsarray)) {$importresults['languages'] = count($surveylsarray)-1;} else {$importresults['languages'] = 1;}
    if (isset($grouparray)) {$importresults['groups'] = count($grouparray)-1;} else {$importresults['groups'] = 0;}
    if (isset($questionarray)) {$importresults['questions'] = count($questionarray);} else {$importresults['questions']=0;}
    if (isset($answerarray)) {$importresults['answers'] = count($answerarray);} else {$importresults['answers']=0;}
    if (isset($conditionsarray)) {$importresults['conditions'] = count($conditionsarray);} else {$importresults['conditions']=0;}
    if (isset($labelsetsarray)) {$importresults['labelsets'] = count($labelsetsarray);} else {$importresults['labelsets']=0;}
    if (isset($assessmentsarray)) {$importresults['assessments']=count($assessmentsarray);} else {$importresults['assessments']=0;}
    if (isset($quotaarray)) {$importresults['quota']=count($quotaarray);} else {$importresults['quota']=0;}
    if (isset($quotamembersarray)) {$importresults['quotamembers']=count($quotamembersarray);} else {$importresults['quotamembers']=0;}
    if (isset($quotalsarray)) {$importresults['quotals']=count($quotalsarray);} else {$importresults['quotals']=0;}

    // CREATE SURVEY

    if ($importresults['surveys']>0){$importresults['surveys']--;};
    if ($importresults['answers']>0){$importresults['answers']=($importresults['answers']-1)/$importresults['languages'];};
    if ($importresults['groups']>0){$countgroups=($importresults['groups']-1)/$importresults['languages'];};
    if ($importresults['questions']>0){$importresults['questions']=($importresults['questions']-1)/$importresults['languages'];};
    if ($importresults['assessments']>0){$importresults['assessments']--;};
    if ($importresults['conditions']>0){$importresults['conditions']--;};
    if ($importresults['labelsets']>0){$importresults['labelsets']--;};
    if ($importresults['quota']>0){$importresults['quota']--;};
    $sfieldorders  =convertCSVRowToArray($surveyarray[0],',','"');
    $sfieldcontents=convertCSVRowToArray($surveyarray[1],',','"');
    $surveyrowdata=array_combine($sfieldorders,$sfieldcontents);
    $oldsid=$surveyrowdata["sid"];

    if($iDesiredSurveyId!=NULL)
        $oldsid = $iDesiredSurveyId;

    if (!$oldsid)
    {
        if ($importingfrom == "http")
        {
            $importsurvey .= "<br /><div class='warningheader'>".$clang->gT("Error")."</div><br />\n";
            $importsurvey .= $clang->gT("Import of this survey file failed")."<br />\n";
            $importsurvey .= $clang->gT("File does not contain LimeSurvey data in the correct format.")."<br /><br />\n"; //Couldn't find the SID - cannot continue
            $importsurvey .= "<input type='submit' value='".$clang->gT("Main Admin Screen")."' onclick=\"window.open('$scriptname', '_top')\" />\n";
            $importsurvey .= "</div>\n";
            unlink($sFullFilepath); //Delete the uploaded file
            return;
        }
        else
        {
            echo $clang->gT("Import of this survey file failed")."\n".$clang->gT("File does not contain LimeSurvey data in the correct format.")."\n";
            return;
        }
    }

    $newsid = GetNewSurveyID($oldsid);

    $insert=$surveyarray[0];
    $sfieldorders  =convertCSVRowToArray($surveyarray[0],',','"');
    $sfieldcontents=convertCSVRowToArray($surveyarray[1],',','"');
    $surveyrowdata=array_combine($sfieldorders,$sfieldcontents);
    // Set new owner ID
    $surveyrowdata['owner_id']=$_SESSION['loginID'];
    // Set new survey ID
    $surveyrowdata['sid']=$newsid;
    $surveyrowdata['active']='N';

    if (validate_templatedir($surveyrowdata['template'])!==$surveyrowdata['template']) $importresults['importwarnings'][] = sprintf($clang->gT('Template %s not found, please review when activating.'),$surveyrowdata['template']);

    if (isset($surveyrowdata['datecreated'])) {$surveyrowdata['datecreated']=$connect->BindTimeStamp($surveyrowdata['datecreated']);}
    unset($surveyrowdata['expires']);
    unset($surveyrowdata['attribute1']);
    unset($surveyrowdata['attribute2']);
    unset($surveyrowdata['usestartdate']);
    unset($surveyrowdata['notification']);
    unset($surveyrowdata['useexpiry']);
    unset($surveyrowdata['url']);
    unset($surveyrowdata['lastpage']);
    if (isset($surveyrowdata['private'])){
        $surveyrowdata['anonymized']=$surveyrowdata['private'];
        unset($surveyrowdata['private']);
    }
    if (isset($surveyrowdata['startdate'])) {unset($surveyrowdata['startdate']);}
    $surveyrowdata['bounce_email']=$surveyrowdata['adminemail'];
    if (!isset($surveyrowdata['datecreated']) || $surveyrowdata['datecreated']=='' || $surveyrowdata['datecreated']=='null') {$surveyrowdata['datecreated']=$connect->BindTimeStamp(date_shift(date("Y-m-d H:i:s"), "Y-m-d", $timeadjust));}

    $values=array_values($surveyrowdata);
    $values=array_map(array(&$connect, "qstr"),$values); // quote everything accordingly
    $insert = "INSERT INTO {$dbprefix}surveys (".implode(',',array_keys($surveyrowdata)).") VALUES (".implode(',',$values).")"; //handle db prefix
    $iresult = $connect->Execute($insert) or safe_die("<br />".$clang->gT("Import of this survey file failed")."<br />\n[$insert]<br />{$surveyarray[0]}<br /><br />\n" . $connect->ErrorMsg());

    // Now import the survey language settings
    $fieldorders=convertCSVRowToArray($surveylsarray[0],',','"');
    unset($surveylsarray[0]);
    foreach ($surveylsarray as $slsrow) {
        $fieldcontents=convertCSVRowToArray($slsrow,',','"');
        $surveylsrowdata=array_combine($fieldorders,$fieldcontents);
        // convert back the '\'.'n' char from the CSV file to true return char "\n"
        $surveylsrowdata=array_map('convertCsvreturn2return', $surveylsrowdata);
        // Convert the \n return char from welcometext to <br />

        // translate internal links
        $surveylsrowdata['surveyls_title']=translink('survey', $oldsid, $newsid, $surveylsrowdata['surveyls_title']);
        $surveylsrowdata['surveyls_description']=translink('survey', $oldsid, $newsid, $surveylsrowdata['surveyls_description']);
        $surveylsrowdata['surveyls_welcometext']=translink('survey', $oldsid, $newsid, $surveylsrowdata['surveyls_welcometext']);
        $surveylsrowdata['surveyls_urldescription']=translink('survey', $oldsid, $newsid, $surveylsrowdata['surveyls_urldescription']);
        $surveylsrowdata['surveyls_email_invite']=translink('survey', $oldsid, $newsid, $surveylsrowdata['surveyls_email_invite']);
        $surveylsrowdata['surveyls_email_remind']=translink('survey', $oldsid, $newsid, $surveylsrowdata['surveyls_email_remind']);
        $surveylsrowdata['surveyls_email_register']=translink('survey', $oldsid, $newsid, $surveylsrowdata['surveyls_email_register']);
        $surveylsrowdata['surveyls_email_confirm']=translink('survey', $oldsid, $newsid, $surveylsrowdata['surveyls_email_confirm']);
        unset($surveylsrowdata['lastpage']);
        $surveylsrowdata['surveyls_survey_id']=$newsid;
        $newvalues=array_values($surveylsrowdata);
        $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly
        $lsainsert = "INSERT INTO {$dbprefix}surveys_languagesettings (".implode(',',array_keys($surveylsrowdata)).") VALUES (".implode(',',$newvalues).")"; //handle db prefix
        $lsiresult=$connect->Execute($lsainsert) or safe_die("<br />".$clang->gT("Import of this survey file failed")."<br />\n[$lsainsert]<br />\n" . $connect->ErrorMsg() );
    }

    // The survey languagesettings are imported now
    $aLanguagesSupported = array();  // this array will keep all the languages supported for the survey

    $sBaseLanguage = GetBaseLanguageFromSurveyID($newsid);
    $aLanguagesSupported[]=$sBaseLanguage;     // adds the base language to the list of supported languages
    $aLanguagesSupported=array_merge($aLanguagesSupported,GetAdditionalLanguagesFromSurveyID($newsid));


    // DO SURVEY_RIGHTS
    GiveAllSurveyPermissions($_SESSION['loginID'],$newsid);
    $importresults['deniedcountls'] =0;


    $qtypes = getqtypelist("" ,"array");
    $results['labels']=0;
    $results['labelsets']=0;
    $results['answers']=0;
    $results['subquestions']=0;

    //Do label sets
    if (isset($labelsetsarray) && $labelsetsarray)
    {
        $csarray=buildLabelSetCheckSumArray();   // build checksums over all existing labelsets
        $count=0;
        foreach ($labelsetsarray as $lsa) {
            $fieldorders  =convertCSVRowToArray($labelsetsarray[0],',','"');
            $fieldcontents=convertCSVRowToArray($lsa,',','"');
            if ($count==0) {$count++; continue;}

            $labelsetrowdata=array_combine($fieldorders,$fieldcontents);

            // Save old labelid
            $oldlid=$labelsetrowdata['lid'];

            unset($labelsetrowdata['lid']);
            $newvalues=array_values($labelsetrowdata);
            $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly
            $lsainsert = "INSERT INTO {$dbprefix}labelsets (".implode(',',array_keys($labelsetrowdata)).") VALUES (".implode(',',$newvalues).")"; //handle db prefix
            $lsiresult=$connect->Execute($lsainsert);
            $results['labelsets']++;
            // Get the new insert id for the labels inside this labelset
            $newlid=$connect->Insert_ID("{$dbprefix}labelsets",'lid');

            if ($labelsarray) {
                $count=0;
                foreach ($labelsarray as $la) {
                    $lfieldorders  =convertCSVRowToArray($labelsarray[0],',','"');
                    $lfieldcontents=convertCSVRowToArray($la,',','"');
                    if ($count==0) {$count++; continue;}

                    // Combine into one array with keys and values since its easier to handle
                    $labelrowdata=array_combine($lfieldorders,$lfieldcontents);
                    $labellid=$labelrowdata['lid'];
                    if ($importversion<=132)
                    {
                        $labelrowdata["assessment_value"]=(int)$labelrowdata["code"];
                    }
                    if ($labellid == $oldlid) {
                        $labelrowdata['lid']=$newlid;

                        // translate internal links
                        $labelrowdata['title']=translink('label', $oldlid, $newlid, $labelrowdata['title']);

                        $newvalues=array_values($labelrowdata);
                        $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly
                        $lainsert = "INSERT INTO {$dbprefix}labels (".implode(',',array_keys($labelrowdata)).") VALUES (".implode(',',$newvalues).")"; //handle db prefix
                        $liresult=$connect->Execute($lainsert);
                        if ($liresult!==false) $results['labels']++;
                    }
                }
            }

            //CHECK FOR DUPLICATE LABELSETS
            $thisset="";

            $query2 = "SELECT code, title, sortorder, language, assessment_value
                       FROM {$dbprefix}labels
                       WHERE lid=".$newlid."
                       ORDER BY language, sortorder, code";
            $result2 = db_execute_num($query2) or safe_die("Died querying labelset $lid<br />$query2<br />".$connect->ErrorMsg());
            while($row2=$result2->FetchRow())
            {
                $thisset .= implode('.', $row2);
            } // while
            $newcs=dechex(crc32($thisset)*1);
            unset($lsmatch);
            if (isset($csarray))
            {
                foreach($csarray as $key=>$val)
                {
                    if ($val == $newcs)
                    {
                        $lsmatch=$key;
                    }
                }
            }
            if (isset($lsmatch) || ($_SESSION['USER_RIGHT_MANAGE_LABEL'] != 1))
            {
                //There is a matching labelset or the user is not allowed to edit labels -
                // So, we will delete this one and refer to the matched one.
                $query = "DELETE FROM {$dbprefix}labels WHERE lid=$newlid";
                $result=$connect->Execute($query) or safe_die("Couldn't delete labels<br />$query<br />".$connect->ErrorMsg());
                $results['labels']=$results['labels']-$connect->Affected_Rows();

                $query = "DELETE FROM {$dbprefix}labelsets WHERE lid=$newlid";
                $result=$connect->Execute($query) or safe_die("Couldn't delete labelset<br />$query<br />".$connect->ErrorMsg());
                $results['labelsets']=$results['labelsets']-$connect->Affected_Rows();
                $newlid=$lsmatch;
            }
            else
            {
                //There isn't a matching labelset, add this checksum to the $csarray array
                $csarray[$newlid]=$newcs;
            }
            //END CHECK FOR DUPLICATES
            $aLIDReplacements[$oldlid]=$newlid;
        }
    }

    // Import groups
    if (isset($grouparray) && $grouparray)
    {
        // do GROUPS
        $gafieldorders=convertCSVRowToArray($grouparray[0],',','"');
        unset($grouparray[0]);
        foreach ($grouparray as $ga)
        {
            $gacfieldcontents=convertCSVRowToArray($ga,',','"');
            $grouprowdata=array_combine($gafieldorders,$gacfieldcontents);

            //Now an additional integrity check if there are any groups not belonging into this survey
            if ($grouprowdata['sid'] != $oldsid)
            {
                $results['fatalerror'] = $clang->gT("A group in the CSV/SQL file is not part of the same survey. The import of the survey was stopped.")."<br />\n";
                return $results;
            }
            $grouprowdata['sid']=$newsid;
            // remember group id
            $oldgid=$grouprowdata['gid'];

            //update/remove the old group id
            if (isset($aGIDReplacements[$oldgid]))
            $grouprowdata['gid'] = $aGIDReplacements[$oldgid];
            else
            unset($grouprowdata['gid']);

            // Everything set - now insert it
            $grouprowdata=array_map('convertCsvreturn2return', $grouprowdata);

            // translate internal links
            $grouprowdata['group_name']=translink('survey', $oldsid, $newsid, $grouprowdata['group_name']);
            $grouprowdata['description']=translink('survey', $oldsid, $newsid, $grouprowdata['description']);

            if (isset($grouprowdata['gid'])) db_switchIDInsert('groups',true);
            $tablename=$dbprefix.'groups';
            $ginsert = $connect->GetinsertSQL($tablename,$grouprowdata);
            $gres = $connect->Execute($ginsert) or safe_die($clang->gT('Error').": Failed to insert group<br />\n$ginsert<br />\n".$connect->ErrorMsg());
            if (isset($grouprowdata['gid'])) db_switchIDInsert('groups',false);
            //GET NEW GID
            if (!isset($grouprowdata['gid'])) {$aGIDReplacements[$oldgid]=$connect->Insert_ID("{$dbprefix}groups","gid");}
        }
        // Fix sortorder of the groups  - if users removed groups manually from the csv file there would be gaps
        fixSortOrderGroups($newsid);
    }
    // GROUPS is DONE

    // Import questions
    if (isset($questionarray) && $questionarray)
    {
        $qafieldorders=convertCSVRowToArray($questionarray[0],',','"');
        unset($questionarray[0]);
        foreach ($questionarray as $qa)
        {
            $qacfieldcontents=convertCSVRowToArray($qa,',','"');
            $questionrowdata=array_combine($qafieldorders,$qacfieldcontents);
            $questionrowdata=array_map('convertCsvreturn2return', $questionrowdata);
            $questionrowdata["type"]=strtoupper($questionrowdata["type"]);

            // Skip not supported languages
            if (!in_array($questionrowdata['language'],$aLanguagesSupported))
                continue;

            // replace the sid
            $questionrowdata["sid"] = $newsid;
            // Skip if gid is invalid
            if (!isset($aGIDReplacements[$questionrowdata['gid']])) continue;
            $questionrowdata["gid"] = $aGIDReplacements[$questionrowdata['gid']];
            if (isset($aQIDReplacements[$questionrowdata['qid']]))
            {
                $questionrowdata['qid']=$aQIDReplacements[$questionrowdata['qid']];
            }
            else
            {
                $oldqid=$questionrowdata['qid'];
                unset($questionrowdata['qid']);
            }

            unset($oldlid1); unset($oldlid2);
            if ((isset($questionrowdata['lid']) && $questionrowdata['lid']>0))
            {
                $oldlid1=$questionrowdata['lid'];
            }
            if ((isset($questionrowdata['lid1']) && $questionrowdata['lid1']>0))
            {
                $oldlid2=$questionrowdata['lid1'];
            }
            unset($questionrowdata['lid']);
            unset($questionrowdata['lid1']);
            if ($questionrowdata['type']=='W')
            {
                $questionrowdata['type']='!';
            }
            elseif ($questionrowdata['type']=='Z')
            {
                $questionrowdata['type']='L';
                $aIgnoredAnswers[]=$oldqid;
            }

            if (!isset($questionrowdata["question_order"]) || $questionrowdata["question_order"]=='') {$questionrowdata["question_order"]=0;}
            // translate internal links
            $questionrowdata['title']=translink('survey', $oldsid, $newsid, $questionrowdata['title']);
            $questionrowdata['question']=translink('survey', $oldsid, $newsid, $questionrowdata['question']);
            $questionrowdata['help']=translink('survey', $oldsid, $newsid, $questionrowdata['help']);


            if (isset($questionrowdata['qid'])) {
                db_switchIDInsert('questions',true);
            }

            $tablename=$dbprefix.'questions';
            $qinsert = $connect->GetInsertSQL($tablename,$questionrowdata);
            $qres = $connect->Execute($qinsert) or safe_die ($clang->gT("Error").": Failed to insert question<br />\n$qinsert<br />\n".$connect->ErrorMsg());

            if (isset($questionrowdata['qid'])) {
                db_switchIDInsert('questions',false);
                $saveqid=$questionrowdata['qid'];
            }
            else
            {
                $aQIDReplacements[$oldqid]=$connect->Insert_ID("{$dbprefix}questions",'qid');
                $saveqid=$aQIDReplacements[$oldqid];
            }


            // Now we will fix up old label sets where they are used as answers
            if (((isset($oldlid1) && isset($aLIDReplacements[$oldlid1])) || (isset($oldlid2) && isset($aLIDReplacements[$oldlid2]))) && ($qtypes[$questionrowdata['type']]['answerscales']>0 || $qtypes[$questionrowdata['type']]['subquestions']>1))
            {
                $query="select * from ".db_table_name('labels')." where lid={$aLIDReplacements[$oldlid1]} and language='{$questionrowdata['language']}'";
                $oldlabelsresult=db_execute_assoc($query);
                while($labelrow=$oldlabelsresult->FetchRow())
                {
                    if (in_array($labelrow['language'],$aLanguagesSupported))
                    {

                        if ($qtypes[$questionrowdata['type']]['subquestions']<2)
                        {
                            $qinsert = "insert INTO ".db_table_name('answers')." (qid,code,answer,sortorder,language,assessment_value)
                                        VALUES ({$aQIDReplacements[$oldqid]},".db_quoteall($labelrow['code']).",".db_quoteall($labelrow['title']).",".db_quoteall($labelrow['sortorder']).",".db_quoteall($labelrow['language']).",".db_quoteall($labelrow['assessment_value']).")";
                            $qres = $connect->Execute($qinsert) or safe_die ($clang->gT("Error").": Failed to insert answer (lid1) <br />\n$qinsert<br />\n".$connect->ErrorMsg());
                        }
                        else
                        {
                            if (isset($aSQIDReplacements[$labelrow['code'].'_'.$saveqid])){
                               $fieldname='qid,';
                               $data=$aSQIDReplacements[$labelrow['code'].'_'.$saveqid].',';
                            }
                            else{
                               $fieldname='' ;
                               $data='';
                            }

                            $qinsert = "insert INTO ".db_table_name('questions')." ($fieldname parent_qid,title,question,question_order,language,scale_id,type, sid, gid)
                                        VALUES ($data{$aQIDReplacements[$oldqid]},".db_quoteall($labelrow['code']).",".db_quoteall($labelrow['title']).",".db_quoteall($labelrow['sortorder']).",".db_quoteall($labelrow['language']).",1,'{$questionrowdata['type']}',{$questionrowdata['sid']},{$questionrowdata['gid']})";
                            $qres = $connect->Execute($qinsert) or safe_die ($clang->gT("Error").": Failed to insert question <br />\n$qinsert<br />\n".$connect->ErrorMsg());
                            if ($fieldname=='')
                            {
                               $aSQIDReplacements[$labelrow['code'].'_'.$saveqid]=$connect->Insert_ID("{$dbprefix}questions","qid");
                            }
                        }
                    }
                }
                if (isset($oldlid2) && $qtypes[$questionrowdata['type']]['answerscales']>1)
                {
                    $query="select * from ".db_table_name('labels')." where lid={$aLIDReplacements[$oldlid2]} and language='{$questionrowdata['language']}'";
                    $oldlabelsresult=db_execute_assoc($query);
                    while($labelrow=$oldlabelsresult->FetchRow())
                    {
                        $qinsert = "insert INTO ".db_table_name('answers')." (qid,code,answer,sortorder,language,assessment_value,scale_id)
                                    VALUES ({$aQIDReplacements[$oldqid]},".db_quoteall($labelrow['code']).",".db_quoteall($labelrow['title']).",".db_quoteall($labelrow['sortorder']).",".db_quoteall($labelrow['language']).",".db_quoteall($labelrow['assessment_value']).",1)";
                        $qres = $connect->Execute($qinsert) or safe_die ($clang->gT("Error").": Failed to insert answer (lid2)<br />\n$qinsert<br />\n".$connect->ErrorMsg());
                    }
                }
            }
        }
    }

    //Do answers
    if (isset($answerarray) && $answerarray)
    {
        $answerfieldnames = convertCSVRowToArray($answerarray[0],',','"');
        unset($answerarray[0]);
        foreach ($answerarray as $aa)
        {
            $answerfieldcontents = convertCSVRowToArray($aa,',','"');
            $answerrowdata = array_combine($answerfieldnames,$answerfieldcontents);
            if (in_array($answerrowdata['qid'],$aIgnoredAnswers))
            {
                 // Due to a bug in previous LS versions there may be orphaned answers with question type Z (which is now L)
                 // this way they are ignored
                 continue;
            }
            if ($answerrowdata===false)
            {
                $importquestion.='<br />'.$clang->gT("Faulty line in import - fields and data don't match").":".implode(',',$answerfieldcontents);
            }
            // Skip not supported languages
            if (!in_array($answerrowdata['language'],$aLanguagesSupported))
                continue;

            // replace the qid for the new one (if there is no new qid in the $aQIDReplacements array it mean that this answer is orphan -> error, skip this record)
            if (isset($aQIDReplacements[$answerrowdata["qid"]]))
            $answerrowdata["qid"] = $aQIDReplacements[$answerrowdata["qid"]];
            else
            continue; // a problem with this answer record -> don't consider

            if ($importversion<=132)
            {
                $answerrowdata["assessment_value"]=(int)$answerrowdata["code"];
            }
            // Convert default values for single select questions
            $questiontemp=$connect->GetRow('select type,gid from '.db_table_name('questions').' where qid='.$answerrowdata["qid"]);
            $oldquestion['newtype']=$questiontemp['type'];
            $oldquestion['gid']=$questiontemp['gid'];
            if ($answerrowdata['default_value']=='Y' && ($oldquestion['newtype']=='L' || $oldquestion['newtype']=='O' || $oldquestion['newtype']=='!'))
                            {
                $insertdata=array();
                $insertdata['qid']=$newqid;
                $insertdata['language']=$answerrowdata['language'];
                $insertdata['defaultvalue']=$answerrowdata['answer'];
                $query=$connect->GetInsertSQL($dbprefix.'defaultvalues',$insertdata);
                $qres = $connect->Execute($query) or safe_die ("Error: Failed to insert defaultvalue <br />{$query}<br />\n".$connect->ErrorMsg());

            }
            // translate internal links
            $answerrowdata['answer']=translink('survey', $oldsid, $newsid, $answerrowdata['answer']);
            // Everything set - now insert it
            $answerrowdata = array_map('convertCsvreturn2return', $answerrowdata);

            if ($qtypes[$oldquestion['newtype']]['subquestions']>0) //hmmm.. this is really a subquestion
            {
                $questionrowdata=array();
                if (isset($aSQIDReplacements[$answerrowdata['code'].$answerrowdata['qid']])){
                   $questionrowdata['qid']=$aSQIDReplacements[$answerrowdata['code'].$answerrowdata['qid']];
                }
                $questionrowdata['parent_qid']=$answerrowdata['qid'];;
                $questionrowdata['sid']=$newsid;
                $questionrowdata['gid']=$oldquestion['gid'];
                $questionrowdata['title']=$answerrowdata['code'];
                $questionrowdata['question']=$answerrowdata['answer'];
                $questionrowdata['question_order']=$answerrowdata['sortorder'];
                $questionrowdata['language']=$answerrowdata['language'];
                $questionrowdata['type']=$oldquestion['newtype'];

                $tablename=$dbprefix.'questions';
                $query=$connect->GetInsertSQL($tablename,$questionrowdata);
                if (isset($questionrowdata['qid'])) db_switchIDInsert('questions',true);
                $qres = $connect->Execute($query) or safe_die ("Error: Failed to insert subquestion <br />{$query}<br />".$connect->ErrorMsg());
                if (!isset($questionrowdata['qid']))
                {
                   $aSQIDReplacements[$answerrowdata['code'].$answerrowdata['qid']]=$connect->Insert_ID("{$dbprefix}questions","qid");
                }
                else
                {
                    db_switchIDInsert('questions',false);
                }
                $results['subquestions']++;
                // also convert default values subquestions for multiple choice
                if ($answerrowdata['default_value']=='Y' && ($oldquestion['newtype']=='M' || $oldquestion['newtype']=='P'))
                {
                    $insertdata=array();
                    $insertdata['qid']=$newqid;
                    $insertdata['sqid']=$aSQIDReplacements[$answerrowdata['code']];
                    $insertdata['language']=$answerrowdata['language'];
                    $insertdata['defaultvalue']='Y';
                    $tablename=$dbprefix.'defaultvalues';
                    $query=$connect->GetInsertSQL($tablename,$insertdata);
                    $qres = $connect->Execute($query) or safe_die ("Error: Failed to insert defaultvalue <br />{$query}<br />\n".$connect->ErrorMsg());
                }

            }
            else   // insert answers
            {
                unset($answerrowdata['default_value']);
                $tablename=$dbprefix.'answers';
                $query=$connect->GetInsertSQL($tablename,$answerrowdata);
                $ares = $connect->Execute($query) or safe_die ("Error: Failed to insert answer<br />{$query}<br />\n".$connect->ErrorMsg());
                $results['answers']++;
            }

        }
    }

    // get all group ids and fix questions inside each group
    $gquery = "SELECT gid FROM {$dbprefix}groups where sid=$newsid group by gid ORDER BY gid"; //Get last question added (finds new qid)
    $gres = db_execute_assoc($gquery);
    while ($grow = $gres->FetchRow())
    {
        fixsortorderQuestions($grow['gid'], $newsid);
    }

    //We've built two arrays along the way - one containing the old SID, GID and QIDs - and their NEW equivalents
    //and one containing the old 'extended fieldname' and its new equivalent.  These are needed to import conditions and question_attributes.
    if (isset($question_attributesarray) && $question_attributesarray) {//ONLY DO THIS IF THERE ARE QUESTION_ATTRIBUES
        $fieldorders  =convertCSVRowToArray($question_attributesarray[0],',','"');
        unset($question_attributesarray[0]);
        foreach ($question_attributesarray as $qar) {
            $fieldcontents=convertCSVRowToArray($qar,',','"');
            $qarowdata=array_combine($fieldorders,$fieldcontents);
            $newqid="";
            $qarowdata["qid"]=$aQIDReplacements[$qarowdata["qid"]];
            unset($qarowdata["qaid"]);

            $newvalues=array_values($qarowdata);
            $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly
            $qainsert = "insert INTO {$dbprefix}question_attributes (".implode(',',array_keys($qarowdata)).") VALUES (".implode(',',$newvalues).")";
            $result=$connect->Execute($qainsert); // no safe_die since some LimeSurvey version export duplicate question attributes - these are just ignored
            if ($connect->Affected_Rows()>0) {$importresults['question_attributes']++;}
        }
    }

    if (isset($assessmentsarray) && $assessmentsarray) {//ONLY DO THIS IF THERE ARE QUESTION_ATTRIBUTES
        $fieldorders=convertCSVRowToArray($assessmentsarray[0],',','"');
        unset($assessmentsarray[0]);
        foreach ($assessmentsarray as $qar)
        {
            $fieldcontents=convertCSVRowToArray($qar,',','"');
            $asrowdata=array_combine($fieldorders,$fieldcontents);
            if (isset($asrowdata['link']))
            {
                if (trim($asrowdata['link'])!='') $asrowdata['message']=$asrowdata['message'].'<br /><a href="'.$asrowdata['link'].'">'.$asrowdata['link'].'</a>';
                unset($asrowdata['link']);
            }
            if  ($asrowdata["gid"]>0)
            {
                $asrowdata["gid"]=$aGIDReplacements[$asrowdata["gid"]];
            }

            $asrowdata["sid"]=$newsid;
            unset($asrowdata["id"]);

            $tablename=$dbprefix.'assessments';
            $asinsert = $connect->GetInsertSQL($tablename,$asrowdata);
            $result=$connect->Execute($asinsert) or safe_die ("Couldn't insert assessment<br />$asinsert<br />".$connect->ErrorMsg());

            unset($newgid);
        }
    }

    if (isset($quotaarray) && $quotaarray) {//ONLY DO THIS IF THERE ARE QUOTAS
        $fieldorders=convertCSVRowToArray($quotaarray[0],',','"');
        unset($quotaarray[0]);
        foreach ($quotaarray as $qar)
        {
            $fieldcontents=convertCSVRowToArray($qar,',','"');

            $asrowdata=array_combine($fieldorders,$fieldcontents);

            $oldsid=$asrowdata["sid"];
            foreach ($substitutions as $subs) {
                if ($oldsid==$subs[0]) {$newsid=$subs[3];}
            }

            $asrowdata["sid"]=$newsid;
            $oldid = $asrowdata["id"];
            unset($asrowdata["id"]);
            $quotadata[]=$asrowdata; //For use later if needed
            $tablename=$dbprefix.'quota';
            $asinsert = $connect->getInsertSQL($tablename,$asrowdata);
            $result=$connect->Execute($asinsert) or safe_die ("Couldn't insert quota<br />$asinsert<br />".$connect->ErrorMsg());
            $aQuotaReplacements[$oldid] = $connect->Insert_ID(db_table_name_nq('quota'),"id");
        }
    }

    if (isset($quotamembersarray) && $quotamembersarray) {//ONLY DO THIS IF THERE ARE QUOTA MEMBERS
        $count=0;
        foreach ($quotamembersarray as $qar) {

            $fieldorders  =convertCSVRowToArray($quotamembersarray[0],',','"');
            $fieldcontents=convertCSVRowToArray($qar,',','"');
            if ($count==0) {$count++; continue;}

            $asrowdata=array_combine($fieldorders,$fieldcontents);

            $oldsid=$asrowdata["sid"];
            $newqid="";
            $newquotaid="";
            $oldqid=$asrowdata['qid'];
            $oldquotaid=$asrowdata['quota_id'];

            foreach ($substitutions as $subs) {
                if ($oldsid==$subs[0]) {$newsid=$subs[3];}
                if ($oldqid==$subs[2]) {$newqid=$subs[5];}
            }

            $newquotaid=$aQuotaReplacements[$oldquotaid];

            $asrowdata["sid"]=$newsid;
            $asrowdata["qid"]=$newqid;
            $asrowdata["quota_id"]=$newquotaid;
            unset($asrowdata["id"]);

            $tablename=$dbprefix.'quota_members';
            $asinsert = $connect->getInsertSQL($tablename,$asrowdata);

            $result=$connect->Execute($asinsert) or safe_die ("Couldn't insert quota<br />$asinsert<br />".$connect->ErrorMsg());

        }
    }

    if (isset($quotalsarray) && $quotalsarray) {//ONLY DO THIS IF THERE ARE QUOTA LANGUAGE SETTINGS
        $count=0;
        foreach ($quotalsarray as $qar) {

            $fieldorders  =convertCSVRowToArray($quotalsarray[0],',','"');
            $fieldcontents=convertCSVRowToArray($qar,',','"');
            if ($count==0) {$count++; continue;}

            $asrowdata=array_combine($fieldorders,$fieldcontents);

            $newquotaid="";
            $oldquotaid=$asrowdata['quotals_quota_id'];

            $newquotaid=$aQuotaReplacements[$oldquotaid];

            $asrowdata["quotals_quota_id"]=$newquotaid;
            unset($asrowdata["quotals_id"]);

            $tablename=$dbprefix.'quota_languagesettings';
            $asinsert = $connect->getInsertSQL($tablename,$asrowdata);
            $result=$connect->Execute($asinsert) or safe_die ("Couldn't insert quota<br />$asinsert<br />".$connect->ErrorMsg());
        }
    }

    //if there are quotas, but no quotals, then we need to create default dummy for each quota (this handles exports from pre-language quota surveys)
    if ($importresults['quota'] > 0 && (!isset($importresults['quotals']) || $importresults['quotals'] == 0)) {
        $i=0;
        $defaultsurveylanguage=isset($defaultsurveylanguage) ? $defaultsurveylanguage : "en";
        foreach($aQuotaReplacements as $oldquotaid=>$newquotaid) {
            $asrowdata=array("quotals_quota_id" => $newquotaid,
                             "quotals_language" => $defaultsurveylanguage,
                             "quotals_name" => $quotadata[$i]["name"],
                             "quotals_message" => $clang->gT("Sorry your responses have exceeded a quota on this survey."),
                             "quotals_url" => "",
                             "quotals_urldescrip" => "");
            $i++;
        }
        $tablename=$dbprefix.'quota_languagesettings';
        $asinsert = $connect->getInsertSQL($tablename,$asrowdata);
        $result=$connect->Execute($asinsert) or safe_die ("Couldn't insert quota<br />$asinsert<br />".$connect->ErrorMsg());
        $countquotals=$i;
    }

    // Do conditions
    if (isset($conditionsarray) && $conditionsarray) {//ONLY DO THIS IF THERE ARE CONDITIONS!
        $fieldorders  =convertCSVRowToArray($conditionsarray[0],',','"');
        unset($conditionsarray[0]);
       // Exception for conditions based on attributes
        $aQIDReplacements[0]=0;
        foreach ($conditionsarray as $car) {
            $fieldcontents=convertCSVRowToArray($car,',','"');
            $conditionrowdata=array_combine($fieldorders,$fieldcontents);

            unset($conditionrowdata["cid"]);
            if (!isset($conditionrowdata["method"]) || trim($conditionrowdata["method"])=='')
            {
                $conditionrowdata["method"]='==';
            }
            if (!isset($conditionrowdata["scenario"]) || trim($conditionrowdata["scenario"])=='')
            {
                $conditionrowdata["scenario"]=1;
            }
            $oldcqid=$conditionrowdata["cqid"];
            $oldgid=array_search($connect->GetOne('select gid from '.db_table_name('questions').' where qid='.$aQIDReplacements[$conditionrowdata["cqid"]]),$aGIDReplacements);
            $conditionrowdata["qid"]=$aQIDReplacements[$conditionrowdata["qid"]];
            $conditionrowdata["cqid"]=$aQIDReplacements[$conditionrowdata["cqid"]];
            $oldcfieldname=$conditionrowdata["cfieldname"];
            $conditionrowdata["cfieldname"]=str_replace($oldsid.'X'.$oldgid.'X'.$oldcqid,$newsid.'X'.$aGIDReplacements[$oldgid].'X'.$conditionrowdata["cqid"],$conditionrowdata["cfieldname"]);

            $tablename=$dbprefix.'conditions';
            $conditioninsert = $connect->getInsertSQL($tablename,$conditionrowdata);
            $result=$connect->Execute($conditioninsert) or safe_die ("Couldn't insert condition<br />$conditioninsert<br />".$connect->ErrorMsg());

        }
    }
    $importresults['importversion']=$importversion;
    $importresults['newsid']=$newsid;
    $importresults['oldsid']=$oldsid;
    return $importresults;
}
/**
 * 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;
}
Example #4
0
     $editsurvey .= " selected='selected'";
 }
 $editsurvey .= ">" . $clang->gT("Question by Question") . "</option>\n" . "<option value='G'";
 if ($esrow['format'] == "G") {
     $editsurvey .= " selected='selected'";
 }
 $editsurvey .= ">" . $clang->gT("Group by Group") . "</option>\n" . "<option value='A'";
 if ($esrow['format'] == "A") {
     $editsurvey .= " selected='selected'";
 }
 $editsurvey .= ">" . $clang->gT("All in one") . "</option>\n" . "</select>\n" . "</li>\n";
 //TEMPLATES
 if (!$esrow['template']) {
     $esrow['template'] = $defaulttemplate;
 }
 $esrow['template'] = validate_templatedir($esrow['template']);
 $editsurvey .= "<li><label for='template'>" . $clang->gT("Template:") . "</label>\n" . "<select id='template' name='template'>\n";
 foreach (array_keys(gettemplatelist()) as $tname) {
     if ($_SESSION['USER_RIGHT_SUPERADMIN'] == 1 || $_SESSION['USER_RIGHT_MANAGE_TEMPLATE'] == 1 || hasTemplateManageRights($_SESSION["loginID"], $tname) == 1) {
         $editsurvey .= "<option value='{$tname}'";
         if ($esrow['template'] && htmlspecialchars($tname) == $esrow['template']) {
             $editsurvey .= " selected='selected'";
         }
         $editsurvey .= ">{$tname}</option>\n";
     }
 }
 $editsurvey .= "</select>\n" . "</li>\n";
 $editsurvey .= "<li><label for='preview'>" . $clang->gT("Template Preview:") . "</label>\n" . "<img alt='" . $clang->gT("Template preview image") . "' id='preview' src='" . sGetTemplateURL($esrow['template']) . "/preview.png' />\n" . "</li>\n";
 //SHOW WELCOMESCRN
 $editsurvey .= "<li><label for='showwelcome'>" . $clang->gT("Show welcome screen?") . "</label>\n" . "<select id='showwelcome' name='showwelcome'>\n" . "<option value='Y'";
 if (!$esrow['showwelcome'] || $esrow['showwelcome'] == "Y") {
Example #5
0
/**
 * This function returns an array containing the "question/answer" html display
 * and a list of the question/answer fieldnames associated. It is called from
 * question.php, group.php or survey.php
 *
 * @param mixed $ia
 * @param mixed $notanswered
 * @param mixed $notvalidated
 * @param mixed $filenotvalidated
 * @return mixed
 */
function retrieveAnswers($ia, $notanswered=null, $notvalidated=null, $filenotvalidated=null)
{
    //globalise required config variables
    global $dbprefix, $clang; //These are from the config-defaults.php file
    global $thissurvey, $gl; //These are set by index.php
    global $connect;

    //DISPLAY
    $display = $ia[7];

    //QUESTION NAME
    $name = $ia[0];

    $qtitle=$ia[3];
    //Replace INSERTANS statements with previously provided answers;
    $qtitle=dTexts::run($qtitle);


    //GET HELP
    $hquery="SELECT help FROM {$dbprefix}questions WHERE qid=$ia[0] AND language='".$_SESSION['s_lang']."'";
    $hresult=db_execute_num($hquery) or safe_die($connect->ErrorMsg());       //Checked
    $help="";
    while ($hrow=$hresult->FetchRow()) {$help=$hrow[0];}

    //A bit of housekeeping to stop PHP Notices
    $answer = "";
    if (!isset($_SESSION[$ia[1]])) {$_SESSION[$ia[1]] = "";}
    $qidattributes=getQuestionAttributes($ia[0],$ia[4]);
    //echo "<pre>";print_r($qidattributes);echo "</pre>";
    //Create the question/answer html

    // Previously in limesurvey, it was virtually impossible to control how the start of questions were formatted.
    // this is an attempt to allow users (or rather system admins) some control over how the starting text is formatted.
    $number = isset($ia[9]) ? $ia[9] : '';

    $question_text = array(
				 'all' => '' // All has been added for backwards compatibility with templates that use question_start.pstpl (now redundant)
    ,'text' => $qtitle
    ,'code' => $ia[2]
    ,'number' => $number
    ,'help' => ''
    ,'mandatory' => ''
    ,'man_message' => ''
    ,'valid_message' => ''
    ,'file_valid_message' => ''
    ,'class' => ''
    ,'man_class' => ''
    ,'input_error_class' => ''// provides a class.
    ,'essentials' => ''
    );

    switch ($ia[4])
    {
        case 'X': //BOILERPLATE QUESTION
            $values = do_boilerplate($ia);
            break;
        case '5': //5 POINT CHOICE radio-buttons
            $values = do_5pointchoice($ia);
            break;
        case 'D': //DATE
            $values = do_date($ia);
            break;
        case 'L': //LIST drop-down/radio-button list
            $values = do_list_radio($ia);
            if ($qidattributes['hide_tip']==0)
            {
                $qtitle .= "<br />\n<span class=\"questionhelp\">"
                . $clang->gT('Choose one of the following answers').'</span>';
                $question_text['help'] = $clang->gT('Choose one of the following answers');
            }
            break;
        case '!': //List - dropdown
            $values=do_list_dropdown($ia);
            if ($qidattributes['hide_tip']==0)
            {
                $qtitle .= "<br />\n<span class=\"questionhelp\">"
                . $clang->gT('Choose one of the following answers').'</span>';
                $question_text['help'] = $clang->gT('Choose one of the following answers');
            }
            break;
        case 'O': //LIST WITH COMMENT drop-down/radio-button list + textarea
            $values=do_listwithcomment($ia);
            if (count($values[1]) > 1 && $qidattributes['hide_tip']==0)
            {
                $qtitle .= "<br />\n<span class=\"questionhelp\">"
                . $clang->gT('Choose one of the following answers').'</span>';
                $question_text['help'] = $clang->gT('Choose one of the following answers');
            }
            break;
        case 'R': //RANKING STYLE
            $values=do_ranking($ia);
            if (count($values[1]) > 1 && $qidattributes['hide_tip']==0)
            {
                $question_text['help'] = $clang->gT("Click on an item in the list on the left, starting with your highest ranking item, moving through to your lowest ranking item.");
                if (trim($qidattributes['min_answers'])!='')
                {
                    $qtitle .= "<br />\n<span class=\"questionhelp\">"
                    . sprintf($clang->ngT("Check at least %d item","Check at least %d items",$qidattributes['min_answers']),$qidattributes['min_answers'])."</span>";
                    $question_text['help'] .=' '.sprintf($clang->ngT("Check at least %d item","Check at least %d items",$qidattributes['min_answers']),$qidattributes['min_answers']);
                }
            }
            break;
        case 'M': //Multiple choice checkbox
            $values=do_multiplechoice($ia);
            if (count($values[1]) > 1 && $qidattributes['hide_tip']==0)
            {
                $maxansw=trim($qidattributes['max_answers']);
                $minansw=trim($qidattributes['min_answers']);
                if (!($maxansw || $minansw))
                {
                    $qtitle .= "<br />\n<span class=\"questionhelp\">"
                    . $clang->gT('Check any that apply').'</span>';
                    $question_text['help'] = $clang->gT('Check any that apply');
                }
                else
                {
                    if ($maxansw && $minansw)
                    {
                        $qtitle .= "<br />\n<span class=\"questionhelp\">"
                        . sprintf($clang->gT("Check between %d and %d answers"), $minansw, $maxansw)."</span>";
                        $question_text['help'] = sprintf($clang->gT("Check between %d and %d answers"), $minansw, $maxansw);
                    } elseif ($maxansw)
                    {
                        $qtitle .= "<br />\n<span class=\"questionhelp\">"
                        . sprintf($clang->gT("Check at most %d answers"), $maxansw)."</span>";
                        $question_text['help'] = sprintf($clang->gT("Check at most %d answers"), $maxansw);
                    } else
                    {
                        $qtitle .= "<br />\n<span class=\"questionhelp\">"
                        . sprintf($clang->ngT("Check at least %d answer","Check at least %d answers",$minansw),$minansw)."</span>";
                        $question_text['help'] = sprintf($clang->ngT("Check at least %d answer","Check at least %d answers",$minansw),$minansw);
                    }
                }
            }
            break;

        case 'I': //Language Question
            $values=do_language($ia);
            if (count($values[1]) > 1)
            {
                $qtitle .= "<br />\n<span class=\"questionhelp\">"
                . $clang->gT('Choose your language').'</span>';
                $question_text['help'] = $clang->gT('Choose your language');
            }
            break;
        case 'P': //Multiple choice with comments checkbox + text
            $values=do_multiplechoice_withcomments($ia);
            if (count($values[1]) > 1 && $qidattributes['hide_tip']==0)
            {
                $maxansw=trim($qidattributes["max_answers"]);
                $minansw=trim($qidattributes["min_answers"]);
                if (!($maxansw || $minansw))
                {
                    $qtitle .= "<br />\n<span class=\"questionhelp\">"
                    . $clang->gT('Check any that apply').'</span>';
                    $question_text['help'] = $clang->gT('Check any that apply');
                }
                else
                {
                    if ($maxansw && $minansw)
                    {
                        $qtitle .= "<br />\n<span class=\"questionhelp\">"
                        . sprintf($clang->gT("Check between %d and %d answers"), $minansw, $maxansw)."</span>";
                        $question_text['help'] = sprintf($clang->gT("Check between %d and %d answers"), $minansw, $maxansw);
                    } elseif ($maxansw)
                    {
                        $qtitle .= "<br />\n<span class=\"questionhelp\">"
                        . sprintf($clang->gT("Check at most %d answers"), $maxansw)."</span>";
                        $question_text['help'] = sprintf($clang->gT("Check at most %d answers"), $maxansw);
                    } else
                    {
                        $qtitle .= "<br />\n<span class=\"questionhelp\">"
                        . sprintf($clang->gT("Check at least %d answers"), $minansw)."</span>";
                        $question_text['help'] = sprintf($clang->gT("Check at least %d answers"), $minansw);
                    }
                }
            }
            break;
        case '|': //File Upload
            $values=do_file_upload($ia);
            if ($qidattributes['min_num_of_files'] != 0)
            {
                if (trim($qidattributes['min_num_of_files']) != 0)
                {
                    $qtitle .= "<br />\n<span class = \"questionhelp\">"
                    .sprintf($clang->gT("At least %d files must be uploaded for this question"), $qidattributes['min_num_of_files'])."<span>";
                    $question_text['help'] .= ' '.sprintf($clang->gT("At least %d files must be uploaded for this question"), $qidattributes['min_num_of_files']);
                }
            }
            break;
        case 'Q': //MULTIPLE SHORT TEXT
            $values=do_multipleshorttext($ia);
            break;
        case 'K': //MULTIPLE NUMERICAL QUESTION
            $values=do_multiplenumeric($ia);
            break;
        case 'N': //NUMERICAL QUESTION TYPE
            $values=do_numerical($ia);
            break;
        case 'S': //SHORT FREE TEXT
            $values=do_shortfreetext($ia);
            break;
        case 'T': //LONG FREE TEXT
            $values=do_longfreetext($ia);
            break;
        case 'U': //HUGE FREE TEXT
            $values=do_hugefreetext($ia);
            break;
        case 'Y': //YES/NO radio-buttons
            $values=do_yesno($ia);
            break;
        case 'G': //GENDER drop-down list
            $values=do_gender($ia);
            break;
        case 'A': //ARRAY (5 POINT CHOICE) radio-buttons
            $values=do_array_5point($ia);
            break;
        case 'B': //ARRAY (10 POINT CHOICE) radio-buttons
            $values=do_array_10point($ia);
            break;
        case 'C': //ARRAY (YES/UNCERTAIN/NO) radio-buttons
            $values=do_array_yesnouncertain($ia);
            break;
        case 'E': //ARRAY (Increase/Same/Decrease) radio-buttons
            $values=do_array_increasesamedecrease($ia);
            break;
        case 'F': //ARRAY (Flexible) - Row Format
            $values=do_array($ia);
            break;
        case 'H': //ARRAY (Flexible) - Column Format
            $values=do_arraycolumns($ia);
            break;
        case ':': //ARRAY (Multi Flexi) 1 to 10
            $values=do_array_multiflexi($ia);
            break;
        case ';': //ARRAY (Multi Flexi) Text
            $values=do_array_multitext($ia);  //It's like the "5th element" movie, come to life
            break;
        case '1': //Array (Flexible Labels) dual scale
            $values=do_array_dual($ia);
            break;
    } //End Switch

    if (isset($values)) //Break apart $values array returned from switch
    {
        //$answer is the html code to be printed
        //$inputnames is an array containing the names of each input field
        list($answer, $inputnames)=$values;
    }

    $answer .= "\n\t<input type='hidden' name='display$ia[1]' id='display$ia[0]' value='";
    $answer .= 'on'; //If this is single format, then it must be showing. Needed for checking conditional mandatories
    $answer .= "' />\n"; //for conditional mandatory questions

    if ($ia[6] == 'Y')
    {
        $qtitle = '<span class="asterisk">'.$clang->gT('*').'</span>'.$qtitle;
        $question_text['mandatory'] = $clang->gT('*');
    }
    //If this question is mandatory but wasn't answered in the last page
    //add a message HIGHLIGHTING the question
    $qtitle .= mandatory_message($ia);
    $question_text['man_message'] = mandatory_message($ia);

    $qtitle .= validation_message($ia);
    $question_text['valid_message'] = validation_message($ia);

    $qtitle .= $ia[4] == "|" ? file_validation_message($ia) : "";
    $question_text['file_valid_message'] = $ia[4] == "|" ? file_validation_message($ia) : "";

    if(!empty($question_text['man_message']) || !empty($question_text['valid_message']) || !empty($question_text['file_valid_message']))
    {
        $question_text['input_error_class'] = ' input-error';// provides a class to style question wrapper differently if there is some kind of user input error;
    }

    // =====================================================
    // START: legacy question_start.pstpl code
    // The following section adds to the templating system by allowing
    // templaters to control where the various parts of the question text
    // are put.

    if(is_file('templates/'.validate_templatedir($thissurvey['template']).'/question_start.pstpl'))
    {
        $qtitle_custom = '';

        $replace=array();
        foreach($question_text as $key => $value)
        {
            $find[] = '{QUESTION_'.strtoupper($key).'}'; // Match key words from template
            $replace[] = $value; // substitue text
        };
        if(!defined('QUESTION_START'))
        {
            define('QUESTION_START' , file_get_contents(sGetTemplatePath($thissurvey['template']).'/question_start.pstpl' , true));
        };
        $qtitle_custom = str_replace( $find , $replace , QUESTION_START);

        $c = 1;
        // START: <EMBED> work-around step 1
        $qtitle_custom = preg_replace( '/(<embed[^>]+>)(<\/embed>)/i' , '\1NOT_EMPTY\2' , $qtitle_custom );
        // END <EMBED> work-around step 1
        while($c > 0) // This recursively strips any empty tags to minimise rendering bugs.
        {
            $matches = 0;
            $oldtitle=$qtitle_custom;
            $qtitle_custom = preg_replace( '/<([^ >]+)[^>]*>[\r\n\t ]*<\/\1>[\r\n\t ]*/isU' , '' , $qtitle_custom , -1); // I removed the $count param because it is PHP 5.1 only.

            $c = ($qtitle_custom!=$oldtitle)?1:0;
        };
        // START <EMBED> work-around step 2
        $qtitle_custom = preg_replace( '/(<embed[^>]+>)NOT_EMPTY(<\/embed>)/i' , '\1\2' , $qtitle_custom );
        // END <EMBED> work-around step 2
        while($c > 0) // This recursively strips any empty tags to minimise rendering bugs.
        {
            $matches = 0;
            $oldtitle=$qtitle_custom;
            $qtitle_custom = preg_replace( '/(<br(?: ?\/)?>(?:&nbsp;|\r\n|\n\r|\r|\n| )*)+$/i' , '' , $qtitle_custom , -1 ); // I removed the $count param because it is PHP 5.1 only.
            $c = ($qtitle_custom!=$oldtitle)?1:0;
        };

        //		$qtitle = $qtitle_custom;
        $question_text['all'] = $qtitle_custom;
    }
    else
    {
        $question_text['all'] = $qtitle;
    };
    // END: legacy question_start.pstpl code
    //===================================================================
    //	echo '<pre>[qanda.php] line '.__LINE__.": $question_text =\n".htmlspecialchars(print_r($question_text,true)).'</pre>';
    $qtitle = $question_text;
    // =====================================================

    $qanda=array($qtitle, $answer, $help, $display, $name, $ia[2], $gl[0], $ia[1] );
    //New Return
    return array($qanda, $inputnames);
}
require_once $rootdir . '/classes/core/language.php';
// has been secured
if (isset($_SESSION['s_lang'])) {
    $clang = SetSurveyLanguage($surveyid, $_SESSION['s_lang']);
    $language = $_SESSION['s_lang'];
} else {
    $language = GetBaseLanguageFromSurveyID($surveyid);
    $clang = SetSurveyLanguage($surveyid, $language);
}
// Get the survey inforamtion
$thissurvey = getSurveyInfo($surveyid, $language);
//SET THE TEMPLATE DIRECTORY
if (!isset($thissurvey['templatedir']) || !$thissurvey['templatedir']) {
    $thistpl = validate_templatedir("default");
} else {
    $thistpl = validate_templatedir($thissurvey['templatedir']);
}
if ($thissurvey['printanswers'] == 'N') {
    die;
}
//Die quietly if print answers is not permitted
//CHECK IF SURVEY IS ACTIVATED AND EXISTS
$actquery = "SELECT * FROM " . db_table_name('surveys') . " as a inner join " . db_table_name('surveys_languagesettings') . " as b on (b.surveyls_survey_id=a.sid and b.surveyls_language=a.language) WHERE a.sid={$surveyid}";
$actresult = db_execute_assoc($actquery);
//Checked
$actcount = $actresult->RecordCount();
if ($actcount > 0) {
    while ($actrow = $actresult->FetchRow()) {
        $surveytable = db_table_name("survey_" . $actrow['sid']);
        $surveyname = "{$actrow['surveyls_title']}";
    }
Example #7
0
/**
* This function returns an array containing the "question/answer" html display
* and a list of the question/answer fieldnames associated. It is called from
* question.php, group.php or survey.php
*
* @param mixed $ia
* @param mixed $notanswered
* @param mixed $notvalidated
* @param mixed $filenotvalidated
* @return mixed
*/
function retrieveAnswers($ia)
{
    //globalise required config variables
    global $dbprefix, $clang;
    //These are from the config-defaults.php file
    global $thissurvey, $gl;
    //These are set by index.php
    global $connect;
    //DISPLAY
    $display = $ia[7];
    //QUESTION NAME
    $name = $ia[0];
    $qtitle = $ia[3];
    $inputnames = array();
    // TMSW - eliminate this - get from LEM
    //A bit of housekeeping to stop PHP Notices
    $answer = "";
    if (!isset($_SESSION[$ia[1]])) {
        $_SESSION[$ia[1]] = "";
    }
    $qidattributes = getQuestionAttributes($ia[0], $ia[4]);
    //Create the question/answer html
    // Previously in limesurvey, it was virtually impossible to control how the start of questions were formatted.
    // this is an attempt to allow users (or rather system admins) some control over how the starting text is formatted.
    $number = isset($ia[9]) ? $ia[9] : '';
    // TMSW - populate this directly from LEM? - this this is global
    $question_text = array('all' => '', 'text' => $qtitle, 'code' => $ia[2], 'number' => $number, 'help' => '', 'mandatory' => '', 'man_message' => '', 'valid_message' => '', 'file_valid_message' => '', 'class' => '', 'man_class' => '', 'input_error_class' => '', 'essentials' => '');
    switch ($ia[4]) {
        case 'X':
            //BOILERPLATE QUESTION
            $values = do_boilerplate($ia);
            break;
        case '5':
            //5 POINT CHOICE radio-buttons
            $values = do_5pointchoice($ia);
            break;
        case 'D':
            //DATE
            $values = do_date($ia);
            break;
        case 'L':
            //LIST drop-down/radio-button list
            $values = do_list_radio($ia);
            if ($qidattributes['hide_tip'] == 0) {
                $qtitle .= "<br />\n<span class=\"questionhelp\">" . $clang->gT('Choose one of the following answers') . '</span>';
                $question_text['help'] = $clang->gT('Choose one of the following answers');
            }
            break;
        case '!':
            //List - dropdown
            $values = do_list_dropdown($ia);
            if ($qidattributes['hide_tip'] == 0) {
                $qtitle .= "<br />\n<span class=\"questionhelp\">" . $clang->gT('Choose one of the following answers') . '</span>';
                $question_text['help'] = $clang->gT('Choose one of the following answers');
            }
            break;
        case 'O':
            //LIST WITH COMMENT drop-down/radio-button list + textarea
            $values = do_listwithcomment($ia);
            if (count($values[1]) > 1 && $qidattributes['hide_tip'] == 0) {
                $qtitle .= "<br />\n<span class=\"questionhelp\">" . $clang->gT('Choose one of the following answers') . '</span>';
                $question_text['help'] = $clang->gT('Choose one of the following answers');
            }
            break;
        case 'R':
            //RANKING STYLE
            $values = do_ranking($ia);
            if (count($values[1]) > 1 && $qidattributes['hide_tip'] == 0) {
                $question_text['help'] = $clang->gT("Click on an item in the list on the left, starting with your highest ranking item, moving through to your lowest ranking item.");
                if (trim($qidattributes['min_answers']) != '') {
                    $qtitle .= "<br />\n<span class=\"questionhelp\">" . sprintf($clang->ngT("Check at least %d item", "Check at least %d items", $qidattributes['min_answers']), $qidattributes['min_answers']) . "</span>";
                    $question_text['help'] .= ' ' . sprintf($clang->ngT("Check at least %d item", "Check at least %d items", $qidattributes['min_answers']), $qidattributes['min_answers']);
                }
            }
            break;
        case 'M':
            //Multiple choice checkbox
            $values = do_multiplechoice($ia);
            if (count($values[1]) > 1 && $qidattributes['hide_tip'] == 0) {
                $maxansw = trim($qidattributes['max_answers']);
                $minansw = trim($qidattributes['min_answers']);
                if (!($maxansw || $minansw)) {
                    $qtitle .= "<br />\n<span class=\"questionhelp\">" . $clang->gT('Check any that apply') . '</span>';
                    $question_text['help'] = $clang->gT('Check any that apply');
                }
                //                else
                //                {
                //                    if ($maxansw && $minansw)
                //                    {
                //                        $qtitle .= "<br />\n<span class=\"questionhelp\">"
                //                        . sprintf($clang->gT("Check between %d and %d answers"), $minansw, $maxansw)."</span>";
                //                        $question_text['help'] = sprintf($clang->gT("Check between %d and %d answers"), $minansw, $maxansw);
                //                    } elseif ($maxansw)
                //                    {
                //                        $qtitle .= "<br />\n<span class=\"questionhelp\">"
                //                        . sprintf($clang->gT("Check at most %d answers"), $maxansw)."</span>";
                //                        $question_text['help'] = sprintf($clang->gT("Check at most %d answers"), $maxansw);
                //                    } else
                //                    {
                //                        $qtitle .= "<br />\n<span class=\"questionhelp\">"
                //                        . sprintf($clang->ngT("Check at least %d answer","Check at least %d answers",$minansw),$minansw)."</span>";
                //                        $question_text['help'] = sprintf($clang->ngT("Check at least %d answer","Check at least %d answers",$minansw),$minansw);
                //                    }
                //                }
            }
            break;
        case 'I':
            //Language Question
            $values = do_language($ia);
            if (count($values[1]) > 1) {
                $qtitle .= "<br />\n<span class=\"questionhelp\">" . $clang->gT('Choose your language') . '</span>';
                $question_text['help'] = $clang->gT('Choose your language');
            }
            break;
        case 'P':
            //Multiple choice with comments checkbox + text
            $values = do_multiplechoice_withcomments($ia);
            if (count($values[1]) > 1 && $qidattributes['hide_tip'] == 0) {
                $maxansw = trim($qidattributes["max_answers"]);
                $minansw = trim($qidattributes["min_answers"]);
                if (!($maxansw || $minansw)) {
                    $qtitle .= "<br />\n<span class=\"questionhelp\">" . $clang->gT('Check any that apply') . '</span>';
                    $question_text['help'] = $clang->gT('Check any that apply');
                }
                //                else
                //                {
                //                    if ($maxansw && $minansw)
                //                    {
                //                        $qtitle .= "<br />\n<span class=\"questionhelp\">"
                //                        . sprintf($clang->gT("Check between %d and %d answers"), $minansw, $maxansw)."</span>";
                //                        $question_text['help'] = sprintf($clang->gT("Check between %d and %d answers"), $minansw, $maxansw);
                //                    } elseif ($maxansw)
                //                    {
                //                        $qtitle .= "<br />\n<span class=\"questionhelp\">"
                //                        . sprintf($clang->gT("Check at most %d answers"), $maxansw)."</span>";
                //                        $question_text['help'] = sprintf($clang->gT("Check at most %d answers"), $maxansw);
                //                    } else
                //                    {
                //                        $qtitle .= "<br />\n<span class=\"questionhelp\">"
                //                        . sprintf($clang->gT("Check at least %d answers"), $minansw)."</span>";
                //                        $question_text['help'] = sprintf($clang->gT("Check at least %d answers"), $minansw);
                //                    }
                //                }
            }
            break;
        case '|':
            //File Upload
            $values = do_file_upload($ia);
            if ($qidattributes['min_num_of_files'] != 0) {
                if (trim($qidattributes['min_num_of_files']) != 0) {
                    $qtitle .= "<br />\n<span class = \"questionhelp\">" . sprintf($clang->gT("At least %d files must be uploaded for this question"), $qidattributes['min_num_of_files']) . "<span>";
                    $question_text['help'] .= ' ' . sprintf($clang->gT("At least %d files must be uploaded for this question"), $qidattributes['min_num_of_files']);
                }
            }
            break;
        case 'Q':
            //MULTIPLE SHORT TEXT
            $values = do_multipleshorttext($ia);
            break;
        case 'K':
            //MULTIPLE NUMERICAL QUESTION
            $values = do_multiplenumeric($ia);
            break;
        case 'N':
            //NUMERICAL QUESTION TYPE
            $values = do_numerical($ia);
            break;
        case 'S':
            //SHORT FREE TEXT
            $values = do_shortfreetext($ia);
            break;
        case 'T':
            //LONG FREE TEXT
            $values = do_longfreetext($ia);
            break;
        case 'U':
            //HUGE FREE TEXT
            $values = do_hugefreetext($ia);
            break;
        case 'Y':
            //YES/NO radio-buttons
            $values = do_yesno($ia);
            break;
        case 'G':
            //GENDER drop-down list
            $values = do_gender($ia);
            break;
        case 'A':
            //ARRAY (5 POINT CHOICE) radio-buttons
            $values = do_array_5point($ia);
            break;
        case 'B':
            //ARRAY (10 POINT CHOICE) radio-buttons
            $values = do_array_10point($ia);
            break;
        case 'C':
            //ARRAY (YES/UNCERTAIN/NO) radio-buttons
            $values = do_array_yesnouncertain($ia);
            break;
        case 'E':
            //ARRAY (Increase/Same/Decrease) radio-buttons
            $values = do_array_increasesamedecrease($ia);
            break;
        case 'F':
            //ARRAY (Flexible) - Row Format
            $values = do_array($ia);
            break;
        case 'H':
            //ARRAY (Flexible) - Column Format
            $values = do_arraycolumns($ia);
            break;
        case ':':
            //ARRAY (Multi Flexi) 1 to 10
            $values = do_array_multiflexi($ia);
            break;
        case ';':
            //ARRAY (Multi Flexi) Text
            $values = do_array_multitext($ia);
            //It's like the "5th element" movie, come to life
            break;
        case '1':
            //Array (Flexible Labels) dual scale
            $values = do_array_dual($ia);
            break;
        case '*':
            // Equation
            $values = do_equation($ia);
            break;
    }
    //End Switch
    if (isset($values)) {
        //$answer is the html code to be printed
        //$inputnames is an array containing the names of each input field
        list($answer, $inputnames) = $values;
    }
    if ($ia[6] == 'Y') {
        $qtitle = '<span class="asterisk">' . $clang->gT('*') . '</span>' . $qtitle;
        $question_text['mandatory'] = $clang->gT('*');
    }
    //If this question is mandatory but wasn't answered in the last page
    //add a message HIGHLIGHTING the question
    if ($_SESSION['step'] != $_SESSION['maxstep'] || $_SESSION['step'] == $_SESSION['prevstep']) {
        $mandatory_msg = mandatory_message($ia);
    } else {
        $mandatory_msg = '';
    }
    $qtitle .= $mandatory_msg;
    $question_text['man_message'] = $mandatory_msg;
    //    if (($_SESSION['step'] != $_SESSION['maxstep']) || ($_SESSION['step'] == $_SESSION['prevstep'])) {
    if (!isset($qidattributes['hide_tip']) || $qidattributes['hide_tip'] == 0) {
        $_vshow = true;
        // whether should initially be visible - TODO should also depend upon 'hidetip'?
    } else {
        $_vshow = false;
    }
    list($validation_msg, $isValid) = validation_message($ia, $_vshow);
    $qtitle .= $validation_msg;
    $question_text['valid_message'] = $validation_msg;
    if ($_SESSION['step'] != $_SESSION['maxstep'] || $_SESSION['step'] == $_SESSION['prevstep']) {
        $file_validation_msg = file_validation_message($ia);
    } else {
        $file_validation_msg = '';
        $isValid = true;
        // don't want to show any validation messages.
    }
    $qtitle .= $ia[4] == "|" ? $file_validation_msg : "";
    $question_text['file_valid_message'] = $ia[4] == "|" ? $file_validation_msg : "";
    if (!empty($question_text['man_message']) || !$isValid || !empty($question_text['file_valid_message'])) {
        $question_text['input_error_class'] = ' input-error';
        // provides a class to style question wrapper differently if there is some kind of user input error;
    }
    // =====================================================
    // START: legacy question_start.pstpl code
    // The following section adds to the templating system by allowing
    // templaters to control where the various parts of the question text
    // are put.
    if (is_file('templates/' . validate_templatedir($thissurvey['template']) . '/question_start.pstpl')) {
        $qtitle_custom = '';
        $replace = array();
        foreach ($question_text as $key => $value) {
            $find[] = '{QUESTION_' . strtoupper($key) . '}';
            // Match key words from template
            $replace[] = $value;
            // substitue text
        }
        if (!defined('QUESTION_START')) {
            define('QUESTION_START', file_get_contents(sGetTemplatePath($thissurvey['template']) . '/question_start.pstpl', true));
        }
        $qtitle_custom = str_replace($find, $replace, QUESTION_START);
        $c = 1;
        // START: <EMBED> work-around step 1
        $qtitle_custom = preg_replace('/(<embed[^>]+>)(<\\/embed>)/i', '\\1NOT_EMPTY\\2', $qtitle_custom);
        // END <EMBED> work-around step 1
        while ($c > 0) {
            $matches = 0;
            $oldtitle = $qtitle_custom;
            $qtitle_custom = preg_replace('/<([^ >]+)[^>]*>[\\r\\n\\t ]*<\\/\\1>[\\r\\n\\t ]*/isU', '', $qtitle_custom, -1);
            // I removed the $count param because it is PHP 5.1 only.
            $c = $qtitle_custom != $oldtitle ? 1 : 0;
        }
        // START <EMBED> work-around step 2
        $qtitle_custom = preg_replace('/(<embed[^>]+>)NOT_EMPTY(<\\/embed>)/i', '\\1\\2', $qtitle_custom);
        // END <EMBED> work-around step 2
        while ($c > 0) {
            $matches = 0;
            $oldtitle = $qtitle_custom;
            $qtitle_custom = preg_replace('/(<br(?: ?\\/)?>(?:&nbsp;|\\r\\n|\\n\\r|\\r|\\n| )*)+$/i', '', $qtitle_custom, -1);
            // I removed the $count param because it is PHP 5.1 only.
            $c = $qtitle_custom != $oldtitle ? 1 : 0;
        }
        $question_text['all'] = $qtitle_custom;
    } else {
        $question_text['all'] = $qtitle;
    }
    // END: legacy question_start.pstpl code
    //===================================================================
    $qtitle = $question_text;
    // =====================================================
    $qanda = array($qtitle, $answer, 'help', $display, $name, $ia[2], $gl[0], $ia[1]);
    //New Return
    return array($qanda, $inputnames);
}
Example #8
0
/**
 * This function replaces keywords in a text and is mainly intended for templates
 * If you use this functions put your replacement strings into the $replacements variable
 * instead of using global variables
 *
 * @param mixed $line Text to search in
 * @param mixed $replacements Array of replacements:  Array( <stringtosearch>=><stringtoreplacewith>
 * @return string  Text with replaced strings
 */
function templatereplace($line, $replacements = array())
{
    global $surveylist, $sitename, $clienttoken, $rooturl;
    global $thissurvey, $imagefiles, $defaulttemplate;
    global $percentcomplete, $move;
    global $groupname, $groupdescription;
    global $question;
    global $answer, $navigator;
    global $help, $totalquestions, $surveyformat;
    global $completed, $register_errormsg;
    global $notanswered, $privacy, $surveyid;
    global $publicurl, $templatedir, $token;
    global $assessments, $s_lang;
    global $errormsg, $clang;
    global $saved_id, $usertemplaterootdir;
    global $totalBoilerplatequestions, $relativeurl;
    global $languagechanger;
    global $printoutput, $captchapath, $loadname;
    // lets sanitize the survey template
    if (isset($thissurvey['templatedir'])) {
        $templatename = $thissurvey['templatedir'];
    } else {
        $templatename = $defaulttemplate;
    }
    $templatename = validate_templatedir($templatename);
    // create absolute template URL and template dir vars
    $templateurl = sGetTemplateURL($templatename) . '/';
    $templatedir = sgetTemplatePath($templatename);
    if (stripos($line, "</head>")) {
        $line = str_ireplace("</head>", "<script type=\"text/javascript\" src=\"{$rooturl}/scripts/survey_runtime.js\"></script>\n" . use_firebug() . "\t</head>", $line);
    }
    // If there are non-bracketed replacements to be made do so above this line.
    // Only continue in this routine if there are bracketed items to replace {}
    if (strpos($line, "{") === false) {
        return $line;
    }
    foreach ($replacements as $replacementkey => $replacementvalue) {
        if (strpos($line, '{' . $replacementkey . '}') !== false) {
            $line = str_replace('{' . $replacementkey . '}', $replacementvalue, $line);
        }
    }
    if (strpos($line, "{SURVEYLISTHEADING}") !== false) {
        $line = str_replace("{SURVEYLISTHEADING}", $surveylist['listheading'], $line);
    }
    if (strpos($line, "{SURVEYLIST}") !== false) {
        $line = str_replace("{SURVEYLIST}", $surveylist['list'], $line);
    }
    if (strpos($line, "{NOSURVEYID}") !== false) {
        $line = str_replace("{NOSURVEYID}", $surveylist['nosid'], $line);
    }
    if (strpos($line, "{SURVEYCONTACT}") !== false) {
        $line = str_replace("{SURVEYCONTACT}", $surveylist['contact'], $line);
    }
    if (strpos($line, "{SITENAME}") !== false) {
        $line = str_replace("{SITENAME}", $sitename, $line);
    }
    if (strpos($line, "{SURVEYLIST}") !== false) {
        $line = str_replace("{SURVEYLIST}", $surveylist, $line);
    }
    if (strpos($line, "{CHECKJAVASCRIPT}") !== false) {
        $line = str_replace("{CHECKJAVASCRIPT}", "<noscript><span class='warningjs'>" . $clang->gT("Caution: JavaScript execution is disabled in your browser. You may not be able to answer all questions in this survey. Please, verify your browser parameters.") . "</span></noscript>", $line);
    }
    if (strpos($line, "{ANSWERTABLE}") !== false) {
        $line = str_replace("{ANSWERTABLE}", $printoutput, $line);
    }
    if (strpos($line, "{SURVEYNAME}") !== false) {
        $line = str_replace("{SURVEYNAME}", $thissurvey['name'], $line);
    }
    if (strpos($line, "{SURVEYDESCRIPTION}") !== false) {
        $line = str_replace("{SURVEYDESCRIPTION}", $thissurvey['description'], $line);
    }
    if (strpos($line, "{WELCOME}") !== false) {
        $line = str_replace("{WELCOME}", $thissurvey['welcome'], $line);
    }
    if (strpos($line, "{LANGUAGECHANGER}") !== false) {
        $line = str_replace("{LANGUAGECHANGER}", $languagechanger, $line);
    }
    if (strpos($line, "{PERCENTCOMPLETE}") !== false) {
        $line = str_replace("{PERCENTCOMPLETE}", $percentcomplete, $line);
    }
    if (strpos($line, "{GROUPNAME}") !== false) {
        $line = str_replace("{GROUPNAME}", $groupname, $line);
    }
    if (strpos($line, "{GROUPDESCRIPTION}") !== false) {
        $line = str_replace("{GROUPDESCRIPTION}", $groupdescription, $line);
    }
    if (is_array($question)) {
        if (strpos($line, "{QUESTION}") !== false) {
            $line = str_replace("{QUESTION}", $question['all'], $line);
        } else {
            if (strpos($line, "{QUESTION_TEXT}") !== false) {
                $line = str_replace("{QUESTION_TEXT}", $question['text'], $line);
            }
            if (strpos($line, "{QUESTION_HELP}") !== false) {
                $line = str_replace("{QUESTION_HELP}", $question['help'], $line);
            }
            if (strpos($line, "{QUESTION_MANDATORY}") !== false) {
                $line = str_replace("{QUESTION_MANDATORY}", $question['mandatory'], $line);
            }
            if (strpos($line, "{QUESTION_MAN_MESSAGE}") !== false) {
                $line = str_replace("{QUESTION_MAN_MESSAGE}", $question['man_message'], $line);
            }
            if (strpos($line, "{QUESTION_VALID_MESSAGE}") !== false) {
                $line = str_replace("{QUESTION_VALID_MESSAGE}", $question['valid_message'], $line);
            }
        }
    } else {
        if (strpos($line, "{QUESTION}") !== false) {
            $line = str_replace("{QUESTION}", $question, $line);
        }
    }
    if (strpos($line, '{QUESTION_ESSENTIALS}') !== false) {
        $line = str_replace('{QUESTION_ESSENTIALS}', $question['essentials'], $line);
    }
    if (strpos($line, '{QUESTION_CLASS}') !== false) {
        $line = str_replace('{QUESTION_CLASS}', $question['class'], $line);
    }
    if (strpos($line, '{QUESTION_MAN_CLASS}') !== false) {
        $line = str_replace('{QUESTION_MAN_CLASS}', $question['man_class'], $line);
    }
    if (strpos($line, "{QUESTION_INPUT_ERROR_CLASS}") !== false) {
        $line = str_replace("{QUESTION_INPUT_ERROR_CLASS}", $question['input_error_class'], $line);
    }
    if (strpos($line, "{QUESTION_CODE}") !== false) {
        $line = str_replace("{QUESTION_CODE}", $question['code'], $line);
    }
    if (strpos($line, "{ANSWER}") !== false) {
        $line = str_replace("{ANSWER}", $answer, $line);
    }
    $totalquestionsAsked = $totalquestions - $totalBoilerplatequestions;
    if ($totalquestionsAsked < 1) {
        if (strpos($line, "{THEREAREXQUESTIONS}") !== false) {
            $line = str_replace("{THEREAREXQUESTIONS}", $clang->gT("There are no questions in this survey"), $line);
        }
        //Singular
    }
    if ($totalquestionsAsked == 1) {
        if (strpos($line, "{THEREAREXQUESTIONS}") !== false) {
            $line = str_replace("{THEREAREXQUESTIONS}", $clang->gT("There is 1 question in this survey"), $line);
        }
        //Singular
    } else {
        if (strpos($line, "{THEREAREXQUESTIONS}") !== false) {
            $line = str_replace("{THEREAREXQUESTIONS}", $clang->gT("There are {NUMBEROFQUESTIONS} questions in this survey."), $line);
        }
        //Note this line MUST be before {NUMBEROFQUESTIONS}
    }
    if (strpos($line, "{NUMBEROFQUESTIONS}") !== false) {
        $line = str_replace("{NUMBEROFQUESTIONS}", $totalquestionsAsked, $line);
    }
    if (strpos($line, "{TOKEN}") !== false) {
        if (isset($token)) {
            $line = str_replace("{TOKEN}", $token, $line);
        } elseif (isset($clienttoken)) {
            $line = str_replace("{TOKEN}", htmlentities($clienttoken, ENT_QUOTES, 'UTF-8'), $line);
        } else {
            $line = str_replace("{TOKEN}", '', $line);
        }
    }
    if (strpos($line, "{SID}") !== false) {
        $line = str_replace("{SID}", $surveyid, $line);
    }
    if (strpos($line, "{EXPIRY}") !== false) {
        $line = str_replace("{EXPIRY}", $thissurvey['expiry'], $line);
    }
    if (strpos($line, "{EXPIRY-DMY}") !== false) {
        $line = str_replace("{EXPIRY-DMY}", date("d-m-Y", strtotime($thissurvey["expiry"])), $line);
    }
    if (strpos($line, "{EXPIRY-MDY}") !== false) {
        $line = str_replace("{EXPIRY-MDY}", date("m-d-Y", strtotime($thissurvey["expiry"])), $line);
    }
    if (strpos($line, "{NAVIGATOR}") !== false) {
        $line = str_replace("{NAVIGATOR}", $navigator, $line);
    }
    if (strpos($line, "{SUBMITBUTTON}") !== false) {
        $submitbutton = "          <input class='submit' type='submit' value=' " . $clang->gT("Submit") . " ' name='move2' onclick=\"javascript:document.limesurvey.move.value = 'movesubmit';\" />";
        $line = str_replace("{SUBMITBUTTON}", $submitbutton, $line);
    }
    if (strpos($line, "{COMPLETED}") !== false) {
        $line = str_replace("{COMPLETED}", $completed, $line);
    }
    if (strpos($line, "{URL}") !== false) {
        if ($thissurvey['surveyls_url'] != "") {
            if (trim($thissurvey['surveyls_urldescription']) != '') {
                $linkreplace = "<a href='{$thissurvey['surveyls_url']}'>{$thissurvey['surveyls_urldescription']}</a>";
            } else {
                $linkreplace = "<a href='{$thissurvey['surveyls_url']}'>{$thissurvey['surveyls_url']}</a>";
            }
        } else {
            $linkreplace = '';
        }
        $line = str_replace("{URL}", $linkreplace, $line);
        $line = str_replace("{SAVEDID}", $saved_id, $line);
        // to activate the SAVEDID in the END URL
        if (isset($clienttoken)) {
            $token = $clienttoken;
        } else {
            $token = '';
        }
        $line = str_replace("{TOKEN}", urlencode($token), $line);
        // to activate the TOKEN in the END URL
        $line = str_replace("{SID}", $surveyid, $line);
        // to activate the SID in the RND URL
    }
    if (strpos($line, "{PRIVACY}") !== false) {
        $line = str_replace("{PRIVACY}", $privacy, $line);
    }
    if (strpos($line, "{PRIVACYMESSAGE}") !== false) {
        $line = str_replace("{PRIVACYMESSAGE}", "<span style='font-weight:bold; font-style: italic;'>" . $clang->gT("A Note On Privacy") . "</span><br />" . $clang->gT("This survey is anonymous.") . "<br />" . $clang->gT("The record kept of your survey responses does not contain any identifying information about you unless a specific question in the survey has asked for this."), $line);
        // If you have responded to a survey that used an identifying token to allow you to access the survey, you can rest assured that the identifying token is not kept with your responses. It is managed in a separate database, and will only be updated to indicate that you have (or haven't) completed this survey. There is no way of matching identification tokens with survey responses in this survey.
    }
    if (strpos($line, "{CLEARALL}") !== false) {
        $clearall = "          <input type='button' name='clearallbtn' value='" . $clang->gT("Exit and Clear Survey") . "' class='clearall' " . "onclick=\"if (confirm('" . $clang->gT("Are you sure you want to clear all your responses?", 'js') . "')) {window.open('{$publicurl}/index.php?sid={$surveyid}&amp;move=clearall&amp;lang=" . $_SESSION['s_lang'];
        if (returnglobal('token')) {
            $clearall .= "&amp;token=" . urlencode(trim(sanitize_xss_string(strip_tags(returnglobal('token')))));
        }
        $clearall .= "', '_top')}\" />";
        $line = str_replace("{CLEARALL}", $clearall, $line);
    }
    // --> START NEW FEATURE - SAVE
    if (strpos($line, "{DATESTAMP}") !== false) {
        if (isset($_SESSION['datestamp'])) {
            $line = str_replace("{DATESTAMP}", $_SESSION['datestamp'], $line);
        } else {
            $line = str_replace("{DATESTAMP}", "-", $line);
        }
    }
    // <-- END NEW FEATURE - SAVE
    if (strpos($line, "{SAVE}") !== false) {
        //Set up save/load feature
        if ($thissurvey['allowsave'] == "Y") {
            // Find out if the user has any saved data
            if ($thissurvey['format'] == 'A') {
                $saveall = "          <input type='submit' name='loadall' value='" . $clang->gT("Load Unfinished Survey") . "' class='saveall' " . ($thissurvey['active'] != "Y" ? "disabled='disabled'" : "") . "/>" . "          <input type='button' name='saveallbtn' value='" . $clang->gT("Resume Later") . "' class='saveall' onclick=\"javascript:document.limesurvey.move.value = this.value;addHiddenField(document.getElementById('limesurvey'),'saveall',this.value);document.getElementById('limesurvey').submit();\" " . ($thissurvey['active'] != "Y" ? "disabled='disabled'" : "") . "/>";
                // Show Save So Far button
            } elseif (!isset($_SESSION['step']) || !$_SESSION['step']) {
                $saveall = "          <input type='submit' name='loadall' value='" . $clang->gT("Load Unfinished Survey") . "' class='saveall' " . ($thissurvey['active'] != "Y" ? "disabled='disabled'" : "") . "/>";
            } elseif (isset($_SESSION['scid']) && (isset($move) && $move == "movelast")) {
                $saveall = "";
            } else {
                $saveall = "          <input type='button' name='saveallbtn' value='" . $clang->gT("Resume Later") . "' class='saveall' onclick=\"javascript:document.limesurvey.move.value = this.value;addHiddenField(document.getElementById('limesurvey'),'saveall',this.value);document.getElementById('limesurvey').submit();\" " . ($thissurvey['active'] != "Y" ? "disabled='disabled'" : "") . "/>";
                // Show Save So Far button
            }
        } else {
            $saveall = "";
        }
        $line = str_replace("{SAVE}", $saveall, $line);
    }
    if (strpos($line, "{TEMPLATEURL}") !== false) {
        $line = str_replace("{TEMPLATEURL}", $templateurl, $line);
    }
    if (strpos($line, "{TEMPLATECSS}") !== false) {
        $templatecss = "<link rel='stylesheet' type='text/css' href='{$templateurl}template.css' />\n";
        if (getLanguageRTL($clang->langcode)) {
            $templatecss .= "<link rel='stylesheet' type='text/css' href='{$templateurl}template-rtl.css' />\n";
        }
        $line = str_replace("{TEMPLATECSS}", $templatecss, $line);
    }
    if (FlattenText($help, true) != '') {
        if (strpos($line, "{QUESTIONHELP}") !== false) {
            if (!isset($helpicon)) {
                if (file_exists($templatedir . '/help.gif')) {
                    $helpicon = $templateurl . 'help.gif';
                } elseif (file_exists($templatedir . '/help.png')) {
                    $helpicon = $templateurl . 'help.png';
                } else {
                    $helpicon = $imagefiles . "/help.gif";
                }
            }
            $line = str_replace("{QUESTIONHELP}", "<img src='{$helpicon}' alt='Help' align='left' />" . $help, $line);
        }
        if (strpos($line, "{QUESTIONHELPPLAINTEXT}") !== false) {
            $line = str_replace("{QUESTIONHELPPLAINTEXT}", strip_tags(addslashes($help)), $line);
        }
    } else {
        if (strpos($line, "{QUESTIONHELP}") !== false) {
            $line = str_replace("{QUESTIONHELP}", $help, $line);
        }
        if (strpos($line, "{QUESTIONHELPPLAINTEXT}") !== false) {
            $line = str_replace("{QUESTIONHELPPLAINTEXT}", strip_tags(addslashes($help)), $line);
        }
    }
    $line = insertansReplace($line);
    if (strpos($line, "{SUBMITCOMPLETE}") !== false) {
        $line = str_replace("{SUBMITCOMPLETE}", "<strong>" . $clang->gT("Thank You!") . "<br /><br />" . $clang->gT("You have completed answering the questions in this survey.") . "</strong><br /><br />" . $clang->gT("Click on 'Submit' now to complete the process and save your answers."), $line);
    }
    if (strpos($line, "{SUBMITREVIEW}") !== false) {
        if (isset($thissurvey['allowprev']) && $thissurvey['allowprev'] == "N") {
            $strreview = "";
        } else {
            $strreview = $clang->gT("If you want to check any of the answers you have made, and/or change them, you can do that now by clicking on the [<< prev] button and browsing through your responses.");
        }
        $line = str_replace("{SUBMITREVIEW}", $strreview, $line);
    }
    $line = tokenReplace($line);
    if (strpos($line, "{ANSWERSCLEARED}") !== false) {
        $line = str_replace("{ANSWERSCLEARED}", $clang->gT("Answers Cleared"), $line);
    }
    if (strpos($line, "{RESTART}") !== false) {
        if ($thissurvey['active'] == "N") {
            $replacetext = "<a href='{$publicurl}/index.php?sid={$surveyid}&amp;newtest=Y";
            if (isset($s_lang) && $s_lang != '') {
                $replacetext .= "&amp;lang=" . $s_lang;
            }
            $replacetext .= "'>" . $clang->gT("Restart this Survey") . "</a>";
            $line = str_replace("{RESTART}", $replacetext, $line);
        } else {
            $restart_extra = "";
            $restart_token = returnglobal('token');
            if (!empty($restart_token)) {
                $restart_extra .= "&amp;token=" . urlencode($restart_token);
            } else {
                $restart_extra = "&amp;newtest=Y";
            }
            if (!empty($_GET['lang'])) {
                $restart_extra .= "&amp;lang=" . returnglobal('lang');
            }
            $line = str_replace("{RESTART}", "<a href='{$publicurl}/index.php?sid={$surveyid}" . $restart_extra . "'>" . $clang->gT("Restart this Survey") . "</a>", $line);
        }
    }
    if (strpos($line, "{CLOSEWINDOW}") !== false) {
        $line = str_replace("{CLOSEWINDOW}", "<a href='javascript:%20self.close()'>" . $clang->gT("Close this Window") . "</a>", $line);
    }
    if (strpos($line, "{SAVEERROR}") !== false) {
        $line = str_replace("{SAVEERROR}", $errormsg, $line);
    }
    if (strpos($line, "{SAVEHEADING}") !== false) {
        $line = str_replace("{SAVEHEADING}", $clang->gT("Save Your Unfinished Survey"), $line);
    }
    if (strpos($line, "{SAVEMESSAGE}") !== false) {
        $line = str_replace("{SAVEMESSAGE}", $clang->gT("Enter a name and password for this survey and click save below.") . "<br />\n" . $clang->gT("Your survey will be saved using that name and password, and can be completed later by logging in with the same name and password.") . "<br /><br />\n" . $clang->gT("If you give an email address, an email containing the details will be sent to you."), $line);
    }
    if (strpos($line, "{RETURNTOSURVEY}") !== false) {
        $savereturn = "<a href='{$relativeurl}/index.php?sid={$surveyid}";
        if (returnglobal('token')) {
            $savereturn .= "&amp;token=" . urlencode(trim(sanitize_xss_string(strip_tags(returnglobal('token')))));
        }
        $savereturn .= "'>" . $clang->gT("Return To Survey") . "</a>";
        $line = str_replace("{RETURNTOSURVEY}", $savereturn, $line);
    }
    if (strpos($line, "{SAVEFORM}") !== false) {
        //SAVE SURVEY DETAILS
        $saveform = "<table><tr><td align='right'>" . $clang->gT("Name") . ":</td><td><input type='text' name='savename' value='";
        if (isset($_POST['savename'])) {
            $saveform .= html_escape(auto_unescape($_POST['savename']));
        }
        $saveform .= "' /></td></tr>\n" . "<tr><td align='right'>" . $clang->gT("Password") . ":</td><td><input type='password' name='savepass' value='";
        if (isset($_POST['savepass'])) {
            $saveform .= html_escape(auto_unescape($_POST['savepass']));
        }
        $saveform .= "' /></td></tr>\n" . "<tr><td align='right'>" . $clang->gT("Repeat Password") . ":</td><td><input type='password' name='savepass2' value='";
        if (isset($_POST['savepass2'])) {
            $saveform .= html_escape(auto_unescape($_POST['savepass2']));
        }
        $saveform .= "' /></td></tr>\n" . "<tr><td align='right'>" . $clang->gT("Your Email") . ":</td><td><input type='text' name='saveemail' value='";
        if (isset($_POST['saveemail'])) {
            $saveform .= html_escape(auto_unescape($_POST['saveemail']));
        }
        $saveform .= "' /></td></tr>\n";
        if (function_exists("ImageCreate") && captcha_enabled('saveandloadscreen', $thissurvey['usecaptcha'])) {
            $saveform .= "<tr><td align='right'>" . $clang->gT("Security Question") . ":</td><td><table><tr><td valign='middle'><img src='{$captchapath}verification.php?sid={$surveyid}' alt='' /></td><td valign='middle' style='text-align:left'><input type='text' size='5' maxlength='3' name='loadsecurity' value='' /></td></tr></table></td></tr>\n";
        }
        $saveform .= "<tr><td align='right'></td><td></td></tr>\n" . "<tr><td></td><td><input type='submit'  id='savebutton' name='savesubmit' value='" . $clang->gT("Save Now") . "' /></td></tr>\n" . "</table>";
        $line = str_replace("{SAVEFORM}", $saveform, $line);
    }
    if (strpos($line, "{LOADERROR}") !== false) {
        $line = str_replace("{LOADERROR}", $errormsg, $line);
    }
    if (strpos($line, "{LOADHEADING}") !== false) {
        $line = str_replace("{LOADHEADING}", $clang->gT("Load A Previously Saved Survey"), $line);
    }
    if (strpos($line, "{LOADMESSAGE}") !== false) {
        $line = str_replace("{LOADMESSAGE}", $clang->gT("You can load a survey that you have previously saved from this screen.") . "<br />" . $clang->gT("Type in the 'name' you used to save the survey, and the password.") . "<br />", $line);
    }
    if (strpos($line, "{LOADFORM}") !== false) {
        //LOAD SURVEY DETAILS
        $loadform = "<table><tr><td align='right'>" . $clang->gT("Saved name") . ":</td><td><input type='text' name='loadname' value='";
        if ($loadname) {
            $loadform .= html_escape(auto_unescape($loadname));
        }
        $loadform .= "' /></td></tr>\n" . "<tr><td align='right'>" . $clang->gT("Password") . ":</td><td><input type='password' name='loadpass' value='";
        if (isset($loadpass)) {
            $loadform .= html_escape(auto_unescape($loadpass));
        }
        $loadform .= "' /></td></tr>\n";
        if (function_exists("ImageCreate") && captcha_enabled('saveandloadscreen', $thissurvey['usecaptcha'])) {
            $loadform .= "<tr><td align='right'>" . $clang->gT("Security Question") . ":</td><td><table><tr><td valign='middle'><img src='{$captchapath}verification.php?sid={$surveyid}' alt='' /></td><td valign='middle'><input type='text' size='5' maxlength='3' name='loadsecurity' value='' alt=''/></td></tr></table></td></tr>\n";
        }
        $loadform .= "<tr><td align='right'></td><td></td></tr>\n" . "<tr><td></td><td><input type='submit' id='loadbutton' value='" . $clang->gT("Load Now") . "' /></td></tr></table>\n";
        $line = str_replace("{LOADFORM}", $loadform, $line);
    }
    //REGISTER SURVEY DETAILS
    if (strpos($line, "{REGISTERERROR}") !== false) {
        $line = str_replace("{REGISTERERROR}", $register_errormsg, $line);
    }
    if (strpos($line, "{REGISTERMESSAGE1}") !== false) {
        $line = str_replace("{REGISTERMESSAGE1}", $clang->gT("You must be registered to complete this survey"), $line);
    }
    if (strpos($line, "{REGISTERMESSAGE2}") !== false) {
        $line = str_replace("{REGISTERMESSAGE2}", $clang->gT("You may register for this survey if you wish to take part.") . "<br />\n" . $clang->gT("Enter your details below, and an email containing the link to participate in this survey will be sent immediately."), $line);
    }
    if (strpos($line, "{REGISTERFORM}") !== false) {
        $registerform = "<form method='post' action='{$publicurl}/register.php'>\n" . "<table class='register' summary='Registrationform'>\n" . "<tr><td align='right'>" . "<input type='hidden' name='sid' value='{$surveyid}' id='sid' />\n" . $clang->gT("First Name") . ":</td>" . "<td align='left'><input class='text' type='text' name='register_firstname'";
        if (isset($_POST['register_firstname'])) {
            $registerform .= " value='" . htmlentities(returnglobal('register_firstname'), ENT_QUOTES, 'UTF-8') . "'";
        }
        $registerform .= " /></td></tr>" . "<tr><td align='right'>" . $clang->gT("Last Name") . ":</td>\n" . "<td align='left'><input class='text' type='text' name='register_lastname'";
        if (isset($_POST['register_lastname'])) {
            $registerform .= " value='" . htmlentities(returnglobal('register_lastname'), ENT_QUOTES, 'UTF-8') . "'";
        }
        $registerform .= " /></td></tr>\n" . "<tr><td align='right'>" . $clang->gT("Email Address") . ":</td>\n" . "<td align='left'><input class='text' type='text' name='register_email'";
        if (isset($_POST['register_email'])) {
            $registerform .= " value='" . htmlentities(returnglobal('register_email'), ENT_QUOTES, 'UTF-8') . "'";
        }
        $registerform .= " /></td></tr>\n";
        if (!isset($_REQUEST['lang'])) {
            $reglang = GetBaseLanguageFromSurveyID($surveyid);
        } else {
            $reglang = returnglobal('lang');
        }
        if (function_exists("ImageCreate") && captcha_enabled('registrationscreen', $thissurvey['usecaptcha'])) {
            $registerform .= "<tr><td align='right'>" . $clang->gT("Security Question") . ":</td><td><table><tr><td valign='middle'><img src='{$captchapath}verification.php?sid={$surveyid}' alt='' /></td><td valign='middle'><input type='text' size='5' maxlength='3' name='loadsecurity' value='' /></td></tr></table></td></tr>\n";
        }
        $registerform .= "<tr><td align='right'><input type='hidden' name='lang' value='" . $reglang . "' /></td><td></td></tr>\n";
        /*      if(isset($thissurvey['attribute1']) && $thissurvey['attribute1'])
                {
                $registerform .= "<tr><td align='right'>".$thissurvey['attribute1'].":</td>\n"
                ."<td align='left'><input class='text' type='text' name='register_attribute1'";
                if (isset($_POST['register_attribute1']))
                {
                $registerform .= " value='".htmlentities(returnglobal('register_attribute1'),ENT_QUOTES,'UTF-8')."'";
                }
                $registerform .= " /></td></tr>\n";
                }
                if(isset($thissurvey['attribute2']) && $thissurvey['attribute2'])
                {
                $registerform .= "<tr><td align='right'>".$thissurvey['attribute2'].":</td>\n"
                ."<td align='left'><input class='text' type='text' name='register_attribute2'";
                if (isset($_POST['register_attribute2']))
                {
                $registerform .= " value='".htmlentities(returnglobal('register_attribute2'),ENT_QUOTES,'UTF-8')."'";
                }
                $registerform .= " /></td></tr>\n";
                }        */
        $registerform .= "<tr><td></td><td><input id='registercontinue' class='submit' type='submit' value='" . $clang->gT("Continue") . "' />" . "</td></tr>\n" . "</table>\n" . "</form>\n";
        $line = str_replace("{REGISTERFORM}", $registerform, $line);
    }
    if (strpos($line, "{ASSESSMENT_CURRENT_TOTAL}") !== false && function_exists('doAssessment')) {
        $assessmentdata = doAssessment($surveyid, true);
        $line = str_replace("{ASSESSMENT_CURRENT_TOTAL}", $assessmentdata['total'], $line);
    }
    if (strpos($line, "{ASSESSMENTS}") !== false) {
        $line = str_replace("{ASSESSMENTS}", $assessments, $line);
    }
    if (strpos($line, "{ASSESSMENT_HEADING}") !== false) {
        $line = str_replace("{ASSESSMENT_HEADING}", $clang->gT("Your Assessment"), $line);
    }
    return $line;
}