public function run($args) { global $surveyid; if (isset($_SESSION['token']) && $_SESSION['token'] != '') { //Gather survey data for tokenised surveys, for use in presenting questions $_SESSION['thistoken'] = getTokenData($surveyid, $_SESSION['token']); } if (isset($_SESSION['thistoken'])) { if (!strcmp(strtolower($args[0]), 'firstname')) { return $_SESSION['thistoken']['firstname']; } if (!strcmp(strtolower($args[0]), 'lastname')) { return $_SESSION['thistoken']['lastname']; } if (!strcmp(strtolower($args[0]), 'email')) { return $_SESSION['thistoken']['email']; } } else { return ""; } if (stripos($args[0], 'attribute_') !== FALSE) { $attr_no = (int) str_replace('ATTRIBUTE_', '', $args[0]); if (isset($_SESSION['thistoken']['attribute_' . $attr_no])) { return $_SESSION['thistoken']['attribute_' . $attr_no]; } } throw new Exception('TOKEN incorrect!'); }
/** * This function builds all the required session variables when a survey is first started and * it loads any answer defaults from command line or from the table defaultvalues * It is called from the related format script (group.php, question.php, survey.php) * if the survey has just started. */ function buildsurveysession($surveyid, $preview = false) { global $secerror, $clienttoken; global $tokensexist; //global $surveyid; global $templang, $move, $rooturl; $clang = Yii::app()->lang; $thissurvey = getSurveyInfo($surveyid); if (empty($templang)) { $templang = $thissurvey['language']; } $_SESSION['survey_' . $surveyid]['templatename'] = validateTemplateDir($thissurvey['template']); $_SESSION['survey_' . $surveyid]['templatepath'] = getTemplatePath($_SESSION['survey_' . $surveyid]['templatename']) . DIRECTORY_SEPARATOR; $sTemplatePath = $_SESSION['survey_' . $surveyid]['templatepath']; $loadsecurity = returnGlobal('loadsecurity'); // NO TOKEN REQUIRED BUT CAPTCHA ENABLED FOR SURVEY ACCESS if ($tokensexist == 0 && isCaptchaEnabled('surveyaccessscreen', $thissurvey['usecaptcha'])) { // IF CAPTCHA ANSWER IS NOT CORRECT OR NOT SET if (!isset($loadsecurity) || !isset($_SESSION['survey_' . $surveyid]['secanswer']) || $loadsecurity != $_SESSION['survey_' . $surveyid]['secanswer']) { sendCacheHeaders(); doHeader(); // No or bad answer to required security question $redata = compact(array_keys(get_defined_vars())); echo templatereplace(file_get_contents($sTemplatePath . "startpage.pstpl"), array(), $redata, 'frontend_helper[1525]'); //echo makedropdownlist(); echo templatereplace(file_get_contents($sTemplatePath . "survey.pstpl"), array(), $redata, 'frontend_helper[1527]'); if (isset($loadsecurity)) { // was a bad answer echo "<font color='#FF0000'>" . $clang->gT("The answer to the security question is incorrect.") . "</font><br />"; } echo "<p class='captcha'>" . $clang->gT("Please confirm access to survey by answering the security question below and click continue.") . "</p>" . CHtml::form(array("/survey/index/sid/{$surveyid}"), 'post', array('class' => 'captcha')) . "\n <table align='center'>\n <tr>\n <td align='right' valign='middle'>\n <input type='hidden' name='sid' value='" . $surveyid . "' id='sid' />\n <input type='hidden' name='lang' value='" . $templang . "' id='lang' />"; // In case we this is a direct Reload previous answers URL, then add hidden fields if (isset($_GET['loadall']) && isset($_GET['scid']) && isset($_GET['loadname']) && isset($_GET['loadpass'])) { echo "\n <input type='hidden' name='loadall' value='" . htmlspecialchars($_GET['loadall']) . "' id='loadall' />\n <input type='hidden' name='scid' value='" . returnGlobal('scid') . "' id='scid' />\n <input type='hidden' name='loadname' value='" . htmlspecialchars($_GET['loadname']) . "' id='loadname' />\n <input type='hidden' name='loadpass' value='" . htmlspecialchars($_GET['loadpass']) . "' id='loadpass' />"; } echo "\n </td>\n </tr>"; if (function_exists("ImageCreate") && isCaptchaEnabled('surveyaccessscreen', $thissurvey['usecaptcha'])) { echo "<tr>\n <td align='center' valign='middle'><label for='captcha'>" . $clang->gT("Security question:") . "</label></td><td align='left' valign='middle'><table><tr><td valign='middle'><img src='" . Yii::app()->getController()->createUrl('/verification/image/sid/' . $surveyid) . "' alt='captcha' /></td>\n <td valign='middle'><input id='captcha' type='text' size='5' maxlength='3' name='loadsecurity' value='' /></td></tr></table>\n </td>\n </tr>"; } echo "<tr><td colspan='2' align='center'><input class='submit' type='submit' value='" . $clang->gT("Continue") . "' /></td></tr>\n </table>\n </form>"; echo templatereplace(file_get_contents($sTemplatePath . "endpage.pstpl"), array(), $redata, 'frontend_helper[1567]'); doFooter(); exit; } } //BEFORE BUILDING A NEW SESSION FOR THIS SURVEY, LET'S CHECK TO MAKE SURE THE SURVEY SHOULD PROCEED! // TOKEN REQUIRED BUT NO TOKEN PROVIDED if ($tokensexist == 1 && !$clienttoken && !$preview) { if ($thissurvey['nokeyboard'] == 'Y') { includeKeypad(); $kpclass = "text-keypad"; } else { $kpclass = ""; } // DISPLAY REGISTER-PAGE if needed // DISPLAY CAPTCHA if needed sendCacheHeaders(); doHeader(); $redata = compact(array_keys(get_defined_vars())); echo templatereplace(file_get_contents($sTemplatePath . "startpage.pstpl"), array(), $redata, 'frontend_helper[1594]'); //echo makedropdownlist(); echo templatereplace(file_get_contents($sTemplatePath . "survey.pstpl"), array(), $redata, 'frontend_helper[1596]'); if (isset($thissurvey) && $thissurvey['allowregister'] == "Y") { echo templatereplace(file_get_contents($sTemplatePath . "register.pstpl"), array(), $redata, 'frontend_helper[1599]'); } else { // ->renderPartial('entertoken_view'); if (isset($secerror)) { echo "<span class='error'>" . $secerror . "</span><br />"; } echo '<div id="wrapper"><p id="tokenmessage">' . $clang->gT("This is a controlled survey. You need a valid token to participate.") . "<br />"; echo $clang->gT("If you have been issued a token, please enter it in the box below and click continue.") . "</p>\n <script type='text/javascript'>var focus_element='#token';</script>" . CHtml::form(array("/survey/index/sid/{$surveyid}"), 'post', array('id' => 'tokenform')) . "\n <ul>\n <li>"; ?> <label for='token'><?php $clang->eT("Token:"); ?> </label><input class='text <?php echo $kpclass; ?> ' id='token' type='text' name='token' /> <?php echo "<input type='hidden' name='sid' value='" . $surveyid . "' id='sid' />\n <input type='hidden' name='lang' value='" . $templang . "' id='lang' />"; if (isset($_GET['newtest']) && $_GET['newtest'] == "Y") { echo " <input type='hidden' name='newtest' value='Y' id='newtest' />"; } // If this is a direct Reload previous answers URL, then add hidden fields if (isset($_GET['loadall']) && isset($_GET['scid']) && isset($_GET['loadname']) && isset($_GET['loadpass'])) { echo "\n <input type='hidden' name='loadall' value='" . htmlspecialchars($_GET['loadall']) . "' id='loadall' />\n <input type='hidden' name='scid' value='" . returnGlobal('scid') . "' id='scid' />\n <input type='hidden' name='loadname' value='" . htmlspecialchars($_GET['loadname']) . "' id='loadname' />\n <input type='hidden' name='loadpass' value='" . htmlspecialchars($_GET['loadpass']) . "' id='loadpass' />"; } echo "</li>"; if (function_exists("ImageCreate") && isCaptchaEnabled('surveyaccessscreen', $thissurvey['usecaptcha'])) { echo "<li>\n <label for='captchaimage'>" . $clang->gT("Security Question") . "</label><img id='captchaimage' src='" . Yii::app()->getController()->createUrl('/verification/image/sid/' . $surveyid) . "' alt='captcha' /><input type='text' size='5' maxlength='3' name='loadsecurity' value='' />\n </li>"; } echo "<li>\n <input class='submit' type='submit' value='" . $clang->gT("Continue") . "' />\n </li>\n </ul>\n </form></div>"; } echo templatereplace(file_get_contents($sTemplatePath . "endpage.pstpl"), array(), $redata, 'frontend_helper[1645]'); doFooter(); exit; } elseif ($tokensexist == 1 && $clienttoken && !isCaptchaEnabled('surveyaccessscreen', $thissurvey['usecaptcha'])) { //check if tokens actually haven't been already used $areTokensUsed = usedTokens(trim(strip_tags($clienttoken)), $surveyid); //check if token actually does exist // check also if it is allowed to change survey after completion if ($thissurvey['alloweditaftercompletion'] == 'Y') { $oTokenEntry = Tokens_dynamic::model($surveyid)->find('token=:token', array(':token' => trim(strip_tags($clienttoken)))); } else { $oTokenEntry = Tokens_dynamic::model($surveyid)->find("token=:token AND (completed = 'N' or completed='')", array(':token' => trim(strip_tags($clienttoken)))); } if (is_null($oTokenEntry) || $areTokensUsed && $thissurvey['alloweditaftercompletion'] != 'Y') { //TOKEN DOESN'T EXIST OR HAS ALREADY BEEN USED. EXPLAIN PROBLEM AND EXIT killSurveySession($surveyid); sendCacheHeaders(); doHeader(); $redata = compact(array_keys(get_defined_vars())); echo templatereplace(file_get_contents($sTemplatePath . "startpage.pstpl"), array(), $redata, 'frontend_helper[1676]'); echo templatereplace(file_get_contents($sTemplatePath . "survey.pstpl"), array(), $redata, 'frontend_helper[1677]'); echo '<div id="wrapper"><p id="tokenmessage">' . $clang->gT("This is a controlled survey. You need a valid token to participate.") . "<br /><br />\n" . "\t" . $clang->gT("The token you have provided is either not valid, or has already been used.") . "<br /><br />\n" . "\t" . sprintf($clang->gT("For further information please contact %s"), $thissurvey['adminname']) . " (<a href='mailto:{$thissurvey['adminemail']}'>" . "{$thissurvey['adminemail']}</a>)</p></div>\n"; echo templatereplace(file_get_contents($sTemplatePath . "endpage.pstpl"), array(), $redata, 'frontend_helper[1684]'); doFooter(); exit; } } elseif ($tokensexist == 1 && $clienttoken && isCaptchaEnabled('surveyaccessscreen', $thissurvey['usecaptcha'])) { // IF CAPTCHA ANSWER IS CORRECT if (isset($loadsecurity) && isset($_SESSION['survey_' . $surveyid]['secanswer']) && $loadsecurity == $_SESSION['survey_' . $surveyid]['secanswer']) { //check if tokens actually haven't been already used $areTokensUsed = usedTokens(trim(strip_tags($clienttoken)), $surveyid); //check if token actually does exist $oTokenEntry = Tokens_dynamic::model($surveyid)->find('token=:token', array(':token' => trim(strip_tags($clienttoken)))); if ($thissurvey['alloweditaftercompletion'] == 'Y') { $oTokenEntry = Tokens_dynamic::model($surveyid)->find('token=:token', array(':token' => trim(strip_tags($clienttoken)))); } else { $oTokenEntry = Tokens_dynamic::model($surveyid)->find("token=:token AND (completed = 'N' or completed='')", array(':token' => trim(strip_tags($clienttoken)))); } if (is_null($oTokenEntry) || $areTokensUsed && $thissurvey['alloweditaftercompletion'] != 'Y') { sendCacheHeaders(); doHeader(); //TOKEN DOESN'T EXIST OR HAS ALREADY BEEN USED. EXPLAIN PROBLEM AND EXIT $redata = compact(array_keys(get_defined_vars())); echo templatereplace(file_get_contents($sTemplatePath . "startpage.pstpl"), array(), $redata, 'frontend_helper[1719]'); echo templatereplace(file_get_contents($sTemplatePath . "survey.pstpl"), array(), $redata, 'frontend_helper[1720]'); echo "\t<div id='wrapper'>\n" . "\t<p id='tokenmessage'>\n" . "\t" . $clang->gT("This is a controlled survey. You need a valid token to participate.") . "<br /><br />\n" . "\t" . $clang->gT("The token you have provided is either not valid, or has already been used.") . "<br/><br />\n" . "\t" . sprintf($clang->gT("For further information please contact %s"), $thissurvey['adminname']) . " (<a href='mailto:{$thissurvey['adminemail']}'>" . "{$thissurvey['adminemail']}</a>)\n" . "\t</p>\n" . "\t</div>\n"; echo templatereplace(file_get_contents($sTemplatePath . "endpage.pstpl"), array(), $redata, 'frontend_helper[1731]'); doFooter(); exit; } } else { if (!isset($move) || is_null($move)) { unset($_SESSION['survey_' . $surveyid]['srid']); $gettoken = $clienttoken; sendCacheHeaders(); doHeader(); // No or bad answer to required security question $redata = compact(array_keys(get_defined_vars())); echo templatereplace(file_get_contents($sTemplatePath . "startpage.pstpl"), array(), $redata, 'frontend_helper[1745]'); echo templatereplace(file_get_contents($sTemplatePath . "survey.pstpl"), array(), $redata, 'frontend_helper[1746]'); // If token wasn't provided and public registration // is enabled then show registration form if (!isset($gettoken) && isset($thissurvey) && $thissurvey['allowregister'] == "Y") { echo templatereplace(file_get_contents($sTemplatePath . "register.pstpl"), array(), $redata, 'frontend_helper[1751]'); } else { // only show CAPTCHA echo '<div id="wrapper"><p id="tokenmessage">'; if (isset($loadsecurity)) { // was a bad answer echo "<span class='error'>" . $clang->gT("The answer to the security question is incorrect.") . "</span><br />"; } echo $clang->gT("This is a controlled survey. You need a valid token to participate.") . "<br /><br />"; // IF TOKEN HAS BEEN GIVEN THEN AUTOFILL IT // AND HIDE ENTRY FIELD if (!isset($gettoken)) { echo $clang->gT("If you have been issued a token, please enter it in the box below and click continue.") . "</p>\n <form id='tokenform' method='get' action='" . Yii::app()->getController()->createUrl("/survey/index") . "'>\n <ul>\n <li>\n <input type='hidden' name='sid' value='" . $surveyid . "' id='sid' />\n <input type='hidden' name='lang' value='" . $templang . "' id='lang' />"; if (isset($_GET['loadall']) && isset($_GET['scid']) && isset($_GET['loadname']) && isset($_GET['loadpass'])) { echo "<input type='hidden' name='loadall' value='" . htmlspecialchars($_GET['loadall']) . "' id='loadall' />\n <input type='hidden' name='scid' value='" . returnGlobal('scid') . "' id='scid' />\n <input type='hidden' name='loadname' value='" . htmlspecialchars($_GET['loadname']) . "' id='loadname' />\n <input type='hidden' name='loadpass' value='" . htmlspecialchars($_GET['loadpass']) . "' id='loadpass' />"; } echo '<label for="token">' . $clang->gT("Token") . "</label><input class='text' type='text' id='token' name='token'></li>"; } else { echo $clang->gT("Please confirm the token by answering the security question below and click continue.") . "</p>\n <form id='tokenform' method='get' action='" . Yii::app()->getController()->createUrl("/survey/index") . "'>\n <ul>\n <li>\n <input type='hidden' name='sid' value='" . $surveyid . "' id='sid' />\n <input type='hidden' name='lang' value='" . $templang . "' id='lang' />"; if (isset($_GET['loadall']) && isset($_GET['scid']) && isset($_GET['loadname']) && isset($_GET['loadpass'])) { echo "<input type='hidden' name='loadall' value='" . htmlspecialchars($_GET['loadall']) . "' id='loadall' />\n <input type='hidden' name='scid' value='" . returnGlobal('scid') . "' id='scid' />\n <input type='hidden' name='loadname' value='" . htmlspecialchars($_GET['loadname']) . "' id='loadname' />\n <input type='hidden' name='loadpass' value='" . htmlspecialchars($_GET['loadpass']) . "' id='loadpass' />"; } echo '<label for="token">' . $clang->gT("Token:") . "</label><span id='token'>{$gettoken}</span>" . "<input type='hidden' name='token' value='{$gettoken}'></li>"; } if (function_exists("ImageCreate") && isCaptchaEnabled('surveyaccessscreen', $thissurvey['usecaptcha'])) { echo "<li>\n <label for='captchaimage'>" . $clang->gT("Security Question") . "</label><img id='captchaimage' src='" . Yii::app()->getController()->createUrl('/verification/image/sid/' . $surveyid) . "' alt='captcha' /><input type='text' size='5' maxlength='3' name='loadsecurity' value='' />\n </li>"; } echo "<li><input class='submit' type='submit' value='" . $clang->gT("Continue") . "' /></li>\n </ul>\n </form>\n </id>"; } echo '</div>' . templatereplace(file_get_contents($sTemplatePath . "endpage.pstpl"), array(), $redata, 'frontend_helper[1817]'); doFooter(); exit; } } } //RESET ALL THE SESSION VARIABLES AND START AGAIN unset($_SESSION['survey_' . $surveyid]['grouplist']); unset($_SESSION['survey_' . $surveyid]['fieldarray']); unset($_SESSION['survey_' . $surveyid]['insertarray']); unset($_SESSION['survey_' . $surveyid]['thistoken']); unset($_SESSION['survey_' . $surveyid]['fieldnamesInfo']); unset($_SESSION['survey_' . $surveyid]['fieldmap-' . $surveyid . '-randMaster']); unset($_SESSION['survey_' . $surveyid]['groupReMap']); $_SESSION['survey_' . $surveyid]['fieldnamesInfo'] = array(); //RL: multilingual support if (isset($_GET['token']) && tableExists('{{tokens_' . $surveyid . '}}')) { //get language from token (if one exists) $tkquery2 = "SELECT * FROM {{tokens_" . $surveyid . "}} WHERE token='" . $clienttoken . "' AND (completed = 'N' or completed='')"; //echo $tkquery2; $result = dbExecuteAssoc($tkquery2) or safeDie("Couldn't get tokens<br />{$tkquery}<br />"); //Checked foreach ($result->readAll() as $rw) { $tklanguage = $rw['language']; } } if (returnGlobal('lang')) { $language_to_set = returnGlobal('lang'); } elseif (isset($tklanguage)) { $language_to_set = $tklanguage; } else { $language_to_set = $thissurvey['language']; } if (!isset($_SESSION['survey_' . $surveyid]['s_lang'])) { SetSurveyLanguage($surveyid, $language_to_set); } UpdateGroupList($surveyid, $_SESSION['survey_' . $surveyid]['s_lang']); $sQuery = "SELECT count(*)\n" . " FROM {{groups}} INNER JOIN {{questions}} ON {{groups}}.gid = {{questions}}.gid\n" . " WHERE {{questions}}.sid=" . $surveyid . "\n" . " AND {{groups}}.language='" . $_SESSION['survey_' . $surveyid]['s_lang'] . "'\n" . " AND {{questions}}.language='" . $_SESSION['survey_' . $surveyid]['s_lang'] . "'\n" . " AND {{questions}}.parent_qid=0\n"; $totalquestions = Yii::app()->db->createCommand($sQuery)->queryScalar(); // Fix totalquestions by substracting Test Display questions $iNumberofQuestions = dbExecuteAssoc("SELECT count(*)\n" . " FROM {{questions}}" . " WHERE type in ('X','*')\n" . " AND sid={$surveyid}" . " AND language='" . $_SESSION['survey_' . $surveyid]['s_lang'] . "'" . " AND parent_qid=0")->read(); $_SESSION['survey_' . $surveyid]['totalquestions'] = $totalquestions - (int) reset($iNumberofQuestions); //2. SESSION VARIABLE: totalsteps //The number of "pages" that will be presented in this survey //The number of pages to be presented will differ depending on the survey format switch ($thissurvey['format']) { case "A": $_SESSION['survey_' . $surveyid]['totalsteps'] = 1; break; case "G": if (isset($_SESSION['survey_' . $surveyid]['grouplist'])) { $_SESSION['survey_' . $surveyid]['totalsteps'] = count($_SESSION['survey_' . $surveyid]['grouplist']); } break; case "S": $_SESSION['survey_' . $surveyid]['totalsteps'] = $totalquestions; } if ($totalquestions == 0) { sendCacheHeaders(); doHeader(); $redata = compact(array_keys(get_defined_vars())); echo templatereplace(file_get_contents($sTemplatePath . "startpage.pstpl"), array(), $redata, 'frontend_helper[1914]'); echo templatereplace(file_get_contents($sTemplatePath . "survey.pstpl"), array(), $redata, 'frontend_helper[1915]'); echo "\t<div id='wrapper'>\n" . "\t<p id='tokenmessage'>\n" . "\t" . $clang->gT("This survey does not yet have any questions and cannot be tested or completed.") . "<br /><br />\n" . "\t" . sprintf($clang->gT("For further information please contact %s"), $thissurvey['adminname']) . " (<a href='mailto:{$thissurvey['adminemail']}'>" . "{$thissurvey['adminemail']}</a>)<br /><br />\n" . "\t</p>\n" . "\t</div>\n"; echo templatereplace(file_get_contents($sTemplatePath . "endpage.pstpl"), array(), $redata, 'frontend_helper[1925]'); doFooter(); exit; } //Perform a case insensitive natural sort on group name then question title of a multidimensional array // usort($arows, 'groupOrderThenQuestionOrder'); //3. SESSION VARIABLE - insertarray //An array containing information about used to insert the data into the db at the submit stage //4. SESSION VARIABLE - fieldarray //See rem at end.. $_SESSION['survey_' . $surveyid]['token'] = $clienttoken; if ($thissurvey['anonymized'] == "N") { $_SESSION['survey_' . $surveyid]['insertarray'][] = "token"; } if ($tokensexist == 1 && $thissurvey['anonymized'] == "N" && tableExists('{{tokens_' . $surveyid . '}}')) { //Gather survey data for "non anonymous" surveys, for use in presenting questions $_SESSION['survey_' . $surveyid]['thistoken'] = getTokenData($surveyid, $clienttoken); } $qtypes = getQuestionTypeList('', 'array'); $fieldmap = createFieldMap($surveyid, 'full', true, false, $_SESSION['survey_' . $surveyid]['s_lang']); // Randomization groups for groups $aRandomGroups = array(); $aGIDCompleteMap = array(); // first find all groups and their groups IDS $criteria = new CDbCriteria(); $criteria->addColumnCondition(array('sid' => $surveyid, 'language' => $_SESSION['survey_' . $surveyid]['s_lang'])); $criteria->addCondition("randomization_group != ''"); $oData = Groups::model()->findAll($criteria); foreach ($oData as $aGroup) { $aRandomGroups[$aGroup['randomization_group']][] = $aGroup['gid']; } // Shuffle each group and create a map for old GID => new GID foreach ($aRandomGroups as $sGroupName => $aGIDs) { $aShuffledIDs = $aGIDs; shuffle($aShuffledIDs); $aGIDCompleteMap = $aGIDCompleteMap + array_combine($aGIDs, $aShuffledIDs); } $_SESSION['survey_' . $surveyid]['groupReMap'] = $aGIDCompleteMap; $randomized = false; // So we can trigger reorder once for group and question randomization // Now adjust the grouplist if (count($aRandomGroups) > 0) { $randomized = true; // So we can trigger reorder once for group and question randomization // Now adjust the grouplist Yii::import('application.helpers.frontend_helper', true); // make sure frontend helper is loaded UpdateGroupList($surveyid, $_SESSION['survey_' . $surveyid]['s_lang']); // ... and the fieldmap // First create a fieldmap with GID as key foreach ($fieldmap as $aField) { if (isset($aField['gid'])) { $GroupFieldMap[$aField['gid']][] = $aField; } else { $GroupFieldMap['other'][] = $aField; } } // swap it foreach ($GroupFieldMap as $iOldGid => $fields) { $iNewGid = $iOldGid; if (isset($aGIDCompleteMap[$iOldGid])) { $iNewGid = $aGIDCompleteMap[$iOldGid]; } $newGroupFieldMap[$iNewGid] = $GroupFieldMap[$iNewGid]; } $GroupFieldMap = $newGroupFieldMap; // and convert it back to a fieldmap unset($fieldmap); foreach ($GroupFieldMap as $aGroupFields) { foreach ($aGroupFields as $aField) { if (isset($aField['fieldname'])) { $fieldmap[$aField['fieldname']] = $aField; // isset() because of the shuffled flag above } } } unset($GroupFieldMap); } // Randomization groups for questions // Find all defined randomization groups through question attribute values $randomGroups = array(); if (in_array(Yii::app()->db->getDriverName(), array('mssql', 'sqlsrv'))) { $rgquery = "SELECT attr.qid, CAST(value as varchar(255)) as value FROM {{question_attributes}} as attr right join {{questions}} as quests on attr.qid=quests.qid WHERE attribute='random_group' and CAST(value as varchar(255)) <> '' and sid={$surveyid} GROUP BY attr.qid, CAST(value as varchar(255))"; } else { $rgquery = "SELECT attr.qid, value FROM {{question_attributes}} as attr right join {{questions}} as quests on attr.qid=quests.qid WHERE attribute='random_group' and value <> '' and sid={$surveyid} GROUP BY attr.qid, value"; } $rgresult = dbExecuteAssoc($rgquery); foreach ($rgresult->readAll() as $rgrow) { // Get the question IDs for each randomization group $randomGroups[$rgrow['value']][] = $rgrow['qid']; } // If we have randomization groups set, then lets cycle through each group and // replace questions in the group with a randomly chosen one from the same group if (count($randomGroups) > 0) { $randomized = true; // So we can trigger reorder once for group and question randomization $copyFieldMap = array(); $oldQuestOrder = array(); $newQuestOrder = array(); $randGroupNames = array(); foreach ($randomGroups as $key => $value) { $oldQuestOrder[$key] = $randomGroups[$key]; $newQuestOrder[$key] = $oldQuestOrder[$key]; // We shuffle the question list to get a random key->qid which will be used to swap from the old key shuffle($newQuestOrder[$key]); $randGroupNames[] = $key; } // Loop through the fieldmap and swap each question as they come up foreach ($fieldmap as $fieldkey => $fieldval) { $found = 0; foreach ($randomGroups as $gkey => $gval) { // We found a qid that is in the randomization group if (isset($fieldval['qid']) && in_array($fieldval['qid'], $oldQuestOrder[$gkey])) { // Get the swapped question $idx = array_search($fieldval['qid'], $oldQuestOrder[$gkey]); foreach ($fieldmap as $key => $field) { if (isset($field['qid']) && $field['qid'] == $newQuestOrder[$gkey][$idx]) { $field['random_gid'] = $fieldval['gid']; // It is possible to swap to another group $copyFieldMap[$key] = $field; } } $found = 1; break; } else { $found = 2; } } if ($found == 2) { $copyFieldMap[$fieldkey] = $fieldval; } reset($randomGroups); } $fieldmap = $copyFieldMap; } if ($randomized === true) { // reset the sequencing counts $gseq = -1; $_gid = -1; $qseq = -1; $_qid = -1; $copyFieldMap = array(); foreach ($fieldmap as $key => $val) { if ($val['gid'] != '') { if (isset($val['random_gid'])) { $gid = $val['random_gid']; } else { $gid = $val['gid']; } if ($gid != $_gid) { $_gid = $gid; ++$gseq; } } if ($val['qid'] != '' && $val['qid'] != $_qid) { $_qid = $val['qid']; ++$qseq; } if ($val['gid'] != '' && $val['qid'] != '') { $val['groupSeq'] = $gseq; $val['questionSeq'] = $qseq; } $copyFieldMap[$key] = $val; } $fieldmap = $copyFieldMap; unset($copyFieldMap); $_SESSION['survey_' . $surveyid]['fieldmap-' . $surveyid . $_SESSION['survey_' . $surveyid]['s_lang']] = $fieldmap; $_SESSION['survey_' . $surveyid]['fieldmap-' . $surveyid . '-randMaster'] = 'fieldmap-' . $surveyid . $_SESSION['survey_' . $surveyid]['s_lang']; } // TMSW Conditions->Relevance: don't need hasconditions, or usedinconditions $_SESSION['survey_' . $surveyid]['fieldmap'] = $fieldmap; foreach ($fieldmap as $field) { if (isset($field['qid']) && $field['qid'] != '') { $_SESSION['survey_' . $surveyid]['fieldnamesInfo'][$field['fieldname']] = $field['sid'] . 'X' . $field['gid'] . 'X' . $field['qid']; $_SESSION['survey_' . $surveyid]['insertarray'][] = $field['fieldname']; //fieldarray ARRAY CONTENTS - // [0]=questions.qid, // [1]=fieldname, // [2]=questions.title, // [3]=questions.question // [4]=questions.type, // [5]=questions.gid, // [6]=questions.mandatory, // [7]=conditionsexist, // [8]=usedinconditions // [8]=usedinconditions // [9]=used in group.php for question count // [10]=new group id for question in randomization group (GroupbyGroup Mode) if (!isset($_SESSION['survey_' . $surveyid]['fieldarray'][$field['sid'] . 'X' . $field['gid'] . 'X' . $field['qid']])) { //JUST IN CASE : PRECAUTION! //following variables are set only if $style=="full" in createFieldMap() in common_helper. //so, if $style = "short", set some default values here! if (isset($field['title'])) { $title = $field['title']; } else { $title = ""; } if (isset($field['question'])) { $question = $field['question']; } else { $question = ""; } if (isset($field['mandatory'])) { $mandatory = $field['mandatory']; } else { $mandatory = 'N'; } if (isset($field['hasconditions'])) { $hasconditions = $field['hasconditions']; } else { $hasconditions = 'N'; } if (isset($field['usedinconditions'])) { $usedinconditions = $field['usedinconditions']; } else { $usedinconditions = 'N'; } $_SESSION['survey_' . $surveyid]['fieldarray'][$field['sid'] . 'X' . $field['gid'] . 'X' . $field['qid']] = array($field['qid'], $field['sid'] . 'X' . $field['gid'] . 'X' . $field['qid'], $title, $question, $field['type'], $field['gid'], $mandatory, $hasconditions, $usedinconditions); } if (isset($field['random_gid'])) { $_SESSION['survey_' . $surveyid]['fieldarray'][$field['sid'] . 'X' . $field['gid'] . 'X' . $field['qid']][10] = $field['random_gid']; } } } // Prefill questions/answers from command line params $reservedGetValues = array('token', 'sid', 'gid', 'qid', 'lang', 'newtest', 'action'); $startingValues = array(); if (isset($_GET)) { foreach ($_GET as $k => $v) { if (!in_array($k, $reservedGetValues) && isset($_SESSION['survey_' . $surveyid]['fieldmap'][$k])) { $startingValues[$k] = $v; } } } $_SESSION['survey_' . $surveyid]['startingValues'] = $startingValues; if (isset($_SESSION['survey_' . $surveyid]['fieldarray'])) { $_SESSION['survey_' . $surveyid]['fieldarray'] = array_values($_SESSION['survey_' . $surveyid]['fieldarray']); } //Check if a passthru label and value have been included in the query url $oResult = Survey_url_parameters::model()->getParametersForSurvey($surveyid); foreach ($oResult->readAll() as $aRow) { if (isset($_GET[$aRow['parameter']]) && !$preview) { $_SESSION['survey_' . $surveyid]['urlparams'][$aRow['parameter']] = $_GET[$aRow['parameter']]; if ($aRow['targetqid'] != '') { foreach ($fieldmap as $sFieldname => $aField) { if ($aRow['targetsqid'] != '') { if ($aField['qid'] == $aRow['targetqid'] && $aField['sqid'] == $aRow['targetsqid']) { $_SESSION['survey_' . $surveyid]['startingValues'][$sFieldname] = $_GET[$aRow['parameter']]; $_SESSION['survey_' . $surveyid]['startingValues'][$aRow['parameter']] = $_GET[$aRow['parameter']]; } } else { if ($aField['qid'] == $aRow['targetqid']) { $_SESSION['survey_' . $surveyid]['startingValues'][$sFieldname] = $_GET[$aRow['parameter']]; $_SESSION['survey_' . $surveyid]['startingValues'][$aRow['parameter']] = $_GET[$aRow['parameter']]; } } } } } } }
/** * Create the arrays of answer and token replacement fields * This function should only be called once per page display (e.g. only if $fieldMap changes) * * @param <type> $forceRefresh * @return boolean - true if $fieldmap had been re-created, so ExpressionManager variables need to be re-set */ function getAnswerAndTokenMappings($forceRefresh=false,$anonymized=false) { global $globalfieldmap, $clang, $surveyid; //checks to see if fieldmap has already been built for this page. if (isset($globalfieldmap[$surveyid]['full'][$clang->langcode])) { if (isset($globalfieldmap[$surveyid]['full-VarMap'][$clang->langcode]) && !$forceRefresh) { return $globalfieldmap[$surveyid]['full-VarMap'][$clang->langcode]; // means the mappings have already been set and don't need to be re-created } } if (!isset($surveyid)) { return array(); // will happen on public root view } $fieldmap=createFieldMap($surveyid,$style='full',$forceRefresh); if (!isset($fieldmap)) { return array(); // implies an error occurred } $sgqaMap = array(); // mapping of SGQA to Value foreach($fieldmap as $fielddata) { $code = $fielddata['fieldname']; if (!preg_match('#^\d+X\d+X\d+#',$code)) { continue; // not an SGQA value } if (isset($_SESSION[$code])) { $displayValue= retrieve_Answer($code, $_SESSION['dateformats']['phpdate']); $sgqaMap['INSERTANS:' . $code] = $displayValue; } else { $sgqaMap['INSERTANS:' . $code] = ""; // so if know value has been set, replace with blank - is that the desired behavior? } } // Now set tokens $tokenMap = array(); // mapping of TOKENS to values if (isset($_SESSION['token']) && $_SESSION['token'] != '') { //Gather survey data for tokenised surveys, for use in presenting questions $_SESSION['thistoken']=getTokenData($surveyid, $_SESSION['token']); } if (isset($_SESSION['thistoken'])) { foreach (array_keys($_SESSION['thistoken']) as $tokenkey) { if ($anonymized) { $val = ""; } else { $val = $_SESSION['thistoken'][$tokenkey]; } $key = "TOKEN:" . strtoupper($tokenkey); $tokenMap[$key] = $val; } } else { // Explicitly set all tokens to blank $tokenMap['TOKEN:FIRSTNAME'] = ""; $tokenMap['TOKEN:LASTNAME'] = ""; $tokenMap['TOKEN:EMAIL'] = ""; $tokenMap['TOKEN:USESLEFT'] = ""; for ($i=1;$i<=100;++$i) // TODO - is there a way to know how many attributes are set? Looks like max is 100 { $tokenMap['TOKEN:ATTRIBUTE_' . $i] = ""; } } $fullMap = array_merge($sgqaMap, $tokenMap); $globalfieldmap[$surveyid]['full-VarMap'][$clang->langcode] = $fullMap; return $fullMap; }
/** * Create the arrays needed by ExpressionManager to process LimeSurvey strings. * The long part of this function should only be called once per page display (e.g. only if $fieldMap changes) * * @param <integer> $surveyid * @param <Boolean> $forceRefresh * @param <Boolean> $anonymized * @param <Boolean> $allOnOnePage - if true (like for survey_format), uses certain optimizations * @return boolean - true if $fieldmap had been re-created, so ExpressionManager variables need to be re-set */ private function setVariableAndTokenMappingsForExpressionManager($surveyid, $forceRefresh = false, $anonymized = false, $allOnOnePage = false) { if (isset($_SESSION['LEMforceRefresh'])) { unset($_SESSION['LEMforceRefresh']); $forceRefresh = true; } else { if (!$forceRefresh && isset($this->knownVars) && !$this->sPreviewMode) { return false; // means that those variables have been cached and no changes needed } } $now = microtime(true); $this->em->SetSurveyMode($this->surveyMode); // TODO - do I need to force refresh, or trust that createFieldMap will cache langauges properly? $fieldmap = createFieldMap($surveyid, $style = 'full', $forceRefresh, false, $_SESSION['LEMlang']); $this->sid = $surveyid; $this->runtimeTimings[] = array(__METHOD__ . '.createFieldMap', microtime(true) - $now); // LimeExpressionManager::ShowStackTrace(); $now = microtime(true); if (!isset($fieldmap)) { return false; // implies an error occurred } $this->knownVars = array(); // mapping of VarName to Value $this->qcode2sgqa = array(); $this->tempVars = array(); $this->qid2code = array(); // List of codes for each question - needed to know which to NULL if a question is irrelevant $this->jsVar2qid = array(); $this->qcode2sgq = array(); $this->alias2varName = array(); $this->varNameAttr = array(); $this->questionId2questionSeq = array(); $this->questionId2groupSeq = array(); $this->questionSeq2relevance = array(); $this->groupId2groupSeq = array(); $this->qid2validationEqn = array(); $this->groupSeqInfo = array(); $this->gseq2relevanceStatus = array(); // Since building array of allowable answers, need to know preset values for certain question types $presets = array(); $presets['G'] = array('M' => $this->gT("Male"), 'F' => $this->gT("Female")); $presets['Y'] = array('Y' => $this->gT("Yes"), 'N' => $this->gT("No")); $presets['C'] = array('Y' => $this->gT("Yes"), 'N' => $this->gT("No"), 'U' => $this->gT("Uncertain")); $presets['E'] = array('I' => $this->gT("Increase"), 'S' => $this->gT("Same"), 'D' => $this->gT("Decrease")); $this->gseq2info = $this->getGroupInfoForEM($surveyid, $_SESSION['LEMlang']); foreach ($this->gseq2info as $aGroupInfo) { $this->groupId2groupSeq[$aGroupInfo['gid']] = $aGroupInfo['group_order']; } $qattr = $this->getQuestionAttributesForEM($surveyid, NULL, $_SESSION['LEMlang']); $this->qattr = $qattr; $this->runtimeTimings[] = array(__METHOD__ . ' - question_attributes_model->getQuestionAttributesForEM', microtime(true) - $now); $now = microtime(true); $this->qans = $this->getAnswerSetsForEM($surveyid, NULL, $_SESSION['LEMlang']); $this->runtimeTimings[] = array(__METHOD__ . ' - answers_model->getAnswerSetsForEM', microtime(true) - $now); $now = microtime(true); $q2subqInfo = array(); $this->multiflexiAnswers = array(); foreach ($fieldmap as $fielddata) { if (!isset($fielddata['fieldname']) || !preg_match('#^\\d+X\\d+X\\d+#', $fielddata['fieldname'])) { continue; // not an SGQA value } $sgqa = $fielddata['fieldname']; $type = $fielddata['type']; $mandatory = $fielddata['mandatory']; $fieldNameParts = explode('X', $sgqa); $groupNum = $fieldNameParts[1]; $aid = isset($fielddata['aid']) ? $fielddata['aid'] : ''; $sqid = isset($fielddata['sqid']) ? $fielddata['sqid'] : ''; if ($this->sPreviewMode == 'question') { $fielddata['relevance'] = 1; } if ($this->sPreviewMode == 'group') { $fielddata['grelevance'] = 1; } $questionId = $fieldNameParts[2]; $questionNum = $fielddata['qid']; $relevance = isset($fielddata['relevance']) ? $fielddata['relevance'] : 1; $grelevance = isset($fielddata['grelevance']) ? $fielddata['grelevance'] : 1; $hidden = isset($qattr[$questionNum]['hidden']) ? $qattr[$questionNum]['hidden'] == '1' : false; $scale_id = isset($fielddata['scale_id']) ? $fielddata['scale_id'] : '0'; $preg = isset($fielddata['preg']) ? $fielddata['preg'] : NULL; // a perl regular exrpession validation function $defaultValue = isset($fielddata['defaultvalue']) ? $fielddata['defaultvalue'] : NULL; if (trim($preg) == '') { $preg = NULL; } $help = isset($fielddata['help']) ? $fielddata['help'] : ''; $other = isset($fielddata['other']) ? $fielddata['other'] : ''; if (isset($this->questionId2groupSeq[$questionNum])) { $groupSeq = $this->questionId2groupSeq[$questionNum]; } else { $groupSeq = isset($fielddata['groupSeq']) ? $fielddata['groupSeq'] : -1; $this->questionId2groupSeq[$questionNum] = $groupSeq; } if (isset($this->questionId2questionSeq[$questionNum])) { $questionSeq = $this->questionId2questionSeq[$questionNum]; } else { $questionSeq = isset($fielddata['questionSeq']) ? $fielddata['questionSeq'] : -1; $this->questionId2questionSeq[$questionNum] = $questionSeq; } if (!isset($this->groupSeqInfo[$groupSeq])) { $this->groupSeqInfo[$groupSeq] = array('qstart' => $questionSeq, 'qend' => $questionSeq); } else { $this->groupSeqInfo[$groupSeq]['qend'] = $questionSeq; // with each question, update so know ending value } // Create list of codes associated with each question $codeList = isset($this->qid2code[$questionNum]) ? $this->qid2code[$questionNum] : ''; if ($codeList == '') { $codeList = $sgqa; } else { $codeList .= '|' . $sgqa; } $this->qid2code[$questionNum] = $codeList; $readWrite = 'Y'; // Set $ansArray switch ($type) { case '!': //List - dropdown //List - dropdown case 'L': //LIST drop-down/radio-button list //LIST drop-down/radio-button list case 'O': //LIST WITH COMMENT drop-down/radio-button list + textarea //LIST WITH COMMENT drop-down/radio-button list + textarea case '1': //Array (Flexible Labels) dual scale // need scale //Array (Flexible Labels) dual scale // need scale case 'H': //ARRAY (Flexible) - Column Format //ARRAY (Flexible) - Column Format case 'F': //ARRAY (Flexible) - Row Format //ARRAY (Flexible) - Row Format case 'R': //RANKING STYLE $ansArray = isset($this->qans[$questionNum]) ? $this->qans[$questionNum] : NULL; if ($other == 'Y' && ($type == 'L' || $type == '!')) { if (preg_match('/other$/', $sgqa)) { $ansArray = NULL; // since the other variable doesn't need it } else { $_qattr = isset($qattr[$questionNum]) ? $qattr[$questionNum] : array(); if (isset($_qattr['other_replace_text']) && trim($_qattr['other_replace_text']) != '') { $othertext = trim($_qattr['other_replace_text']); } else { $othertext = $this->gT('Other:'); } $ansArray['0~-oth-'] = '0|' . $othertext; } } break; case 'A': //ARRAY (5 POINT CHOICE) radio-buttons //ARRAY (5 POINT CHOICE) radio-buttons case 'B': //ARRAY (10 POINT CHOICE) radio-buttons //ARRAY (10 POINT CHOICE) radio-buttons case ':': //ARRAY (Multi Flexi) 1 to 10 //ARRAY (Multi Flexi) 1 to 10 case '5': //5 POINT CHOICE radio-buttons $ansArray = NULL; break; case 'N': //NUMERICAL QUESTION TYPE //NUMERICAL QUESTION TYPE case 'K': //MULTIPLE NUMERICAL QUESTION //MULTIPLE NUMERICAL QUESTION case 'Q': //MULTIPLE SHORT TEXT //MULTIPLE SHORT TEXT case ';': //ARRAY (Multi Flexi) Text //ARRAY (Multi Flexi) Text case 'S': //SHORT FREE TEXT //SHORT FREE TEXT case 'T': //LONG FREE TEXT //LONG FREE TEXT case 'U': //HUGE FREE TEXT //HUGE FREE TEXT case 'M': //Multiple choice checkbox //Multiple choice checkbox case 'P': //Multiple choice with comments checkbox + text //Multiple choice with comments checkbox + text case 'D': //DATE //DATE case '*': //Equation //Equation case 'I': //Language Question //Language Question case '|': //File Upload //File Upload case 'X': //BOILERPLATE QUESTION $ansArray = NULL; break; case 'G': //GENDER drop-down list //GENDER drop-down list case 'Y': //YES/NO radio-buttons //YES/NO radio-buttons case 'C': //ARRAY (YES/UNCERTAIN/NO) radio-buttons //ARRAY (YES/UNCERTAIN/NO) radio-buttons case 'E': //ARRAY (Increase/Same/Decrease) radio-buttons $ansArray = $presets[$type]; break; } // set $subqtext text - for display of primary sub-question $subqtext = ''; switch ($type) { default: $subqtext = isset($fielddata['subquestion']) ? $fielddata['subquestion'] : ''; break; case ':': //ARRAY (Multi Flexi) 1 to 10 //ARRAY (Multi Flexi) 1 to 10 case ';': //ARRAY (Multi Flexi) Text $subqtext = isset($fielddata['subquestion1']) ? $fielddata['subquestion1'] : ''; $ansList = array(); if (isset($fielddata['answerList'])) { foreach ($fielddata['answerList'] as $ans) { $ansList['1~' . $ans['code']] = $ans['code'] . '|' . $ans['answer']; } $this->multiflexiAnswers[$questionNum] = $ansList; } break; } // Set $varName (question code / questions.title), $rowdivid, $csuffix, $sqsuffix, and $question $rowdivid = NULL; // so that blank for types not needing it. $sqsuffix = ''; switch ($type) { case '!': //List - dropdown //List - dropdown case '5': //5 POINT CHOICE radio-buttons //5 POINT CHOICE radio-buttons case 'D': //DATE //DATE case 'G': //GENDER drop-down list //GENDER drop-down list case 'I': //Language Question //Language Question case 'L': //LIST drop-down/radio-button list //LIST drop-down/radio-button list case 'N': //NUMERICAL QUESTION TYPE //NUMERICAL QUESTION TYPE case 'O': //LIST WITH COMMENT drop-down/radio-button list + textarea //LIST WITH COMMENT drop-down/radio-button list + textarea case 'S': //SHORT FREE TEXT //SHORT FREE TEXT case 'T': //LONG FREE TEXT //LONG FREE TEXT case 'U': //HUGE FREE TEXT //HUGE FREE TEXT case 'X': //BOILERPLATE QUESTION //BOILERPLATE QUESTION case 'Y': //YES/NO radio-buttons //YES/NO radio-buttons case '|': //File Upload //File Upload case '*': //Equation $csuffix = ''; $sqsuffix = ''; $varName = $fielddata['title']; if ($fielddata['aid'] != '') { $varName .= '_' . $fielddata['aid']; } $question = $fielddata['question']; break; case '1': //Array (Flexible Labels) dual scale $csuffix = $fielddata['aid'] . '#' . $fielddata['scale_id']; $sqsuffix = '_' . $fielddata['aid']; $varName = $fielddata['title'] . '_' . $fielddata['aid'] . '_' . $fielddata['scale_id']; $question = $fielddata['subquestion'] . '[' . $fielddata['scale'] . ']'; // $question = $fielddata['question'] . ': ' . $fielddata['subquestion'] . '[' . $fielddata['scale'] . ']'; $rowdivid = substr($sgqa, 0, -2); break; case 'A': //ARRAY (5 POINT CHOICE) radio-buttons //ARRAY (5 POINT CHOICE) radio-buttons case 'B': //ARRAY (10 POINT CHOICE) radio-buttons //ARRAY (10 POINT CHOICE) radio-buttons case 'C': //ARRAY (YES/UNCERTAIN/NO) radio-buttons //ARRAY (YES/UNCERTAIN/NO) radio-buttons case 'E': //ARRAY (Increase/Same/Decrease) radio-buttons //ARRAY (Increase/Same/Decrease) radio-buttons case 'F': //ARRAY (Flexible) - Row Format //ARRAY (Flexible) - Row Format case 'H': //ARRAY (Flexible) - Column Format // note does not have javatbd equivalent - so array filters don't work on it //ARRAY (Flexible) - Column Format // note does not have javatbd equivalent - so array filters don't work on it case 'K': //MULTIPLE NUMERICAL QUESTION // note does not have javatbd equivalent - so array filters don't work on it, but need rowdivid to process validations //MULTIPLE NUMERICAL QUESTION // note does not have javatbd equivalent - so array filters don't work on it, but need rowdivid to process validations case 'M': //Multiple choice checkbox //Multiple choice checkbox case 'P': //Multiple choice with comments checkbox + text //Multiple choice with comments checkbox + text case 'Q': //MULTIPLE SHORT TEXT // note does not have javatbd equivalent - so array filters don't work on it //MULTIPLE SHORT TEXT // note does not have javatbd equivalent - so array filters don't work on it case 'R': //RANKING STYLE // note does not have javatbd equivalent - so array filters don't work on it $csuffix = $fielddata['aid']; $varName = $fielddata['title'] . '_' . $fielddata['aid']; $question = $fielddata['subquestion']; // $question = $fielddata['question'] . ': ' . $fielddata['subquestion']; if ($type != 'H') { if ($type == 'P' && preg_match("/comment\$/", $sgqa)) { // $rowdivid = substr($sgqa,0,-7); } else { $sqsuffix = '_' . $fielddata['aid']; $rowdivid = $sgqa; } } break; case ':': //ARRAY (Multi Flexi) 1 to 10 //ARRAY (Multi Flexi) 1 to 10 case ';': //ARRAY (Multi Flexi) Text $csuffix = $fielddata['aid']; $sqsuffix = '_' . substr($fielddata['aid'], 0, strpos($fielddata['aid'], '_')); $varName = $fielddata['title'] . '_' . $fielddata['aid']; $question = $fielddata['subquestion1'] . '[' . $fielddata['subquestion2'] . ']'; // $question = $fielddata['question'] . ': ' . $fielddata['subquestion1'] . '[' . $fielddata['subquestion2'] . ']'; $rowdivid = substr($sgqa, 0, strpos($sgqa, '_')); break; } // $onlynum $onlynum = false; // the default switch ($type) { case 'K': //MULTIPLE NUMERICAL QUESTION //MULTIPLE NUMERICAL QUESTION case 'N': //NUMERICAL QUESTION TYPE //NUMERICAL QUESTION TYPE case ':': //ARRAY (Multi Flexi) 1 to 10 $onlynum = true; break; case '*': // Equation // Equation case ';': //ARRAY (Multi Flexi) Text //ARRAY (Multi Flexi) Text case 'Q': //MULTIPLE SHORT TEXT //MULTIPLE SHORT TEXT case 'S': //SHORT FREE TEXT if (isset($qattr[$questionNum]['numbers_only']) && $qattr[$questionNum]['numbers_only'] == '1') { $onlynum = true; } break; case 'L': //LIST drop-down/radio-button list //LIST drop-down/radio-button list case 'M': //Multiple choice checkbox //Multiple choice checkbox case 'P': //Multiple choice with comments checkbox + text if (isset($qattr[$questionNum]['other_numbers_only']) && $qattr[$questionNum]['other_numbers_only'] == '1' && preg_match('/other$/', $sgqa)) { $onlynum = true; } break; default: break; } // Set $jsVarName_on (for on-page variables - e.g. answerSGQA) and $jsVarName (for off-page variables; the primary name - e.g. javaSGQA) switch ($type) { case 'R': //RANKING STYLE $jsVarName_on = 'answer' . $sgqa; $jsVarName = 'java' . $sgqa; break; case 'D': //DATE //DATE case 'N': //NUMERICAL QUESTION TYPE //NUMERICAL QUESTION TYPE case 'S': //SHORT FREE TEXT //SHORT FREE TEXT case 'T': //LONG FREE TEXT //LONG FREE TEXT case 'U': //HUGE FREE TEXT //HUGE FREE TEXT case 'Q': //MULTIPLE SHORT TEXT //MULTIPLE SHORT TEXT case 'K': //MULTIPLE NUMERICAL QUESTION //MULTIPLE NUMERICAL QUESTION case 'X': //BOILERPLATE QUESTION $jsVarName_on = 'answer' . $sgqa; $jsVarName = 'java' . $sgqa; break; case '!': //List - dropdown if (preg_match("/other\$/", $sgqa)) { $jsVarName = 'java' . $sgqa; $jsVarName_on = 'othertext' . substr($sgqa, 0, -5); } else { $jsVarName = 'java' . $sgqa; $jsVarName_on = $jsVarName; } break; case 'L': //LIST drop-down/radio-button list if (preg_match("/other\$/", $sgqa)) { $jsVarName = 'java' . $sgqa; $jsVarName_on = 'answer' . $sgqa . "text"; } else { $jsVarName = 'java' . $sgqa; $jsVarName_on = $jsVarName; } break; case '5': //5 POINT CHOICE radio-buttons //5 POINT CHOICE radio-buttons case 'G': //GENDER drop-down list //GENDER drop-down list case 'I': //Language Question //Language Question case 'Y': //YES/NO radio-buttons //YES/NO radio-buttons case '*': //Equation //Equation case 'A': //ARRAY (5 POINT CHOICE) radio-buttons //ARRAY (5 POINT CHOICE) radio-buttons case 'B': //ARRAY (10 POINT CHOICE) radio-buttons //ARRAY (10 POINT CHOICE) radio-buttons case 'C': //ARRAY (YES/UNCERTAIN/NO) radio-buttons //ARRAY (YES/UNCERTAIN/NO) radio-buttons case 'E': //ARRAY (Increase/Same/Decrease) radio-buttons //ARRAY (Increase/Same/Decrease) radio-buttons case 'F': //ARRAY (Flexible) - Row Format //ARRAY (Flexible) - Row Format case 'H': //ARRAY (Flexible) - Column Format //ARRAY (Flexible) - Column Format case 'M': //Multiple choice checkbox //Multiple choice checkbox case 'O': //LIST WITH COMMENT drop-down/radio-button list + textarea if ($type == 'O' && preg_match('/_comment$/', $varName)) { $jsVarName_on = 'answer' . $sgqa; } else { $jsVarName_on = 'java' . $sgqa; } $jsVarName = 'java' . $sgqa; break; case '1': //Array (Flexible Labels) dual scale $jsVarName = 'java' . str_replace('#', '_', $sgqa); $jsVarName_on = $jsVarName; break; case ':': //ARRAY (Multi Flexi) 1 to 10 //ARRAY (Multi Flexi) 1 to 10 case ';': //ARRAY (Multi Flexi) Text $jsVarName = 'java' . $sgqa; $jsVarName_on = 'answer' . $sgqa; break; case '|': //File Upload $jsVarName = $sgqa; $jsVarName_on = $jsVarName; break; case 'P': //Multiple choice with comments checkbox + text if (preg_match("/(other|comment)\$/", $sgqa)) { $jsVarName_on = 'answer' . $sgqa; // is this true for survey.php and not for group.php? $jsVarName = 'java' . $sgqa; } else { $jsVarName = 'java' . $sgqa; $jsVarName_on = $jsVarName; } break; } if (!is_null($rowdivid) || $type == 'L' || $type == 'N' || $type == '!' || !is_null($preg) || $type == 'S' || $type == 'T' || $type == 'U' || $type == '|') { if (!isset($q2subqInfo[$questionNum])) { $q2subqInfo[$questionNum] = array('qid' => $questionNum, 'qseq' => $questionSeq, 'gseq' => $groupSeq, 'sgqa' => $surveyid . 'X' . $groupNum . 'X' . $questionNum, 'mandatory' => $mandatory, 'varName' => $varName, 'type' => $type, 'fieldname' => $sgqa, 'preg' => $preg, 'rootVarName' => $fielddata['title']); } if (!isset($q2subqInfo[$questionNum]['subqs'])) { $q2subqInfo[$questionNum]['subqs'] = array(); } if ($type == 'L' || $type == '!') { if (!is_null($ansArray)) { foreach (array_keys($ansArray) as $key) { $parts = explode('~', $key); if ($parts[1] == '-oth-') { $parts[1] = 'other'; } $q2subqInfo[$questionNum]['subqs'][] = array('rowdivid' => $surveyid . 'X' . $groupNum . 'X' . $questionNum . $parts[1], 'varName' => $varName, 'sqsuffix' => '_' . $parts[1]); } } } else { if ($type == 'N' || $type == 'S' || $type == 'T' || $type == 'U') { $q2subqInfo[$questionNum]['subqs'][] = array('varName' => $varName, 'rowdivid' => $surveyid . 'X' . $groupNum . 'X' . $questionNum, 'jsVarName' => 'java' . $surveyid . 'X' . $groupNum . 'X' . $questionNum, 'jsVarName_on' => $jsVarName_on); } else { $q2subqInfo[$questionNum]['subqs'][] = array('rowdivid' => $rowdivid, 'varName' => $varName, 'jsVarName_on' => $jsVarName_on, 'jsVarName' => $jsVarName, 'csuffix' => $csuffix, 'sqsuffix' => $sqsuffix); } } } $ansList = ''; if (isset($ansArray) && !is_null($ansArray)) { $answers = array(); foreach ($ansArray as $key => $value) { $answers[] = "'" . $key . "':'" . htmlspecialchars(preg_replace('/[[:space:]]/', ' ', $value), ENT_QUOTES) . "'"; } $ansList = ",'answers':{ " . implode(",", $answers) . "}"; } // Set mappings of variable names to needed attributes $varInfo_Code = array('jsName_on' => $jsVarName_on, 'jsName' => $jsVarName, 'readWrite' => $readWrite, 'hidden' => $hidden, 'question' => $question, 'qid' => $questionNum, 'gid' => $groupNum, 'grelevance' => $grelevance, 'relevance' => $relevance, 'qcode' => $varName, 'qseq' => $questionSeq, 'gseq' => $groupSeq, 'type' => $type, 'sgqa' => $sgqa, 'ansList' => $ansList, 'ansArray' => $ansArray, 'scale_id' => $scale_id, 'default' => $defaultValue, 'rootVarName' => $fielddata['title'], 'subqtext' => $subqtext, 'rowdivid' => is_null($rowdivid) ? '' : $rowdivid, 'onlynum' => $onlynum); $this->questionSeq2relevance[$questionSeq] = array('relevance' => $relevance, 'grelevance' => $grelevance, 'qid' => $questionNum, 'qseq' => $questionSeq, 'gseq' => $groupSeq, 'jsResultVar_on' => $jsVarName_on, 'jsResultVar' => $jsVarName, 'type' => $type, 'hidden' => $hidden, 'gid' => $groupNum, 'mandatory' => $mandatory, 'eqn' => $type == '*' ? $question : '', 'help' => $help, 'qtext' => $fielddata['question'], 'code' => $varName, 'other' => $other, 'default' => $defaultValue, 'rootVarName' => $fielddata['title'], 'rowdivid' => is_null($rowdivid) ? '' : $rowdivid, 'aid' => $aid, 'sqid' => $sqid); $this->knownVars[$sgqa] = $varInfo_Code; $this->qcode2sgqa[$varName] = $sgqa; $this->jsVar2qid[$jsVarName] = $questionNum; $this->qcode2sgq[$fielddata['title']] = $surveyid . 'X' . $groupNum . 'X' . $questionNum; // Create JavaScript arrays $this->alias2varName[$varName] = array('jsName' => $jsVarName, 'jsPart' => "'" . $varName . "':'" . $jsVarName . "'"); $this->alias2varName[$sgqa] = array('jsName' => $jsVarName, 'jsPart' => "'" . $sgqa . "':'" . $jsVarName . "'"); $this->varNameAttr[$jsVarName] = "'" . $jsVarName . "':{ " . "'jsName':'" . $jsVarName . "','jsName_on':'" . $jsVarName_on . "','sgqa':'" . $sgqa . "','qid':" . $questionNum . ",'gid':" . $groupNum . ",'type':'" . $type . "','default':'" . (is_null($defaultValue) ? '' : $defaultValue) . "','rowdivid':'" . (is_null($rowdivid) ? '' : $rowdivid) . "','onlynum':'" . ($onlynum ? '1' : '') . "','gseq':" . $groupSeq . $ansList; if ($type == 'M' || $type == 'P') { $this->varNameAttr[$jsVarName] .= ",'question':'" . htmlspecialchars(preg_replace('/[[:space:]]/', ' ', $question), ENT_QUOTES) . "'"; } $this->varNameAttr[$jsVarName] .= "}"; } $this->q2subqInfo = $q2subqInfo; // Now set tokens if (isset($_SESSION[$this->sessid]['token']) && $_SESSION[$this->sessid]['token'] != '') { //Gather survey data for tokenised surveys, for use in presenting questions $_SESSION[$this->sessid]['thistoken'] = getTokenData($surveyid, $_SESSION[$this->sessid]['token']); $this->knownVars['TOKEN:TOKEN'] = array('code' => $_SESSION[$this->sessid]['token'], 'jsName_on' => '', 'jsName' => '', 'readWrite' => 'N'); } if (isset($_SESSION[$this->sessid]['thistoken'])) { foreach (array_keys($_SESSION[$this->sessid]['thistoken']) as $tokenkey) { if ($anonymized) { $val = ""; } else { $val = $_SESSION[$this->sessid]['thistoken'][$tokenkey]; } $key = "TOKEN:" . strtoupper($tokenkey); $this->knownVars[$key] = array('code' => $val, 'jsName_on' => '', 'jsName' => '', 'readWrite' => 'N'); } } else { // Read list of available tokens from the tokens table so that preview and error checking works correctly $attrs = array_keys(getTokenFieldsAndNames($surveyid)); $blankVal = array('code' => '', 'type' => '', 'jsName_on' => '', 'jsName' => '', 'readWrite' => 'N'); foreach ($attrs as $key) { if (preg_match('/^(firstname|lastname|email|usesleft|token|attribute_\\d+)$/', $key)) { $this->knownVars['TOKEN:' . strtoupper($key)] = $blankVal; } } } // set default value for reserved 'this' variable $this->knownVars['this'] = array('jsName_on' => '', 'jsName' => '', 'readWrite' => '', 'hidden' => '', 'question' => 'this', 'qid' => '', 'gid' => '', 'grelevance' => '', 'relevance' => '', 'qcode' => 'this', 'qseq' => '', 'gseq' => '', 'type' => '', 'sgqa' => '', 'rowdivid' => '', 'ansList' => '', 'ansArray' => array(), 'scale_id' => '', 'default' => '', 'rootVarName' => 'this', 'subqtext' => '', 'rowdivid' => ''); $this->runtimeTimings[] = array(__METHOD__ . ' - process fieldMap', microtime(true) - $now); usort($this->questionSeq2relevance, 'cmpQuestionSeq'); $this->numQuestions = count($this->questionSeq2relevance); $this->numGroups = count($this->groupSeqInfo); return true; }
/** * This function builds all the required session variables when a survey is first started and * it loads any answer defaults from command line or from the table defaultvalues * It is called from the related format script (group.php, question.php, survey.php) * if the survey has just started. * * @returns $totalquestions Total number of questions in the survey * */ function buildsurveysession() { global $thissurvey, $secerror, $clienttoken; global $tokensexist, $thistpl; global $surveyid, $dbprefix, $connect; global $register_errormsg, $clang; global $totalBoilerplatequestions; global $templang, $move, $rooturl, $publicurl; if (!isset($templang) || $templang == '') { $templang = $thissurvey['language']; } $totalBoilerplatequestions = 0; // NO TOKEN REQUIRED BUT CAPTCHA ENABLED FOR SURVEY ACCESS if ($tokensexist == 0 && captcha_enabled('surveyaccessscreen', $thissurvey['usecaptcha'])) { // IF CAPTCHA ANSWER IS NOT CORRECT OR NOT SET if (!isset($_GET['loadsecurity']) || !isset($_SESSION['secanswer']) || $_GET['loadsecurity'] != $_SESSION['secanswer']) { sendcacheheaders(); doHeader(); // No or bad answer to required security question echo templatereplace(file_get_contents("{$thistpl}/startpage.pstpl")); //echo makedropdownlist(); echo templatereplace(file_get_contents("{$thistpl}/survey.pstpl")); if (isset($_GET['loadsecurity'])) { // was a bad answer echo "<font color='#FF0000'>" . $clang->gT("The answer to the security question is incorrect.") . "</font><br />"; } echo "<p class='captcha'>" . $clang->gT("Please confirm access to survey by answering the security question below and click continue.") . "</p>\n\t\t\t <form class='captcha' method='get' action='{$publicurl}/index.php'>\n\t\t\t <table align='center'>\n\t\t\t\t <tr>\n\t\t\t\t\t <td align='right' valign='middle'>\n\t\t\t\t\t <input type='hidden' name='sid' value='" . $surveyid . "' id='sid' />\n\t\t\t\t\t <input type='hidden' name='lang' value='" . $templang . "' id='lang' />"; // In case we this is a direct Reload previous answers URL, then add hidden fields if (isset($_GET['loadall']) && isset($_GET['scid']) && isset($_GET['loadname']) && isset($_GET['loadpass'])) { echo "\n\t\t\t\t\t\t<input type='hidden' name='loadall' value='" . htmlspecialchars($_GET['loadall']) . "' id='loadall' />\n\t\t\t\t\t\t<input type='hidden' name='scid' value='" . returnglobal('scid') . "' id='scid' />\n\t\t\t\t\t\t<input type='hidden' name='loadname' value='" . htmlspecialchars($_GET['loadname']) . "' id='loadname' />\n\t\t\t\t\t\t<input type='hidden' name='loadpass' value='" . htmlspecialchars($_GET['loadpass']) . "' id='loadpass' />"; } echo "\n\t\t\t\t </td>\n\t\t\t </tr>"; if (function_exists("ImageCreate") && captcha_enabled('surveyaccessscreen', $thissurvey['usecaptcha'])) { echo "<tr>\n\t\t\t\t <td align='center' valign='middle'><label for='captcha'>" . $clang->gT("Security question:") . "</label></td><td align='left' valign='middle'><table><tr><td valign='middle'><img src='{$rooturl}/verification.php?sid={$surveyid}' alt='captcha' /></td>\n <td valign='middle'><input id='captcha' type='text' size='5' maxlength='3' name='loadsecurity' value='' /></td></tr></table>\n\t\t\t\t </td>\n\t\t\t </tr>"; } echo "<tr><td colspan='2' align='center'><input class='submit' type='submit' value='" . $clang->gT("Continue") . "' /></td></tr>\n\t\t </table>\n\t\t </form>"; echo templatereplace(file_get_contents("{$thistpl}/endpage.pstpl")); doFooter(); exit; } } //BEFORE BUILDING A NEW SESSION FOR THIS SURVEY, LET'S CHECK TO MAKE SURE THE SURVEY SHOULD PROCEED! // TOKEN REQUIRED BUT NO TOKEN PROVIDED if ($tokensexist == 1 && !returnglobal('token')) { // DISPLAY REGISTER-PAGE if needed // DISPLAY CAPTCHA if needed sendcacheheaders(); doHeader(); echo templatereplace(file_get_contents("{$thistpl}/startpage.pstpl")); //echo makedropdownlist(); echo templatereplace(file_get_contents("{$thistpl}/survey.pstpl")); if (isset($thissurvey) && $thissurvey['allowregister'] == "Y") { echo templatereplace(file_get_contents("{$thistpl}/register.pstpl")); } else { if (isset($secerror)) { echo "<span class='error'>" . $secerror . "</span><br />"; } echo '<div id="wrapper"><p id="tokenmessage">' . $clang->gT("This is a controlled survey. You need a valid token to participate.") . "<br />"; echo $clang->gT("If you have been issued a token, please enter it in the box below and click continue.") . "</p>\n <script type='text/javascript'>var focus_element='#token';</script>\n\t <form id='tokenform' method='get' action='{$publicurl}/index.php'>\n\n <ul>\n <li>\n <label for='token'>" . $clang->gT("Token") . "</label><input class='text' id='token' type='text' name='token' />\n <input type='hidden' name='sid' value='" . $surveyid . "' id='sid' />\n\t\t\t\t<input type='hidden' name='lang' value='" . $templang . "' id='lang' />"; if (isset($_GET['newtest']) && ($_GET['newtest'] = "Y")) { echo " <input type='hidden' name='newtest' value='Y' id='newtest' />"; } // If this is a direct Reload previous answers URL, then add hidden fields if (isset($_GET['loadall']) && isset($_GET['scid']) && isset($_GET['loadname']) && isset($_GET['loadpass'])) { echo "\n\t\t\t\t\t<input type='hidden' name='loadall' value='" . htmlspecialchars($_GET['loadall']) . "' id='loadall' />\n\t\t\t\t\t<input type='hidden' name='scid' value='" . returnglobal('scid') . "' id='scid' />\n\t\t\t\t\t<input type='hidden' name='loadname' value='" . htmlspecialchars($_GET['loadname']) . "' id='loadname' />\n\t\t\t\t\t<input type='hidden' name='loadpass' value='" . htmlspecialchars($_GET['loadpass']) . "' id='loadpass' />"; } echo "</li>"; if (function_exists("ImageCreate") && captcha_enabled('surveyaccessscreen', $thissurvey['usecaptcha'])) { echo "<li>\n\t\t\t <label for='captchaimage'>" . $clang->gT("Security Question") . "</label><img id='captchaimage' src='{$rooturl}/verification.php?sid={$surveyid}' alt='captcha' /><input type='text' size='5' maxlength='3' name='loadsecurity' value='' />\n\t\t </li>"; } echo "<li>\n <input class='submit' type='submit' value='" . $clang->gT("Continue") . "' />\n </li>\n </ul>\n\t </form></div>"; } echo templatereplace(file_get_contents("{$thistpl}/endpage.pstpl")); doFooter(); exit; } elseif ($tokensexist == 1 && returnglobal('token') && !captcha_enabled('surveyaccessscreen', $thissurvey['usecaptcha'])) { //check if token actually does exist $tkquery = "SELECT COUNT(*) FROM " . db_table_name('tokens_' . $surveyid) . " WHERE token='" . db_quote(trim(strip_tags(returnglobal('token')))) . "' AND (completed = 'N' or completed='')"; $tkresult = db_execute_num($tkquery); //Checked list($tkexist) = $tkresult->FetchRow(); if (!$tkexist) { //TOKEN DOESN'T EXIST OR HAS ALREADY BEEN USED. EXPLAIN PROBLEM AND EXIT killSession(); sendcacheheaders(); doHeader(); echo templatereplace(file_get_contents("{$thistpl}/startpage.pstpl")); echo templatereplace(file_get_contents("{$thistpl}/survey.pstpl")); echo '<div id="wrapper"><p id="tokenmessage">' . $clang->gT("This is a controlled survey. You need a valid token to participate.") . "<br /><br />\n" . "\t" . $clang->gT("The token you have provided is either not valid, or has already been used.") . "<br />\n" . "\t" . sprintf($clang->gT("For further information contact %s"), $thissurvey['adminname']) . " (<a href='mailto:{$thissurvey['adminemail']}'>" . "{$thissurvey['adminemail']}</a>)</p></div>\n"; echo templatereplace(file_get_contents("{$thistpl}/endpage.pstpl")); doFooter(); exit; } } elseif ($tokensexist == 1 && returnglobal('token') && captcha_enabled('surveyaccessscreen', $thissurvey['usecaptcha'])) { // IF CAPTCHA ANSWER IS CORRECT if (isset($_GET['loadsecurity']) && isset($_SESSION['secanswer']) && $_GET['loadsecurity'] == $_SESSION['secanswer']) { //check if token actually does exist $tkquery = "SELECT COUNT(*) FROM " . db_table_name('tokens_' . $surveyid) . " WHERE token='" . db_quote(trim(sanitize_xss_string(strip_tags(returnglobal('token'))))) . "' AND (completed = 'N' or completed='')"; $tkresult = db_execute_num($tkquery); //Checked list($tkexist) = $tkresult->FetchRow(); if (!$tkexist) { sendcacheheaders(); doHeader(); //TOKEN DOESN'T EXIST OR HAS ALREADY BEEN USED. EXPLAIN PROBLEM AND EXIT echo templatereplace(file_get_contents("{$thistpl}/startpage.pstpl")); echo templatereplace(file_get_contents("{$thistpl}/survey.pstpl")); echo "\t<center><br />\n" . "\t" . $clang->gT("This is a controlled survey. You need a valid token to participate.") . "<br /><br />\n" . "\t" . $clang->gT("The token you have provided is either not valid, or has already been used.") . "<br/>\n" . "\t" . sprintf($clang->gT("For further information contact %s"), $thissurvey['adminname']) . " (<a href='mailto:{$thissurvey['adminemail']}'>" . "{$thissurvey['adminemail']}</a>)<br /><br />\n"; echo templatereplace(file_get_contents("{$thistpl}/endpage.pstpl")); doFooter(); exit; } } else { if (!isset($move) || is_null($move)) { $gettoken = $clienttoken; sendcacheheaders(); doHeader(); // No or bad answer to required security question echo templatereplace(file_get_contents("{$thistpl}/startpage.pstpl")); echo templatereplace(file_get_contents("{$thistpl}/survey.pstpl")); // If token wasn't provided and public registration // is enabled then show registration form if (!isset($gettoken) && isset($thissurvey) && $thissurvey['allowregister'] == "Y") { echo templatereplace(file_get_contents("{$thistpl}/register.pstpl")); } else { // only show CAPTCHA echo '<div id="wrapper"><p id="tokenmessage">'; if (isset($_GET['loadsecurity'])) { // was a bad answer echo "<span class='error'>" . $clang->gT("The answer to the security question is incorrect.") . "</span><br />"; } echo $clang->gT("This is a controlled survey. You need a valid token to participate.") . "<br /><br />"; // IF TOKEN HAS BEEN GIVEN THEN AUTOFILL IT // AND HIDE ENTRY FIELD if (!isset($gettoken)) { echo $clang->gT("If you have been issued with a token, please enter it in the box below and click continue.") . "</p>\n\t\t\t <form id='tokenform' method='get' action='{$publicurl}/index.php'>\n <ul>\n <li>\n\t\t\t\t\t <input type='hidden' name='sid' value='" . $surveyid . "' id='sid' />\n\t\t\t\t\t\t <input type='hidden' name='lang' value='" . $templang . "' id='lang' />"; if (isset($_GET['loadall']) && isset($_GET['scid']) && isset($_GET['loadname']) && isset($_GET['loadpass'])) { echo "<input type='hidden' name='loadall' value='" . htmlspecialchars($_GET['loadall']) . "' id='loadall' />\n\t\t\t\t\t\t <input type='hidden' name='scid' value='" . returnglobal('scid') . "' id='scid' />\n\t\t\t\t\t\t <input type='hidden' name='loadname' value='" . htmlspecialchars($_GET['loadname']) . "' id='loadname' />\n\t\t\t\t\t\t <input type='hidden' name='loadpass' value='" . htmlspecialchars($_GET['loadpass']) . "' id='loadpass' />"; } echo '<label for="token">' . $clang->gT("Token") . "</label><input class='text' type='text' id=token name='token'></li>"; } else { echo $clang->gT("Please confirm the token by answering the security question below and click continue.") . "</p>\n\t\t\t <form id='tokenform' method='get' action='{$publicurl}/index.php'>\n <ul>\n\t\t\t <li>\n\t\t\t\t\t <input type='hidden' name='sid' value='" . $surveyid . "' id='sid' />\n\t\t\t\t\t\t <input type='hidden' name='lang' value='" . $templang . "' id='lang' />"; if (isset($_GET['loadall']) && isset($_GET['scid']) && isset($_GET['loadname']) && isset($_GET['loadpass'])) { echo "<input type='hidden' name='loadall' value='" . htmlspecialchars($_GET['loadall']) . "' id='loadall' />\n <input type='hidden' name='scid' value='" . returnglobal('scid') . "' id='scid' />\n <input type='hidden' name='loadname' value='" . htmlspecialchars($_GET['loadname']) . "' id='loadname' />\n <input type='hidden' name='loadpass' value='" . htmlspecialchars($_GET['loadpass']) . "' id='loadpass' />"; } echo '<label for="token">' . $clang->gT("Token:") . "</label><span id=token>{$gettoken}</span>" . "<input type='hidden' name='token' value='{$gettoken}'></li>"; } if (function_exists("ImageCreate") && captcha_enabled('surveyaccessscreen', $thissurvey['usecaptcha'])) { echo "<li>\n <label for='captchaimage'>" . $clang->gT("Security Question") . "</label><img id='captchaimage' src='{$rooturl}/verification.php?sid={$surveyid}' alt='captcha' /><input type='text' size='5' maxlength='3' name='loadsecurity' value='' />\n </li>"; } echo "<li><input class='submit' type='submit' value='" . $clang->gT("Continue") . "' /></li>\n\t\t </ul>\n\t\t </form>\n\t\t </id>"; } echo '</div>' . templatereplace(file_get_contents("{$thistpl}/endpage.pstpl")); doFooter(); exit; } } } //RESET ALL THE SESSION VARIABLES AND START AGAIN unset($_SESSION['grouplist']); unset($_SESSION['fieldarray']); unset($_SESSION['insertarray']); unset($_SESSION['thistoken']); unset($_SESSION['fieldnamesInfo']); $_SESSION['fieldnamesInfo'] = array(); //RL: multilingual support if (isset($_GET['token']) && db_tables_exist($dbprefix . 'tokens_' . $surveyid)) { //get language from token (if one exists) $tkquery2 = "SELECT * FROM " . db_table_name('tokens_' . $surveyid) . " WHERE token='" . db_quote($clienttoken) . "' AND (completed = 'N' or completed='')"; //echo $tkquery2; $result = db_execute_assoc($tkquery2) or safe_die("Couldn't get tokens<br />{$tkquery}<br />" . $connect->ErrorMsg()); //Checked while ($rw = $result->FetchRow()) { $tklanguage = $rw['language']; } } if (returnglobal('lang')) { $language_to_set = returnglobal('lang'); } elseif (isset($tklanguage)) { $language_to_set = $tklanguage; } else { $language_to_set = $thissurvey['language']; } if (!isset($_SESSION['s_lang'])) { SetSurveyLanguage($surveyid, $language_to_set); } UpdateSessionGroupList($_SESSION['s_lang']); // Optimized Query // Change query to use sub-select to see if conditions exist. $query = "SELECT " . db_table_name('questions') . ".*, " . db_table_name('groups') . ".*,\n" . " (SELECT count(1) FROM " . db_table_name('conditions') . "\n" . " WHERE " . db_table_name('questions') . ".qid = " . db_table_name('conditions') . ".qid) AS hasconditions,\n" . " (SELECT count(1) FROM " . db_table_name('conditions') . "\n" . " WHERE " . db_table_name('questions') . ".qid = " . db_table_name('conditions') . ".cqid) AS usedinconditions\n" . " FROM " . db_table_name('groups') . " INNER JOIN " . db_table_name('questions') . " ON " . db_table_name('groups') . ".gid = " . db_table_name('questions') . ".gid\n" . " WHERE " . db_table_name('questions') . ".sid=" . $surveyid . "\n" . " AND " . db_table_name('groups') . ".language='" . $_SESSION['s_lang'] . "'\n" . " AND " . db_table_name('questions') . ".language='" . $_SESSION['s_lang'] . "'\n" . " AND " . db_table_name('questions') . ".parent_qid=0\n" . " ORDER BY " . db_table_name('groups') . ".group_order," . db_table_name('questions') . ".question_order"; //var_dump($_SESSION); $result = db_execute_assoc($query); //Checked $arows = $result->GetRows(); $totalquestions = $result->RecordCount(); //2. SESSION VARIABLE: totalsteps //The number of "pages" that will be presented in this survey //The number of pages to be presented will differ depending on the survey format switch ($thissurvey['format']) { case "A": $_SESSION['totalsteps'] = 1; break; case "G": if (isset($_SESSION['grouplist'])) { $_SESSION['totalsteps'] = count($_SESSION['grouplist']); } break; case "S": $_SESSION['totalsteps'] = $totalquestions; } if ($totalquestions == "0") { sendcacheheaders(); doHeader(); echo templatereplace(file_get_contents("{$thistpl}/startpage.pstpl")); echo templatereplace(file_get_contents("{$thistpl}/survey.pstpl")); echo "\t<center><br />\n" . "\t" . $clang->gT("This survey does not yet have any questions and cannot be tested or completed.") . "<br /><br />\n" . "\t" . sprintf($clang->gT("For further information contact %s"), $thissurvey['adminname']) . " (<a href='mailto:{$thissurvey['adminemail']}'>" . "{$thissurvey['adminemail']}</a>)<br /><br />\n"; echo templatereplace(file_get_contents("{$thistpl}/endpage.pstpl")); doFooter(); exit; } //Perform a case insensitive natural sort on group name then question title of a multidimensional array // usort($arows, 'GroupOrderThenQuestionOrder'); //3. SESSION VARIABLE - insertarray //An array containing information about used to insert the data into the db at the submit stage //4. SESSION VARIABLE - fieldarray //See rem at end.. $_SESSION['token'] = $clienttoken; if ($thissurvey['private'] == "N") { $_SESSION['insertarray'][] = "token"; } if ($tokensexist == 1 && $thissurvey['private'] == "N" && db_tables_exist($dbprefix . 'tokens_' . $surveyid)) { //Gather survey data for "non anonymous" surveys, for use in presenting questions $_SESSION['thistoken'] = getTokenData($surveyid, $clienttoken); } $qtypes = getqtypelist('', 'array'); $fieldmap = createFieldMap($surveyid, 'full', false, false, $_SESSION['s_lang']); $_SESSION['fieldmap'] = $fieldmap; foreach ($fieldmap as $field) { if ($field['qid'] != '') { $_SESSION['fieldnamesInfo'][$field['fieldname']] = $field['sid'] . 'X' . $field['gid'] . 'X' . $field['qid']; $_SESSION['insertarray'][] = $field['fieldname']; //fieldarray ARRAY CONTENTS - // [0]=questions.qid, // [1]=fieldname, // [2]=questions.title, // [3]=questions.question // [4]=questions.type, // [5]=questions.gid, // [6]=questions.mandatory, // [7]=conditionsexist, // [8]=usedinconditions if (!isset($_SESSION['fieldarray'][$field['sid'] . 'X' . $field['gid'] . 'X' . $field['qid']])) { $_SESSION['fieldarray'][$field['sid'] . 'X' . $field['gid'] . 'X' . $field['qid']] = array($field['qid'], $field['sid'] . 'X' . $field['gid'] . 'X' . $field['qid'], $field['title'], $field['question'], $field['type'], $field['gid'], $field['mandatory'], $field['hasconditions'], $field['usedinconditions']); } } } // Prefill question/answer from defaultvalues foreach ($fieldmap as $field) { if (isset($field['defaultvalue'])) { $_SESSION[$field['fieldname']] = $field['defaultvalue']; } } // Prefill questions/answers from command line params if (isset($_SESSION['insertarray'])) { foreach ($_SESSION['insertarray'] as $field) { if (isset($_GET[$field]) && $field != 'token') { $_SESSION[$field] = $_GET[$field]; } } } $_SESSION['fieldarray'] = array_values($_SESSION['fieldarray']); // Check if the current survey language is set - if not set it // this way it can be changed later (for example by a special question type) //Check if a passthru label and value have been included in the query url if (isset($_GET['passthru']) && $_GET['passthru'] != "") { if (isset($_GET[$_GET['passthru']]) && $_GET[$_GET['passthru']] != "") { $_SESSION['passthrulabel'] = $_GET['passthru']; $_SESSION['passthruvalue'] = $_GET[$_GET['passthru']]; } } return $totalquestions; }
/** * This function builds all the required session variables when a survey is first started and * it loads any answer defaults from command line or from the table defaultvalues * It is called from the related format script (group.php, question.php, survey.php) * if the survey has just started. * * @returns $totalquestions Total number of questions in the survey * */ function buildsurveysession() { global $thissurvey, $secerror, $clienttoken, $databasetype; global $tokensexist, $thistpl; global $surveyid, $dbprefix, $connect; global $register_errormsg, $clang; global $totalBoilerplatequestions; global $templang, $move, $rooturl, $publicurl; if (!isset($templang) || $templang == '') { $templang = $thissurvey['language']; } $totalBoilerplatequestions = 0; $loadsecurity = returnglobal('loadsecurity'); // NO TOKEN REQUIRED BUT CAPTCHA ENABLED FOR SURVEY ACCESS if ($tokensexist == 0 && captcha_enabled('surveyaccessscreen', $thissurvey['usecaptcha'])) { // IF CAPTCHA ANSWER IS NOT CORRECT OR NOT SET if (!isset($loadsecurity) || !isset($_SESSION['secanswer']) || $loadsecurity != $_SESSION['secanswer']) { sendcacheheaders(); doHeader(); // No or bad answer to required security question echo templatereplace(file_get_contents("{$thistpl}/startpage.pstpl")); //echo makedropdownlist(); echo templatereplace(file_get_contents("{$thistpl}/survey.pstpl")); if (isset($loadsecurity)) { // was a bad answer echo "<font color='#FF0000'>" . $clang->gT("The answer to the security question is incorrect.") . "</font><br />"; } echo "<p class='captcha'>" . $clang->gT("Please confirm access to survey by answering the security question below and click continue.") . "</p>\n\t\t\t <form class='captcha' method='get' action='{$publicurl}/index.php'>\n\t\t\t <table align='center'>\n\t\t\t\t <tr>\n\t\t\t\t\t <td align='right' valign='middle'>\n\t\t\t\t\t <input type='hidden' name='sid' value='" . $surveyid . "' id='sid' />\n\t\t\t\t\t <input type='hidden' name='lang' value='" . $templang . "' id='lang' />"; // In case we this is a direct Reload previous answers URL, then add hidden fields if (isset($_GET['loadall']) && isset($_GET['scid']) && isset($_GET['loadname']) && isset($_GET['loadpass'])) { echo "\n\t\t\t\t\t\t<input type='hidden' name='loadall' value='" . htmlspecialchars($_GET['loadall']) . "' id='loadall' />\n\t\t\t\t\t\t<input type='hidden' name='scid' value='" . returnglobal('scid') . "' id='scid' />\n\t\t\t\t\t\t<input type='hidden' name='loadname' value='" . htmlspecialchars($_GET['loadname']) . "' id='loadname' />\n\t\t\t\t\t\t<input type='hidden' name='loadpass' value='" . htmlspecialchars($_GET['loadpass']) . "' id='loadpass' />"; } echo "\n\t\t\t\t </td>\n\t\t\t </tr>"; if (function_exists("ImageCreate") && captcha_enabled('surveyaccessscreen', $thissurvey['usecaptcha'])) { echo "<tr>\n\t\t\t\t <td align='center' valign='middle'><label for='captcha'>" . $clang->gT("Security question:") . "</label></td><td align='left' valign='middle'><table><tr><td valign='middle'><img src='{$rooturl}/verification.php?sid={$surveyid}' alt='captcha' /></td>\n <td valign='middle'><input id='captcha' type='text' size='5' maxlength='3' name='loadsecurity' value='' /></td></tr></table>\n\t\t\t\t </td>\n\t\t\t </tr>"; } echo "<tr><td colspan='2' align='center'><input class='submit' type='submit' value='" . $clang->gT("Continue") . "' /></td></tr>\n\t\t </table>\n\t\t </form>"; echo templatereplace(file_get_contents("{$thistpl}/endpage.pstpl")); doFooter(); exit; } } //BEFORE BUILDING A NEW SESSION FOR THIS SURVEY, LET'S CHECK TO MAKE SURE THE SURVEY SHOULD PROCEED! // TOKEN REQUIRED BUT NO TOKEN PROVIDED if ($tokensexist == 1 && !returnglobal('token')) { if ($thissurvey['nokeyboard'] == 'Y') { vIncludeKeypad(); $kpclass = "text-keypad"; } else { $kpclass = ""; } // DISPLAY REGISTER-PAGE if needed // DISPLAY CAPTCHA if needed sendcacheheaders(); doHeader(); echo templatereplace(file_get_contents("{$thistpl}/startpage.pstpl")); //echo makedropdownlist(); echo templatereplace(file_get_contents("{$thistpl}/survey.pstpl")); if (isset($thissurvey) && $thissurvey['allowregister'] == "Y") { echo templatereplace(file_get_contents("{$thistpl}/register.pstpl")); } else { if (isset($secerror)) { echo "<span class='error'>" . $secerror . "</span><br />"; } echo '<div id="wrapper"><p id="tokenmessage">' . $clang->gT("This is a controlled survey. You need a valid token to participate.") . "<br />"; echo $clang->gT("If you have been issued a token, please enter it in the box below and click continue.") . "</p>\n <script type='text/javascript'>var focus_element='#token';</script>\n\t <form id='tokenform' method='get' action='{$publicurl}/index.php'>\n <ul>\n <li>\n <label for='token'>" . $clang->gT("Token") . "</label><input class='text {$kpclass}' id='token' type='text' name='token' />"; echo "<input type='hidden' name='sid' value='" . $surveyid . "' id='sid' />\n\t\t\t\t<input type='hidden' name='lang' value='" . $templang . "' id='lang' />"; if (isset($_GET['newtest']) && $_GET['newtest'] == "Y") { echo " <input type='hidden' name='newtest' value='Y' id='newtest' />"; } // If this is a direct Reload previous answers URL, then add hidden fields if (isset($_GET['loadall']) && isset($_GET['scid']) && isset($_GET['loadname']) && isset($_GET['loadpass'])) { echo "\n\t\t\t\t\t<input type='hidden' name='loadall' value='" . htmlspecialchars($_GET['loadall']) . "' id='loadall' />\n\t\t\t\t\t<input type='hidden' name='scid' value='" . returnglobal('scid') . "' id='scid' />\n\t\t\t\t\t<input type='hidden' name='loadname' value='" . htmlspecialchars($_GET['loadname']) . "' id='loadname' />\n\t\t\t\t\t<input type='hidden' name='loadpass' value='" . htmlspecialchars($_GET['loadpass']) . "' id='loadpass' />"; } echo "</li>"; if (function_exists("ImageCreate") && captcha_enabled('surveyaccessscreen', $thissurvey['usecaptcha'])) { echo "<li>\n\t\t\t <label for='captchaimage'>" . $clang->gT("Security Question") . "</label><img id='captchaimage' src='{$rooturl}/verification.php?sid={$surveyid}' alt='captcha' /><input type='text' size='5' maxlength='3' name='loadsecurity' value='' />\n\t\t </li>"; } echo "<li>\n <input class='submit' type='submit' value='" . $clang->gT("Continue") . "' />\n </li>\n </ul>\n\t </form></div>"; } echo templatereplace(file_get_contents("{$thistpl}/endpage.pstpl")); doFooter(); exit; } elseif ($tokensexist == 1 && returnglobal('token') && !captcha_enabled('surveyaccessscreen', $thissurvey['usecaptcha'])) { //check if tokens actually haven't been already used $areTokensUsed = usedTokens(db_quote(trim(strip_tags(returnglobal('token'))))); //check if token actually does exist // check also if it is allowed to change survey after completion if ($thissurvey['alloweditaftercompletion'] == 'Y') { $tkquery = "SELECT COUNT(*) FROM " . db_table_name('tokens_' . $surveyid) . " WHERE token='" . db_quote(trim(strip_tags(returnglobal('token')))) . "' "; } else { $tkquery = "SELECT COUNT(*) FROM " . db_table_name('tokens_' . $surveyid) . " WHERE token='" . db_quote(trim(strip_tags(returnglobal('token')))) . "' AND (completed = 'N' or completed='')"; } $tkresult = db_execute_num($tkquery); //Checked list($tkexist) = $tkresult->FetchRow(); if (!$tkexist || $areTokensUsed && $thissurvey['alloweditaftercompletion'] != 'Y') { //TOKEN DOESN'T EXIST OR HAS ALREADY BEEN USED. EXPLAIN PROBLEM AND EXIT killSession(); sendcacheheaders(); doHeader(); echo templatereplace(file_get_contents("{$thistpl}/startpage.pstpl")); echo templatereplace(file_get_contents("{$thistpl}/survey.pstpl")); echo '<div id="wrapper"><p id="tokenmessage">' . $clang->gT("This is a controlled survey. You need a valid token to participate.") . "<br /><br />\n" . "\t" . $clang->gT("The token you have provided is either not valid, or has already been used.") . "<br />\n" . "\t" . sprintf($clang->gT("For further information please contact %s"), $thissurvey['adminname']) . " (<a href='mailto:{$thissurvey['adminemail']}'>" . "{$thissurvey['adminemail']}</a>)</p></div>\n"; echo templatereplace(file_get_contents("{$thistpl}/endpage.pstpl")); doFooter(); exit; } } elseif ($tokensexist == 1 && returnglobal('token') && captcha_enabled('surveyaccessscreen', $thissurvey['usecaptcha'])) { // IF CAPTCHA ANSWER IS CORRECT if (isset($loadsecurity) && isset($_SESSION['secanswer']) && $loadsecurity == $_SESSION['secanswer']) { //check if tokens actually haven't been already used $areTokensUsed = usedTokens(db_quote(trim(strip_tags(returnglobal('token'))))); //check if token actually does exist if ($thissurvey['alloweditaftercompletion'] == 'Y') { $tkquery = "SELECT COUNT(*) FROM " . db_table_name('tokens_' . $surveyid) . " WHERE token='" . db_quote(trim(sanitize_xss_string(strip_tags(returnglobal('token'))))) . "'"; } else { $tkquery = "SELECT COUNT(*) FROM " . db_table_name('tokens_' . $surveyid) . " WHERE token='" . db_quote(trim(sanitize_xss_string(strip_tags(returnglobal('token'))))) . "' AND (completed = 'N' or completed='')"; } $tkresult = db_execute_num($tkquery); //Checked list($tkexist) = $tkresult->FetchRow(); if (!$tkexist || $areTokensUsed && $thissurvey['alloweditaftercompletion'] != 'Y') { sendcacheheaders(); doHeader(); //TOKEN DOESN'T EXIST OR HAS ALREADY BEEN USED. EXPLAIN PROBLEM AND EXIT echo templatereplace(file_get_contents("{$thistpl}/startpage.pstpl")); echo templatereplace(file_get_contents("{$thistpl}/survey.pstpl")); echo "\t<div id='wrapper'>\n" . "\t<p id='tokenmessage'>\n" . "\t" . $clang->gT("This is a controlled survey. You need a valid token to participate.") . "<br /><br />\n" . "\t" . $clang->gT("The token you have provided is either not valid, or has already been used.") . "<br/>\n" . "\t" . sprintf($clang->gT("For further information please contact %s"), $thissurvey['adminname']) . " (<a href='mailto:{$thissurvey['adminemail']}'>" . "{$thissurvey['adminemail']}</a>)\n" . "\t</p>\n" . "\t</div>\n"; echo templatereplace(file_get_contents("{$thistpl}/endpage.pstpl")); doFooter(); exit; } } else { if (!isset($move) || is_null($move)) { $gettoken = $clienttoken; sendcacheheaders(); doHeader(); // No or bad answer to required security question echo templatereplace(file_get_contents("{$thistpl}/startpage.pstpl")); echo templatereplace(file_get_contents("{$thistpl}/survey.pstpl")); // If token wasn't provided and public registration // is enabled then show registration form if (!isset($gettoken) && isset($thissurvey) && $thissurvey['allowregister'] == "Y") { echo templatereplace(file_get_contents("{$thistpl}/register.pstpl")); } else { // only show CAPTCHA echo '<div id="wrapper"><p id="tokenmessage">'; if (isset($loadsecurity)) { // was a bad answer echo "<span class='error'>" . $clang->gT("The answer to the security question is incorrect.") . "</span><br />"; } echo $clang->gT("This is a controlled survey. You need a valid token to participate.") . "<br /><br />"; // IF TOKEN HAS BEEN GIVEN THEN AUTOFILL IT // AND HIDE ENTRY FIELD if (!isset($gettoken)) { echo $clang->gT("If you have been issued a token, please enter it in the box below and click continue.") . "</p>\n\t\t\t <form id='tokenform' method='get' action='{$publicurl}/index.php'>\n <ul>\n <li>\n\t\t\t\t\t <input type='hidden' name='sid' value='" . $surveyid . "' id='sid' />\n\t\t\t\t\t\t <input type='hidden' name='lang' value='" . $templang . "' id='lang' />"; if (isset($_GET['loadall']) && isset($_GET['scid']) && isset($_GET['loadname']) && isset($_GET['loadpass'])) { echo "<input type='hidden' name='loadall' value='" . htmlspecialchars($_GET['loadall']) . "' id='loadall' />\n\t\t\t\t\t\t <input type='hidden' name='scid' value='" . returnglobal('scid') . "' id='scid' />\n\t\t\t\t\t\t <input type='hidden' name='loadname' value='" . htmlspecialchars($_GET['loadname']) . "' id='loadname' />\n\t\t\t\t\t\t <input type='hidden' name='loadpass' value='" . htmlspecialchars($_GET['loadpass']) . "' id='loadpass' />"; } echo '<label for="token">' . $clang->gT("Token") . "</label><input class='text' type='text' id='token' name='token'></li>"; } else { echo $clang->gT("Please confirm the token by answering the security question below and click continue.") . "</p>\n\t\t\t <form id='tokenform' method='get' action='{$publicurl}/index.php'>\n <ul>\n\t\t\t <li>\n\t\t\t\t\t <input type='hidden' name='sid' value='" . $surveyid . "' id='sid' />\n\t\t\t\t\t\t <input type='hidden' name='lang' value='" . $templang . "' id='lang' />"; if (isset($_GET['loadall']) && isset($_GET['scid']) && isset($_GET['loadname']) && isset($_GET['loadpass'])) { echo "<input type='hidden' name='loadall' value='" . htmlspecialchars($_GET['loadall']) . "' id='loadall' />\n <input type='hidden' name='scid' value='" . returnglobal('scid') . "' id='scid' />\n <input type='hidden' name='loadname' value='" . htmlspecialchars($_GET['loadname']) . "' id='loadname' />\n <input type='hidden' name='loadpass' value='" . htmlspecialchars($_GET['loadpass']) . "' id='loadpass' />"; } echo '<label for="token">' . $clang->gT("Token:") . "</label><span id='token'>{$gettoken}</span>" . "<input type='hidden' name='token' value='{$gettoken}'></li>"; } if (function_exists("ImageCreate") && captcha_enabled('surveyaccessscreen', $thissurvey['usecaptcha'])) { echo "<li>\n <label for='captchaimage'>" . $clang->gT("Security Question") . "</label><img id='captchaimage' src='{$rooturl}/verification.php?sid={$surveyid}' alt='captcha' /><input type='text' size='5' maxlength='3' name='loadsecurity' value='' />\n </li>"; } echo "<li><input class='submit' type='submit' value='" . $clang->gT("Continue") . "' /></li>\n\t\t </ul>\n\t\t </form>\n\t\t </id>"; } echo '</div>' . templatereplace(file_get_contents("{$thistpl}/endpage.pstpl")); doFooter(); unset($_SESSION['srid']); exit; } } } //RESET ALL THE SESSION VARIABLES AND START AGAIN unset($_SESSION['grouplist']); unset($_SESSION['fieldarray']); unset($_SESSION['insertarray']); unset($_SESSION['thistoken']); unset($_SESSION['fieldnamesInfo']); $_SESSION['fieldnamesInfo'] = array(); //RL: multilingual support if (isset($_GET['token']) && db_tables_exist($dbprefix . 'tokens_' . $surveyid)) { //get language from token (if one exists) $tkquery2 = "SELECT * FROM " . db_table_name('tokens_' . $surveyid) . " WHERE token='" . db_quote($clienttoken) . "' AND (completed = 'N' or completed='')"; //echo $tkquery2; $result = db_execute_assoc($tkquery2) or safe_die("Couldn't get tokens<br />{$tkquery}<br />" . $connect->ErrorMsg()); //Checked while ($rw = $result->FetchRow()) { $tklanguage = $rw['language']; } } if (returnglobal('lang')) { $language_to_set = returnglobal('lang'); } elseif (isset($tklanguage)) { $language_to_set = $tklanguage; } else { $language_to_set = $thissurvey['language']; } if (!isset($_SESSION['s_lang'])) { SetSurveyLanguage($surveyid, $language_to_set); } UpdateSessionGroupList($_SESSION['s_lang']); // Optimized Query // Change query to use sub-select to see if conditions exist. $query = "SELECT " . db_table_name('questions') . ".*, " . db_table_name('groups') . ".*,\n" . " (SELECT count(1) FROM " . db_table_name('conditions') . "\n" . " WHERE " . db_table_name('questions') . ".qid = " . db_table_name('conditions') . ".qid) AS hasconditions,\n" . " (SELECT count(1) FROM " . db_table_name('conditions') . "\n" . " WHERE " . db_table_name('questions') . ".qid = " . db_table_name('conditions') . ".cqid) AS usedinconditions\n" . " FROM " . db_table_name('groups') . " INNER JOIN " . db_table_name('questions') . " ON " . db_table_name('groups') . ".gid = " . db_table_name('questions') . ".gid\n" . " WHERE " . db_table_name('questions') . ".sid=" . $surveyid . "\n" . " AND " . db_table_name('groups') . ".language='" . $_SESSION['s_lang'] . "'\n" . " AND " . db_table_name('questions') . ".language='" . $_SESSION['s_lang'] . "'\n" . " AND " . db_table_name('questions') . ".parent_qid=0\n" . " ORDER BY " . db_table_name('groups') . ".group_order," . db_table_name('questions') . ".question_order"; //var_dump($_SESSION); $result = db_execute_assoc($query); //Checked $arows = $result->GetRows(); $totalquestions = $result->RecordCount(); //2. SESSION VARIABLE: totalsteps //The number of "pages" that will be presented in this survey //The number of pages to be presented will differ depending on the survey format switch ($thissurvey['format']) { case "A": $_SESSION['totalsteps'] = 1; break; case "G": if (isset($_SESSION['grouplist'])) { $_SESSION['totalsteps'] = count($_SESSION['grouplist']); } break; case "S": $_SESSION['totalsteps'] = $totalquestions; } if ($totalquestions == "0") { sendcacheheaders(); doHeader(); echo templatereplace(file_get_contents("{$thistpl}/startpage.pstpl")); echo templatereplace(file_get_contents("{$thistpl}/survey.pstpl")); echo "\t<div id='wrapper'>\n" . "\t<p id='tokenmessage'>\n" . "\t" . $clang->gT("This survey does not yet have any questions and cannot be tested or completed.") . "<br /><br />\n" . "\t" . sprintf($clang->gT("For further information please contact %s"), $thissurvey['adminname']) . " (<a href='mailto:{$thissurvey['adminemail']}'>" . "{$thissurvey['adminemail']}</a>)<br /><br />\n" . "\t</p>\n" . "\t</div>\n"; echo templatereplace(file_get_contents("{$thistpl}/endpage.pstpl")); doFooter(); exit; } //Perform a case insensitive natural sort on group name then question title of a multidimensional array // usort($arows, 'GroupOrderThenQuestionOrder'); //3. SESSION VARIABLE - insertarray //An array containing information about used to insert the data into the db at the submit stage //4. SESSION VARIABLE - fieldarray //See rem at end.. $_SESSION['token'] = $clienttoken; if ($thissurvey['anonymized'] == "N") { $_SESSION['insertarray'][] = "token"; } if ($tokensexist == 1 && $thissurvey['anonymized'] == "N" && db_tables_exist($dbprefix . 'tokens_' . $surveyid)) { //Gather survey data for "non anonymous" surveys, for use in presenting questions $_SESSION['thistoken'] = getTokenData($surveyid, $clienttoken); } $qtypes = getqtypelist('', 'array'); $fieldmap = createFieldMap($surveyid, 'full', false, false, $_SESSION['s_lang']); // Randomization Groups // Find all defined randomization groups through question attribute values $randomGroups = array(); if ($databasetype == 'odbc_mssql' || $databasetype == 'odbtp' || $databasetype == 'mssql_n' || $databasetype == 'mssqlnative') { $rgquery = "SELECT attr.qid, CAST(value as varchar(255)) FROM " . db_table_name('question_attributes') . " as attr right join " . db_table_name('questions') . " as quests on attr.qid=quests.qid WHERE attribute='random_group' and CAST(value as varchar(255)) <> '' and sid={$surveyid} GROUP BY attr.qid, CAST(value as varchar(255))"; } else { $rgquery = "SELECT attr.qid, value FROM " . db_table_name('question_attributes') . " as attr right join " . db_table_name('questions') . " as quests on attr.qid=quests.qid WHERE attribute='random_group' and value <> '' and sid={$surveyid} GROUP BY attr.qid, value"; } $rgresult = db_execute_assoc($rgquery); while ($rgrow = $rgresult->FetchRow()) { // Get the question IDs for each randomization group $randomGroups[$rgrow['value']][] = $rgrow['qid']; } // If we have randomization groups set, then lets cycle through each group and // replace questions in the group with a randomly chosen one from the same group if (count($randomGroups) > 0) { $copyFieldMap = array(); $oldQuestOrder = array(); $newQuestOrder = array(); $randGroupNames = array(); foreach ($randomGroups as $key => $value) { $oldQuestOrder[$key] = $randomGroups[$key]; $newQuestOrder[$key] = $oldQuestOrder[$key]; // We shuffle the question list to get a random key->qid which will be used to swap from the old key shuffle($newQuestOrder[$key]); $randGroupNames[] = $key; } // Loop through the fieldmap and swap each question as they come up while (list($fieldkey, $fieldval) = each($fieldmap)) { $found = 0; foreach ($randomGroups as $gkey => $gval) { // We found a qid that is in the randomization group if (isset($fieldval['qid']) && in_array($fieldval['qid'], $oldQuestOrder[$gkey])) { // Get the swapped question $oldQuestFlip = array_flip($oldQuestOrder[$gkey]); $qfieldmap = createFieldMap($surveyid, 'full', true, $newQuestOrder[$gkey][$oldQuestFlip[$fieldval['qid']]], $_SESSION['s_lang']); unset($qfieldmap['id']); unset($qfieldmap['submitdate']); unset($qfieldmap['lastpage']); unset($qfieldmap['lastpage']); unset($qfieldmap['token']); foreach ($qfieldmap as $tkey => $tval) { // Assign the swapped question (Might be more than one field) $tval['random_gid'] = $fieldval['gid']; //$tval['gid'] = $fieldval['gid']; $copyFieldMap[$tkey] = $tval; } $found = 1; break; } else { $found = 2; } } if ($found == 2) { $copyFieldMap[$fieldkey] = $fieldval; } reset($randomGroups); } $fieldmap = $copyFieldMap; } //die(print_r($fieldmap)); $_SESSION['fieldmap'] = $fieldmap; foreach ($fieldmap as $field) { if (isset($field['qid']) && $field['qid'] != '') { $_SESSION['fieldnamesInfo'][$field['fieldname']] = $field['sid'] . 'X' . $field['gid'] . 'X' . $field['qid']; $_SESSION['insertarray'][] = $field['fieldname']; //fieldarray ARRAY CONTENTS - // [0]=questions.qid, // [1]=fieldname, // [2]=questions.title, // [3]=questions.question // [4]=questions.type, // [5]=questions.gid, // [6]=questions.mandatory, // [7]=conditionsexist, // [8]=usedinconditions // [8]=usedinconditions // [9]=used in group.php for question count // [10]=new group id for question in randomization group (GroupbyGroup Mode) if (!isset($_SESSION['fieldarray'][$field['sid'] . 'X' . $field['gid'] . 'X' . $field['qid']])) { $_SESSION['fieldarray'][$field['sid'] . 'X' . $field['gid'] . 'X' . $field['qid']] = array($field['qid'], $field['sid'] . 'X' . $field['gid'] . 'X' . $field['qid'], $field['title'], $field['question'], $field['type'], $field['gid'], $field['mandatory'], $field['hasconditions'], $field['usedinconditions']); } if (isset($field['random_gid'])) { $_SESSION['fieldarray'][$field['sid'] . 'X' . $field['gid'] . 'X' . $field['qid']][10] = $field['random_gid']; } } } // Prefill question/answer from defaultvalues foreach ($fieldmap as $field) { if (isset($field['defaultvalue'])) { $_SESSION[$field['fieldname']] = $field['defaultvalue']; } } // Prefill questions/answers from command line params if (isset($_SESSION['insertarray'])) { foreach ($_SESSION['insertarray'] as $field) { if (isset($_GET[$field]) && $field != 'token') { $_SESSION[$field] = $_GET[$field]; } } } if (isset($_SESSION['fieldarray'])) { $_SESSION['fieldarray'] = array_values($_SESSION['fieldarray']); } // Check if the current survey language is set - if not set it // this way it can be changed later (for example by a special question type) //Check if a passthru label and value have been included in the query url if (isset($_GET['passthru']) && $_GET['passthru'] != "") { if (isset($_GET[$_GET['passthru']]) && $_GET[$_GET['passthru']] != "") { $_SESSION['passthrulabel'] = $_GET['passthru']; $_SESSION['passthruvalue'] = $_GET[$_GET['passthru']]; } } elseif (isset($_SERVER['QUERY_STRING'])) { $_SESSION['ls_initialquerystr'] = $_SERVER['QUERY_STRING']; } // END NEW // Fix totalquestions by substracting Test Display questions $sNoOfTextDisplayQuestions = (int) $connect->GetOne("SELECT count(*)\n" . " FROM " . db_table_name('questions') . " WHERE type='X'\n" . " AND sid={$surveyid}" . " AND language='" . $_SESSION['s_lang'] . "'" . " AND parent_qid=0"); $_SESSION['therearexquestions'] = $totalquestions - $sNoOfTextDisplayQuestions; // must be global for THEREAREXQUESTIONS replacement field to work return $totalquestions - $sNoOfTextDisplayQuestions; }
/** * tokenReplace() takes a string and looks for any {TOKEN:xxxx} variables * which it then, one by one, substitutes the TOKEN code with the relevant token * from the session array containing token information * * The operations of this function were previously in the templatereplace function * but have been moved to a function of their own to make it available * to other areas of the script. * * @param mixed $line string - the string to iterate, and then return * * @return string This string is returned containing the substituted responses * */ function tokenReplace($line) { global $surveyid; if (isset($_SESSION['token']) && $_SESSION['token'] != '') { //Gather survey data for tokenised surveys, for use in presenting questions $_SESSION['thistoken'] = getTokenData($surveyid, $_SESSION['token']); } if (isset($_SESSION['thistoken'])) { if (strpos($line, "{TOKEN:FIRSTNAME}") !== false) { $line = str_replace("{TOKEN:FIRSTNAME}", $_SESSION['thistoken']['firstname'], $line); } if (strpos($line, "{TOKEN:LASTNAME}") !== false) { $line = str_replace("{TOKEN:LASTNAME}", $_SESSION['thistoken']['lastname'], $line); } if (strpos($line, "{TOKEN:EMAIL}") !== false) { $line = str_replace("{TOKEN:EMAIL}", $_SESSION['thistoken']['email'], $line); } } else { if (strpos($line, "{TOKEN:FIRSTNAME}") !== false) { $line = str_replace("{TOKEN:FIRSTNAME}", "", $line); } if (strpos($line, "{TOKEN:LASTNAME}") !== false) { $line = str_replace("{TOKEN:LASTNAME}", "", $line); } if (strpos($line, "{TOKEN:EMAIL}") !== false) { $line = str_replace("{TOKEN:EMAIL}", "", $line); } } while (strpos($line, "{TOKEN:ATTRIBUTE_") !== false) { $templine = substr($line, strpos($line, "{TOKEN:ATTRIBUTE_")); $templine = substr($templine, 0, strpos($templine, "}") + 1); $attr_no = (int) substr($templine, 17, strpos($templine, "}") - 17); $replacestr = ''; if (isset($_SESSION['thistoken']['attribute_' . $attr_no])) { $replacestr = $_SESSION['thistoken']['attribute_' . $attr_no]; } $line = str_replace($templine, $replacestr, $line); } return $line; }