function _surveyExistsAndIsActive($surveyId) { $isSurveyActive = false; $surveyExists = false; if ($surveyId) { $aRow = dbExecuteAssoc("SELECT active FROM {{surveys}} WHERE sid='" . $surveyId . "'")->read(); if (isset($aRow['active'])) { $surveyExists = true; if ($aRow['active'] == 'Y') { $isSurveyActive = true; } } } return array($surveyExists, $isSurveyActive); }
function getGroupUserList($ugid) { Yii::app()->loadHelper('database'); $ugid = sanitize_int($ugid); $surveyidquery = "SELECT a.uid, a.users_name, a.full_name FROM {{users}} AS a LEFT JOIN (SELECT uid AS id FROM {{user_in_groups}} WHERE ugid = {$ugid}) AS b ON a.uid = b.id WHERE id IS NULL ORDER BY a.users_name"; $surveyidresult = dbExecuteAssoc($surveyidquery); //Checked if (!$surveyidresult) { return "Database Error"; } $surveyselecter = ""; foreach ($surveyidresult->readAll() as $row) { $surveynames[] = $row; } //$surveynames = $surveyidresult->GetRows(); if (isset($surveynames)) { foreach ($surveynames as $sv) { $surveyselecter .= "<option"; $surveyselecter .= " value='{$sv['uid']}'>{$sv['users_name']} {$sv['full_name']}</option>\n"; } } $surveyselecter = "<option value='-1' selected='selected'>" . gT("Please choose...") . "</option>\n" . $surveyselecter; return $surveyselecter; }
/** * dataentry::view() * view a dataentry * @param mixed $surveyid * @param mixed $lang * @return */ public function view($surveyid, $lang = NULL) { $surveyid = sanitize_int($surveyid); $lang = isset($_GET['lang']) ? $_GET['lang'] : NULL; if (isset($lang)) { $lang = sanitize_languagecode($lang); } $aViewUrls = array(); if (hasSurveyPermission($surveyid, 'responses', 'read')) { $clang = Yii::app()->lang; $sDataEntryLanguage = Survey::model()->findByPk($surveyid)->language; $surveyinfo = getSurveyInfo($surveyid); $slangs = Survey::model()->findByPk($surveyid)->additionalLanguages; $baselang = Survey::model()->findByPk($surveyid)->language; array_unshift($slangs, $baselang); if (is_null($lang) || !in_array($lang, $slangs)) { $sDataEntryLanguage = $baselang; $blang = $clang; } else { Yii::app()->loadLibrary('Limesurvey_lang', array($lang)); $blang = new Limesurvey_lang($lang); $sDataEntryLanguage = $lang; } $langlistbox = languageDropdown($surveyid, $sDataEntryLanguage); $thissurvey = getSurveyInfo($surveyid); //This is the default, presenting a blank dataentry form LimeExpressionManager::StartSurvey($surveyid, 'survey', NULL, false, LEM_PRETTY_PRINT_ALL_SYNTAX); $moveResult = LimeExpressionManager::NavigateForwards(); $aData['thissurvey'] = $thissurvey; $aData['langlistbox'] = $langlistbox; $aData['surveyid'] = $surveyid; $aData['blang'] = $blang; $aData['site_url'] = Yii::app()->homeUrl; LimeExpressionManager::StartProcessingPage(true, Yii::app()->baseUrl); // means that all variables are on the same page $aViewUrls[] = 'caption_view'; Yii::app()->loadHelper('database'); // SURVEY NAME AND DESCRIPTION TO GO HERE $degquery = "SELECT * FROM {{groups}} WHERE sid={$surveyid} AND language='{$sDataEntryLanguage}' ORDER BY {{groups}}.group_order"; $degresult = dbExecuteAssoc($degquery); // GROUP NAME $aDataentryoutput = ''; foreach ($degresult->readAll() as $degrow) { LimeExpressionManager::StartProcessingGroup($degrow['gid'], $thissurvey['anonymized'] != "N", $surveyid); $deqquery = "SELECT * FROM {{questions}} WHERE sid={$surveyid} AND parent_qid=0 AND gid={$degrow['gid']} AND language='{$sDataEntryLanguage}'"; $deqrows = (array) dbExecuteAssoc($deqquery)->readAll(); $aDataentryoutput .= "\t<tr>\n" . "<td colspan='3' align='center'><strong>" . flattenText($degrow['group_name'], true) . "</strong></td>\n" . "\t</tr>\n"; $gid = $degrow['gid']; $aDataentryoutput .= "\t<tr class='data-entry-separator'><td colspan='3'></td></tr>\n"; // Perform a case insensitive natural sort on group name then question title of a multidimensional array usort($deqrows, 'groupOrderThenQuestionOrder'); $bgc = 'odd'; foreach ($deqrows as $deqrow) { $qidattributes = getQuestionAttributeValues($deqrow['qid'], $deqrow['type']); $cdata['qidattributes'] = $qidattributes; $hidden = isset($qidattributes['hidden']) ? $qidattributes['hidden'] : 0; // TODO - can questions be hidden? Are JavaScript variables names used? Consistently with everywhere else? // LimeExpressionManager::ProcessRelevance($qidattributes['relevance'],$deqrow['qid'],NULL,$deqrow['type'],$hidden); // TMSW Conditions->Relevance: Show relevance equation instead of conditions here - better yet, have data entry use survey-at-a-time but with different view $qinfo = LimeExpressionManager::GetQuestionStatus($deqrow['qid']); $relevance = trim($qinfo['info']['relevance']); $explanation = trim($qinfo['relEqn']); $validation = trim($qinfo['prettyValidTip']); $qidattributes = getQuestionAttributeValues($deqrow['qid']); $array_filter_help = flattenText($this->_array_filter_help($qidattributes, $sDataEntryLanguage, $surveyid)); if ($relevance != '' && $relevance != '1' || $validation != '' || $array_filter_help != '') { $showme = ''; if ($bgc == "even") { $bgc = "odd"; } else { $bgc = "even"; } //Do no alternate on explanation row if ($relevance != '' && $relevance != '1') { $showme = "[" . $blang->gT("Only answer this if the following conditions are met:") . "]<br />{$explanation}\n"; } if ($showme != '' && $validation != '') { $showme .= '<br/>'; } if ($validation != '') { $showme .= "[" . $blang->gT("The answer(s) must meet these validation criteria:") . "]<br />{$validation}\n"; } if ($showme != '' && $array_filter_help != '') { $showme .= '<br/>'; } if ($array_filter_help != '') { $showme .= "[" . $blang->gT("The answer(s) must meet these array_filter criteria:") . "]<br />{$array_filter_help}\n"; } $cdata['explanation'] = "<tr class ='data-entry-explanation'><td class='data-entry-small-text' colspan='3' align='left'>{$showme}</td></tr>\n"; } //END OF GETTING CONDITIONS //Alternate bgcolor for different groups if (!isset($bgc)) { $bgc = "even"; } if ($bgc == "even") { $bgc = "odd"; } else { $bgc = "even"; } $qid = $deqrow['qid']; $fieldname = "{$surveyid}" . "X" . "{$gid}" . "X" . "{$qid}"; $cdata['bgc'] = $bgc; $cdata['fieldname'] = $fieldname; $cdata['deqrow'] = $deqrow; $cdata['clang'] = $clang; //DIFFERENT TYPES OF DATA FIELD HERE $cdata['blang'] = $blang; $cdata['thissurvey'] = $thissurvey; if ($deqrow['help']) { $hh = addcslashes($deqrow['help'], "..'\""); //Escape ASCII decimal 0-32 plus single and double quotes to make JavaScript happy. $hh = htmlspecialchars($hh, ENT_QUOTES); //Change & " ' < > to HTML entities to make HTML happy. $cdata['hh'] = $hh; //$aDataentryoutput .= "\t<img src='$imageurl/help.gif' alt='".$blang->gT("Help about this question")."' align='right' onclick=\"javascript:alert('Question {$deqrow['title']} Help: $hh')\" />\n"; } switch ($deqrow['type']) { case "Q": //MULTIPLE SHORT TEXT //MULTIPLE SHORT TEXT case "K": $deaquery = "SELECT question,title FROM {{questions}} WHERE parent_qid={$deqrow['qid']} AND language='{$sDataEntryLanguage}' ORDER BY question_order"; $dearesult = dbExecuteAssoc($deaquery); $cdata['dearesult'] = $dearesult->readAll(); break; case "1": // multi scale^ $deaquery = "SELECT * FROM {{questions}} WHERE parent_qid={$deqrow['qid']} AND language='{$baselang}' ORDER BY question_order"; $dearesult = dbExecuteAssoc($deaquery); $cdata['dearesult'] = $dearesult->readAll(); $oquery = "SELECT other FROM {{questions}} WHERE qid={$deqrow['qid']} AND language='{$baselang}'"; $oresult = dbExecuteAssoc($oquery) or safeDie("Couldn't get other for list question<br />" . $oquery); foreach ($oresult->readAll() as $orow) { $cdata['fother'] = $orow['other']; } break; case "L": //LIST drop-down/radio-button list //LIST drop-down/radio-button list case "!": // $qidattributes=getQuestionAttributeValues($deqrow['qid']); if ($deqrow['type'] == '!' && trim($qidattributes['category_separator']) != '') { $optCategorySeparator = $qidattributes['category_separator']; } else { unset($optCategorySeparator); } $defexists = ""; $deaquery = "SELECT * FROM {{answers}} WHERE qid={$deqrow['qid']} AND language='{$sDataEntryLanguage}' ORDER BY sortorder, answer"; $dearesult = dbExecuteAssoc($deaquery); //$aDataentryoutput .= "\t<select name='$fieldname'>\n"; $aDatatemp = ''; if (!isset($optCategorySeparator)) { foreach ($dearesult->readAll() as $dearow) { $aDatatemp .= "<option value='{$dearow['code']}'"; //if ($dearow['default_value'] == "Y") {$aDatatemp .= " selected='selected'"; $defexists = "Y";} $aDatatemp .= ">{$dearow['answer']}</option>\n"; } } else { $defaultopts = array(); $optgroups = array(); foreach ($dearesult->readAll() as $dearow) { list($categorytext, $answertext) = explode($optCategorySeparator, $dearow['answer']); if ($categorytext == '') { $defaultopts[] = array('code' => $dearow['code'], 'answer' => $answertext, 'default_value' => $dearow['assessment_value']); } else { $optgroups[$categorytext][] = array('code' => $dearow['code'], 'answer' => $answertext, 'default_value' => $dearow['assessment_value']); } } foreach ($optgroups as $categoryname => $optionlistarray) { $aDatatemp .= "<optgroup class=\"dropdowncategory\" label=\"" . $categoryname . "\">\n"; foreach ($optionlistarray as $optionarray) { $aDatatemp .= "\t<option value='{$optionarray['code']}'"; //if ($optionarray['default_value'] == "Y") {$aDatatemp .= " selected='selected'"; $defexists = "Y";} $aDatatemp .= ">{$optionarray['answer']}</option>\n"; } $aDatatemp .= "</optgroup>\n"; } foreach ($defaultopts as $optionarray) { $aDatatemp .= "\t<option value='{$optionarray['code']}'"; //if ($optionarray['default_value'] == "Y") {$aDatatemp .= " selected='selected'"; $defexists = "Y";} $aDatatemp .= ">{$optionarray['answer']}</option>\n"; } } $oquery = "SELECT other FROM {{questions}} WHERE qid={$deqrow['qid']} AND language='{$sDataEntryLanguage}'"; $oresult = dbExecuteAssoc($oquery) or safeDie("Couldn't get other for list question<br />"); foreach ($oresult->readAll() as $orow) { $fother = $orow['other']; } $cdata['fother'] = $fother; $cdata['defexists'] = $defexists; $cdata['datatemp'] = $aDatatemp; break; case "O": //LIST WITH COMMENT drop-down/radio-button list + textarea $defexists = ""; $deaquery = "SELECT * FROM {{answers}} WHERE qid={$deqrow['qid']} AND language='{$sDataEntryLanguage}' ORDER BY sortorder, answer"; $dearesult = dbExecuteAssoc($deaquery); //$aDataentryoutput .= "\t<select name='$fieldname'>\n"; $aDatatemp = ''; foreach ($dearesult->readAll() as $dearow) { $aDatatemp .= "<option value='{$dearow['code']}'"; //if ($dearow['default_value'] == "Y") {$aDatatemp .= " selected='selected'"; $defexists = "Y";} $aDatatemp .= ">{$dearow['answer']}</option>\n"; } $cdata['datatemp'] = $aDatatemp; $cdata['defexists'] = $defexists; break; case "R": //RANKING TYPE QUESTION $thisqid = $deqrow['qid']; $ansquery = "SELECT * FROM {{answers}} WHERE qid={$thisqid} AND language='{$sDataEntryLanguage}' ORDER BY sortorder, answer"; $ansresult = dbExecuteAssoc($ansquery); $ansresult = $ansresult->readAll(); $anscount = count($ansresult); $cdata['thisqid'] = $thisqid; $cdata['anscount'] = $anscount; foreach ($ansresult as $ansrow) { $answers[] = array($ansrow['code'], $ansrow['answer']); } for ($i = 1; $i <= $anscount; $i++) { if (isset($fname)) { $myfname = $fname . $i; } if (isset($myfname) && Yii::app()->session[$myfname]) { $existing++; } } for ($i = 1; $i <= $anscount; $i++) { if (isset($fname)) { $myfname = $fname . $i; } if (isset($myfname) && Yii::app()->session[$myfname]) { foreach ($answers as $ans) { if ($ans[0] == Yii::app()->session[$myfname]) { $thiscode = $ans[0]; $thistext = $ans[1]; } } } if (!isset($ranklist)) { $ranklist = ""; } $ranklist .= " <font color='#000080'>{$i}: <input class='ranklist' type='text' name='RANK{$i}' id='RANK_{$thisqid}{$i}'"; if (isset($myfname) && Yii::app()->session[$myfname]) { $ranklist .= " value='"; $ranklist .= $thistext; $ranklist .= "'"; } $ranklist .= " onFocus=\"this.blur()\" />\n"; $ranklist .= "<input type='hidden' id='d{$fieldname}{$i}' name='{$fieldname}{$i}' value='"; $chosen[] = ""; //create array if (isset($myfname) && Yii::app()->session[$myfname]) { $ranklist .= $thiscode; $chosen[] = array($thiscode, $thistext); } $ranklist .= "' /></font>\n"; $ranklist .= "<img src='" . Yii::app()->getConfig('imageurl') . "/cut.gif' alt='" . $blang->gT("Remove this item") . "' title='" . $blang->gT("Remove this item") . "' "; if (!isset($existing) || $i != $existing) { $ranklist .= "style='display:none'"; } $mfn = $fieldname . $i; $ranklist .= " id='cut_{$thisqid}{$i}' onclick=\"deletethis_{$thisqid}(document.addsurvey.RANK_{$thisqid}{$i}.value, document.addsurvey.d{$fieldname}{$i}.value, document.addsurvey.RANK_{$thisqid}{$i}.id, this.id)\" /><br />\n\n"; } if (!isset($choicelist)) { $choicelist = ""; } $choicelist .= "<select size='{$anscount}' class='choicelist' name='CHOICES' id='CHOICES_{$thisqid}' onclick=\"rankthis_{$thisqid}(this.options[this.selectedIndex].value, this.options[this.selectedIndex].text)\" >\n"; foreach ($answers as $ans) { if (!in_array($ans, $chosen)) { $choicelist .= "\t<option value='{$ans[0]}'>{$ans[1]}</option>\n"; } } $choicelist .= "</select>\n"; $cdata['choicelist'] = $choicelist; $cdata['ranklist'] = $ranklist; if (isset($multifields)) { $cdata['multifields'] = $multifields; } $choicelist = ""; $ranklist = ""; unset($answers); break; case "M": //Multiple choice checkbox (Quite tricky really!) // $qidattributes=getQuestionAttributeValues($deqrow['qid']); if (trim($qidattributes['display_columns']) != '') { $dcols = $qidattributes['display_columns']; } else { $dcols = 0; } $meaquery = "SELECT title, question FROM {{questions}} WHERE parent_qid={$deqrow['qid']} AND language='{$sDataEntryLanguage}' ORDER BY question_order"; $mearesult = dbExecuteAssoc($meaquery); $cdata['dcols'] = $dcols; $cdata['meacount'] = $meacount; $cdata['mearesult'] = $mearesult->readAll(); $meacount = count($cdata['mearesult']); break; case "I": //Language Switch $slangs = Survey::model()->findByPk($surveyid)->additionalLanguages; $sbaselang = Survey::model()->findByPk($surveyid)->language; array_unshift($slangs, $sbaselang); $cdata['slangs'] = $slangs; break; case "P": //Multiple choice with comments checkbox + text //$aDataentryoutput .= "<table border='0'>\n"; $meaquery = "SELECT * FROM {{questions}} WHERE parent_qid={$deqrow['qid']} AND language='{$sDataEntryLanguage}' ORDER BY question_order, question"; $mearesult = dbExecuteAssoc($meaquery); $cdata['mearesult'] = $mearesult->readAll(); break; case "|": // $qidattributes = getQuestionAttributeValues($deqrow['qid']); $cdata['qidattributes'] = $qidattributes; $maxfiles = $qidattributes['max_num_of_files']; $cdata['maxfiles'] = $maxfiles; break; case "A": //ARRAY (5 POINT CHOICE) radio-buttons $meaquery = "SELECT title, question FROM {{questions}} WHERE parent_qid={$deqrow['qid']} AND language='{$sDataEntryLanguage}' ORDER BY question_order"; $mearesult = dbExecuteAssoc($meaquery); $cdata['mearesult'] = $mearesult->readAll(); break; case "B": //ARRAY (10 POINT CHOICE) radio-buttons $meaquery = "SELECT title, question FROM {{questions}} WHERE parent_qid={$deqrow['qid']} AND language='{$sDataEntryLanguage}' ORDER BY question_order"; $mearesult = dbExecuteAssoc($meaquery); $cdata['mearesult'] = $mearesult->readAll(); case "C": //ARRAY (YES/UNCERTAIN/NO) radio-buttons $meaquery = "SELECT title, question FROM {{questions}} WHERE parent_qid={$deqrow['qid']} AND language='{$sDataEntryLanguage}' ORDER BY question_order"; $mearesult = dbExecuteAssoc($meaquery); $cdata['mearesult'] = $mearesult->readAll(); break; case "E": //ARRAY (YES/UNCERTAIN/NO) radio-buttons $meaquery = "SELECT title, question FROM {{questions}} WHERE parent_qid={$deqrow['qid']} AND language='{$sDataEntryLanguage}' ORDER BY question_order"; $mearesult = dbExecuteAssoc($meaquery) or safeDie("Couldn't get answers, Type \"E\"<br />{$meaquery}<br />"); $cdata['mearesult'] = $mearesult->readAll(); break; case ":": //ARRAY (Multi Flexi) // $qidattributes=getQuestionAttributeValues($deqrow['qid']); $minvalue = 1; $maxvalue = 10; if (trim($qidattributes['multiflexible_max']) != '' && trim($qidattributes['multiflexible_min']) == '') { $maxvalue = $qidattributes['multiflexible_max']; $minvalue = 1; } if (trim($qidattributes['multiflexible_min']) != '' && trim($qidattributes['multiflexible_max']) == '') { $minvalue = $qidattributes['multiflexible_min']; $maxvalue = $qidattributes['multiflexible_min'] + 10; } if (trim($qidattributes['multiflexible_min']) != '' && trim($qidattributes['multiflexible_max']) != '') { if ($qidattributes['multiflexible_min'] < $qidattributes['multiflexible_max']) { $minvalue = $qidattributes['multiflexible_min']; $maxvalue = $qidattributes['multiflexible_max']; } } if (trim($qidattributes['multiflexible_step']) != '') { $stepvalue = $qidattributes['multiflexible_step']; } else { $stepvalue = 1; } if ($qidattributes['multiflexible_checkbox'] != 0) { $minvalue = 0; $maxvalue = 1; $stepvalue = 1; } $cdata['minvalue'] = $minvalue; $cdata['maxvalue'] = $maxvalue; $cdata['stepvalue'] = $stepvalue; $lquery = "SELECT question, title FROM {{questions}} WHERE parent_qid={$deqrow['qid']} and scale_id=1 and language='{$sDataEntryLanguage}' ORDER BY question_order"; $lresult = dbExecuteAssoc($lquery) or die("Couldn't get labels, Type \":\"<br />{$lquery}<br />"); $cdata['lresult'] = $lresult->readAll(); $meaquery = "SELECT question, title FROM {{questions}} WHERE parent_qid={$deqrow['qid']} and scale_id=0 and language='{$sDataEntryLanguage}' ORDER BY question_order"; $mearesult = dbExecuteAssoc($meaquery) or die("Couldn't get answers, Type \":\"<br />{$meaquery}<br />"); $cdata['mearesult'] = $mearesult->readAll(); break; case ";": //ARRAY (Multi Flexi) $lquery = "SELECT * FROM {{questions}} WHERE scale_id=1 and parent_qid={$deqrow['qid']} and language='{$sDataEntryLanguage}' ORDER BY question_order"; $lresult = dbExecuteAssoc($lquery) or die("Couldn't get labels, Type \":\"<br />{$lquery}<br />"); $cdata['lresult'] = $lresult->readAll(); $meaquery = "SELECT * FROM {{questions}} WHERE scale_id=0 and parent_qid={$deqrow['qid']} and language='{$sDataEntryLanguage}' ORDER BY question_order"; $mearesult = dbExecuteAssoc($meaquery) or die("Couldn't get answers, Type \":\"<br />{$meaquery}<br />"); $cdata['mearesult'] = $mearesult->readAll(); break; case "F": //ARRAY (Flexible Labels) //ARRAY (Flexible Labels) case "H": $meaquery = "SELECT * FROM {{questions}} WHERE parent_qid={$deqrow['qid']} and language='{$sDataEntryLanguage}' ORDER BY question_order"; $mearesult = dbExecuteAssoc($meaquery) or safeDie("Couldn't get answers, Type \"E\"<br />{$meaquery}<br />"); $cdata['mearesult'] = $mearesult->readAll(); $fquery = "SELECT * FROM {{answers}} WHERE qid={$deqrow['qid']} and language='{$sDataEntryLanguage}' ORDER BY sortorder, code"; $fresult = dbExecuteAssoc($fquery); $cdata['fresult'] = $fresult->readAll(); break; } $cdata['sDataEntryLanguage'] = $sDataEntryLanguage; $viewdata = $this->getController()->render("/admin/dataentry/content_view", $cdata, TRUE); $viewdata_em = LimeExpressionManager::ProcessString($viewdata, $deqrow['qid'], NULL, false, 1, 1); $aDataentryoutput .= $viewdata_em; } LimeExpressionManager::FinishProcessingGroup(); } LimeExpressionManager::FinishProcessingPage(); $aDataentryoutput .= LimeExpressionManager::GetRelevanceAndTailoringJavaScript(); $aViewUrls['output'] = $aDataentryoutput; $aData['thissurvey'] = $thissurvey; $aData['surveyid'] = $surveyid; $aData['sDataEntryLanguage'] = $sDataEntryLanguage; if ($thissurvey['active'] == "Y" && $thissurvey['allowsave'] == "Y") { $slangs = Survey::model()->findByPk($surveyid)->additionalLanguages; $sbaselang = Survey::model()->findByPk($surveyid)->language; array_unshift($slangs, $sbaselang); $aData['slangs'] = $slangs; $aData['baselang'] = $baselang; } $aViewUrls[] = 'active_html_view'; $this->_renderWrappedTemplate('dataentry', $aViewUrls, $aData); } }
/** * Update SESSION VARIABLE: grouplist * A list of groups in this survey, ordered by group name. * @param int surveyid * @param string language */ function UpdateGroupList($surveyid, $language) { $clang = Yii::app()->lang; unset($_SESSION['survey_' . $surveyid]['grouplist']); $query = "SELECT * FROM {{groups}} WHERE sid={$surveyid} AND language='" . $language . "' ORDER BY group_order"; $result = dbExecuteAssoc($query) or safeDie("Couldn't get group list<br />{$query}<br />"); //Checked $groupList = array(); foreach ($result->readAll() as $row) { $group = array('gid' => $row['gid'], 'group_name' => $row['group_name'], 'description' => $row['description']); $groupList[] = $group; $gidList[$row['gid']] = $group; } if (!Yii::app()->getConfig('previewmode') && isset($_SESSION['survey_' . $surveyid]['groupReMap']) && count($_SESSION['survey_' . $surveyid]['groupReMap']) > 0) { // Now adjust the grouplist $groupRemap = $_SESSION['survey_' . $surveyid]['groupReMap']; $groupListCopy = $groupList; foreach ($groupList as $gseq => $info) { $gid = $info['gid']; if (isset($groupRemap[$gid])) { $gid = $groupRemap[$gid]; } $groupListCopy[$gseq] = $gidList[$gid]; } $groupList = $groupListCopy; } $_SESSION['survey_' . $surveyid]['grouplist'] = $groupList; }
$surveyinfo = getSurveyInfo(sanitize_int($_REQUEST['sid'])); if (isset($surveyinfo['assessments']) && $surveyinfo['assessments']=='Y') { $_REQUEST['assessments'] = 'Y'; } } $clang = Yii::app()->lang; Yii::app()->loadHelper('frontend'); if (empty($_REQUEST['sid'])) // || count($_REQUEST) == 0) { { $query = "select a.surveyls_survey_id as sid, a.surveyls_title as title, b.datecreated, b.assessments " . "from {{surveys_languagesettings}} as a join {{surveys}} as b on a.surveyls_survey_id = b.sid" . " where a.surveyls_language='en' order by a.surveyls_title, b.datecreated"; $data = dbExecuteAssoc($query); $surveyList=''; foreach($data->readAll() as $row) { $surveyList .= "<option value='" . $row['sid'] .'|' . $row['assessments'] . "'>#" . $row['sid'] . " [" . $row['datecreated'] . '] ' . flattenText($row['title']) . "</option>\n"; } $url = $this->createUrl('admin/expressions/survey_logic_file'); $form = <<< EOD <form method='post' action='$url'> <h3>Generate a logic file for the survey</h3> <table border='1'> <tr><th>Parameter</th><th>Value</th></tr> <tr><td>Survey ID (SID)</td> <td><select name='sid' id='sid'> $surveyList </select></td></tr> <tr><td>Debug Log Level</td>
function do_array_dual($ia) { global $thissurvey; $aLastMoveResult = LimeExpressionManager::GetLastMoveResult(); $aMandatoryViolationSubQ = $aLastMoveResult['mandViolation'] && $ia[6] == 'Y' ? explode("|", $aLastMoveResult['unansweredSQs']) : array(); $repeatheadings = Yii::app()->getConfig("repeatheadings"); $minrepeatheadings = Yii::app()->getConfig("minrepeatheadings"); $extraclass = ""; $answertypeclass = ""; // Maybe not $caption = ""; // Just leave empty, are replaced after $inputnames = array(); $labelans1 = array(); $labelans = array(); /* * Get Question Attributes */ $aQuestionAttributes = QuestionAttribute::model()->getQuestionAttributes($ia[0]); // Get questions and answers by defined order if ($aQuestionAttributes['random_order'] == 1) { $ansquery = "SELECT * FROM {{questions}} WHERE parent_qid={$ia['0']} AND language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "' and scale_id=0 ORDER BY " . dbRandom(); } else { $ansquery = "SELECT * FROM {{questions}} WHERE parent_qid={$ia['0']} AND language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "' and scale_id=0 ORDER BY question_order"; } $ansresult = dbExecuteAssoc($ansquery); //Checked $aSubQuestions = $ansresult->readAll(); $anscount = count($aSubQuestions); $lquery = "SELECT * FROM {{answers}} WHERE scale_id=0 AND qid={$ia[0]} AND language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "' ORDER BY sortorder, code"; $lresult = dbExecuteAssoc($lquery); //Checked $aAnswersScale0 = $lresult->readAll(); $lquery1 = "SELECT * FROM {{answers}} WHERE scale_id=1 AND qid={$ia[0]} AND language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "' ORDER BY sortorder, code"; $lresult1 = dbExecuteAssoc($lquery1); //Checked $aAnswersScale1 = $lresult1->readAll(); // Set attributes if ($aQuestionAttributes['use_dropdown'] == 1) { $useDropdownLayout = true; $extraclass .= " dropdown-list"; $answertypeclass .= " dropdown"; $doDualScaleFunction = "doDualScaleDropDown"; // javascript funtion to lauch at end of answers $caption = gT("A table with a subquestion on each row, with two answers to provide on each line. Please select the answers."); } else { $useDropdownLayout = false; $extraclass .= " radio-list"; $answertypeclass .= " radio"; $doDualScaleFunction = "doDualScaleRadio"; $caption = gT("A table with one subquestion on each row and two answers to provide on each row. The related answer options are in the top table header row."); } if (ctype_digit(trim($aQuestionAttributes['repeat_headings'])) && trim($aQuestionAttributes['repeat_headings'] != "")) { $repeatheadings = intval($aQuestionAttributes['repeat_headings']); $minrepeatheadings = 0; } $leftheader = trim($aQuestionAttributes['dualscale_headerA'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']]) != '' ? $leftheader = $aQuestionAttributes['dualscale_headerA'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']] : ''; $rightheader = trim($aQuestionAttributes['dualscale_headerB'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']]) != '' ? $aQuestionAttributes['dualscale_headerB'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']] : ''; $answerwidth = trim($aQuestionAttributes['answer_width']) != '' ? $aQuestionAttributes['answer_width'] : 20; // Find if we have rigth and center text $sQuery = "SELECT count(question) FROM {{questions}} WHERE parent_qid=" . $ia[0] . " and scale_id=0 AND question like '%|%'"; $rigthCount = Yii::app()->db->createCommand($sQuery)->queryScalar(); $rightexists = $rigthCount > 0; // $right_exists: flag to find out if there are any right hand answer parts. leaving right column but don't force with $sQuery = "SELECT count(question) FROM {{questions}} WHERE parent_qid=" . $ia[0] . " and scale_id=0 AND question like '%|%|%'"; $centerCount = Yii::app()->db->createCommand($sQuery)->queryScalar(); $centerexists = $centerCount > 0; // $center_exists: flag to find out if there are any center hand answer parts. leaving center column but don't force with // Label and code for input foreach ($aAnswersScale0 as $lrow) { $labels0[] = array('code' => $lrow['code'], 'title' => $lrow['answer']); } foreach ($aAnswersScale1 as $lrow) { $labels1[] = array('code' => $lrow['code'], 'title' => $lrow['answer']); } if (count($aAnswersScale0) > 0 && $anscount) { $answer = ""; $fn = 1; // Used by repeat_heading // No drop-down if ($useDropdownLayout === false) { $aData = array(); $aData['answertypeclass'] = $answertypeclass; $columnswidth = 100 - $answerwidth; $labelans0 = array(); $labelans1 = array(); $labelcode0 = array(); $labelcode1 = array(); foreach ($aAnswersScale0 as $lrow) { $labelans0[] = $lrow['answer']; $labelcode0[] = $lrow['code']; } foreach ($aAnswersScale1 as $lrow) { $labelans1[] = $lrow['answer']; $labelcode1[] = $lrow['code']; } $numrows = count($labelans0) + count($labelans1); // Add needed row and fill some boolean: shownoanswer, rightexists, centerexists $shownoanswer = $ia[6] != "Y" && SHOW_NO_ANSWER == 1; if ($shownoanswer) { $numrows++; $caption .= gT("The last cell is for 'No answer'."); } if ($rightexists) { $numrows++; } if ($centerexists) { $numrows++; } $cellwidth = $columnswidth / $numrows; $cellwidth = sprintf("%02d", $cellwidth); // No reason to do this, except to leave place for separator ? But then table can not be the same in all browser // Header row and colgroups $aData['answerwidth'] = $answerwidth; $aData['cellwidth'] = $cellwidth; $aData['labelans0'] = $labelans0; $aData['labelcode0'] = $labelcode0; $aData['labelans1'] = $labelans1; $aData['labelcode1'] = $labelcode1; $aData['separatorwidth'] = $centerexists ? "style='width: {$cellwidth}%;' " : ""; $aData['shownoanswer'] = $shownoanswer; $aData['rightexists'] = $rightexists; $aData['rigthwidth'] = $rightexists ? "style='width: {$cellwidth}%;' " : ""; // build first row of header if needed $aData['leftheader'] = $leftheader; $aData['rightheader'] = $rightheader; $aData['rigthclass'] = $rightexists ? " header_answer_text_right" : ""; // And no each line of body $trbc = ''; $aData['aSubQuestions'] = $aSubQuestions; foreach ($aSubQuestions as $i => $ansrow) { // Build repeat headings if needed if (isset($repeatheadings) && $repeatheadings > 0 && $fn - 1 > 0 && ($fn - 1) % $repeatheadings == 0) { if ($anscount - $fn + 1 >= $minrepeatheadings) { $aData['aSubQuestions'][$i]['repeatheadings'] = true; } } else { $aData['aSubQuestions'][$i]['repeatheadings'] = false; } $trbc = alternation($trbc, 'row'); $answertext = $ansrow['question']; // rigth and center answertext: not explode for ? Why not if (strpos($answertext, '|')) { $answertextright = substr($answertext, strpos($answertext, '|') + 1); $answertext = substr($answertext, 0, strpos($answertext, '|')); } else { $answertextright = ""; } if ($centerexists) { $answertextcenter = substr($answertextright, 0, strpos($answertextright, '|')); $answertextright = substr($answertextright, strpos($answertextright, '|') + 1); } else { $answertextcenter = ""; } $myfname = $ia[1] . $ansrow['title']; $myfname0 = $ia[1] . $ansrow['title'] . '#0'; $myfid0 = $ia[1] . $ansrow['title'] . '_0'; $myfname1 = $ia[1] . $ansrow['title'] . '#1'; // new multi-scale-answer $myfid1 = $ia[1] . $ansrow['title'] . '_1'; $aData['aSubQuestions'][$i]['myfname'] = $myfname; $aData['aSubQuestions'][$i]['myfname0'] = $myfname0; $aData['aSubQuestions'][$i]['myfid0'] = $myfid0; $aData['aSubQuestions'][$i]['myfname1'] = $myfname1; $aData['aSubQuestions'][$i]['myfid1'] = $myfid1; $aData['aSubQuestions'][$i]['answertext'] = $ansrow['question']; /* Check the Sub Q mandatory violation */ if ($ia[6] == 'Y' && (in_array($myfname0, $aMandatoryViolationSubQ) || in_array($myfname1, $aMandatoryViolationSubQ))) { $aData['aSubQuestions'][$i]['showmandatoryviolation'] = true; } else { $aData['aSubQuestions'][$i]['showmandatoryviolation'] = false; } // Get array_filter stuff list($htmltbody2, $hiddenfield) = return_array_filter_strings($ia, $aQuestionAttributes, $thissurvey, $ansrow, $myfname, $trbc, $myfname, "tr", "{$trbc} answers-list radio-list"); $aData['aSubQuestions'][$i]['htmltbody2'] = $htmltbody2; $aData['aSubQuestions'][$i]['hiddenfield'] = $hiddenfield; array_push($inputnames, $myfname0); if (isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname0])) { $aData['aSubQuestions'][$i]['sessionfname0'] = $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname0]; } else { $aData['aSubQuestions'][$i]['sessionfname0'] = ''; } if (count($labelans1) > 0) { if (isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname1])) { //$answer .= $_SESSION['survey_'.Yii::app()->getConfig('surveyID')][$myfname1]; $aData['aSubQuestions'][$i]['sessionfname1'] = $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname1]; } else { $aData['aSubQuestions'][$i]['sessionfname1'] = ''; } } foreach ($labelcode0 as $j => $ld) { if (isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname0]) && $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname0] == $ld) { $aData['labelcode0_checked'][$ansrow['title']][$ld] = CHECKED; } else { $aData['labelcode0_checked'][$ansrow['title']][$ld] = ""; } } if (count($labelans1) > 0) { if ($shownoanswer) { if (!isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname0]) || $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname0] == "") { $answer .= CHECKED; $aData['myfname0_notset'] = CHECKED; } else { $aData['myfname0_notset'] = ""; } } array_push($inputnames, $myfname1); foreach ($labelcode1 as $j => $ld) { if (isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname1]) && $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname1] == $ld) { $aData['labelcode1_checked'][$ansrow['title']][$ld] = CHECKED; } else { $aData['labelcode1_checked'][$ansrow['title']][$ld] = ""; } } } $aData['answertextright'] = $answertextright; if ($shownoanswer) { if (count($labelans1) > 0) { if (!isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname1]) || $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname1] == "") { $answer .= CHECKED; $aData['myfname1_notset'] = CHECKED; } else { $aData['myfname1_notset'] = ""; } } else { if (!isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname0]) || $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname0] == "") { $answer .= CHECKED; $aData['myfname0_notset'] = CHECKED; } else { $aData['myfname0_notset'] = ''; } } } $fn++; } $answer = doRender('/survey/questions/arrays/dualscale/answer', $aData, true); } elseif ($useDropdownLayout === true) { $aData = array(); $separatorwidth = (100 - $answerwidth) / 10; $cellwidth = (100 - $answerwidth - $separatorwidth) / 2; $answer = ""; // Get attributes for Headers and Prefix/Suffix if (trim($aQuestionAttributes['dropdown_prepostfix'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']]) != '') { list($ddprefix, $ddsuffix) = explode("|", $aQuestionAttributes['dropdown_prepostfix'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']]); $ddprefix = $ddprefix; $ddsuffix = $ddsuffix; } else { $ddprefix = ''; $ddsuffix = ''; } if (trim($aQuestionAttributes['dropdown_separators']) != '') { $aSeparator = explode('|', $aQuestionAttributes['dropdown_separators']); if (isset($aSeparator[1])) { $interddSep = $aSeparator[1]; } else { $interddSep = $aSeparator[0]; } } else { $interddSep = ''; } $aData['answerwidth'] = $answerwidth; $aData['ddprefix'] = $ddprefix; $aData['ddsuffix'] = $ddsuffix; $aData['cellwidth'] = $cellwidth; ////// TODO: check in prev headcolwidth if style='width:$cellwidth' and not style='width:\"$cellwidth\"' $headcolwidth = $ddprefix != '' || $ddsuffix != '' ? "" : " style='width: {$cellwidth}%';"; $aData['headcolwidth'] = $headcolwidth; $aData['separatorwidth'] = $separatorwidth; // colspan : for header only if ($ddprefix != '' && $ddsuffix != '') { $colspan = ' colspan="3"'; } elseif ($ddprefix != '' || $ddsuffix != '') { $colspan = ' colspan="2"'; } else { $colspan = ""; } $aData['colspan'] = $colspan; $aData['leftheader'] = $leftheader; $aData['rightheader'] = $rightheader; $trbc = ''; $aData['aSubQuestions'] = $aSubQuestions; foreach ($aSubQuestions as $i => $ansrow) { $myfname = $ia[1] . $ansrow['title']; $myfname0 = $ia[1] . $ansrow['title'] . "#0"; $myfid0 = $ia[1] . $ansrow['title'] . "_0"; $myfname1 = $ia[1] . $ansrow['title'] . "#1"; $myfid1 = $ia[1] . $ansrow['title'] . "_1"; $sActualAnswer0 = isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname0]) ? $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname0] : ""; $sActualAnswer1 = isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname1]) ? $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname1] : ""; $aData['aSubQuestions'][$i]['myfname'] = $myfname; $aData['aSubQuestions'][$i]['myfname0'] = $myfname0; $aData['aSubQuestions'][$i]['myfid0'] = $myfid0; $aData['aSubQuestions'][$i]['myfname1'] = $myfname1; $aData['aSubQuestions'][$i]['myfid1'] = $myfid1; $aData['aSubQuestions'][$i]['sActualAnswer0'] = $sActualAnswer0; $aData['aSubQuestions'][$i]['sActualAnswer1'] = $sActualAnswer1; // Set mandatory alert $aData['aSubQuestions'][$i]['alert'] = $ia[6] == 'Y' && (in_array($myfname0, $aMandatoryViolationSubQ) || in_array($myfname1, $aMandatoryViolationSubQ)); list($htmltbody2, $hiddenfield) = return_array_filter_strings($ia, $aQuestionAttributes, $thissurvey, $ansrow, $myfname, $trbc, $myfname, "tr", "{$trbc} subquestion-list questions-list dropdown-list"); $aData['aSubQuestions'][$i]['htmltbody2'] = $htmltbody2; $aData['aSubQuestions'][$i]['hiddenfield'] = $hiddenfield; $aData['labels0'] = $labels0; $aData['labels1'] = $labels1; $aData['aSubQuestions'][$i]['showNoAnswer0'] = $sActualAnswer0 != '' && $ia[6] != 'Y' && SHOW_NO_ANSWER; $aData['aSubQuestions'][$i]['showNoAnswer1'] = $sActualAnswer1 != '' && $ia[6] != 'Y' && SHOW_NO_ANSWER; $aData['interddSep'] = $interddSep; $inputnames[] = $myfname0; $inputnames[] = $myfname1; } $answer = doRender('/survey/questions/arrays/dualscale/answer_dropdown', $aData, true); } } else { $answer = "<p class='error'>" . gT("Error: There are no answer options for this question and/or they don't exist in this language.") . "</p>\n"; $inputnames = ""; } Yii::app()->getClientScript()->registerScriptFile(Yii::app()->getConfig('generalscripts') . "dualscale.js"); $answer .= "<script type='text/javascript'>\n" . " <!--\n" . " {$doDualScaleFunction}({$ia[0]});\n" . " -->\n" . "</script>\n"; return array($answer, $inputnames); }
/** * TSV survey definition in format readable by TSVSurveyImport * one line each per group, question, sub-question, and answer * does not use SGQA naming at all. * @param type $sid * @return type */ public static function &TSVSurveyExport($sid) { $fields = array('class', 'type/scale', 'name', 'relevance', 'text', 'help', 'language', 'validation', 'mandatory', 'other', 'default', 'same_default', 'allowed_filetypes', 'alphasort', 'answer_width', 'array_filter', 'array_filter_exclude', 'array_filter_style', 'assessment_value', 'category_separator', 'choice_title', 'code_filter', 'commented_checkbox', 'commented_checkbox_auto', 'date_format', 'date_max', 'date_min', 'display_columns', 'display_rows', 'dropdown_dates', 'dropdown_dates_minute_step', 'dropdown_dates_month_style', 'dropdown_prefix', 'dropdown_prepostfix', 'dropdown_separators', 'dropdown_size', 'dualscale_headerA', 'dualscale_headerB', 'em_validation_q', 'em_validation_q_tip', 'em_validation_sq', 'em_validation_sq_tip', 'equals_num_value', 'exclude_all_others', 'exclude_all_others_auto', 'hidden', 'hide_tip', 'input_boxes', 'location_city', 'location_country', 'location_defaultcoordinates', 'location_mapheight', 'location_mapservice', 'location_mapwidth', 'location_mapzoom', 'location_nodefaultfromip', 'location_postal', 'location_state', 'max_answers', 'max_filesize', 'max_num_of_files', 'max_num_value', 'max_num_value_n', 'maximum_chars', 'min_answers', 'min_num_of_files', 'min_num_value', 'min_num_value_n', 'multiflexible_checkbox', 'multiflexible_max', 'multiflexible_min', 'multiflexible_step', 'num_value_int_only', 'numbers_only', 'other_comment_mandatory', 'other_numbers_only', 'other_replace_text', 'page_break', 'parent_order', 'prefix', 'printable_help', 'public_statistics', 'random_group', 'random_order', 'rank_title', 'repeat_headings', 'reverse', 'samechoiceheight', 'samelistheight', 'scale_export', 'show_comment', 'show_grand_total', 'show_title', 'show_totals', 'showpopups', 'slider_accuracy', 'slider_default', 'slider_layout', 'slider_max', 'slider_middlestart', 'slider_min', 'slider_rating', 'slider_reset', 'slider_separator', 'slider_showminmax', 'statistics_graphtype', 'statistics_showgraph', 'statistics_showmap', 'suffix', 'text_input_width', 'time_limit', 'time_limit_action', 'time_limit_countdown_message', 'time_limit_disable_next', 'time_limit_disable_prev', 'time_limit_message', 'time_limit_message_delay', 'time_limit_message_style', 'time_limit_timer_style', 'time_limit_warning', 'time_limit_warning_2', 'time_limit_warning_2_display_time', 'time_limit_warning_2_message', 'time_limit_warning_2_style', 'time_limit_warning_display_time', 'time_limit_warning_message', 'time_limit_warning_style', 'thousands_separator', 'use_dropdown'); $rows = array(); $primarylang = 'en'; $otherlangs = ''; $langs = array(); // Export survey-level information $query = "select * from {{surveys}} where sid = " . $sid; $data = dbExecuteAssoc($query); foreach ($data->readAll() as $r) { foreach ($r as $key => $value) { if ($value != '') { $row['class'] = 'S'; $row['name'] = $key; $row['text'] = $value; $rows[] = $row; } if ($key == 'language') { $primarylang = $value; } if ($key == 'additional_languages') { $otherlangs = $value; } } } $langs = explode(' ', $primarylang . ' ' . $otherlangs); $langs = array_unique($langs); // Export survey language settings $query = "select * from {{surveys_languagesettings}} where surveyls_survey_id = " . $sid; $data = dbExecuteAssoc($query); foreach ($data->readAll() as $r) { $_lang = $r['surveyls_language']; foreach ($r as $key => $value) { if ($value != '' && $key != 'surveyls_language' && $key != 'surveyls_survey_id') { $row['class'] = 'SL'; $row['name'] = $key; $row['text'] = $value; $row['language'] = $_lang; $rows[] = $row; } } } $surveyinfo = getSurveyInfo($sid); $assessments = false; if (isset($surveyinfo['assessments']) && $surveyinfo['assessments'] == 'Y') { $assessments = true; } foreach ($langs as $lang) { if (trim($lang) == '') { continue; } SetSurveyLanguage($sid, $lang); LimeExpressionManager::StartSurvey($sid, 'survey', array('sgqaNaming' => 'N', 'assessments' => $assessments), true); $moveResult = LimeExpressionManager::NavigateForwards(); $LEM =& LimeExpressionManager::singleton(); if (is_null($moveResult) || is_null($LEM->currentQset) || count($LEM->currentQset) == 0) { continue; } $_gseq = -1; foreach ($LEM->currentQset as $q) { $gseq = $q['info']['gseq']; $gid = $q['info']['gid']; $qid = $q['info']['qid']; ////// // SHOW GROUP-LEVEL INFO ////// if ($gseq != $_gseq) { $_gseq = $gseq; $ginfo = $LEM->gseq2info[$gseq]; // if relevance equation is using SGQA coding, convert to qcoding $grelevance = $ginfo['grelevance'] == '' ? 1 : $ginfo['grelevance']; $LEM->em->ProcessBooleanExpression($grelevance, $gseq, 0); // $qseq $grelevance = trim(strip_tags($LEM->em->GetPrettyPrintString())); $gtext = trim($ginfo['description']) == '' ? '' : $ginfo['description']; $row = array(); $row['class'] = 'G'; //create a group code to allow proper importing of multi-lang survey TSVs $row['type/scale'] = 'G' . $gseq; $row['name'] = $ginfo['group_name']; $row['relevance'] = $grelevance; $row['text'] = $gtext; $row['language'] = $lang; $row['random_group'] = $ginfo['randomization_group']; $rows[] = $row; } ////// // SHOW QUESTION-LEVEL INFO ////// $row = array(); $mandatory = $q['info']['mandatory'] == 'Y' ? 'Y' : ''; $type = $q['info']['type']; $sgqas = explode('|', $q['sgqa']); if (count($sgqas) == 1 && !is_null($q['info']['default'])) { $default = $q['info']['default']; } else { $default = ''; } $qtext = $q['info']['qtext'] != '' ? $q['info']['qtext'] : ''; $help = $q['info']['help'] != '' ? $q['info']['help'] : ''; ////// // SHOW QUESTION ATTRIBUTES THAT ARE PROCESSED BY EM ////// if (isset($LEM->qattr[$qid]) && count($LEM->qattr[$qid]) > 0) { foreach ($LEM->qattr[$qid] as $key => $value) { if (is_null($value) || trim($value) == '') { continue; } switch ($key) { default: case 'exclude_all_others': case 'exclude_all_others_auto': case 'hidden': if ($value == false || $value == '0') { $value = NULL; // so can skip this one - just using continue here doesn't work. } break; case 'relevance': $value = NULL; // means an outdate database structure break; } if (is_null($value) || trim($value) == '') { continue; // since continuing from within a switch statement doesn't work } $row[$key] = $value; } } // if relevance equation is using SGQA coding, convert to qcoding $relevanceEqn = $q['info']['relevance'] == '' ? 1 : $q['info']['relevance']; $LEM->em->ProcessBooleanExpression($relevanceEqn, $gseq, $q['info']['qseq']); // $qseq $relevanceEqn = trim(strip_tags($LEM->em->GetPrettyPrintString())); $rootVarName = $q['info']['rootVarName']; $preg = ''; if (isset($LEM->q2subqInfo[$q['info']['qid']]['preg'])) { $preg = $LEM->q2subqInfo[$q['info']['qid']]['preg']; if (is_null($preg)) { $preg = ''; } } $row['class'] = 'Q'; $row['type/scale'] = $type; $row['name'] = $rootVarName; $row['relevance'] = $relevanceEqn; $row['text'] = $qtext; $row['help'] = $help; $row['language'] = $lang; $row['validation'] = $preg; $row['mandatory'] = $mandatory; $row['other'] = $q['info']['other']; $row['default'] = $default; $row['same_default'] = 1; // TODO - need this: $q['info']['same_default']; $rows[] = $row; ////// // SHOW ALL SUB-QUESTIONS ////// $sawThis = array(); // array of rowdivids already seen so only show them once foreach ($sgqas as $sgqa) { if ($LEM->knownVars[$sgqa]['qcode'] == $rootVarName) { continue; // so don't show the main question as a sub-question too } $rowdivid = $sgqa; $varName = $LEM->knownVars[$sgqa]['qcode']; // if SQrelevance equation is using SGQA coding, convert to qcoding $SQrelevance = $LEM->knownVars[$sgqa]['SQrelevance'] == '' ? 1 : $LEM->knownVars[$sgqa]['SQrelevance']; $LEM->em->ProcessBooleanExpression($SQrelevance, $gseq, $q['info']['qseq']); $SQrelevance = trim(strip_tags($LEM->em->GetPrettyPrintString())); switch ($q['info']['type']) { case '1': if (preg_match('/#1$/', $sgqa)) { $rowdivid = NULL; // so that doesn't show same message for second scale } else { $rowdivid = substr($sgqa, 0, -2); // strip suffix $varName = substr($LEM->knownVars[$sgqa]['qcode'], 0, -2); } break; case 'P': if (preg_match('/comment$/', $sgqa)) { $rowdivid = NULL; } break; case ':': case ';': $_rowdivid = $LEM->knownVars[$sgqa]['rowdivid']; if (isset($sawThis[$qid . '~' . $_rowdivid])) { $rowdivid = NULL; // so don't show again } else { $sawThis[$qid . '~' . $_rowdivid] = true; $rowdivid = $_rowdivid; $sgqa_len = strlen($sid . 'X' . $gid . 'X' . $qid); $varName = $rootVarName . '_' . substr($_rowdivid, $sgqa_len); } break; } if (is_null($rowdivid)) { continue; } $sgqaInfo = $LEM->knownVars[$sgqa]; $subqText = $sgqaInfo['subqtext']; if (isset($sgqaInfo['default'])) { $default = $sgqaInfo['default']; } else { $default = ''; } $row = array(); $row['class'] = 'SQ'; $row['type/scale'] = 0; $row['name'] = substr($varName, strlen($rootVarName) + 1); $row['relevance'] = $SQrelevance; $row['text'] = $subqText; $row['language'] = $lang; $row['default'] = $default; $rows[] = $row; } ////// // SHOW ANSWER OPTIONS FOR ENUMERATED LISTS, AND FOR MULTIFLEXI ////// if (isset($LEM->qans[$qid]) || isset($LEM->multiflexiAnswers[$qid])) { $_scale = -1; if (isset($LEM->multiflexiAnswers[$qid])) { $ansList = $LEM->multiflexiAnswers[$qid]; } else { $ansList = $LEM->qans[$qid]; } foreach ($ansList as $ans => $value) { $ansInfo = explode('~', $ans); $valParts = explode('|', $value); $valInfo[0] = array_shift($valParts); $valInfo[1] = implode('|', $valParts); if ($_scale != $ansInfo[0]) { $_scale = $ansInfo[0]; } $row = array(); if ($type == ':' || $type == ';') { $row['class'] = 'SQ'; } else { $row['class'] = 'A'; } $row['type/scale'] = $_scale; $row['name'] = $ansInfo[1]; $row['relevance'] = $assessments == true ? $valInfo[0] : ''; $row['text'] = $valInfo[1]; $row['language'] = $lang; $rows[] = $row; } } } } // Now generate the array out output data $out = array(); $out[] = $fields; foreach ($rows as $row) { $tsv = array(); foreach ($fields as $field) { $val = isset($row[$field]) ? $row[$field] : ''; $tsv[] = $val; } $out[] = $tsv; } return $out; }
/** * dataentry::view() * view a dataentry * @param mixed $surveyid * @param mixed $lang * @return */ public function view($surveyid, $lang = NULL) { $surveyid = sanitize_int($surveyid); $lang = isset($_GET['lang']) ? $_GET['lang'] : NULL; if (isset($lang)) { $lang = sanitize_languagecode($lang); } $aViewUrls = array(); if (Permission::model()->hasSurveyPermission($surveyid, 'responses', 'create')) { $sDataEntryLanguage = Survey::model()->findByPk($surveyid)->language; $surveyinfo = getSurveyInfo($surveyid); $slangs = Survey::model()->findByPk($surveyid)->additionalLanguages; $baselang = Survey::model()->findByPk($surveyid)->language; array_unshift($slangs, $baselang); if (is_null($lang) || !in_array($lang, $slangs)) { $sDataEntryLanguage = $baselang; } else { $sDataEntryLanguage = $lang; } $langlistbox = languageDropdown($surveyid, $sDataEntryLanguage); $thissurvey = getSurveyInfo($surveyid); //This is the default, presenting a blank dataentry form LimeExpressionManager::StartSurvey($surveyid, 'survey', NULL, false, LEM_PRETTY_PRINT_ALL_SYNTAX); $moveResult = LimeExpressionManager::NavigateForwards(); $aData['thissurvey'] = $thissurvey; $aData['langlistbox'] = $langlistbox; $aData['surveyid'] = $surveyid; $aData['sDataEntryLanguage'] = $sDataEntryLanguage; $aData['site_url'] = Yii::app()->homeUrl; LimeExpressionManager::StartProcessingPage(true, Yii::app()->baseUrl); // means that all variables are on the same page $aViewUrls[] = 'caption_view'; Yii::app()->loadHelper('database'); // SURVEY NAME AND DESCRIPTION TO GO HERE $degquery = "SELECT * FROM {{groups}} WHERE sid={$surveyid} AND language='{$sDataEntryLanguage}' ORDER BY {{groups}}.group_order"; $degresult = dbExecuteAssoc($degquery); // GROUP NAME $aDataentryoutput = ''; foreach ($degresult->readAll() as $degrow) { LimeExpressionManager::StartProcessingGroup($degrow['gid'], $thissurvey['anonymized'] != "N", $surveyid); $deqquery = "SELECT * FROM {{questions}} WHERE sid={$surveyid} AND parent_qid=0 AND gid={$degrow['gid']} AND language='{$sDataEntryLanguage}'"; $deqrows = (array) dbExecuteAssoc($deqquery)->readAll(); $aDataentryoutput .= "\t<tr class='info'>\n" . "<!-- Inside controller dataentry.php -->" . "<td colspan='3'><h4>" . flattenText($degrow['group_name'], true) . "</h4></td>\n" . "\t</tr>\n"; $gid = $degrow['gid']; $aDataentryoutput .= "\t<tr class='data-entry-separator'><td colspan='3'></td></tr>\n"; // Perform a case insensitive natural sort on group name then question title of a multidimensional array usort($deqrows, 'groupOrderThenQuestionOrder'); $bgc = 'odd'; foreach ($deqrows as $deqrow) { $cdata = array(); $qidattributes = getQuestionAttributeValues($deqrow['qid']); $cdata['qidattributes'] = $qidattributes; $hidden = isset($qidattributes['hidden']) ? $qidattributes['hidden'] : 0; // TODO - can questions be hidden? Are JavaScript variables names used? Consistently with everywhere else? // LimeExpressionManager::ProcessRelevance($qidattributes['relevance'],$deqrow['qid'],NULL,$deqrow['type'],$hidden); // TMSW Condition->Relevance: Show relevance equation instead of conditions here - better yet, have data entry use survey-at-a-time but with different view $qinfo = LimeExpressionManager::GetQuestionStatus($deqrow['qid']); $relevance = trim($qinfo['info']['relevance']); $explanation = trim($qinfo['relEqn']); $validation = trim($qinfo['prettyValidTip']); $qidattributes = getQuestionAttributeValues($deqrow['qid']); $array_filter_help = flattenText($this->_array_filter_help($qidattributes, $sDataEntryLanguage, $surveyid)); if ($relevance != '' && $relevance != '1' || $validation != '' || $array_filter_help != '') { $showme = '<div class="alert alert-warning col-sm-8 col-sm-offset-2" role="alert">'; if ($bgc == "even") { $bgc = "odd"; } else { $bgc = "even"; } //Do no alternate on explanation row if ($relevance != '' && $relevance != '1') { $showme = '<strong>' . gT("Only answer this if the following conditions are met:", 'html', $sDataEntryLanguage) . "</strong><br />{$explanation}\n"; } if ($validation != '') { $showme .= '<strong>' . gT("The answer(s) must meet these validation criteria:", 'html', $sDataEntryLanguage) . "</strong><br />{$validation}\n"; } if ($showme != '' && $array_filter_help != '') { $showme .= '<br/>'; } if ($array_filter_help != '') { $showme .= '<strong>' . gT("The answer(s) must meet these array_filter criteria:", 'html', $sDataEntryLanguage) . "</strong><br />{$array_filter_help}\n"; } $showme .= '</div>'; $cdata['explanation'] = "<tr class ='data-entry-explanation'><td class='data-entry-small-text' colspan='3' align='left'>{$showme}</td></tr>\n"; } //END OF GETTING CONDITIONS //Alternate bgcolor for different groups if (!isset($bgc)) { $bgc = "even"; } if ($bgc == "even") { $bgc = "odd"; } else { $bgc = "even"; } $qid = $deqrow['qid']; $fieldname = "{$surveyid}" . "X" . "{$gid}" . "X" . "{$qid}"; $cdata['bgc'] = $bgc; $cdata['fieldname'] = $fieldname; $cdata['deqrow'] = $deqrow; $cdata['thissurvey'] = $thissurvey; if ($deqrow['help']) { $hh = addcslashes($deqrow['help'], "..'\""); //Escape ASCII decimal 0-32 plus single and double quotes to make JavaScript happy. $hh = htmlspecialchars($hh, ENT_QUOTES); //Change & " ' < > to HTML entities to make HTML happy. $cdata['hh'] = $hh; } switch ($deqrow['type']) { case "Q": //MULTIPLE SHORT TEXT //MULTIPLE SHORT TEXT case "K": $deaquery = "SELECT question,title FROM {{questions}} WHERE parent_qid={$deqrow['qid']} AND language='{$sDataEntryLanguage}' ORDER BY question_order"; $dearesult = dbExecuteAssoc($deaquery); $cdata['dearesult'] = $dearesult->readAll(); break; case "1": // multi scale^ $deaquery = "SELECT * FROM {{questions}} WHERE parent_qid={$deqrow['qid']} AND language='{$baselang}' ORDER BY question_order"; $dearesult = dbExecuteAssoc($deaquery); $cdata['dearesult'] = $dearesult->readAll(); $oquery = "SELECT other FROM {{questions}} WHERE qid={$deqrow['qid']} AND language='{$baselang}'"; $oresult = dbExecuteAssoc($oquery) or safeDie("Couldn't get other for list question<br />" . $oquery); foreach ($oresult->readAll() as $orow) { $cdata['fother'] = $orow['other']; } break; case "L": //LIST drop-down/radio-button list //LIST drop-down/radio-button list case "!": // $qidattributes=getQuestionAttributeValues($deqrow['qid']); if ($deqrow['type'] == '!' && trim($qidattributes['category_separator']) != '') { $optCategorySeparator = $qidattributes['category_separator']; } else { unset($optCategorySeparator); } $defexists = ""; $deaquery = "SELECT * FROM {{answers}} WHERE qid={$deqrow['qid']} AND language='{$sDataEntryLanguage}' ORDER BY sortorder, answer"; $dearesult = dbExecuteAssoc($deaquery); //$aDataentryoutput .= "\t<select name='$fieldname' class='form-control' >\n"; $aDatatemp = ''; if (!isset($optCategorySeparator)) { foreach ($dearesult->readAll() as $dearow) { $aDatatemp .= "<option value='{$dearow['code']}'"; //if ($dearow['default_value'] == "Y") {$aDatatemp .= " selected='selected'"; $defexists = "Y";} $aDatatemp .= ">{$dearow['answer']}</option>\n"; } } else { $defaultopts = array(); $optgroups = array(); foreach ($dearesult->readAll() as $dearow) { list($categorytext, $answertext) = explode($optCategorySeparator, $dearow['answer']); if ($categorytext == '') { $defaultopts[] = array('code' => $dearow['code'], 'answer' => $answertext, 'default_value' => $dearow['assessment_value']); } else { $optgroups[$categorytext][] = array('code' => $dearow['code'], 'answer' => $answertext, 'default_value' => $dearow['assessment_value']); } } foreach ($optgroups as $categoryname => $optionlistarray) { $aDatatemp .= "<optgroup class=\"dropdowncategory\" label=\"" . $categoryname . "\">\n"; foreach ($optionlistarray as $optionarray) { $aDatatemp .= "\t<option value='{$optionarray['code']}'"; //if ($optionarray['default_value'] == "Y") {$aDatatemp .= " selected='selected'"; $defexists = "Y";} $aDatatemp .= ">{$optionarray['answer']}</option>\n"; } $aDatatemp .= "</optgroup>\n"; } foreach ($defaultopts as $optionarray) { $aDatatemp .= "\t<option value='{$optionarray['code']}'"; //if ($optionarray['default_value'] == "Y") {$aDatatemp .= " selected='selected'"; $defexists = "Y";} $aDatatemp .= ">{$optionarray['answer']}</option>\n"; } } $oquery = "SELECT other FROM {{questions}} WHERE qid={$deqrow['qid']} AND language='{$sDataEntryLanguage}'"; $oresult = dbExecuteAssoc($oquery) or safeDie("Couldn't get other for list question<br />"); foreach ($oresult->readAll() as $orow) { $fother = $orow['other']; } $cdata['fother'] = $fother; $cdata['defexists'] = $defexists; $cdata['datatemp'] = $aDatatemp; break; case "O": //LIST WITH COMMENT drop-down/radio-button list + textarea $defexists = ""; $deaquery = "SELECT * FROM {{answers}} WHERE qid={$deqrow['qid']} AND language='{$sDataEntryLanguage}' ORDER BY sortorder, answer"; $dearesult = dbExecuteAssoc($deaquery); //$aDataentryoutput .= "\t<select name='$fieldname'>\n"; $aDatatemp = ''; foreach ($dearesult->readAll() as $dearow) { $aDatatemp .= "<option value='{$dearow['code']}'"; //if ($dearow['default_value'] == "Y") {$aDatatemp .= " selected='selected'"; $defexists = "Y";} $aDatatemp .= ">{$dearow['answer']}</option>\n"; } $cdata['datatemp'] = $aDatatemp; $cdata['defexists'] = $defexists; break; case "R": //RANKING TYPE QUESTION $thisqid = $deqrow['qid']; $ansquery = "SELECT * FROM {{answers}} WHERE qid={$thisqid} AND language='{$sDataEntryLanguage}' ORDER BY sortorder, answer"; $ansresult = dbExecuteAssoc($ansquery); $ansresult = $ansresult->readAll(); $anscount = count($ansresult); $cdata['thisqid'] = $thisqid; $cdata['anscount'] = $anscount; $ansresult = Yii::app()->db->createCommand($ansquery)->query()->readAll(); //Checked $anscount = count($ansresult); $answers = array(); foreach ($ansresult as $ansrow) { $answers[] = $ansrow; } $cdata['answers'] = $answers; App()->getClientScript()->registerPackage('jquery-actual'); $this->registerScriptFile('SCRIPT_PATH', 'ranking.js'); $this->registerCssFile('PUBLIC', 'ranking.css'); unset($answers); break; case "M": //Multiple choice checkbox (Quite tricky really!) if (trim($qidattributes['display_columns']) != '') { $dcols = $qidattributes['display_columns']; } else { $dcols = 0; } $meaquery = "SELECT title, question FROM {{questions}} WHERE parent_qid={$deqrow['qid']} AND language='{$sDataEntryLanguage}' ORDER BY question_order"; $mearesult = dbExecuteAssoc($meaquery); $cdata['mearesult'] = $mearesult->readAll(); $meacount = count($cdata['mearesult']); $cdata['meacount'] = $meacount; $cdata['dcols'] = $dcols; break; case "I": //Language Switch $slangs = Survey::model()->findByPk($surveyid)->additionalLanguages; $sbaselang = Survey::model()->findByPk($surveyid)->language; array_unshift($slangs, $sbaselang); $cdata['slangs'] = $slangs; break; case "P": //Multiple choice with comments checkbox + text //$aDataentryoutput .= "<table border='0'>\n"; $meaquery = "SELECT * FROM {{questions}} WHERE parent_qid={$deqrow['qid']} AND language='{$sDataEntryLanguage}' ORDER BY question_order, question"; $mearesult = dbExecuteAssoc($meaquery); $cdata['mearesult'] = $mearesult->readAll(); break; case "|": // $qidattributes = getQuestionAttributeValues($deqrow['qid']); $cdata['qidattributes'] = $qidattributes; $maxfiles = $qidattributes['max_num_of_files']; $cdata['maxfiles'] = $maxfiles; break; case "A": //ARRAY (5 POINT CHOICE) radio-buttons $meaquery = "SELECT title, question FROM {{questions}} WHERE parent_qid={$deqrow['qid']} AND language='{$sDataEntryLanguage}' ORDER BY question_order"; $mearesult = dbExecuteAssoc($meaquery); $cdata['mearesult'] = $mearesult->readAll(); break; case "B": //ARRAY (10 POINT CHOICE) radio-buttons $meaquery = "SELECT title, question FROM {{questions}} WHERE parent_qid={$deqrow['qid']} AND language='{$sDataEntryLanguage}' ORDER BY question_order"; $mearesult = dbExecuteAssoc($meaquery); $cdata['mearesult'] = $mearesult->readAll(); case "C": //ARRAY (YES/UNCERTAIN/NO) radio-buttons $meaquery = "SELECT title, question FROM {{questions}} WHERE parent_qid={$deqrow['qid']} AND language='{$sDataEntryLanguage}' ORDER BY question_order"; $mearesult = dbExecuteAssoc($meaquery); $cdata['mearesult'] = $mearesult->readAll(); break; case "E": //ARRAY (YES/UNCERTAIN/NO) radio-buttons $meaquery = "SELECT title, question FROM {{questions}} WHERE parent_qid={$deqrow['qid']} AND language='{$sDataEntryLanguage}' ORDER BY question_order"; $mearesult = dbExecuteAssoc($meaquery) or safeDie("Couldn't get answers, Type \"E\"<br />{$meaquery}<br />"); $cdata['mearesult'] = $mearesult->readAll(); break; case ":": //ARRAY (Multi Flexi) // $qidattributes=getQuestionAttributeValues($deqrow['qid']); $minvalue = 1; $maxvalue = 10; if (trim($qidattributes['multiflexible_max']) != '' && trim($qidattributes['multiflexible_min']) == '') { $maxvalue = $qidattributes['multiflexible_max']; $minvalue = 1; } if (trim($qidattributes['multiflexible_min']) != '' && trim($qidattributes['multiflexible_max']) == '') { $minvalue = $qidattributes['multiflexible_min']; $maxvalue = $qidattributes['multiflexible_min'] + 10; } if (trim($qidattributes['multiflexible_min']) != '' && trim($qidattributes['multiflexible_max']) != '') { if ($qidattributes['multiflexible_min'] < $qidattributes['multiflexible_max']) { $minvalue = $qidattributes['multiflexible_min']; $maxvalue = $qidattributes['multiflexible_max']; } } if (trim($qidattributes['multiflexible_step']) != '') { $stepvalue = $qidattributes['multiflexible_step']; } else { $stepvalue = 1; } if ($qidattributes['multiflexible_checkbox'] != 0) { $minvalue = 0; $maxvalue = 1; $stepvalue = 1; } $cdata['minvalue'] = $minvalue; $cdata['maxvalue'] = $maxvalue; $cdata['stepvalue'] = $stepvalue; $lquery = "SELECT question, title FROM {{questions}} WHERE parent_qid={$deqrow['qid']} and scale_id=1 and language='{$sDataEntryLanguage}' ORDER BY question_order"; $lresult = dbExecuteAssoc($lquery) or die("Couldn't get labels, Type \":\"<br />{$lquery}<br />"); $lresult = dbExecuteAssoc($lquery); if (!$lresult) { $eMessage = "Couldn't get labels, Type \":\"<br />{$lquery}<br />"; Yii::app()->setFlashMessage($eMessage); $this->getController()->redirect($this->getController()->createUrl("/admin/")); } $cdata['lresult'] = $lresult->readAll(); $meaquery = "SELECT question, title FROM {{questions}} WHERE parent_qid={$deqrow['qid']} and scale_id=0 and language='{$sDataEntryLanguage}' ORDER BY question_order"; $mearesult = dbExecuteAssoc($meaquery); if (!$mearesult) { $eMessage = "Couldn't get answers, Type \":\"<br />{$meaquery}<br />"; Yii::app()->setFlashMessage($eMessage); $this->getController()->redirect($this->getController()->createUrl("/admin/")); } $cdata['mearesult'] = $mearesult->readAll(); break; case ";": //ARRAY (Multi Flexi) $lquery = "SELECT * FROM {{questions}} WHERE scale_id=1 and parent_qid={$deqrow['qid']} and language='{$sDataEntryLanguage}' ORDER BY question_order"; $lresult = dbExecuteAssoc($lquery) or die("Couldn't get labels, Type \":\"<br />{$lquery}<br />"); $cdata['lresult'] = $lresult->readAll(); $meaquery = "SELECT * FROM {{questions}} WHERE scale_id=0 and parent_qid={$deqrow['qid']} and language='{$sDataEntryLanguage}' ORDER BY question_order"; $mearesult = dbExecuteAssoc($meaquery) or die("Couldn't get answers, Type \":\"<br />{$meaquery}<br />"); $cdata['mearesult'] = $mearesult->readAll(); break; case "F": //ARRAY (Flexible Labels) //ARRAY (Flexible Labels) case "H": $meaquery = "SELECT * FROM {{questions}} WHERE parent_qid={$deqrow['qid']} and language='{$sDataEntryLanguage}' ORDER BY question_order"; $mearesult = dbExecuteAssoc($meaquery) or safeDie("Couldn't get answers, Type \"E\"<br />{$meaquery}<br />"); $cdata['mearesult'] = $mearesult->readAll(); $fquery = "SELECT * FROM {{answers}} WHERE qid={$deqrow['qid']} and language='{$sDataEntryLanguage}' ORDER BY sortorder, code"; $fresult = dbExecuteAssoc($fquery); $cdata['fresult'] = $fresult->readAll(); break; } $cdata['sDataEntryLanguage'] = $sDataEntryLanguage; $viewdata = $this->getController()->renderPartial("/admin/dataentry/content_view", $cdata, TRUE); $viewdata_em = LimeExpressionManager::ProcessString($viewdata, $deqrow['qid'], NULL, false, 1, 1); $aDataentryoutput .= $viewdata_em; } LimeExpressionManager::FinishProcessingGroup(); } LimeExpressionManager::FinishProcessingPage(); $aDataentryoutput .= LimeExpressionManager::GetRelevanceAndTailoringJavaScript(); $aViewUrls['output'] = $aDataentryoutput; $aData['thissurvey'] = $thissurvey; $aData['surveyid'] = $surveyid; $aData['sDataEntryLanguage'] = $sDataEntryLanguage; if ($thissurvey['active'] == "Y" && $thissurvey['allowsave'] == "Y") { $slangs = Survey::model()->findByPk($surveyid)->additionalLanguages; $sbaselang = Survey::model()->findByPk($surveyid)->language; array_unshift($slangs, $sbaselang); $aData['slangs'] = $slangs; $aData['baselang'] = $baselang; } $aViewUrls[] = 'active_html_view'; $aData['sidemenu']['state'] = false; $aData['menu']['edition'] = true; $aData['menu']['save'] = true; $aData['menu']['close'] = true; $this->_renderWrappedTemplate('dataentry', $aViewUrls, $aData); } }
/** * Used in frontend helper, buildsurveysession. * @todo Rename * @param int $surveyid * @return array|false??? Return from CDbDataReader::read() */ public static function getNumberOfQuestions($surveyid) { return 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(); }
function do_array_dual($ia) { global $thissurvey; global $notanswered; $repeatheadings = Yii::app()->getConfig("repeatheadings"); $minrepeatheadings = Yii::app()->getConfig("minrepeatheadings"); $extraclass = ""; $answertypeclass = ""; // Maybe not $clang = Yii::app()->lang; $checkconditionFunction = "checkconditions"; $inputnames = array(); $labelans1 = array(); $labelans = array(); $qquery = "SELECT other FROM {{questions}} WHERE qid=" . $ia[0] . " AND language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "'"; $other = dbExecuteAssoc($qquery)->read(); $other = reset($other); //Checked $lquery = "SELECT * FROM {{answers}} WHERE scale_id=0 AND qid={$ia[0]} AND language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "' ORDER BY sortorder, code"; $lquery1 = "SELECT * FROM {{answers}} WHERE scale_id=1 AND qid={$ia[0]} AND language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "' ORDER BY sortorder, code"; $aQuestionAttributes = getQuestionAttributeValues($ia[0], $ia[4]); if ($aQuestionAttributes['use_dropdown'] == 1) { $useDropdownLayout = true; $extraclass .= " dropdown-list"; $answertypeclass .= " dropdown"; } else { $useDropdownLayout = false; $extraclass .= " radio-list"; $answertypeclass .= " radio"; } if (ctype_digit(trim($aQuestionAttributes['repeat_headings'])) && trim($aQuestionAttributes['repeat_headings'] != "")) { $repeatheadings = intval($aQuestionAttributes['repeat_headings']); $minrepeatheadings = 0; } if (trim($aQuestionAttributes['dualscale_headerA'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']]) != '') { $leftheader = $clang->gT($aQuestionAttributes['dualscale_headerA'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']]); } else { $leftheader = ''; } if (trim($aQuestionAttributes['dualscale_headerB'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']]) != '') { $rightheader = $clang->gT($aQuestionAttributes['dualscale_headerB'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']]); } else { $rightheader = ''; } $lresult = dbExecuteAssoc($lquery); //Checked $aAnswersScale1 = $lresult->readAll(); if ($useDropdownLayout === false && count($aAnswersScale1) > 0) { if (trim($aQuestionAttributes['answer_width']) != '') { $answerwidth = $aQuestionAttributes['answer_width']; } else { $answerwidth = 20; } $columnswidth = 100 - $answerwidth; foreach ($aAnswersScale1 as $lrow) { $labelans[] = $lrow['answer']; $labelcode[] = $lrow['code']; } $lresult1 = dbExecuteAssoc($lquery1); //Checked foreach ($lresult1->readAll() as $lrow1) { $labelans1[] = $lrow1['answer']; $labelcode1[] = $lrow1['code']; } $numrows = count($labelans) + count($labelans1); if ($ia[6] != "Y" && SHOW_NO_ANSWER == 1) { $numrows++; } $cellwidth = $columnswidth / $numrows; $cellwidth = sprintf("%02d", $cellwidth); $sQuery = "SELECT count(question) FROM {{questions}} WHERE parent_qid=" . $ia[0] . " and scale_id=0 AND question like '%|%'"; $iCount = Yii::app()->db->createCommand($sQuery)->queryScalar(); $right_exists = $iCount > 0; // $right_exists is a flag to find out if there are any right hand answer parts. If there aren't we can leave out the right td column if ($aQuestionAttributes['random_order'] == 1) { $ansquery = "SELECT * FROM {{questions}} WHERE parent_qid={$ia['0']} AND language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "' and scale_id=0 ORDER BY " . dbRandom(); } else { $ansquery = "SELECT * FROM {{questions}} WHERE parent_qid={$ia['0']} AND language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "' and scale_id=0 ORDER BY question_order"; } $ansresult = dbExecuteAssoc($ansquery); //Checked $aQuestionsRight = $ansresult->readAll(); $anscount = count($aQuestionsRight); $fn = 1; // unselect second scale when using "no answer" $answer = "<script type='text/javascript'>\n" . "<!--\n" . "function noanswer_checkconditions(value, name, type)\n" . "{\n" . "\tvar vname;\n" . "\tvname = name.replace(/#.*\$/,\"\");\n" . "\t\$('input[name^=\"' + vname + '\"]').attr('checked',false);\n" . "\t\$('input[id=\"answer' + vname + '#0-\"]').attr('checked',true);\n" . "\t\$('input[name^=\"java' + vname + '\"]').val('');\n" . "\t{$checkconditionFunction}(value, name, type);\n" . "}\n" . "function secondlabel_checkconditions(value, name, type)\n" . "{\n" . "\tvar vname;\n" . "\tvname = \"answer\"+name.replace(/#1/g,\"#0-\");\n" . "\tif(document.getElementById(vname))\n" . "\t{\n" . "\tdocument.getElementById(vname).checked=false;\n" . "\t}\n" . "\t{$checkconditionFunction}(value, name, type);\n" . "}\n" . " //-->\n" . " </script>\n"; // Header row and colgroups $mycolumns = "\t<colgroup class=\"col-responses group-1\">\n" . "\t<col class=\"col-answers\" width=\"{$answerwidth}%\" />\n"; $answer_head_line = "\t<th class=\"header_answer_text\"> </th>\n\n"; $odd_even = ''; foreach ($labelans as $ld) { $answer_head_line .= "\t<th>" . $ld . "</th>\n"; $odd_even = alternation($odd_even); $mycolumns .= "<col class=\"{$odd_even}\" width=\"{$cellwidth}%\" />\n"; } $mycolumns .= "\t</colgroup>\n"; if (count($labelans1) > 0) { $mycolumns .= "\t<colgroup class=\"col-responses group-2\">\n" . "\t<col class=\"seperator\" />\n"; $answer_head_line .= "\n\t<td class=\"header_separator\"> </td>\n\n"; // Separator foreach ($labelans1 as $ld) { $answer_head_line .= "\t<th>" . $ld . "</th>\n"; $odd_even = alternation($odd_even); $mycolumns .= "<col class=\"{$odd_even}\" width=\"{$cellwidth}%\" />\n"; } } if ($right_exists) { $answer_head_line .= "\t<td class=\"header_answer_text_right\"> </td>\n"; $mycolumns .= "\n\t<col class=\"answertextright\" />\n\n"; } if ($ia[6] != 'Y' && SHOW_NO_ANSWER == 1) { $answer_head_line .= "\t<td class=\"header_separator\"> </td>\n"; // Separator $answer_head_line .= "\t<th class=\"header_no_answer\">" . $clang->gT('No answer') . "</th>\n"; $odd_even = alternation($odd_even); $mycolumns .= "\n\t<col class=\"seperator\" />\n\n"; $mycolumns .= "\t<col class=\"col-no-answer {$odd_even}\" width=\"{$cellwidth}%\" />\n"; } $mycolumns .= "\t</colgroup>\n"; $answer_head2 = "\n<tr class=\"array1 header_row\">\n" . $answer_head_line . "</tr>\n"; // build first row of header if needed if ($leftheader != '' || $rightheader != '') { $answer_head1 = "<tr class=\"array1 groups header_row\">\n" . "\t<th class=\"header_answer_text\"> </th>\n" . "\t<th colspan=\"" . count($labelans) . "\" class=\"dsheader\">{$leftheader}</th>\n"; if (count($labelans1) > 0) { $answer_head1 .= "\t<td class=\"header_separator\"> </td>\n" . "\t<th colspan=\"" . count($labelans1) . "\" class=\"dsheader\">{$rightheader}</th>\n"; } if ($right_exists) { $answer_head1 .= "\t<td class=\"header_answer_text_right\"> </td>\n"; } if ($ia[6] != 'Y' && SHOW_NO_ANSWER == 1) { $answer_head1 .= "\t<td class=\"header_separator\"> </td>\n"; // Separator $answer_head1 .= "\t<th class=\"header_no_answer\"> </th>\n"; } $answer_head1 .= "</tr>\n"; } else { $answer_head1 = ''; } $answer .= "\n<table class=\"question subquestions-list questions-list\" summary=\"" . str_replace('"', '', strip_tags($ia[3])) . " - a dual array type question\">\n" . $mycolumns . "\n\t<thead>\n" . $answer_head1 . $answer_head2 . "\n\t</thead>\n" . "<tbody>\n"; $trbc = ''; foreach ($aQuestionsRight as $ansrow) { // Build repeat headings if needed if (isset($repeatheadings) && $repeatheadings > 0 && $fn - 1 > 0 && ($fn - 1) % $repeatheadings == 0) { if ($anscount - $fn + 1 >= $minrepeatheadings) { $answer .= "</tbody>\n<tbody>"; // Close actual body and open another one //$answer .= $answer_head1; $answer .= "\n<tr class=\"repeat headings\">\n" . $answer_head_line . "</tr>\n"; } } $trbc = alternation($trbc, 'row'); $answertext = dTexts__run($ansrow['question']); $answertextsave = $answertext; $dualgroup = 0; $myfname0 = $ia[1] . $ansrow['title']; $myfname = $ia[1] . $ansrow['title'] . '#0'; $myfname1 = $ia[1] . $ansrow['title'] . '#1'; // new multi-scale-answer /* Check if this item has not been answered: the 'notanswered' variable must be an array, containing a list of unanswered questions, the current question must be in the array, and there must be no answer available for the item in this session. */ if ($ia[6] == 'Y' && is_array($notanswered) && (array_search($myfname, $notanswered) !== FALSE || array_search($myfname1, $notanswered) !== FALSE) && ($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname] == '' || $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname1] == '')) { $answertext = "<span class='errormandatory'>{$answertext}</span>"; } // Get array_filter stuff list($htmltbody2, $hiddenfield) = return_array_filter_strings($ia, $aQuestionAttributes, $thissurvey, $ansrow, $myfname0, $trbc, $myfname, "tr", "{$trbc} answers-list radio-list"); $answer .= $htmltbody2; if (strpos($answertext, '|')) { $answertext = substr($answertext, 0, strpos($answertext, '|')); } array_push($inputnames, $myfname); $answer .= "\t<th class=\"answertext\">\n" . $hiddenfield . "{$answertext}\n" . "<input type=\"hidden\" name=\"java{$myfname}\" id=\"java{$myfname}\" value=\""; if (isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname])) { $answer .= $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname]; } $answer .= "\" />\n\t</th>\n"; $hiddenanswers = ''; $thiskey = 0; foreach ($labelcode as $ld) { $answer .= "\t<td class=\"answer_cell_1_00{$ld} answer-item {$answertypeclass}-item\">\n" . "<label for=\"answer{$myfname}-{$ld}\">\n" . "\t<input class=\"radio\" type=\"radio\" name=\"{$myfname}\" value=\"{$ld}\" id=\"answer{$myfname}-{$ld}\" title=\"" . HTMLEscape(strip_tags($labelans[$thiskey])) . '"'; if (isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname]) && $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname] == $ld) { $answer .= CHECKED; } // --> START NEW FEATURE - SAVE $answer .= " onclick=\"{$checkconditionFunction}(this.value, this.name, this.type)\" />\n</label>\n"; // --> END NEW FEATURE - SAVE $answer .= "\n\t</td>\n"; $thiskey++; } if (count($labelans1) > 0) { $dualgroup++; $hiddenanswers = ''; $answer .= "\t<td class=\"dual_scale_separator information-item\"> </td>\n"; // separator array_push($inputnames, $myfname1); $hiddenanswers .= "<input type=\"hidden\" name=\"java{$myfname1}\" id=\"java{$myfname1}\" value=\""; if (isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname1])) { $hiddenanswers .= $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname1]; } $hiddenanswers .= "\" />\n"; $thiskey = 0; foreach ($labelcode1 as $ld) { $answer .= "\t<td class=\"answer_cell_2_00{$ld} answer-item radio-item\">\n"; if ($hiddenanswers != '') { $answer .= $hiddenanswers; $hiddenanswers = ''; } $answer .= "<label for=\"answer{$myfname1}-{$ld}\">\n" . "\t<input class=\"radio\" type=\"radio\" name=\"{$myfname1}\" value=\"{$ld}\" id=\"answer{$myfname1}-{$ld}\" title=\"" . HTMLEscape(strip_tags($labelans1[$thiskey])) . '"'; if (isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname1]) && $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname1] == $ld) { $answer .= CHECKED; } // --> START NEW FEATURE - SAVE $answer .= " onclick=\"secondlabel_checkconditions(this.value, this.name, this.type)\" />\n</label>\n"; // --> END NEW FEATURE - SAVE $answer .= "\t</td>\n"; $thiskey++; } } if (strpos($answertextsave, '|')) { $answertext = substr($answertextsave, strpos($answertextsave, '|') + 1); $answer .= "\t<td class=\"answertextright\">{$answertext}</td>\n"; $hiddenanswers = ''; } elseif ($right_exists) { $answer .= "\t<td class=\"answertextright\"> </td>\n"; } if ($ia[6] != "Y" && SHOW_NO_ANSWER == 1) { $answer .= "\t<td class=\"dual_scale_separator information-item\"> </td>\n"; // separator $answer .= "\t<td class=\"dual_scale_no_answer answer-item radio-item noanswer-item\">\n" . "<label for='answer{$myfname}-'>\n" . "\t<input class='radio' type='radio' name='{$myfname}' value='' id='answer{$myfname}-' title='" . $clang->gT("No answer") . "'"; if (!isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname]) || $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname] == "") { $answer .= CHECKED; } // --> START NEW FEATURE - SAVE $answer .= " onclick=\"noanswer_checkconditions(this.value, this.name, this.type)\" />\n" . "</label>\n" . "\t</td>\n"; // --> END NEW FEATURE - SAVE } $answer .= "</tr>\n"; // $inputnames[]=$myfname; //IF a MULTIPLE of flexi-redisplay figure, repeat the headings $fn++; } $answer .= "\t</tbody>\n"; $answer .= "</table>\n"; } elseif ($useDropdownLayout === true && count($aAnswersScale1) > 0) { if (trim($aQuestionAttributes['answer_width']) != '') { $answerwidth = $aQuestionAttributes['answer_width']; } else { $answerwidth = 20; } $separatorwidth = (100 - $answerwidth) / 10; $columnswidth = 100 - $answerwidth - $separatorwidth * 2; $answer = ""; // Get Answers //question atribute random_order set? if ($aQuestionAttributes['random_order'] == 1) { $ansquery = "SELECT * FROM {{questions}} WHERE parent_qid={$ia['0']} and scale_id=0 AND language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "' ORDER BY " . dbRandom(); } else { $ansquery = "SELECT * FROM {{questions}} WHERE parent_qid={$ia['0']} and scale_id=0 AND language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "' ORDER BY question_order"; } $ansresult = dbExecuteAssoc($ansquery); $aSubquestions = $ansresult->readAll(); //Checked $anscount = count($aSubquestions); if ($anscount == 0) { $inputnames = array(); $answer .= "\n<p class=\"error\">" . $clang->gT('Error: This question has no answers.') . "</p>\n"; } else { //already done $lresult = dbExecuteAssoc($lquery); foreach ($aAnswersScale1 as $lrow) { $labels0[] = array('code' => $lrow['code'], 'title' => $lrow['answer']); } $lresult1 = dbExecuteAssoc($lquery1); //Checked foreach ($lresult1->readAll() as $lrow1) { $labels1[] = array('code' => $lrow1['code'], 'title' => $lrow1['answer']); } // Get attributes for Headers and Prefix/Suffix if (trim($aQuestionAttributes['dropdown_prepostfix'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']]) != '') { list($ddprefix, $ddsuffix) = explode("|", $aQuestionAttributes['dropdown_prepostfix'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']]); $ddprefix = $ddprefix; $ddsuffix = $ddsuffix; } else { $ddprefix = ''; $ddsuffix = ''; } if (trim($aQuestionAttributes['dropdown_separators']) != '') { list($postanswSep, $interddSep) = explode('|', $aQuestionAttributes['dropdown_separators']); $postanswSep = $postanswSep; $interddSep = $interddSep; } else { $postanswSep = ''; $interddSep = ''; } $colspan_1 = ''; $colspan_2 = ''; $suffix_cell = ''; $answer .= "\n<table class=\"question subquestion-list questions-list dropdown-list\" summary=\"" . str_replace('"', '', strip_tags($ia[3])) . " - an dual array type question\">\n\n" . "\t<col class=\"answertext\" width=\"{$answerwidth}%\" />\n"; if ($ddprefix != '') { $answer .= "\t<col class=\"ddprefix\" />\n"; $colspan_1 = ' colspan="2"'; } $answer .= "\t<col class=\"dsheader\" />\n"; if ($ddsuffix != '') { $answer .= "\t<col class=\"ddsuffix\" />\n"; if (!empty($colspan_1)) { $colspan_2 = ' colspan="3"'; } $suffix_cell = "\t<td> </td>\n"; // suffix } $answer .= "\t<col class=\"ddarrayseparator\" width=\"{$separatorwidth}%\" />\n"; if ($ddprefix != '') { $answer .= "\t<col class=\"ddprefix\" />\n"; } $answer .= "\t<col class=\"dsheader\" />\n"; if ($ddsuffix != '') { $answer .= "\t<col class=\"ddsuffix\" />\n"; } // headers $answer .= "\n\t<thead>\n" . "<tr>\n" . "\t<td{$colspan_1}> </td>\n" . "\n" . "\t<th>{$leftheader}</th>\n" . "\n" . "\t<td{$colspan_2}> </td>\n" . "\t<th>{$rightheader}</th>\n" . $suffix_cell . "</tr>\n" . "\t</thead>\n\n"; $answer .= "\n<tbody>\n"; $trbc = ''; foreach ($aSubquestions as $ansrow) { $rowname = $ia[1] . $ansrow['title']; $dualgroup = 0; $myfname = $ia[1] . $ansrow['title'] . "#" . $dualgroup; $dualgroup1 = 1; $myfname1 = $ia[1] . $ansrow['title'] . "#" . $dualgroup1; if ($ia[6] == 'Y' && is_array($notanswered) && (array_search($myfname, $notanswered) !== FALSE || array_search($myfname1, $notanswered) !== FALSE) && ($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname] == '' || $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname1] == '')) { $answertext = "<span class='errormandatory'>" . dTexts__run($ansrow['question']) . "</span>"; } else { $answertext = dTexts__run($ansrow['question']); } $trbc = alternation($trbc, 'row'); // Get array_filter stuff list($htmltbody2, $hiddenfield) = return_array_filter_strings($ia, $aQuestionAttributes, $thissurvey, $ansrow, $rowname, $trbc, $myfname, "tr", "{$trbc} subquestion-list questions-list dropdown-list"); $answer .= $htmltbody2; $answer .= "\t<th class=\"answertext\">\n" . "<label for=\"answer{$rowname}\">\n" . $hiddenfield . "{$answertext}\n" . "</label>\n" . "\t</th>\n"; // Label0 // prefix if ($ddprefix != '') { $answer .= "\t<td class=\"ddprefix information-item\">{$ddprefix}</td>\n"; } $answer .= "\t<td class=\"answer-item dropdown-item\">\n" . "<select name=\"{$myfname}\" id=\"answer{$myfname}\" onchange=\"array_dual_dd_checkconditions(this.value, this.name, this.type,{$dualgroup},{$checkconditionFunction});\">\n"; if (!isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname]) || $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname] == '') { $answer .= "\t<option value=\"\" " . SELECTED . '>' . $clang->gT('Please choose...') . "</option>\n"; } foreach ($labels0 as $lrow) { $answer .= "\t<option value=\"" . $lrow['code'] . '" '; if (isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname]) && $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname] == $lrow['code']) { $answer .= SELECTED; } $answer .= '>' . flattenText($lrow['title']) . "</option>\n"; } // If not mandatory and showanswer, show no ans if ($ia[6] != 'Y' && SHOW_NO_ANSWER == 1) { $answer .= "\t<option class=\"noanswer-item\" value=\"\" "; if (!isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname]) || $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname] == '') { $answer .= SELECTED; } $answer .= '>' . $clang->gT('No answer') . "</option>\n"; } $answer .= "</select>\n"; // suffix if ($ddsuffix != '') { $answer .= "\t<td class=\"ddsuffix information-item\">{$ddsuffix}</td>\n"; } $answer .= "<input type=\"hidden\" name=\"java{$myfname}\" id=\"java{$myfname}\" value=\""; if (isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname])) { $answer .= $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname]; } $answer .= "\" />\n" . "\t</td>\n"; $inputnames[] = $myfname; $answer .= "\t<td class=\"ddarrayseparator information-item\">{$interddSep}</td>\n"; //Separator // Label1 // prefix if ($ddprefix != '') { $answer .= "\t<td class='ddprefix information-item'>{$ddprefix}</td>\n"; } // $answer .= "\t<td align='left' width='$columnswidth%'>\n" $answer .= "\t<td class=\"answer-item dropdown-item\">\n" . "<select name=\"{$myfname1}\" id=\"answer{$myfname1}\" onchange=\"array_dual_dd_checkconditions(this.value, this.name, this.type,{$dualgroup1},{$checkconditionFunction});\">\n"; if (empty($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname])) { $answer .= "\t<option value=\"\"" . SELECTED . '>' . $clang->gT('Please choose...') . "</option>\n"; } foreach ($labels1 as $lrow1) { $answer .= "\t<option value=\"" . $lrow1['code'] . '" '; if (isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname1]) && $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname1] == $lrow1['code']) { $answer .= SELECTED; } $answer .= '>' . flattenText($lrow1['title']) . "</option>\n"; } // If not mandatory and showanswer, show no ans if ($ia[6] != 'Y' && SHOW_NO_ANSWER == 1) { $answer .= "\t<option class=\"noanswer-item\" value='' "; if (empty($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname])) { $answer .= SELECTED; } $answer .= ">" . $clang->gT('No answer') . "</option>\n"; } $answer .= "</select>\n"; // suffix if ($ddsuffix != '') { $answer .= "\t<td class=\"ddsuffix information-item\">{$ddsuffix}</td>\n"; } $answer .= "<input type=\"hidden\" name=\"java{$myfname1}\" id=\"java{$myfname1}\" value=\""; if (isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname1])) { $answer .= $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname1]; } $answer .= "\" />\n" . "\t</td>\n"; $inputnames[] = $myfname1; $answer .= "</tr>\n"; } } // End there are answers $answer .= "\t</tbody>\n"; $answer .= "</table>\n"; } else { $answer = "<p class='error'>" . $clang->gT("Error: There are no answer options for this question and/or they don't exist in this language.") . "</p>\n"; $inputnames = ""; } return array($answer, $inputnames); }
/** * savesilent() saves survey responses when the "Resume later" button * is press but has no interaction. i.e. it does not ask for email, * username or password or capture. * * @return string confirming successful save. */ function savedsilent() { global $surveyid, $thissurvey, $errormsg, $publicurl, $sitename, $timeadjust, $clang, $clienttoken, $thisstep; submitanswer(); // Prepare email $tokenentryquery = 'SELECT * from {{tokens_' . $surveyid . '}} WHERE token=\'' . sanitize_paranoid_string($clienttoken) . '\';'; $tokenentryresult = dbExecuteAssoc($tokenentryquery); $tokenentryarray = $tokenentryresult->read(); $from = $thissurvey['adminname'] . ' <' . $thissurvey['adminemail'] . '>'; $to = $tokenentryarray['firstname'] . ' ' . $tokenentryarray['lastname'] . ' <' . $tokenentryarray['email'] . '>'; $subject = $clang->gT("Saved Survey Details") . " - " . $thissurvey['name']; $message = $clang->gT("Thank you for saving your survey in progress. You can return to the survey at the same point you saved it at any time using the link from this or any previous email sent to regarding this survey.") . "\n\n"; $message .= $clang->gT("Reload your survey by clicking on the following link (or pasting it into your browser):") . ":\n"; $language = $tokenentryarray['language']; //$message .= "\n\n$publicurl/$surveyid/lang-$language/tk-$clienttoken"; $message .= "\n\n" . Yii::app()->getController()->createAbsoluteUrl("/survey/index/sid/{$surveyid}/lang/{$language}/token/{$clienttoken}"); if (SendEmailMessage($message, $subject, $to, $from, $sitename, false, getBounceEmail($surveyid))) { $emailsent = "Y"; } else { $clang->eT('Error: Email failed, this may indicate a PHP Mail Setup problem on your server. Your survey details have still been saved, however you will not get an email with the details. You should note the "name" and "password" you just used for future reference.'); if (trim($thissurvey['adminemail']) == '') { $clang->eT('(Reason: Admin email address empty)'); } } return $clang->gT('Your survey was successfully saved.'); }
</th> <th><?php $clang->eT("Answer option"); ?> </th> <th><?php $clang->eT("Actions"); ?> </th> </tr></thead> <tbody> <?php $alternate = true; $query = "SELECT * FROM {{answers}} WHERE qid='{$qid}' AND language='{$anslang}' and scale_id={$scale_id} ORDER BY sortorder, code"; $result = dbExecuteAssoc($query); $aResults = $result->readAll(); $anscount = count($aResults); foreach ($aResults as $row) { $row['code'] = htmlspecialchars($row['code']); $row['answer'] = htmlspecialchars($row['answer']); ?> <tr class='row_<?php echo $position; if ($alternate == true) { ?> highlight<?php } $alternate = !$alternate; ?> '><td>
/** * TSV survey definition in format readable by TSVSurveyImport * one line each per group, question, sub-question, and answer * does not use SGQA naming at all. * @param type $sid * @return type */ public static function &TSVSurveyExport($sid) { $aBaseFields = array('class', 'type/scale', 'name', 'relevance', 'text', 'help', 'language', 'validation', 'mandatory', 'other', 'default', 'same_default'); // Advanced question attributes : @todo get used question attribute by question in survey ? $aQuestionAttributes = array_keys(\ls\helpers\questionHelper::getAttributesDefinitions()); sort($aQuestionAttributes); $fields = array_merge($aBaseFields, $aQuestionAttributes); $rows = array(); $primarylang = 'en'; $otherlangs = ''; $langs = array(); // Export survey-level information $query = "select * from {{surveys}} where sid = " . $sid; $data = dbExecuteAssoc($query); foreach ($data->readAll() as $r) { foreach ($r as $key => $value) { if ($value != '') { $row['class'] = 'S'; $row['name'] = $key; $row['text'] = $value; $rows[] = $row; } if ($key == 'language') { $primarylang = $value; } if ($key == 'additional_languages') { $otherlangs = $value; } } } $langs = explode(' ', $primarylang . ' ' . $otherlangs); $langs = array_unique($langs); // Export survey language settings $query = "select * from {{surveys_languagesettings}} where surveyls_survey_id = " . $sid; $data = dbExecuteAssoc($query); foreach ($data->readAll() as $r) { $_lang = $r['surveyls_language']; foreach ($r as $key => $value) { if ($value != '' && $key != 'surveyls_language' && $key != 'surveyls_survey_id') { $row['class'] = 'SL'; $row['name'] = $key; $row['text'] = $value; $row['language'] = $_lang; $rows[] = $row; } } } $surveyinfo = getSurveyInfo($sid); $assessments = false; if (isset($surveyinfo['assessments']) && $surveyinfo['assessments'] == 'Y') { $assessments = true; } foreach ($langs as $lang) { if (trim($lang) == '') { continue; } SetSurveyLanguage($sid, $lang); LimeExpressionManager::StartSurvey($sid, 'survey', array('sgqaNaming' => 'N', 'assessments' => $assessments), true); $moveResult = LimeExpressionManager::NavigateForwards(); $LEM =& LimeExpressionManager::singleton(); if (is_null($moveResult) || is_null($LEM->currentQset) || count($LEM->currentQset) == 0) { continue; } $_gseq = -1; foreach ($LEM->currentQset as $q) { $gseq = $q['info']['gseq']; $gid = $q['info']['gid']; $qid = $q['info']['qid']; ////// // SHOW GROUP-LEVEL INFO ////// if ($gseq != $_gseq) { $_gseq = $gseq; $ginfo = $LEM->gseq2info[$gseq]; // if relevance equation is using SGQA coding, convert to qcoding $grelevance = $ginfo['grelevance'] == '' ? 1 : $ginfo['grelevance']; $LEM->em->ProcessBooleanExpression($grelevance, $gseq, 0); // $qseq $grelevance = trim(strip_tags($LEM->em->GetPrettyPrintString())); $gtext = trim($ginfo['description']) == '' ? '' : $ginfo['description']; $row = array(); $row['class'] = 'G'; //create a group code to allow proper importing of multi-lang survey TSVs $row['type/scale'] = 'G' . $gseq; $row['name'] = $ginfo['group_name']; $row['relevance'] = $grelevance; $row['text'] = $gtext; $row['language'] = $lang; $row['random_group'] = $ginfo['randomization_group']; $rows[] = $row; } ////// // SHOW QUESTION-LEVEL INFO ////// $row = array(); $mandatory = $q['info']['mandatory'] == 'Y' ? 'Y' : ''; $type = $q['info']['type']; $sgqas = explode('|', $q['sgqa']); if (count($sgqas) == 1 && !is_null($q['info']['default'])) { $default = $q['info']['default']; } else { $default = ''; } $qtext = $q['info']['qtext'] != '' ? $q['info']['qtext'] : ''; $help = $q['info']['help'] != '' ? $q['info']['help'] : ''; ////// // SHOW QUESTION ATTRIBUTES THAT ARE PROCESSED BY EM ////// if (isset($LEM->qattr[$qid]) && count($LEM->qattr[$qid]) > 0) { foreach ($LEM->qattr[$qid] as $key => $value) { if (is_null($value) || trim($value) == '') { continue; } switch ($key) { default: case 'exclude_all_others': case 'exclude_all_others_auto': case 'hidden': if ($value == false || $value == '0') { $value = NULL; // so can skip this one - just using continue here doesn't work. } break; case 'relevance': $value = NULL; // means an outdate database structure break; } if (is_null($value) || trim($value) == '') { continue; // since continuing from within a switch statement doesn't work } $row[$key] = $value; } } // if relevance equation is using SGQA coding, convert to qcoding $relevanceEqn = $q['info']['relevance'] == '' ? 1 : $q['info']['relevance']; $LEM->em->ProcessBooleanExpression($relevanceEqn, $gseq, $q['info']['qseq']); // $qseq $relevanceEqn = trim(preg_replace("#</(span|a)>#i", "", preg_replace("#<(span|a)[^>]+\\>#i", "", $LEM->em->GetPrettyPrintString()))); // Relevance can not have HTML : only span and a are returned from GetPrettyPrintString $rootVarName = $q['info']['rootVarName']; $preg = ''; if (isset($LEM->q2subqInfo[$q['info']['qid']]['preg'])) { $preg = $LEM->q2subqInfo[$q['info']['qid']]['preg']; if (is_null($preg)) { $preg = ''; } } $row['class'] = 'Q'; $row['type/scale'] = $type; $row['name'] = $rootVarName; $row['relevance'] = $relevanceEqn; $row['text'] = $qtext; $row['help'] = $help; $row['language'] = $lang; $row['validation'] = $preg; $row['mandatory'] = $mandatory; $row['other'] = $q['info']['other']; $row['default'] = $default; $row['same_default'] = 1; // TODO - need this: $q['info']['same_default']; $rows[] = $row; ////// // SHOW ALL SUB-QUESTIONS ////// $sawThis = array(); // array of rowdivids already seen so only show them once foreach ($sgqas as $sgqa) { if ($LEM->knownVars[$sgqa]['qcode'] == $rootVarName) { continue; // so don't show the main question as a sub-question too } $rowdivid = $sgqa; $varName = $LEM->knownVars[$sgqa]['qcode']; // if SQrelevance equation is using SGQA coding, convert to qcoding $SQrelevance = $LEM->knownVars[$sgqa]['SQrelevance'] == '' ? 1 : $LEM->knownVars[$sgqa]['SQrelevance']; $LEM->em->ProcessBooleanExpression($SQrelevance, $gseq, $q['info']['qseq']); $SQrelevance = trim(preg_replace("#</(span|a)>#i", "", preg_replace("#<(span|a)[^>]+\\>#i", "", $LEM->em->GetPrettyPrintString()))); // Relevance can not have HTML : only span and a are returned from GetPrettyPrintString switch ($q['info']['type']) { case '1': if (preg_match('/#1$/', $sgqa)) { $rowdivid = NULL; // so that doesn't show same message for second scale } else { $rowdivid = substr($sgqa, 0, -2); // strip suffix $varName = substr($LEM->knownVars[$sgqa]['qcode'], 0, -2); } break; case 'P': if (preg_match('/comment$/', $sgqa)) { $rowdivid = NULL; } break; case ':': case ';': $_rowdivid = $LEM->knownVars[$sgqa]['rowdivid']; if (isset($sawThis[$qid . '~' . $_rowdivid])) { $rowdivid = NULL; // so don't show again } else { $sawThis[$qid . '~' . $_rowdivid] = true; $rowdivid = $_rowdivid; $sgqa_len = strlen($sid . 'X' . $gid . 'X' . $qid); $varName = $rootVarName . '_' . substr($_rowdivid, $sgqa_len); } break; } if (is_null($rowdivid)) { continue; } $sgqaInfo = $LEM->knownVars[$sgqa]; $subqText = $sgqaInfo['subqtext']; if (isset($sgqaInfo['default'])) { $default = $sgqaInfo['default']; } else { $default = ''; } $row = array(); $row['class'] = 'SQ'; $row['type/scale'] = 0; $row['name'] = substr($varName, strlen($rootVarName) + 1); $row['relevance'] = $SQrelevance; $row['text'] = $subqText; $row['language'] = $lang; $row['default'] = $default; $rows[] = $row; } ////// // SHOW ANSWER OPTIONS FOR ENUMERATED LISTS, AND FOR MULTIFLEXI ////// if (isset($LEM->qans[$qid]) || isset($LEM->multiflexiAnswers[$qid])) { $_scale = -1; if (isset($LEM->multiflexiAnswers[$qid])) { $ansList = $LEM->multiflexiAnswers[$qid]; } else { $ansList = $LEM->qans[$qid]; } foreach ($ansList as $ans => $value) { $ansInfo = explode('~', $ans); $valParts = explode('|', $value); $valInfo[0] = array_shift($valParts); $valInfo[1] = implode('|', $valParts); if ($_scale != $ansInfo[0]) { $_scale = $ansInfo[0]; } $row = array(); if ($type == ':' || $type == ';') { $row['class'] = 'SQ'; } else { $row['class'] = 'A'; } $row['type/scale'] = $_scale; $row['name'] = $ansInfo[1]; $row['relevance'] = $assessments == true ? $valInfo[0] : ''; $row['text'] = $valInfo[1]; $row['language'] = $lang; $rows[] = $row; } } } } // Now generate the array out output data $out = array(); $out[] = $fields; foreach ($rows as $row) { $tsv = array(); foreach ($fields as $field) { $val = isset($row[$field]) ? $row[$field] : ''; $tsv[] = $val; } $out[] = $tsv; } return $out; }
/** * Load viewing of a user group screen. * @param bool $ugid * @param array|bool $header (type=success, warning)(message=localized message) * @return void */ public function index($ugid = false, $header = false) { if (!Permission::model()->hasGlobalPermission('usergroups', 'read')) { Yii::app()->session['flashmessage'] = gT('Access denied!'); $this->getController()->redirect(App()->createUrl("/admin")); } if ($ugid != false) { $ugid = (int) $ugid; } if (!empty($header)) { $aData['headercfg'] = $header; } else { $aData = array(); } $aViewUrls = array(); $aData['ugid'] = $ugid; $aData['imageurl'] = Yii::app()->getConfig("adminimageurl"); if (Yii::app()->session['loginID']) { if ($ugid) { $ugid = sanitize_int($ugid); $aData["usergroupid"] = $ugid; $result = UserGroup::model()->requestViewGroup($ugid, Yii::app()->session["loginID"]); $crow = $result[0]; if ($result) { $aData["groupfound"] = true; $aData["groupname"] = $crow['name']; if (!empty($crow['description'])) { $aData["usergroupdescription"] = $crow['description']; } else { $aData["usergroupdescription"] = ""; } } //$this->user_in_groups_model = new User_in_groups; $eguquery = "SELECT * FROM {{user_in_groups}} AS a INNER JOIN {{users}} AS b ON a.uid = b.uid WHERE ugid = " . $ugid . " ORDER BY b.users_name"; $eguresult = dbExecuteAssoc($eguquery); $aUserInGroupsResult = $eguresult->readAll(); $query2 = "SELECT ugid FROM {{user_groups}} WHERE ugid = " . $ugid; if (!Permission::model()->hasGlobalPermission('superadmin', 'read')) { $query2 .= " AND owner_id = " . Yii::app()->session['loginID']; } $result2 = dbSelectLimitAssoc($query2, 1); $row2 = $result2->readAll(); $row = 1; $userloop = array(); $bgcc = "oddrow"; foreach ($aUserInGroupsResult as $egurow) { if ($bgcc == "evenrow") { $bgcc = "oddrow"; } else { $bgcc = "evenrow"; } $userloop[$row]["userid"] = $egurow['uid']; // output users $userloop[$row]["rowclass"] = $bgcc; if (Permission::model()->hasGlobalPermission('superadmin', 'update')) { $userloop[$row]["displayactions"] = true; } else { $userloop[$row]["displayactions"] = false; } $userloop[$row]["username"] = $egurow['users_name']; $userloop[$row]["email"] = $egurow['email']; $row++; } $aData["userloop"] = $userloop; if (isset($row2[0]['ugid'])) { $aData["useradddialog"] = true; $aData["useraddusers"] = getGroupUserList($ugid, 'optionlist'); $aData["useraddurl"] = ""; } $aViewUrls[] = 'viewUserGroup_view'; } else { //show listing $aViewUrls['usergroups_view'][] = array(); $aData['model'] = UserGroup::model(); } } if ($ugid == false) { $aData['usergroupbar']['returnbutton']['url'] = 'admin/index'; $aData['usergroupbar']['returnbutton']['text'] = gT('Return to admin home'); } else { $aData['usergroupbar']['edit'] = TRUE; $aData['usergroupbar']['closebutton']['url'] = Yii::app()->createUrl('admin/usergroups/sa/view'); // Close button } if (isset($_GET['pageSize'])) { Yii::app()->user->setState('pageSize', (int) $_GET['pageSize']); } if (!empty($header)) { return array($aViewUrls, $aData); } else { $this->_renderWrappedTemplate('usergroup', $aViewUrls, $aData); } }
function getUrlParamsJSON($iSurveyID) { $iSurveyID = (int) $iSurveyID; Yii::app()->loadHelper('database'); $oResult = dbExecuteAssoc("select '' as act, up.*,q.title, sq.title as sqtitle, q.question, sq.question as sqquestion from {{survey_url_parameters}} up\n left join {{questions}} q on q.qid=up.targetqid\n left join {{questions}} sq on sq.qid=up.targetsqid\n where up.sid={$iSurveyID}"); $oResult = $oResult->readAll(); $i = 0; $clang = $this->getController()->lang; $aData = new stdClass(); foreach ($oResult as $oRow) { $aData->rows[$i]['id'] = $oRow['id']; if (!is_null($oRow['question'])) { $oRow['title'] .= ': ' . ellipsize(flattenText($oRow['question'], false, true), 43, 0.7); } else { $oRow['title'] = $clang->gT('(No target question)'); } if ($oRow['sqquestion'] != '') { $oRow['title'] .= ' - ' . ellipsize(flattenText($oRow['sqquestion'], false, true), 30, 0.75); } unset($oRow['sqquestion']); unset($oRow['sqtitle']); unset($oRow['question']); $aData->rows[$i]['cell'] = array_values($oRow); $i++; } $aData->page = 1; $aData->records = count($oResult); $aData->total = 1; echo ls_json_encode($aData); }
function UpdateSessionGroupList($surveyid, $language) { unset($_SESSION['survey_' . $surveyid]['grouplist']); $query = "SELECT * FROM {{groups}} WHERE sid={$surveyid} AND language='" . $language . "' ORDER BY group_order"; $result = dbExecuteAssoc($query) or safeDie("Couldn't get group list<br />{$query}<br />" . $connect->ErrorMsg()); //Checked foreach ($result->readAll() as $row) { $_SESSION['survey_' . $surveyid]['grouplist'][] = array($row['gid'], $row['group_name'], $row['description']); } }
</td> <?php if (Permission::model()->hasGlobalPermission('superadmin', 'read')) { ?> <td><?php echo $noofsurveyslist[$i]; ?> </td> <?php } ?> <?php $uquery = "SELECT users_name FROM {{users}} WHERE uid=" . $usr['parent_id']; $uresult = dbExecuteAssoc($uquery); //Checked $userlist = array(); $srow = $uresult->read(); $usr['parent'] = $srow['users_name']; ?> <?php if (isset($usr['parent_id'])) { ?> <td><?php echo htmlspecialchars($usr['parent']); ?> </td> <?php } else {
/** * Load viewing of a user group screen. * @param bool $ugid * @param array|bool $header (type=success, warning)(message=localized message) * @return void */ public function index($ugid = false, $header = false) { if ($ugid != false) { $ugid = (int) $ugid; } if (!empty($header)) { $aData['headercfg'] = $header; } else { $aData = array(); } $aViewUrls = array(); $aData['ugid'] = $ugid; $aData['imageurl'] = Yii::app()->getConfig("adminimageurl"); $clang = Yii::app()->lang; if (Yii::app()->session['loginID']) { if ($ugid) { $ugid = sanitize_int($ugid); $aData["usergroupid"] = $ugid; $result = UserGroup::model()->requestViewGroup($ugid, Yii::app()->session["loginID"]); $crow = $result[0]; if ($result) { $aData["groupfound"] = true; $aData["groupname"] = $crow['name']; if (!empty($crow['description'])) { $aData["usergroupdescription"] = $crow['description']; } else { $aData["usergroupdescription"] = ""; } } //$this->user_in_groups_model = new User_in_groups; $eguquery = "SELECT * FROM {{user_in_groups}} AS a INNER JOIN {{users}} AS b ON a.uid = b.uid WHERE ugid = " . $ugid . " ORDER BY b.users_name"; $eguresult = dbExecuteAssoc($eguquery); $aUserInGroupsResult = $eguresult->readAll(); $query2 = "SELECT ugid FROM {{user_groups}} WHERE ugid = " . $ugid . " AND owner_id = " . Yii::app()->session['loginID']; $result2 = dbSelectLimitAssoc($query2, 1); $row2 = $result2->readAll(); $row = 1; $userloop = array(); $bgcc = "oddrow"; foreach ($aUserInGroupsResult as $egurow) { if ($bgcc == "evenrow") { $bgcc = "oddrow"; } else { $bgcc = "evenrow"; } $userloop[$row]["userid"] = $egurow['uid']; // output users $userloop[$row]["rowclass"] = $bgcc; if (Permission::model()->hasGlobalPermission('superadmin', 'update')) { $userloop[$row]["displayactions"] = true; } else { $userloop[$row]["displayactions"] = false; } $userloop[$row]["username"] = $egurow['users_name']; $userloop[$row]["email"] = $egurow['email']; $row++; } $aData["userloop"] = $userloop; if (isset($row2[0]['ugid'])) { $aData["useradddialog"] = true; $aData["useraddusers"] = getGroupUserList($ugid, 'optionlist'); $aData["useraddurl"] = ""; } } $aViewUrls[] = 'viewUserGroup_view'; } if (!empty($header)) { return array($aViewUrls, $aData); } else { $this->_renderWrappedTemplate('usergroup', $aViewUrls, $aData); } }
<input type='image' src='<?php echo $imageurl;?>token_delete.png' alt='<?php $clang->eT("Delete this user");?>' onclick='return confirm("<?php $clang->eT("Are you sure you want to delete this entry?","js");?>")' /> <input type='hidden' name='action' value='deluser' /> <input type='hidden' name='user' value='<?php echo htmlspecialchars($usr['user']);?>' /> <input type='hidden' name='uid' value='<?php echo $usr['uid'];?>' /> </form> <?php } ?> </td> <td><?php echo htmlspecialchars($usr['user']);?></td> <td><a href='mailto:<?php echo htmlspecialchars($usr['email']);?>'><?php echo htmlspecialchars($usr['email']);?></a></td> <td><?php echo htmlspecialchars($usr['full_name']);?></td> <td><?php echo $noofsurveyslist[$i];?></td> <?php $uquery = "SELECT users_name FROM {{users}} WHERE uid=".$usr['parent_id']; $uresult = dbExecuteAssoc($uquery); //Checked $userlist = array(); $srow = $uresult->read(); $usr['parent'] = $srow['users_name']; ?> <?php if (isset($usr['parent_id'])) { ?> <td><?php echo htmlspecialchars($usr['parent']);?></td> <?php } else { ?> <td>-----</td> <?php } ?> </tr> <?php $row++; } ?> </tbody></table><br />
foreach ($delresult as $delrow) { ?> <option value='<?php echo $delrow['code']; ?> '><?php echo $delrow['answer']; ?> </option> <?php } ?> </select></td> <?php $delquery = "SELECT * FROM {{answers}} WHERE qid={$deqrow['qid']} AND language='{$sDataEntryLanguage}' and scale_id=1 ORDER BY sortorder, code"; $delresult = dbExecuteAssoc($delquery); ?> <td> <select name='<?php echo $fieldname . $dearow['title']; ?> #1'> <option selected='selected' value=''><?php eT("Please choose..."); ?> </option> <?php foreach ($delresult as $delrow) { ?> <option value='<?php echo $delrow['code'];
function action() { global $surveyid; global $thissurvey, $thisstep; global $clienttoken, $tokensexist, $token; // only attempt to change session lifetime if using a DB backend // with file based sessions, it's up to the admin to configure maxlifetime if (isset(Yii::app()->session->connectionID)) { @ini_set('session.gc_maxlifetime', Yii::app()->getConfig('iSessionExpirationTime')); } $this->_loadRequiredHelpersAndLibraries(); $param = $this->_getParameters(func_get_args(), $_POST); $surveyid = $param['sid']; Yii::app()->setConfig('surveyID', $surveyid); $thisstep = $param['thisstep']; $move = getMove(); Yii::app()->setConfig('move', $move); $clienttoken = trim($param['token']); $standardtemplaterootdir = Yii::app()->getConfig('standardtemplaterootdir'); if (is_null($thissurvey) && !is_null($surveyid)) { $thissurvey = getSurveyInfo($surveyid); } // unused vars in this method (used in methods using compacted method vars) @($loadname = $param['loadname']); @($loadpass = $param['loadpass']); $sitename = Yii::app()->getConfig('sitename'); if (isset($param['newtest']) && $param['newtest'] == "Y") { killSurveySession($surveyid); } $surveyExists = $surveyid && Survey::model()->findByPk($surveyid); $isSurveyActive = $surveyExists && Survey::model()->findByPk($surveyid)->active == "Y"; // collect all data in this method to pass on later $redata = compact(array_keys(get_defined_vars())); $this->_loadLimesurveyLang($surveyid); if ($this->_isClientTokenDifferentFromSessionToken($clienttoken, $surveyid)) { $sReloadUrl = $this->getController()->createUrl("/survey/index/sid/{$surveyid}", array('token' => $clienttoken, 'lang' => App()->language, 'newtest' => 'Y')); $asMessage = array(gT('Token mismatch'), gT('The token you provided doesn\'t match the one in your session.'), "<a class='reloadlink newsurvey' href={$sReloadUrl}>" . gT("Click here to start the survey.") . "</a>"); $this->_createNewUserSessionAndRedirect($surveyid, $redata, __LINE__, $asMessage); } if ($this->_isSurveyFinished($surveyid) && ($thissurvey['alloweditaftercompletion'] != 'Y' || $thissurvey['tokenanswerspersistence'] != 'Y')) { $aReloadUrlParam = array('lang' => App()->language, 'newtest' => 'Y'); if ($clienttoken) { $aReloadUrlParam['token'] = $clienttoken; } $sReloadUrl = $this->getController()->createUrl("/survey/index/sid/{$surveyid}", $aReloadUrlParam); $asMessage = array(gT('Previous session is set to be finished.'), gT('Your browser reports that it was used previously to answer this survey. We are resetting the session so that you can start from the beginning.'), "<a class='reloadlink newsurvey' href={$sReloadUrl}>" . gT("Click here to start the survey.") . "</a>"); $this->_createNewUserSessionAndRedirect($surveyid, $redata, __LINE__, $asMessage); } $previewmode = false; if (isset($param['action']) && in_array($param['action'], array('previewgroup', 'previewquestion'))) { if (!$this->_canUserPreviewSurvey($surveyid)) { $asMessage = array(gT('Error'), gT("We are sorry but you don't have permissions to do this.")); $this->_niceExit($redata, __LINE__, null, $asMessage); } else { if (intval($param['qid']) && $param['action'] == 'previewquestion') { $previewmode = 'question'; } if (intval($param['gid']) && $param['action'] == 'previewgroup') { $previewmode = 'group'; } } } Yii::app()->setConfig('previewmode', $previewmode); if ($this->_surveyCantBeViewedWithCurrentPreviewAccess($surveyid, $isSurveyActive, $surveyExists)) { $bPreviewRight = $this->_userHasPreviewAccessSession($surveyid); if ($bPreviewRight === false) { $asMessage = array(gT("Error"), gT("We are sorry but you don't have permissions to do this."), sprintf(gT("Please contact %s ( %s ) for further assistance."), $thissurvey['adminname'], $thissurvey['adminemail'])); $this->_niceExit($redata, __LINE__, null, $asMessage); } } // TODO can this be moved to the top? // (Used to be global, used in ExpressionManager, merged into amVars. If not filled in === '') // can this be added in the first computation of $redata? if (isset($_SESSION['survey_' . $surveyid]['srid'])) { $saved_id = $_SESSION['survey_' . $surveyid]['srid']; } // recompute $redata since $saved_id used to be a global $redata = compact(array_keys(get_defined_vars())); if ($this->_didSessionTimeOut($surveyid)) { // @TODO is this still required ? $asMessage = array(gT("Error"), gT("We are sorry but your session has expired."), gT("Either you have been inactive for too long, you have cookies disabled for your browser, or there were problems with your connection."), sprintf(gT("Please contact %s ( %s ) for further assistance."), $thissurvey['adminname'], $thissurvey['adminemail'])); $this->_niceExit($redata, __LINE__, null, $asMessage); } // Set the language of the survey, either from POST, GET parameter of session var // Keep the old value, because SetSurveyLanguage update $_SESSION $sOldLang = isset($_SESSION['survey_' . $surveyid]['s_lang']) ? $_SESSION['survey_' . $surveyid]['s_lang'] : ""; // Keep the old value, because SetSurveyLanguage update $_SESSION if (!empty($param['lang'])) { $sDisplayLanguage = $param['lang']; // $param take lang from returnGlobal and returnGlobal sanitize langagecode } elseif (isset($_SESSION['survey_' . $surveyid]['s_lang'])) { $sDisplayLanguage = $_SESSION['survey_' . $surveyid]['s_lang']; } elseif (Survey::model()->findByPk($surveyid)) { $sDisplayLanguage = Survey::model()->findByPk($surveyid)->language; } else { $sDisplayLanguage = Yii::app()->getConfig('defaultlang'); } //CHECK FOR REQUIRED INFORMATION (sid) if ($surveyid && $surveyExists) { LimeExpressionManager::SetSurveyId($surveyid); // must be called early - it clears internal cache if a new survey is being used SetSurveyLanguage($surveyid, $sDisplayLanguage); if ($previewmode) { LimeExpressionManager::SetPreviewMode($previewmode); } if (App()->language != $sOldLang) { UpdateGroupList($surveyid, App()->language); // to refresh the language strings in the group list session variable UpdateFieldArray(); // to refresh question titles and question text } } else { throw new CHttpException(404, "The survey in which you are trying to participate does not seem to exist. It may have been deleted or the link you were given is outdated or incorrect."); } // Get token if (!isset($token)) { $token = $clienttoken; } //GET BASIC INFORMATION ABOUT THIS SURVEY $thissurvey = getSurveyInfo($surveyid, $_SESSION['survey_' . $surveyid]['s_lang']); $event = new PluginEvent('beforeSurveyPage'); $event->set('surveyId', $surveyid); App()->getPluginManager()->dispatchEvent($event); if (!is_null($event->get('template'))) { $thissurvey['templatedir'] = $event->get('template'); } //SEE IF SURVEY USES TOKENS if ($surveyExists == 1 && tableExists('{{tokens_' . $thissurvey['sid'] . '}}')) { $tokensexist = 1; } else { $tokensexist = 0; unset($_POST['token']); unset($param['token']); unset($token); unset($clienttoken); } //SET THE TEMPLATE DIRECTORY global $oTemplate; $thistpl = $oTemplate->viewPath; $timeadjust = Yii::app()->getConfig("timeadjust"); //MAKE SURE SURVEY HASN'T EXPIRED if ($thissurvey['expiry'] != '' and dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust) > $thissurvey['expiry'] && $thissurvey['active'] != 'N' && !$previewmode) { $redata = compact(array_keys(get_defined_vars())); $asMessage = array(gT("Error"), gT("This survey is no longer available."), sprintf(gT("Please contact %s ( %s ) for further assistance."), $thissurvey['adminname'], $thissurvey['adminemail'])); $this->_niceExit($redata, __LINE__, $thissurvey['templatedir'], $asMessage); } //MAKE SURE SURVEY IS ALREADY VALID if ($thissurvey['startdate'] != '' and dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust) < $thissurvey['startdate'] && $thissurvey['active'] != 'N' && !$previewmode) { $redata = compact(array_keys(get_defined_vars())); $asMessage = array(gT("Error"), gT("This survey is not yet started."), sprintf(gT("Please contact %s ( %s ) for further assistance."), $thissurvey['adminname'], $thissurvey['adminemail'])); $this->_niceExit($redata, __LINE__, $thissurvey['templatedir'], $asMessage); } //CHECK FOR PREVIOUSLY COMPLETED COOKIE //If cookies are being used, and this survey has been completed, a cookie called "PHPSID[sid]STATUS" will exist (ie: SID6STATUS) and will have a value of "COMPLETE" $sCookieName = "LS_" . $surveyid . "_STATUS"; if (isset($_COOKIE[$sCookieName]) && $_COOKIE[$sCookieName] == "COMPLETE" && $thissurvey['usecookie'] == "Y" && $tokensexist != 1 && (!isset($param['newtest']) || $param['newtest'] != "Y")) { $redata = compact(array_keys(get_defined_vars())); $asMessage = array(gT("Error"), gT("You have already completed this survey."), sprintf(gT("Please contact %s ( %s ) for further assistance."), $thissurvey['adminname'], $thissurvey['adminemail'])); $this->_niceExit($redata, __LINE__, $thissurvey['templatedir'], $asMessage); } //LOAD SAVED SURVEY if (Yii::app()->request->getParam('loadall') == "reload") { $errormsg = ""; $sLoadName = Yii::app()->request->getParam('loadname'); $sLoadPass = Yii::app()->request->getParam('loadpass'); if (isset($sLoadName) && !$sLoadName) { $errormsg .= gT("You did not provide a name") . "<br />\n"; } if (isset($sLoadPass) && !$sLoadPass) { $errormsg .= gT("You did not provide a password") . "<br />\n"; } // if security question answer is incorrect // Not called if scid is set in GET params (when using email save/reload reminder URL) if (function_exists("ImageCreate") && isCaptchaEnabled('saveandloadscreen', $thissurvey['usecaptcha']) && is_null(Yii::app()->request->getQuery('scid'))) { $sLoadSecurity = Yii::app()->request->getPost('loadsecurity'); if (empty($sLoadSecurity)) { $errormsg .= gT("You did not answer to the security question.") . "<br />\n"; } elseif (!isset($_SESSION['survey_' . $surveyid]['secanswer']) || $sLoadSecurity != $_SESSION['survey_' . $surveyid]['secanswer']) { $errormsg .= gT("The answer to the security question is incorrect.") . "<br />\n"; } } if ($errormsg == "") { LimeExpressionManager::SetDirtyFlag(); buildsurveysession($surveyid); if (loadanswers()) { Yii::app()->setConfig('move', 'reload'); $move = "reload"; // veyRunTimeHelper use $move in $arg } else { $errormsg .= gT("There is no matching saved survey"); } } if ($errormsg) { Yii::app()->setConfig('move', "loadall"); // Show loading form } } //Allow loading of saved survey if (Yii::app()->getConfig('move') == "loadall") { $redata = compact(array_keys(get_defined_vars())); Yii::import("application.libraries.Load_answers"); $tmp = new Load_answers(); $tmp->run($redata); } //Check if TOKEN is used for EVERY PAGE //This function fixes a bug where users able to submit two surveys/votes //by checking that the token has not been used at each page displayed. // bypass only this check at first page (Step=0) because // this check is done in buildsurveysession and error message // could be more interresting there (takes into accound captcha if used) if ($tokensexist == 1 && isset($token) && $token != "" && isset($_SESSION['survey_' . $surveyid]['step']) && $_SESSION['survey_' . $surveyid]['step'] > 0 && tableExists("tokens_{$surveyid}}}")) { // check also if it is allowed to change survey after completion if ($thissurvey['alloweditaftercompletion'] == 'Y') { $tokenInstance = Token::model($surveyid)->findByAttributes(array('token' => $token)); } else { $tokenInstance = Token::model($surveyid)->usable()->incomplete()->findByAttributes(array('token' => $token)); } if (!isset($tokenInstance) && !$previewmode) { //TOKEN DOESN'T EXIST OR HAS ALREADY BEEN USED. EXPLAIN PROBLEM AND EXIT $asMessage = array(null, gT("This is a controlled survey. You need a valid token to participate."), sprintf(gT("For further information please contact %s"), $thissurvey['adminname'] . " (<a href='mailto:{$thissurvey['adminemail']}'>" . "{$thissurvey['adminemail']}</a>)")); $this->_niceExit($redata, __LINE__, $thistpl, $asMessage, true); } } if ($tokensexist == 1 && isset($token) && $token != "" && tableExists("{{tokens_" . $surveyid . "}}") && !$previewmode) { // check also if it is allowed to change survey after completion if ($thissurvey['alloweditaftercompletion'] == 'Y') { $tokenInstance = Token::model($surveyid)->editable()->findByAttributes(array('token' => $token)); } else { $tokenInstance = Token::model($surveyid)->usable()->incomplete()->findByAttributes(array('token' => $token)); } if (!isset($tokenInstance)) { $oToken = Token::model($surveyid)->findByAttributes(array('token' => $token)); if ($oToken) { $now = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", Yii::app()->getConfig("timeadjust")); if ($oToken->completed != 'N' && !empty($oToken->completed)) { $sError = gT("This invitation has already been used."); } elseif (strtotime($now) < strtotime($oToken->validfrom)) { $sError = gT("This invitation is not valid yet."); } elseif (strtotime($now) > strtotime($oToken->validuntil)) { $sError = gT("This invitation is not valid anymore."); } else { $sError = gT("This is a controlled survey. You need a valid token to participate."); } } else { $sError = gT("This is a controlled survey. You need a valid token to participate."); } $asMessage = array($sError, gT("We are sorry but you are not allowed to enter this survey."), sprintf(gT("For further information please contact %s"), $thissurvey['adminname'] . " (<a href='mailto:{$thissurvey['adminemail']}'>" . "{$thissurvey['adminemail']}</a>)")); $this->_niceExit($redata, __LINE__, $thistpl, $asMessage, true); } } //Clear session and remove the incomplete response if requested. if (isset($move) && $move == "clearall") { // delete the response but only if not already completed $s_lang = $_SESSION['survey_' . $surveyid]['s_lang']; if (isset($_SESSION['survey_' . $surveyid]['srid']) && !SurveyDynamic::model($surveyid)->isCompleted($_SESSION['survey_' . $surveyid]['srid'])) { // delete the response but only if not already completed $result = dbExecuteAssoc('DELETE FROM {{survey_' . $surveyid . '}} WHERE id=' . $_SESSION['survey_' . $surveyid]['srid'] . " AND submitdate IS NULL"); if ($result->count() > 0) { // Using count() here *should* be okay for MSSQL because it is a delete statement // find out if there are any fuqt questions - checked $fieldmap = createFieldMap($surveyid, 'short', false, false, $s_lang); foreach ($fieldmap as $field) { if ($field['type'] == "|" && !strpos($field['fieldname'], "_filecount")) { if (!isset($qid)) { $qid = array(); } $qid[] = $field['fieldname']; } } // if yes, extract the response json to those questions if (isset($qid)) { $query = "SELECT * FROM {{survey_" . $surveyid . "}} WHERE id=" . $_SESSION['survey_' . $surveyid]['srid']; $result = dbExecuteAssoc($query); foreach ($result->readAll() as $row) { foreach ($qid as $question) { $json = $row[$question]; if ($json == "" || $json == NULL) { continue; } // decode them $phparray = json_decode($json); foreach ($phparray as $metadata) { $target = Yii::app()->getConfig("uploaddir") . "/surveys/" . $surveyid . "/files/"; // delete those files unlink($target . $metadata->filename); } } } } // done deleting uploaded files } // also delete a record from saved_control when there is one dbExecuteAssoc('DELETE FROM {{saved_control}} WHERE srid=' . $_SESSION['survey_' . $surveyid]['srid'] . ' AND sid=' . $surveyid); } killSurveySession($surveyid); sendCacheHeaders(); doHeader(); $redata = compact(array_keys(get_defined_vars())); $this->_printTemplateContent($thistpl . '/startpage.pstpl', $redata, __LINE__); echo "\n\n<!-- JAVASCRIPT FOR CONDITIONAL QUESTIONS -->\n" . "\t<script type='text/javascript'>\n" . "\t<!--\n" . "function checkconditions(value, name, type, evt_type)\n" . "\t{\n" . "\t}\n" . "\t//-->\n" . "\t</script>\n\n"; //Present the clear all page using clearall.pstpl template $this->_printTemplateContent($thistpl . '/clearall.pstpl', $redata, __LINE__); $this->_printTemplateContent($thistpl . '/endpage.pstpl', $redata, __LINE__); doFooter(); exit; } //Check to see if a refering URL has been captured. if (!isset($_SESSION['survey_' . $surveyid]['refurl'])) { $_SESSION['survey_' . $surveyid]['refurl'] = GetReferringUrl(); // do not overwrite refurl } // Let's do this only if // - a saved answer record hasn't been loaded through the saved feature // - the survey is not anonymous // - the survey is active // - a token information has been provided // - the survey is setup to allow token-response-persistence if (!isset($_SESSION['survey_' . $surveyid]['srid']) && $thissurvey['anonymized'] == "N" && $thissurvey['active'] == "Y" && isset($token) && $token != '') { // load previous answers if any (dataentry with nosubmit) $oResponses = Response::model($surveyid)->findAllByAttributes(array('token' => $token), array('order' => 'id DESC')); if (!empty($oResponses)) { /** * We fire the response selection event when at least 1 response was found. * If there is just 1 response the plugin still has to option to choose * NOT to use it. */ $event = new PluginEvent('beforeLoadResponse'); $event->set('responses', $oResponses); $event->set('surveyId', $surveyid); App()->pluginManager->dispatchEvent($event); $oResponse = $event->get('response'); // If $oResponse is false we act as if no response was found. // This allows a plugin to deny continuing a response. if ($oResponse !== false) { // If plugin does not set a response we use the first one found, (this replicates pre-plugin behavior) if (!isset($oResponse) && (!isset($oResponses[0]->submitdate) || $thissurvey['alloweditaftercompletion'] == 'Y') && $thissurvey['tokenanswerspersistence'] == 'Y') { $oResponse = $oResponses[0]; } if (isset($oResponse)) { $_SESSION['survey_' . $surveyid]['srid'] = $oResponse->id; if (!empty($oResponse->lastpage)) { $_SESSION['survey_' . $surveyid]['LEMtokenResume'] = true; // If the response was completed and user is allowed to edit after completion start at the beginning and not at the last page - just makes more sense if (!($oResponse->submitdate && $thissurvey['alloweditaftercompletion'] == 'Y')) { $_SESSION['survey_' . $surveyid]['step'] = $oResponse->lastpage; } } buildsurveysession($surveyid); if (!empty($oResponse->submitdate)) { $_SESSION['survey_' . $surveyid]['maxstep'] = $_SESSION['survey_' . $surveyid]['totalsteps']; } loadanswers(); } } } } // Preview action : Preview right already tested before if ($previewmode) { // Unset all SESSION: be sure to have the last version unset($_SESSION['fieldmap-' . $surveyid . App()->language]); // Needed by createFieldMap: else fieldmap can be outdated unset($_SESSION['survey_' . $surveyid]); if ($param['action'] == 'previewgroup') { $thissurvey['format'] = 'G'; } elseif ($param['action'] == 'previewquestion') { $thissurvey['format'] = 'S'; } buildsurveysession($surveyid, true); } sendCacheHeaders(); //Send local variables to the appropriate survey type unset($redata); $redata = compact(array_keys(get_defined_vars())); Yii::import('application.helpers.SurveyRuntimeHelper'); $tmp = new SurveyRuntimeHelper(); $tmp->run($surveyid, $redata); if (isset($_POST['saveall']) || isset($flashmessage)) { echo "<script type='text/javascript'> \$(document).ready( function() { alert('" . gT("Your responses were successfully saved.", "js") . "');}) </script>"; } }
public function doQuestion($ia) { global $thissurvey; if ($thissurvey['nokeyboard'] == 'Y') { includeKeypad(); $kpclass = "text-keypad"; } else { $kpclass = ""; } $checkconditionFunction = "checkconditions"; $aQuestionAttributes = getQuestionAttributeValues($ia[0]); $query = "SELECT other FROM {{questions}} WHERE qid=" . $ia[0] . " AND language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "' "; $result = Yii::app()->db->createCommand($query)->query(); foreach ($result->readAll() as $row) { $other = $row['other']; } //question attribute random order set? if ($aQuestionAttributes['random_order'] == 1) { $ansquery = "SELECT * FROM {{answers}} WHERE qid={$ia['0']} AND language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "' and scale_id=0 ORDER BY " . dbRandom(); } elseif ($aQuestionAttributes['alphasort'] == 1) { $ansquery = "SELECT * FROM {{answers}} WHERE qid={$ia['0']} AND language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "' and scale_id=0 ORDER BY answer"; } else { $ansquery = "SELECT * FROM {{answers}} WHERE qid={$ia['0']} AND language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "' and scale_id=0 ORDER BY sortorder, answer"; } $ansresult = dbExecuteAssoc($ansquery)->readAll(); //Checked $anscount = count($ansresult); if (trim($aQuestionAttributes['display_columns']) != '') { $dcols = $aQuestionAttributes['display_columns']; } else { $dcols = 1; } if (trim($aQuestionAttributes['other_replace_text'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']]) != '') { $othertext = $aQuestionAttributes['other_replace_text'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']]; } else { $othertext = gT('Other:'); } if (isset($other) && $other == 'Y') { $anscount++; } //Count up for the Other answer if ($ia[6] != 'Y' && SHOW_NO_ANSWER == 1) { $anscount++; } //Count up if "No answer" is showing $wrapper = setupColumns($dcols, $anscount, "answers-list radio-list", "answer-item radio-item"); $iBootCols = round(12 / $dcols); $ansByCol = round($anscount / $dcols); $ansByCol = $ansByCol > 0 ? $ansByCol : 1; //$answer = 'IKI: '.$iBootCols.' '.$ansByCol.' '.$wrapper['whole-start']; $answer = '<div class="row">'; $answer .= ' <div class="col-xs-' . $iBootCols . '">AAAAAAAAAAAAAA'; //Time Limit Code if (trim($aQuestionAttributes['time_limit']) != '') { $answer .= return_timer_script($aQuestionAttributes, $ia); } //End Time Limit Code // Get array_filter stuff $rowcounter = 0; $colcounter = 1; $trbc = ''; foreach ($ansresult as $key => $ansrow) { $myfname = $ia[1] . $ansrow['code']; $check_ans = ''; if ($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$ia[1]] == $ansrow['code']) { $check_ans = CHECKED; } list($htmltbody2, $hiddenfield) = return_array_filter_strings($ia, $aQuestionAttributes, $thissurvey, $ansrow, $myfname, '', $myfname, "div", "form-group answer-item radio-item"); /* if(substr($wrapper['item-start'],0,4) == "\t<li") { $startitem = "\t$htmltbody2\n"; } else { $startitem = $wrapper['item-start']; } $answer .= $startitem;*/ $answer .= "\t{$hiddenfield}\n"; $answer .= '<div class="form-group">'; $answer .= ' <label for="answer' . $ia[1] . $ansrow['code'] . '" class="answertext control-label">' . $ansrow['answer'] . '</label>'; $answer .= ' <input class="radio" type="radio" value="' . $ansrow['code'] . '" name="' . $ia[1] . '" id="answer' . $ia[1] . $ansrow['code'] . '"' . $check_ans . ' onclick="if (document.getElementById(\'answer' . $ia[1] . 'othertext\') != null) document.getElementById(\'answer' . $ia[1] . 'othertext\').value=\'\';' . $checkconditionFunction . '(this.value, this.name, this.type)" />'; $answer .= $wrapper['item-end']; $answer .= '</div>'; ++$rowcounter; //if ($rowcounter == $wrapper['maxrows'] && $colcounter < $wrapper['cols'] || (count($ansresult)-$key)==$wrapper['cols']-$colcounter) if ($rowcounter == $ansByCol && $colcounter < $wrapper['cols']) { if ($colcounter == $wrapper['cols']) { //$answer .= 'là '.$wrapper['col-devide-last']; $answer .= ' </div><!-- last -->'; } else { //$answer .= 'et là '.$wrapper['col-devide']; $answer .= ' </div><!-- devide --> '; $answer .= ' <div class="col-xs-' . $iBootCols . '">'; } $rowcounter = 0; ++$colcounter; } } if (isset($other) && $other == 'Y') { $sSeparator = getRadixPointData($thissurvey['surveyls_numberformat']); $sSeparator = $sSeparator['separator']; if ($aQuestionAttributes['other_numbers_only'] == 1) { $oth_checkconditionFunction = 'fixnum_checkconditions'; } else { $oth_checkconditionFunction = 'checkconditions'; } if ($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$ia[1]] == '-oth-') { $check_ans = CHECKED; } else { $check_ans = ''; } $thisfieldname = $ia[1] . 'other'; if (isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$thisfieldname])) { $dispVal = $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$thisfieldname]; if ($aQuestionAttributes['other_numbers_only'] == 1) { $dispVal = str_replace('.', $sSeparator, $dispVal); } $answer_other = ' value="' . htmlspecialchars($dispVal, ENT_QUOTES) . '"'; } else { $answer_other = ' value=""'; } list($htmltbody2, $hiddenfield) = return_array_filter_strings($ia, $aQuestionAttributes, $thissurvey, array("code" => "other"), $thisfieldname, $trbc, $myfname, "div", "form-group answer-item radio-item other-item other"); $answer .= "\t{$hiddenfield}\n"; $answer .= '<div class="form-group">'; $answer .= ' <label for="SOTH' . $ia[1] . '" class="answertext control-label">' . $othertext . '</label>'; $answer .= ' <input class="radio" type="radio" value="-oth-" name="' . $ia[1] . '" id="SOTH' . $ia[1] . '"' . $check_ans . ' onclick="' . $checkconditionFunction . '(this.value, this.name, this.type)" />'; $answer .= ' <input type="text" class="text ' . $kpclass . '" id="answer' . $ia[1] . 'othertext" name="' . $ia[1] . 'other" title="' . gT('Other') . '"' . $answer_other . ' onkeyup="if($.trim($(this).val())!=\'\'){ $(\'#SOTH' . $ia[1] . '\').click(); }; ' . $oth_checkconditionFunction . '(this.value, this.name, this.type);" />'; $answer .= $wrapper['item-end']; $answer .= '</div>'; $inputnames[] = $thisfieldname; ++$rowcounter; if ($rowcounter == $ansByCol && $colcounter < $wrapper['cols']) { if ($colcounter == $wrapper['cols']) { $answer .= ' </div><!-- last -->'; } else { $answer .= ' </div><!-- devide -->'; $answer .= ' <div class="col-xs-' . $iBootCols . '">'; } $rowcounter = 0; ++$colcounter; } } if ($ia[6] != 'Y' && SHOW_NO_ANSWER == 1) { if (!isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$ia[1]]) || $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$ia[1]] == '' || $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$ia[1]] == ' ') { $check_ans = CHECKED; //Check the "no answer" radio button if there is no answer in session. } else { $check_ans = ''; } $answer .= '<div class="form-group">'; $answer .= ' <label for="answer' . $ia[1] . 'NANS" class="answertext control-label">' . gT('No answer') . '</label>'; $answer .= ' <input class="radio" type="radio" name="' . $ia[1] . '" id="answer' . $ia[1] . 'NANS" value=""' . $check_ans . ' onclick="if (document.getElementById(\'answer' . $ia[1] . 'othertext\') != null) document.getElementById(\'answer' . $ia[1] . 'othertext\').value=\'\';' . $checkconditionFunction . '(this.value, this.name, this.type)" />'; $answer .= $wrapper['item-end']; $answer .= '</div>'; // --> END NEW FEATURE - SAVE ++$rowcounter; //if ($rowcounter == $wrapper['maxrows'] && $colcounter < $wrapper['cols']) if ($rowcounter == $ansByCol && $colcounter < $wrapper['cols']) { if ($colcounter == $wrapper['cols']) { //$answer .= $wrapper['col-devide-last']; $answer .= ' </div><!-- last -->'; } else { //$answer .= $wrapper['col-devide']; $answer .= ' </div><!-- devide -->'; $answer .= ' <div class="col-xs-' . $iBootCols . '">'; } $rowcounter = 0; ++$colcounter; } } //END OF ITEMS //$answer .= $wrapper['whole-end'].' $answer .= ' <input type="hidden" name="java' . $ia[1] . '" id="java' . $ia[1] . "\" value=\"" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$ia[1]] . "\" />\n"; $answer .= '</div> <!-- wrapper row -->'; $inputnames[] = $ia[1]; return array($answer, $inputnames); }
function upgradeSurveys145() { global $modifyoutputt; $sSurveyQuery = "SELECT * FROM {{surveys}} where notification<>'0'"; $oSurveyResult = dbExecuteAssoc($sSurveyQuery); foreach ($oSurveyResult->readAll() as $aSurveyRow) { if ($aSurveyRow['notification'] == '1' && trim($aSurveyRow['adminemail']) != '') { $aEmailAddresses = explode(';', $aSurveyRow['adminemail']); $sAdminEmailAddress = $aEmailAddresses[0]; $sEmailnNotificationAddresses = implode(';', $aEmailAddresses); $sSurveyUpdateQuery = "update {{surveys}} set adminemail='{$sAdminEmailAddress}', emailnotificationto='{$sEmailnNotificationAddresses}' where sid=" . $aSurveyRow['sid']; Yii::app()->getDb()->createCommand($sSurveyUpdateQuery)->execute(); } else { $aEmailAddresses = explode(';', $aSurveyRow['adminemail']); $sAdminEmailAddress = $aEmailAddresses[0]; $sEmailDetailedNotificationAddresses = implode(';', $aEmailAddresses); if (trim($aSurveyRow['emailresponseto']) != '') { $sEmailDetailedNotificationAddresses = $sEmailDetailedNotificationAddresses . ';' . trim($aSurveyRow['emailresponseto']); } $sSurveyUpdateQuery = "update {{surveys}} set adminemail='{$sAdminEmailAddress}', emailnotificationto='{$sEmailDetailedNotificationAddresses}' where sid=" . $aSurveyRow['sid']; Yii::app()->getDb()->createCommand($sSurveyUpdateQuery)->execute(); } } $sSurveyQuery = "SELECT * FROM {{surveys_languagesettings}}"; $oSurveyResult = Yii::app()->getDb()->createCommand($sSurveyQuery)->queryAll(); foreach ($oSurveyResult as $aSurveyRow) { $sLanguage = App()->language; $aDefaultTexts = templateDefaultTexts($sLanguage, 'unescaped'); unset($sLanguage); $aDefaultTexts['admin_detailed_notification'] = $aDefaultTexts['admin_detailed_notification'] . $aDefaultTexts['admin_detailed_notification_css']; $sSurveyUpdateQuery = "update {{surveys_languagesettings}} set\n email_admin_responses_subj=" . $aDefaultTexts['admin_detailed_notification_subject'] . ",\n email_admin_responses=" . $aDefaultTexts['admin_detailed_notification'] . ",\n email_admin_notification_subj=" . $aDefaultTexts['admin_notification_subject'] . ",\n email_admin_notification=" . $aDefaultTexts['admin_notification'] . "\n where surveyls_survey_id=" . $aSurveyRow['surveyls_survey_id']; Yii::app()->getDb()->createCommand()->update('{{surveys_languagesettings}}', array('email_admin_responses_subj' => $aDefaultTexts['admin_detailed_notification_subject'], 'email_admin_responses' => $aDefaultTexts['admin_detailed_notification'], 'email_admin_notification_subj' => $aDefaultTexts['admin_notification_subject'], 'email_admin_notification' => $aDefaultTexts['admin_notification']), "surveyls_survey_id={$aSurveyRow['surveyls_survey_id']}"); } }
/** * get subquestions fort the current question object in the right order */ public function getOrderedSubQuestions($random = 0, $exclude_all_others = '') { if ($random == 1) { // TODO : USE AR PATTERN $ansquery = "SELECT * FROM {{questions}} WHERE parent_qid='{$this->qid}' AND scale_id=0 AND language='{$this->language}' ORDER BY " . dbRandom(); } else { // TODO : USE AR PATTERN $ansquery = "SELECT * FROM {{questions}} WHERE parent_qid='{$this->qid}' AND scale_id=0 AND language='{$this->language}' ORDER BY question_order"; } $ansresult = dbExecuteAssoc($ansquery)->readAll(); //Checked //if exclude_all_others is set then the related answer should keep its position at all times //thats why we have to re-position it if it has been randomized if (trim($exclude_all_others) != '' && $random == 1) { $position = 0; foreach ($ansresult as $answer) { if ($answer['title'] == trim($exclude_all_others)) { if ($position == $answer['question_order'] - 1) { break; } //already in the right position $tmp = array_splice($ansresult, $position, 1); array_splice($ansresult, $answer['question_order'] - 1, 0, $tmp); break; } $position++; } } return $ansresult; }
/** * register::index() * Process register form data and take appropriate action * @return */ function actionIndex($surveyid = null) { Yii::app()->loadHelper('database'); Yii::app()->loadHelper('replacements'); $postlang = Yii::app()->request->getPost('lang'); if ($surveyid == null) { $surveyid = Yii::app()->request->getPost('sid'); } if (!$surveyid) { Yii::app()->request->redirect(Yii::app()->baseUrl); } // Get passed language from form, so that we dont loose this! if (!isset($postlang) || $postlang == "" || !$postlang) { $baselang = Survey::model()->findByPk($surveyid)->language; Yii::import('application.libraries.Limesurvey_lang'); Yii::app()->lang = new Limesurvey_lang($baselang); $clang = Yii::app()->lang; } else { Yii::import('application.libraries.Limesurvey_lang'); Yii::app()->lang = new Limesurvey_lang($postlang); $clang = Yii::app()->lang; $baselang = $postlang; } $thissurvey = getSurveyInfo($surveyid, $baselang); $register_errormsg = ""; // Check the security question's answer if (function_exists("ImageCreate") && isCaptchaEnabled('registrationscreen', $thissurvey['usecaptcha'])) { if (!isset($_POST['loadsecurity']) || !isset($_SESSION['survey_' . $surveyid]['secanswer']) || Yii::app()->request->getPost('loadsecurity') != $_SESSION['survey_' . $surveyid]['secanswer']) { $register_errormsg .= $clang->gT("The answer to the security question is incorrect.") . "<br />\n"; } } //Check that the email is a valid style address if (!validateEmailAddress(Yii::app()->request->getPost('register_email'))) { $register_errormsg .= $clang->gT("The email you used is not valid. Please try again."); } // Check for additional fields $attributeinsertdata = array(); foreach (GetParticipantAttributes($surveyid) as $field => $data) { if (empty($data['show_register']) || $data['show_register'] != 'Y') { continue; } $value = sanitize_xss_string(Yii::app()->request->getPost('register_' . $field)); if (trim($value) == '' && $data['mandatory'] == 'Y') { $register_errormsg .= sprintf($clang->gT("%s cannot be left empty"), $thissurvey['attributecaptions'][$field]); } $attributeinsertdata[$field] = $value; } if ($register_errormsg != "") { $_SESSION['survey_' . $surveyid]['register_errormsg'] = $register_errormsg; Yii::app()->request->redirect(Yii::app()->createUrl('survey/index/sid/' . $surveyid)); } //Check if this email already exists in token database $query = "SELECT email FROM {{tokens_{$surveyid}}}\n" . "WHERE email = '" . sanitize_email(Yii::app()->request->getPost('register_email')) . "'"; $usrow = Yii::app()->db->createCommand($query)->queryRow(); if ($usrow) { $register_errormsg = $clang->gT("The email you used has already been registered."); $_SESSION['survey_' . $surveyid]['register_errormsg'] = $register_errormsg; Yii::app()->request->redirect(Yii::app()->createUrl('survey/index/sid/' . $surveyid)); //include "index.php"; //exit; } $mayinsert = false; // Get the survey settings for token length //$this->load->model("surveys_model"); $tlresult = Survey::model()->findAllByAttributes(array("sid" => $surveyid)); if (isset($tlresult[0])) { $tlrow = $tlresult[0]; } else { $tlrow = $tlresult; } $tokenlength = $tlrow['tokenlength']; //if tokenlength is not set or there are other problems use the default value (15) if (!isset($tokenlength) || $tokenlength == '') { $tokenlength = 15; } while ($mayinsert != true) { $newtoken = randomChars($tokenlength); $ntquery = "SELECT * FROM {{tokens_{$surveyid}}} WHERE token='{$newtoken}'"; $usrow = Yii::app()->db->createCommand($ntquery)->queryRow(); if (!$usrow) { $mayinsert = true; } } $postfirstname = sanitize_xss_string(strip_tags(Yii::app()->request->getPost('register_firstname'))); $postlastname = sanitize_xss_string(strip_tags(Yii::app()->request->getPost('register_lastname'))); $starttime = sanitize_xss_string(Yii::app()->request->getPost('startdate')); $endtime = sanitize_xss_string(Yii::app()->request->getPost('enddate')); /*$postattribute1=sanitize_xss_string(strip_tags(returnGlobal('register_attribute1'))); $postattribute2=sanitize_xss_string(strip_tags(returnGlobal('register_attribute2'))); */ // Insert new entry into tokens db Tokens_dynamic::sid($thissurvey['sid']); $token = new Tokens_dynamic(); $token->firstname = $postfirstname; $token->lastname = $postlastname; $token->email = Yii::app()->request->getPost('register_email'); $token->emailstatus = 'OK'; $token->token = $newtoken; if ($starttime && $endtime) { $token->validfrom = $starttime; $token->validuntil = $endtime; } foreach ($attributeinsertdata as $k => $v) { $token->{$k} = $v; } $result = $token->save(); /** $result = $connect->Execute($query, array($postfirstname, $postlastname, returnGlobal('register_email'), 'OK', $newtoken) // $postattribute1, $postattribute2) ) or safeDie ($query."<br />".$connect->ErrorMsg()); //Checked - According to adodb docs the bound variables are quoted automatically */ $tid = getLastInsertID($token->tableName()); $fieldsarray["{ADMINNAME}"] = $thissurvey['adminname']; $fieldsarray["{ADMINEMAIL}"] = $thissurvey['adminemail']; $fieldsarray["{SURVEYNAME}"] = $thissurvey['name']; $fieldsarray["{SURVEYDESCRIPTION}"] = $thissurvey['description']; $fieldsarray["{FIRSTNAME}"] = $postfirstname; $fieldsarray["{LASTNAME}"] = $postlastname; $fieldsarray["{EXPIRY}"] = $thissurvey["expiry"]; $message = $thissurvey['email_register']; $subject = $thissurvey['email_register_subj']; $from = "{$thissurvey['adminname']} <{$thissurvey['adminemail']}>"; if (getEmailFormat($surveyid) == 'html') { $useHtmlEmail = true; $surveylink = $this->createAbsoluteUrl($surveyid . '/lang-' . $baselang . '/tk-' . $newtoken); $optoutlink = $this->createAbsoluteUrl('optout/local/' . $surveyid . '/' . $baselang . '/' . $newtoken); $optinlink = $this->createAbsoluteUrl('optin/local/' . $surveyid . '/' . $baselang . '/' . $newtoken); $fieldsarray["{SURVEYURL}"] = "<a href='{$surveylink}'>" . $surveylink . "</a>"; $fieldsarray["{OPTOUTURL}"] = "<a href='{$optoutlink}'>" . $optoutlink . "</a>"; $fieldsarray["{OPTINURL}"] = "<a href='{$optinlink}'>" . $optinlink . "</a>"; } else { $useHtmlEmail = false; $fieldsarray["{SURVEYURL}"] = $this->createAbsoluteUrl('' . $surveyid . '/lang-' . $baselang . '/tk-' . $newtoken); $fieldsarray["{OPTOUTURL}"] = $this->createAbsoluteUrl('optout/local/' . $surveyid . '/' . $baselang . '/' . $newtoken); $fieldsarray["{OPTINURL}"] = $this->createAbsoluteUrl('optin/local/' . $surveyid . '/' . $baselang . '/' . $newtoken); } $message = ReplaceFields($message, $fieldsarray); $subject = ReplaceFields($subject, $fieldsarray); $html = ""; //Set variable $sitename = Yii::app()->getConfig('sitename'); if (SendEmailMessage($message, $subject, Yii::app()->request->getPost('register_email'), $from, $sitename, $useHtmlEmail, getBounceEmail($surveyid))) { // TLR change to put date into sent $today = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i", Yii::app()->getConfig('timeadjust')); $query = "UPDATE {{tokens_{$surveyid}}}\n" . "SET sent='{$today}' WHERE tid={$tid}"; $result = dbExecuteAssoc($query) or show_error("Unable to execute this query : {$query}<br />"); //Checked $html = "<center>" . $clang->gT("Thank you for registering to participate in this survey.") . "<br /><br />\n" . $clang->gT("An email has been sent to the address you provided with access details for this survey. Please follow the link in that email to proceed.") . "<br /><br />\n" . $clang->gT("Survey administrator") . " {ADMINNAME} ({ADMINEMAIL})"; $html = ReplaceFields($html, $fieldsarray); $html .= "<br /><br /></center>\n"; } else { $html = "Email Error"; } //PRINT COMPLETED PAGE if (!$thissurvey['template']) { $thistpl = getTemplatePath(validateTemplateDir('default')); } else { $thistpl = getTemplatePath(validateTemplateDir($thissurvey['template'])); } sendCacheHeaders(); doHeader(); Yii::app()->lang = $clang; // fetch the defined variables and pass it to the header footer templates. $redata = compact(array_keys(get_defined_vars())); $this->_printTemplateContent($thistpl . '/startpage.pstpl', $redata, __LINE__); $this->_printTemplateContent($thistpl . '/survey.pstpl', $redata, __LINE__); echo $html; $this->_printTemplateContent($thistpl . '/endpage.pstpl', $redata, __LINE__); doFooter(); }
function _canUserPreviewSurvey($iSurveyID) { if (!isset($_SESSION['loginID'], $_SESSION['USER_RIGHT_SUPERADMIN'])) { return false; } if ($_SESSION['USER_RIGHT_SUPERADMIN'] == 1) { return true; } $sQuery = dbExecuteAssoc("SELECT uid\n FROM {{survey_permissions}}\n WHERE sid = " . $iSurveyID . " AND uid = '" . $_SESSION['loginID']); $aRow = Yii::app()->db->createCommand($sQuery)->queryRow(); if ($aRow) { return true; } return false; }
function do_array_dual($ia) { global $thissurvey; $aLastMoveResult = LimeExpressionManager::GetLastMoveResult(); $aMandatoryViolationSubQ = $aLastMoveResult['mandViolation'] && $ia[6] == 'Y' ? explode("|", $aLastMoveResult['unansweredSQs']) : array(); $repeatheadings = Yii::app()->getConfig("repeatheadings"); $minrepeatheadings = Yii::app()->getConfig("minrepeatheadings"); $extraclass = ""; $answertypeclass = ""; // Maybe not $caption = ""; // Just leave empty, are replaced after $inputnames = array(); $labelans1 = array(); $labelans = array(); $aQuestionAttributes = getQuestionAttributeValues($ia[0]); if ($aQuestionAttributes['random_order'] == 1) { $ansquery = "SELECT * FROM {{questions}} WHERE parent_qid={$ia['0']} AND language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "' and scale_id=0 ORDER BY " . dbRandom(); } else { $ansquery = "SELECT * FROM {{questions}} WHERE parent_qid={$ia['0']} AND language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "' and scale_id=0 ORDER BY question_order"; } $ansresult = dbExecuteAssoc($ansquery); //Checked $aSubQuestions = $ansresult->readAll(); $anscount = count($aSubQuestions); $lquery = "SELECT * FROM {{answers}} WHERE scale_id=0 AND qid={$ia[0]} AND language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "' ORDER BY sortorder, code"; $lresult = dbExecuteAssoc($lquery); //Checked $aAnswersScale0 = $lresult->readAll(); $lquery1 = "SELECT * FROM {{answers}} WHERE scale_id=1 AND qid={$ia[0]} AND language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "' ORDER BY sortorder, code"; $lresult1 = dbExecuteAssoc($lquery1); //Checked $aAnswersScale1 = $lresult1->readAll(); if ($aQuestionAttributes['use_dropdown'] == 1) { $useDropdownLayout = true; $extraclass .= " dropdown-list"; $answertypeclass .= " dropdown"; $doDualScaleFunction = "doDualScaleDropDown"; // javascript funtion to lauch at end of answers $caption = gT("An array with sub-question on each line, with 2 answers to provide on each line. You have to select the answer."); } else { $useDropdownLayout = false; $extraclass .= " radio-list"; $answertypeclass .= " radio"; $doDualScaleFunction = "doDualScaleRadio"; $caption = gT("An array with sub-question on each line, with 2 answers to provide on each line. The answers are contained in the table header. "); } if (ctype_digit(trim($aQuestionAttributes['repeat_headings'])) && trim($aQuestionAttributes['repeat_headings'] != "")) { $repeatheadings = intval($aQuestionAttributes['repeat_headings']); $minrepeatheadings = 0; } if (trim($aQuestionAttributes['dualscale_headerA'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']]) != '') { $leftheader = $aQuestionAttributes['dualscale_headerA'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']]; } else { $leftheader = ''; } if (trim($aQuestionAttributes['dualscale_headerB'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']]) != '') { $rightheader = $aQuestionAttributes['dualscale_headerB'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']]; } else { $rightheader = ''; } if (trim($aQuestionAttributes['answer_width']) != '') { $answerwidth = $aQuestionAttributes['answer_width']; } else { $answerwidth = 20; } // Find if we have rigth and center text // TODO move "|" to attribute $sQuery = "SELECT count(question) FROM {{questions}} WHERE parent_qid=" . $ia[0] . " and scale_id=0 AND question like '%|%'"; $rigthCount = Yii::app()->db->createCommand($sQuery)->queryScalar(); $rightexists = $rigthCount > 0; // $right_exists: flag to find out if there are any right hand answer parts. leaving right column but don't force with $sQuery = "SELECT count(question) FROM {{questions}} WHERE parent_qid=" . $ia[0] . " and scale_id=0 AND question like '%|%|%'"; $centerCount = Yii::app()->db->createCommand($sQuery)->queryScalar(); $centerexists = $centerCount > 0; // $center_exists: flag to find out if there are any center hand answer parts. leaving center column but don't force with // Label and code for input foreach ($aAnswersScale0 as $lrow) { $labels0[] = array('code' => $lrow['code'], 'title' => $lrow['answer']); } foreach ($aAnswersScale1 as $lrow) { $labels1[] = array('code' => $lrow['code'], 'title' => $lrow['answer']); } if (count($aAnswersScale0) > 0 && $anscount) { $answer = ""; $fn = 1; // Used by repeat_heading if ($useDropdownLayout === false) { $columnswidth = 100 - $answerwidth; foreach ($aAnswersScale0 as $lrow) { $labelans0[] = $lrow['answer']; $labelcode0[] = $lrow['code']; } foreach ($aAnswersScale1 as $lrow) { $labelans1[] = $lrow['answer']; $labelcode1[] = $lrow['code']; } $numrows = count($labelans0) + count($labelans1); // Add needed row and fill some boolean: shownoanswer, rightexists, centerexists $shownoanswer = $ia[6] != "Y" && SHOW_NO_ANSWER == 1; if ($shownoanswer) { $numrows++; $caption .= gT("The last cell are for no answer. "); } if ($rightexists) { $numrows++; } if ($centerexists) { $numrows++; } $cellwidth = $columnswidth / $numrows; //$cellwidth=sprintf("%02d", $cellwidth); // No reason to do this, except to leave place for separator ? But then table can not be the same in all browser // Header row and colgroups $mycolumns = "\t<col class=\"col-answers\" width=\"{$answerwidth}%\" />\n"; $answer_head_line = "\t<th class=\"header_answer_text\"> </th>\n\n"; $mycolumns .= "\t<colgroup class=\"col-responses group-1\">\n"; $odd_even = ''; foreach ($labelans0 as $ld) { $answer_head_line .= "\t<th>" . $ld . "</th>\n"; $odd_even = alternation($odd_even); $mycolumns .= "<col class=\"{$odd_even}\" width=\"{$cellwidth}%\" />\n"; } $mycolumns .= "\t</colgroup>\n"; if (count($labelans1) > 0) { $separatorwidth = $centerexists ? "width=\"{$cellwidth}%\" " : ""; $mycolumns .= "\t<col class=\"separator\" {$separatorwidth}/>\n"; $mycolumns .= "\t<colgroup class=\"col-responses group-2\">\n"; $answer_head_line .= "\n\t<td class=\"header_separator\"> </td>\n\n"; // Separator : and No answer for accessibility for first colgroup foreach ($labelans1 as $ld) { $answer_head_line .= "\t<th>" . $ld . "</th>\n"; $odd_even = alternation($odd_even); $mycolumns .= "<col class=\"{$odd_even}\" width=\"{$cellwidth}%\" />\n"; } $mycolumns .= "\t</colgroup>\n"; } if ($shownoanswer || $rightexists) { $rigthwidth = $rightexists ? "width=\"{$cellwidth}%\" " : ""; $mycolumns .= "\t<col class=\"separator rigth_separator\" {$rigthwidth}/>\n"; $answer_head_line .= "\n\t<td class=\"header_separator rigth_separator\"> </td>\n"; } if ($shownoanswer) { $mycolumns .= "\t<col class=\"col-no-answer\" width=\"{$cellwidth}%\" />\n"; $answer_head_line .= "\n\t<th class=\"header_no_answer\">" . gT('No answer') . "</th>\n"; } $answer_head2 = "\n<tr class=\"array1 header_row dontread\">\n" . $answer_head_line . "</tr>\n"; // build first row of header if needed if ($leftheader != '' || $rightheader != '') { $answer_head1 = "<tr class=\"array1 groups header_row\">\n" . "\t<th class=\"header_answer_text\"> </th>\n" . "\t<th colspan=\"" . count($labelans0) . "\" class=\"dsheader\">{$leftheader}</th>\n"; if (count($labelans1) > 0) { $answer_head1 .= "\t<td class=\"header_separator\"> </td>\n" . "\t<th colspan=\"" . count($labelans1) . "\" class=\"dsheader\">{$rightheader}</th>\n"; } if ($shownoanswer || $rightexists) { $rigthclass = $rightexists ? " header_answer_text_right" : ""; $answer_head1 .= "\t<td class=\"header_separator {$rigthclass}\"> </td>\n"; if ($shownoanswer) { $answer_head1 .= "\t<th class=\"header_no_answer\"> </th>\n"; } } $answer_head1 .= "</tr>\n"; } else { $answer_head1 = ""; } $answer .= "\n<table class=\"question subquestions-list questions-list\" summary=\"{$caption}\">\n" . $mycolumns . "\n\t<thead>\n" . $answer_head1 . $answer_head2 . "\n\t</thead>\n" . "<tbody>\n"; // And no each line of body $trbc = ''; foreach ($aSubQuestions as $ansrow) { // Build repeat headings if needed if (isset($repeatheadings) && $repeatheadings > 0 && $fn - 1 > 0 && ($fn - 1) % $repeatheadings == 0) { if ($anscount - $fn + 1 >= $minrepeatheadings) { $answer .= "</tbody>\n<tbody>"; // Close actual body and open another one //$answer .= $answer_head1; $answer .= "\n<tr class=\"repeat headings\">\n" . $answer_head_line . "</tr>\n"; } } $trbc = alternation($trbc, 'row'); $answertext = $ansrow['question']; // rigth and center answertext: not explode for ? Why not if (strpos($answertext, '|')) { $answertextrigth = substr($answertext, strpos($answertext, '|') + 1); $answertext = substr($answertext, 0, strpos($answertext, '|')); } else { $answertextrigth = ""; } if ($centerexists) { $answertextcenter = substr($answertextrigth, 0, strpos($answertextrigth, '|')); $answertextrigth = substr($answertextrigth, strpos($answertextrigth, '|') + 1); } else { $answertextcenter = ""; } $myfname = $ia[1] . $ansrow['title']; $myfname0 = $ia[1] . $ansrow['title'] . '#0'; $myfid0 = $ia[1] . $ansrow['title'] . '_0'; $myfname1 = $ia[1] . $ansrow['title'] . '#1'; // new multi-scale-answer $myfid1 = $ia[1] . $ansrow['title'] . '_1'; /* Check the Sub Q mandatory violation */ if ($ia[6] == 'Y' && (in_array($myfname0, $aMandatoryViolationSubQ) || in_array($myfname1, $aMandatoryViolationSubQ))) { $answertext = "<span class='errormandatory'>{$answertext}</span>"; } // Get array_filter stuff list($htmltbody2, $hiddenfield) = return_array_filter_strings($ia, $aQuestionAttributes, $thissurvey, $ansrow, $myfname, $trbc, $myfname, "tr", "{$trbc} answers-list radio-list"); $answer .= $htmltbody2; array_push($inputnames, $myfname0); $answer .= "\t<th class=\"answertext\">\n" . $hiddenfield . "{$answertext}\n"; // Hidden answers used by EM: sure can be added in javascript $answer .= "<input type=\"hidden\" disabled=\"disabled\" name=\"java{$myfid0}\" id=\"java{$myfid0}\" value=\""; if (isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname0])) { $answer .= $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname0]; } $answer .= "\" />\n"; if (count($labelans1) > 0) { $answer .= "<input type=\"hidden\" disabled=\"disabled\" name=\"java{$myfid1}\" id=\"java{$myfid1}\" value=\""; if (isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname1])) { $answer .= $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname1]; } $answer .= "\" />\n"; } $answer .= "\t</th>\n"; $hiddenanswers = ''; $thiskey = 0; foreach ($labelcode0 as $ld) { $answer .= "\t<td class=\"answer_cell_1_00{$ld} answer-item {$answertypeclass}-item\">\n" . "\t<input class=\"radio\" type=\"radio\" name=\"{$myfname0}\" value=\"{$ld}\" id=\"answer{$myfid0}-{$ld}\" "; if (isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname0]) && $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname0] == $ld) { $answer .= CHECKED; } $answer .= " />\n" . "<label class=\"hide read\" for=\"answer{$myfid0}-{$ld}\">{$labelans0[$thiskey]}</label>\n" . "\n\t</td>\n"; $thiskey++; } if (count($labelans1) > 0) { $answer .= "\t<td class=\"dual_scale_separator information-item\">"; if ($shownoanswer) { $answer .= "\t<input class='radio jshide read' type='radio' name='{$myfname0}' value='' id='answer{$myfid0}-' "; if (!isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname0]) || $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname0] == "") { $answer .= CHECKED; } $answer .= " />\n"; } $answer .= "<label for='answer{$myfid0}-' class= \"hide read\">" . gT("No answer") . "</label>"; $answer .= "\t{$answertextcenter}</td>\n"; // separator array_push($inputnames, $myfname1); $thiskey = 0; foreach ($labelcode1 as $ld) { $answer .= "\t<td class=\"answer_cell_2_00{$ld} answer-item radio-item\">\n" . "\t<input class=\"radio\" type=\"radio\" name=\"{$myfname1}\" value=\"{$ld}\" id=\"answer{$myfid1}-{$ld}\" "; if (isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname1]) && $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname1] == $ld) { $answer .= CHECKED; } $answer .= " />\n" . "<label class=\"hide read\" for=\"answer{$myfid1}-{$ld}\">{$labelans1[$thiskey]}</label>\n" . "\t</td>\n"; $thiskey++; } } if ($shownoanswer || $rightexists) { $answer .= "\t<td class=\"answertextright dual_scale_separator information-item\">{$answertextrigth}</td>\n"; } if ($shownoanswer) { $answer .= "\t<td class=\"dual_scale_no_answer answer-item radio-item noanswer-item\">\n"; if (count($labelans1) > 0) { $answer .= "\t<input class='radio' type='radio' name='{$myfname1}' value='' id='answer{$myfid1}-' "; if (!isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname1]) || $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname1] == "") { $answer .= CHECKED; } // --> START NEW FEATURE - SAVE $answer .= " />\n"; $answer .= "<label class='hide read' for='answer{$myfid1}-'>" . gT("No answer") . "</label>"; } else { $answer .= "\t<input class='radio' type='radio' name='{$myfname0}' value='' id='answer{$myfid0}-' "; if (!isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname0]) || $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname0] == "") { $answer .= CHECKED; } $answer .= "<label class='hide read' for='answer{$myfid0}-'>" . gT("No answer") . "<label>\n"; $answer .= " />\n"; } $answer .= "\t</td>\n"; } $answer .= "</tr>\n"; $fn++; } $answer .= "</tbody>\n"; $answer .= "</table>"; } elseif ($useDropdownLayout === true) { $separatorwidth = (100 - $answerwidth) / 10; $cellwidth = (100 - $answerwidth - $separatorwidth) / 2; $answer = ""; // Get attributes for Headers and Prefix/Suffix if (trim($aQuestionAttributes['dropdown_prepostfix'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']]) != '') { list($ddprefix, $ddsuffix) = explode("|", $aQuestionAttributes['dropdown_prepostfix'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']]); $ddprefix = $ddprefix; $ddsuffix = $ddsuffix; } else { $ddprefix = ''; $ddsuffix = ''; } if (trim($aQuestionAttributes['dropdown_separators']) != '') { $aSeparator = explode('|', $aQuestionAttributes['dropdown_separators']); if (isset($aSeparator[1])) { $interddSep = $aSeparator[1]; } else { $interddSep = $aSeparator[0]; } } else { $interddSep = ''; } $colspan_1 = ''; $colspan_2 = ''; $suffix_cell = ''; $answer .= "\n<table class=\"question subquestion-list questions-list dropdown-list\" summary=\"{$caption}\">\n" . "\t<col class=\"answertext\" width=\"{$answerwidth}%\" />\n"; if ($ddprefix != '' || $ddsuffix != '') { $answer .= "\t<colgroup width=\"{$cellwidth}%\">\n"; } if ($ddprefix != '') { $answer .= "\t\t<col class=\"ddprefix\" />\n"; $colspan_1 = ' colspan="2"'; } $headcolwidth = $ddprefix != '' || $ddsuffix != '' ? "" : " width=\"{$cellwidth}%\""; $answer .= "\t<col class=\"dsheader\"{$headcolwidth} />\n"; if ($ddsuffix != '') { $answer .= "\t<col class=\"ddsuffix\" />\n"; } if ($ddprefix != '' || $ddsuffix != '') { $answer .= "\t</colgroup>\n"; } $answer .= "\t<col class=\"ddarrayseparator\" width=\"{$separatorwidth}%\" />\n"; if ($ddprefix != '' || $ddsuffix != '') { $answer .= "\t<colgroup width=\"{$cellwidth}%\">\n"; } if ($ddprefix != '') { $answer .= "\t\t<col class=\"ddprefix\" />\n"; } $answer .= "\t<col class=\"dsheader\"{$headcolwidth} />\n"; if ($ddsuffix != '') { $answer .= "\t<col class=\"ddsuffix\" />\n"; } if ($ddprefix != '' || $ddsuffix != '') { $answer .= "\t</colgroup>\n"; } // colspan : for header only if ($ddprefix != '' && $ddsuffix != '') { $colspan = ' colspan="3"'; } elseif ($ddprefix != '' || $ddsuffix != '') { $colspan = ' colspan="2"'; } else { $colspan = ""; } // headers $answer .= "\n\t<thead>\n" . "<tr>\n" . "\t<td> </td>\n" . "\t<th{$colspan}>{$leftheader}</th>\n" . "\t<td> </td>\n" . "\t<th{$colspan}>{$rightheader}</th>\n"; $answer .= "\t</tr>\n" . "\t</thead>\n"; $answer .= "\n<tbody>\n"; $trbc = ''; foreach ($aSubQuestions as $ansrow) { $myfname = $ia[1] . $ansrow['title']; $myfname0 = $ia[1] . $ansrow['title'] . "#0"; $myfid0 = $ia[1] . $ansrow['title'] . "_0"; $myfname1 = $ia[1] . $ansrow['title'] . "#1"; $myfid1 = $ia[1] . $ansrow['title'] . "_1"; $sActualAnswer0 = isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname0]) ? $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname0] : ""; $sActualAnswer1 = isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname1]) ? $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname1] : ""; if ($ia[6] == 'Y' && (in_array($myfname0, $aMandatoryViolationSubQ) || in_array($myfname1, $aMandatoryViolationSubQ))) { $answertext = "<span class='errormandatory'>" . $ansrow['question'] . "</span>"; } else { $answertext = $ansrow['question']; } list($htmltbody2, $hiddenfield) = return_array_filter_strings($ia, $aQuestionAttributes, $thissurvey, $ansrow, $myfname, $trbc, $myfname, "tr", "{$trbc} subquestion-list questions-list dropdown-list"); $answer .= $htmltbody2; $answer .= "\t<th class=\"answertext\">\n" . "<label for=\"answer{$myfid0}\">{$answertext}</label>\n"; // Hidden answers used by EM: sure can be added in javascript $answer .= "<input type=\"hidden\" disabled=\"disabled\" name=\"java{$myfid0}\" id=\"java{$myfid0}\" value=\"{$sActualAnswer0}\" />\n"; $answer .= "<input type=\"hidden\" disabled=\"disabled\" name=\"java{$myfid1}\" id=\"java{$myfid1}\" value=\"{$sActualAnswer1}\" />\n"; $answer . "\t</th>\n"; // Selector 0 if ($ddprefix != '') { $answer .= "\t<td class=\"ddprefix information-item\">{$ddprefix}</td>\n"; } $answer .= "\t<td class=\"answer-item dropdown-item\">\n" . "<select name=\"{$myfname0}\" id=\"answer{$myfid0}\">\n"; // Show the 'Please choose' if there are no answer actually if ($sActualAnswer0 == '') { $answer .= "\t<option value=\"\" " . SELECTED . ">" . gT('Please choose...') . "</option>\n"; } foreach ($labels0 as $lrow) { $answer .= "\t<option value=\"" . $lrow['code'] . '" '; if ($sActualAnswer0 == $lrow['code']) { $answer .= SELECTED; } $answer .= '>' . flattenText($lrow['title']) . "</option>\n"; } if ($sActualAnswer0 != '' && $ia[6] != 'Y' && SHOW_NO_ANSWER) { $answer .= "\t<option value=\"\">" . gT('No answer') . "</option>\n"; } $answer .= "</select>\n"; $answer .= "</td>\n"; if ($ddsuffix != '') { $answer .= "\t<td class=\"ddsuffix information-item\">{$ddsuffix}</td>\n"; } $inputnames[] = $myfname0; $answer .= "\t<td class=\"ddarrayseparator information-item\">{$interddSep}</td>\n"; //Separator // Selector 1 if ($ddprefix != '') { $answer .= "\t<td class='ddprefix information-item'>{$ddprefix}</td>\n"; } $answer .= "\t<td class=\"answer-item dropdown-item\">\n" . "<label class=\"hide read\" for=\"answer{$myfid1}\">{$answertext}</label>" . "<select name=\"{$myfname1}\" id=\"answer{$myfid1}\">\n"; // Show the 'Please choose' if there are no answer actually if ($sActualAnswer1 == '') { $answer .= "\t<option value=\"\" " . SELECTED . ">" . gT('Please choose...') . "</option>\n"; } foreach ($labels1 as $lrow1) { $answer .= "\t<option value=\"" . $lrow1['code'] . '" '; if ($sActualAnswer1 == $lrow1['code']) { $answer .= SELECTED; } $answer .= '>' . flattenText($lrow1['title']) . "</option>\n"; } if ($sActualAnswer1 != '' && $ia[6] != 'Y' && SHOW_NO_ANSWER) { $answer .= "\t<option value=\"\">" . gT('No answer') . "</option>\n"; } $answer .= "</select>\n"; $answer .= "</td>\n"; if ($ddsuffix != '') { $answer .= "\t<td class=\"ddsuffix information-item\">{$ddsuffix}</td>\n"; } $inputnames[] = $myfname1; $answer .= "</tr>\n"; } $answer .= "\t</tbody>\n"; $answer .= "</table>\n"; } } else { $answer = "<p class='error'>" . gT("Error: There are no answer options for this question and/or they don't exist in this language.") . "</p>\n"; $inputnames = ""; } Yii::app()->getClientScript()->registerScriptFile(Yii::app()->getConfig('generalscripts') . "dualscale.js"); $answer .= "<script type='text/javascript'>\n" . " <!--\n" . " {$doDualScaleFunction}({$ia[0]});\n" . " -->\n" . "</script>\n"; return array($answer, $inputnames); }
public function regenquestioncodes($iSurveyID, $sSubAction) { if (Permission::model()->hasSurveyPermission($iSurveyID, 'surveycontent', 'update')) { $clang = $this->getController()->lang; //Automatically renumbers the "question codes" so that they follow //a methodical numbering method $iQuestionNumber = 1; $iGroupNumber = 0; $iSequence = 0; $sQuery = "SELECT a.qid, a.gid\n" . "FROM {{questions}} as a, {{groups}} g " . "WHERE a.gid=g.gid AND a.sid={$iSurveyID} AND a.parent_qid=0 " . "GROUP BY a.gid, a.qid, g.group_order, question_order " . "ORDER BY g.group_order, question_order"; $arResult = dbExecuteAssoc($sQuery) or safe_die("Error: " . $connect->ErrorMsg()); // Checked $grows = array(); //Create an empty array in case FetchRow does not return any rows foreach ($arResult->readAll() as $grow) { $grows[] = $grow; } // Get table output into array foreach ($grows as $grow) { //Go through all the questions if ($sSubAction == 'bygroup' && (!isset($iGroupNumber) || $iGroupNumber != $grow['gid'])) { //If we're doing this by group, restart the numbering when the group number changes $iQuestionNumber = 1; $iGroupNumber = $grow['gid']; $iSequence++; } $usql = "UPDATE {{questions}} " . "SET title='" . ($sSubAction == 'bygroup' ? 'G' . $iSequence : '') . "Q" . str_pad($iQuestionNumber, 5, "0", STR_PAD_LEFT) . "'\n" . "WHERE qid=" . $grow['qid']; //$databaseoutput .= "[$sql]"; $uresult = dbExecuteAssoc($usql) or safe_die("Error: " . $connect->ErrorMsg()); // Checked $iQuestionNumber++; $iGroupNumber = $grow['gid']; } $_SESSION['flashmessage'] = $clang->gT("Question codes were successfully regenerated."); LimeExpressionManager::SetDirtyFlag(); // so refreshes syntax highlighting } $this->getController()->redirect(array('admin/survey/sa/view/surveyid/' . $iSurveyID)); }
function mssql_drop_constraint($fieldname, $tablename) { global $modifyoutput; Yii::app()->loadHelper("database"); // find out the name of the default constraint // Did I already mention that this is the most suckiest thing I have ever seen in MSSQL database? $dfquery = "SELECT c_obj.name AS constraint_name\n FROM sys.sysobjects AS c_obj INNER JOIN\n sys.sysobjects AS t_obj ON c_obj.parent_obj = t_obj.id INNER JOIN\n sys.sysconstraints AS con ON c_obj.id = con.constid INNER JOIN\n sys.syscolumns AS col ON t_obj.id = col.id AND con.colid = col.colid\n WHERE (c_obj.xtype = 'D') AND (col.name = '{$fieldname}') AND (t_obj.name='{{{$tablename}}}')"; $result = dbExecuteAssoc($dfquery)->read(); $defaultname = $result['CONTRAINT_NAME']; if ($defaultname != false) { modifyDatabase("", "ALTER TABLE {{{$tablename}}} DROP CONSTRAINT {$defaultname[0]}"); echo $modifyoutput; flush(); } }
function action() { global $surveyid; global $thissurvey, $thisstep; global $clienttoken, $tokensexist, $token; global $clang; $clang = Yii::app()->lang; @ini_set('session.gc_maxlifetime', Yii::app()->getConfig('iSessionExpirationTime')); $this->_loadRequiredHelpersAndLibraries(); $param = $this->_getParameters(func_get_args(), $_POST); $surveyid = $param['sid']; Yii::app()->setConfig('surveyID', $surveyid); $thisstep = $param['thisstep']; $move = $param['move']; $clienttoken = $param['token']; $standardtemplaterootdir = Yii::app()->getConfig('standardtemplaterootdir'); if (is_null($thissurvey) && !is_null($surveyid)) { $thissurvey = getSurveyInfo($surveyid); } // unused vars in this method (used in methods using compacted method vars) @($loadname = $param['loadname']); @($loadpass = $param['loadpass']); $sitename = Yii::app()->getConfig('sitename'); if (isset($param['newtest']) && $param['newtest'] == "Y") { killSurveySession($surveyid); } $surveyExists = $surveyid && Survey::model()->findByPk($surveyid); $isSurveyActive = $surveyExists && Survey::model()->findByPk($surveyid)->active == "Y"; // collect all data in this method to pass on later $redata = compact(array_keys(get_defined_vars())); $clang = $this->_loadLimesurveyLang($surveyid); if ($this->_isClientTokenDifferentFromSessionToken($clienttoken, $surveyid)) { $asMessage = array($clang->gT('Token mismatch'), $clang->gT('The token you provided doesn\'t match the one in your session.'), $clang->gT('Please wait to begin with a new session.')); $this->_createNewUserSessionAndRedirect($surveyid, $redata, __LINE__, $asMessage); } if ($this->_isSurveyFinished($surveyid)) { $asMessage = array($clang->gT('Previous session is set to be finished.'), $clang->gT('Your browser reports that it was used previously to answer this survey. We are resetting the session so that you can start from the beginning.'), $clang->gT('Please wait to begin with a new session.')); $this->_createNewUserSessionAndRedirect($surveyid, $redata, __LINE__, $asMessage); } $previewmode = false; if (isset($param['action']) && in_array($param['action'], array('previewgroup', 'previewquestion'))) { if (!$this->_canUserPreviewSurvey($surveyid)) { $asMessage = array($clang->gT('Error'), $clang->gT("We are sorry but you don't have permissions to do this.")); $this->_niceExit($redata, __LINE__, null, $asMessage); } else { if (intval($param['qid']) && $param['action'] == 'previewquestion') { $previewmode = 'question'; } if (intval($param['gid']) && $param['action'] == 'previewgroup') { $previewmode = 'group'; } } } if ($this->_surveyCantBeViewedWithCurrentPreviewAccess($surveyid, $isSurveyActive, $surveyExists)) { $bPreviewRight = $this->_userHasPreviewAccessSession($surveyid); if ($bPreviewRight === false) { $asMessage = array($clang->gT("Error"), $clang->gT("We are sorry but you don't have permissions to do this."), sprintf($clang->gT("Please contact %s ( %s ) for further assistance."), $thissurvey['adminname'], $thissurvey['adminemail'])); $this->_niceExit($redata, __LINE__, null, $asMessage); } } // TODO can this be moved to the top? // (Used to be global, used in ExpressionManager, merged into amVars. If not filled in === '') // can this be added in the first computation of $redata? if (isset($_SESSION['survey_' . $surveyid]['srid'])) { $saved_id = $_SESSION['survey_' . $surveyid]['srid']; } // recompute $redata since $saved_id used to be a global $redata = compact(array_keys(get_defined_vars())); /*if ( $this->_didSessionTimeOut() ) { // @TODO is this still required ? $asMessage = array( $clang->gT("Error"), $clang->gT("We are sorry but your session has expired."), $clang->gT("Either you have been inactive for too long, you have cookies disabled for your browser, or there were problems with your connection."), sprintf($clang->gT("Please contact %s ( %s ) for further assistance."),$thissurvey['adminname'],$thissurvey['adminemail']) ); $this->_niceExit($redata, __LINE__, null, $asMessage); };*/ // Set the language of the survey, either from POST, GET parameter of session var if (!empty($_REQUEST['lang'])) { $sTempLanguage = sanitize_languagecode($_REQUEST['lang']); } elseif (!empty($param['lang'])) { $sTempLanguage = sanitize_languagecode($param['lang']); } elseif (isset($_SESSION['survey_' . $surveyid]['s_lang'])) { $sTempLanguage = $_SESSION['survey_' . $surveyid]['s_lang']; } else { $sTempLanguage = ''; } //CHECK FOR REQUIRED INFORMATION (sid) if ($surveyid && $surveyExists) { LimeExpressionManager::SetSurveyId($surveyid); // must be called early - it clears internal cache if a new survey is being used $clang = SetSurveyLanguage($surveyid, $sTempLanguage); if ($previewmode) { LimeExpressionManager::SetPreviewMode($previewmode); } UpdateGroupList($surveyid, $clang->langcode); // to refresh the language strings in the group list session variable UpdateFieldArray(); // to refresh question titles and question text } else { if (!is_null($param['lang'])) { $sDisplayLanguage = $param['lang']; } else { $sDisplayLanguage = Yii::app()->getConfig('defaultlang'); } $clang = $this->_loadLimesurveyLang($sDisplayLanguage); $languagechanger = makeLanguageChanger($sDisplayLanguage); //Find out if there are any publicly available surveys $query = "SELECT sid, surveyls_title, publicstatistics, language\n FROM {{surveys}}\n INNER JOIN {{surveys_languagesettings}}\n ON ( surveyls_survey_id = sid )\n AND (surveyls_language=language)\n WHERE\n active='Y'\n AND listpublic='Y'\n AND ((expires >= '" . date("Y-m-d H:i") . "') OR (expires is null))\n AND ((startdate <= '" . date("Y-m-d H:i") . "') OR (startdate is null))\n ORDER BY surveyls_title"; $result = dbExecuteAssoc($query, false, true) or safeDie("Could not connect to database. If you try to install LimeSurvey please refer to the <a href='http://docs.limesurvey.org'>installation docs</a> and/or contact the system administrator of this webpage."); //Checked $list = array(); foreach ($result->readAll() as $rows) { # $querylang="SELECT surveyls_title # FROM {{surveys_languagesettings}} # WHERE surveyls_survey_id={$rows['sid']} # AND surveyls_language='{$sDisplayLanguage}'"; # $resultlang=Yii::app()->db->createCommand($querylang)->queryRow(); $resultlang = Surveys_languagesettings::model()->find("surveyls_survey_id=:surveyls_survey_id AND surveyls_language=:surveyls_language", array(':surveyls_survey_id' => intval($rows['sid']), ':surveyls_language' => $sDisplayLanguage)); $langparam = array(); $langtag = ""; if ($resultlang) { $rows['surveyls_title'] = $resultlang->surveyls_title; $langparam = array('lang' => $sDisplayLanguage); } else { $langtag = "lang=\"{$rows['language']}\""; } $link = "<li><a href='" . $this->getController()->createUrl('/survey/index/sid/' . $rows['sid'], $langparam); $link .= "' {$langtag} class='surveytitle'>" . $rows['surveyls_title'] . "</a>\n"; if ($rows['publicstatistics'] == 'Y') { $link .= "<a href='" . $this->getController()->createUrl("/statistics_user/action/surveyid/" . $rows['sid']) . "/language/" . $sDisplayLanguage . "'>(" . $clang->gT('View statistics') . ")</a>"; } $link .= "</li>\n"; $list[] = $link; } //Check for inactive surveys which allow public registration. // TODO add a new template replace {SURVEYREGISTERLIST} ? $squery = "SELECT sid, surveyls_title, publicstatistics, language\n FROM {{surveys}}\n INNER JOIN {{surveys_languagesettings}}\n ON (surveyls_survey_id = sid)\n AND (surveyls_language=language)\n WHERE allowregister='Y'\n AND active='Y'\n AND listpublic='Y'\n AND ((expires >= '" . date("Y-m-d H:i") . "') OR (expires is null))\n AND (startdate >= '" . date("Y-m-d H:i") . "')\n ORDER BY surveyls_title"; $sresult = dbExecuteAssoc($squery) or safeDie("Couldn't execute {$squery}"); $aRows = $sresult->readAll(); if (count($aRows) > 0) { $list[] = "</ul>" . " <div class=\"survey-list-heading\">" . $clang->gT("Following survey(s) are not yet active but you can register for them.") . "</div>" . " <ul>"; // TODO give it to template foreach ($aRows as $rows) { $querylang = "SELECT surveyls_title\n FROM {{surveys_languagesettings}}\n WHERE surveyls_survey_id={$rows['sid']}\n AND surveyls_language='{$sDisplayLanguage}'"; $resultlang = Yii::app()->db->createCommand($querylang)->queryRow(); if ($resultlang['surveyls_title']) { $rows['surveyls_title'] = $resultlang['surveyls_title']; $langtag = ""; } else { $langtag = "lang=\"{$rows['language']}\""; } $link = "<li><a href=\"#\" id='inactivesurvey' onclick = 'sendreq(" . $rows['sid'] . ");' "; //$link = "<li><a href=\"#\" id='inactivesurvey' onclick = 'convertGETtoPOST(".$this->getController()->createUrl('survey/send/')."?sid={$rows['sid']}&)sendreq(".$rows['sid'].",".$rows['startdate'].",".$rows['expires'].");' "; $link .= " {$langtag} class='surveytitle'>" . $rows['surveyls_title'] . "</a>\n"; $link .= "</li><div id='regform'></div>\n"; $list[] = $link; } } if (count($list) < 1) { $list[] = "<li class='surveytitle'>" . $clang->gT("No available surveys") . "</li>"; } if (!$surveyid) { $thissurvey['name'] = Yii::app()->getConfig("sitename"); $nosid = $clang->gT("You have not provided a survey identification number"); } else { $thissurvey['name'] = $clang->gT("The survey identification number is invalid"); $nosid = $clang->gT("The survey identification number is invalid"); } $surveylist = array("nosid" => $nosid, "contact" => sprintf($clang->gT("Please contact %s ( %s ) for further assistance."), Yii::app()->getConfig("siteadminname"), encodeEmail(Yii::app()->getConfig("siteadminemail"))), "listheading" => $clang->gT("The following surveys are available:"), "list" => implode("\n", $list)); $data['thissurvey'] = $thissurvey; //$data['privacy'] = $privacy; $data['surveylist'] = $surveylist; $data['surveyid'] = $surveyid; $data['templatedir'] = getTemplatePath(Yii::app()->getConfig("defaulttemplate")); $data['templateurl'] = getTemplateURL(Yii::app()->getConfig("defaulttemplate")) . "/"; $data['templatename'] = Yii::app()->getConfig("defaulttemplate"); $data['sitename'] = Yii::app()->getConfig("sitename"); $data['languagechanger'] = $languagechanger; //A nice exit sendCacheHeaders(); doHeader(); $this->_printTemplateContent(getTemplatePath(Yii::app()->getConfig("defaulttemplate")) . "/startpage.pstpl", $data, __LINE__); $this->_printTemplateContent(getTemplatePath(Yii::app()->getConfig("defaulttemplate")) . "/surveylist.pstpl", $data, __LINE__); echo '<script type="text/javascript" > function sendreq(surveyid) { $.ajax({ type: "GET", url: "' . $this->getController()->createUrl("/register/ajaxregisterform/surveyid") . '/" + surveyid, }).done(function(msg) { document.getElementById("regform").innerHTML = msg; }); } </script>'; $this->_printTemplateContent(getTemplatePath(Yii::app()->getConfig("defaulttemplate")) . "/endpage.pstpl", $data, __LINE__); doFooter(); exit; } // Get token if (!isset($token)) { $token = $clienttoken; } //GET BASIC INFORMATION ABOUT THIS SURVEY $thissurvey = getSurveyInfo($surveyid, $_SESSION['survey_' . $surveyid]['s_lang']); //SEE IF SURVEY USES TOKENS if ($surveyExists == 1 && tableExists('{{tokens_' . $thissurvey['sid'] . '}}')) { $tokensexist = 1; } else { $tokensexist = 0; unset($_POST['token']); unset($param['token']); unset($token); unset($clienttoken); } //SET THE TEMPLATE DIRECTORY $thistpl = getTemplatePath($thissurvey['templatedir']); $timeadjust = Yii::app()->getConfig("timeadjust"); //MAKE SURE SURVEY HASN'T EXPIRED if ($thissurvey['expiry'] != '' and dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust) > $thissurvey['expiry'] && $thissurvey['active'] != 'N' && !$previewmode) { $redata = compact(array_keys(get_defined_vars())); $asMessage = array($clang->gT("Error"), $clang->gT("This survey is no longer available."), sprintf($clang->gT("Please contact %s ( %s ) for further assistance."), $thissurvey['adminname'], $thissurvey['adminemail'])); $this->_niceExit($redata, __LINE__, $thissurvey['templatedir'], $asMessage); } //MAKE SURE SURVEY IS ALREADY VALID if ($thissurvey['startdate'] != '' and dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust) < $thissurvey['startdate'] && $thissurvey['active'] != 'N' && !$previewmode) { $redata = compact(array_keys(get_defined_vars())); $asMessage = array($clang->gT("Error"), $clang->gT("This survey is not yet started."), sprintf($clang->gT("Please contact %s ( %s ) for further assistance."), $thissurvey['adminname'], $thissurvey['adminemail'])); $this->_niceExit($redata, __LINE__, $thissurvey['templatedir'], $asMessage); } //CHECK FOR PREVIOUSLY COMPLETED COOKIE //If cookies are being used, and this survey has been completed, a cookie called "PHPSID[sid]STATUS" will exist (ie: SID6STATUS) and will have a value of "COMPLETE" $sCookieName = "LS_" . $surveyid . "_STATUS"; if (isset($_COOKIE[$sCookieName]) && $_COOKIE[$sCookieName] == "COMPLETE" && $thissurvey['usecookie'] == "Y" && $tokensexist != 1 && (!isset($param['newtest']) || $param['newtest'] != "Y")) { $redata = compact(array_keys(get_defined_vars())); $asMessage = array($clang->gT("Error"), $clang->gT("You have already completed this survey."), sprintf($clang->gT("Please contact %s ( %s ) for further assistance."), $thissurvey['adminname'], $thissurvey['adminemail'])); $this->_niceExit($redata, __LINE__, $thissurvey['templatedir'], $asMessage); } if (isset($_GET['loadall']) && $_GET['loadall'] == "reload") { if (returnGlobal('loadname') && returnGlobal('loadpass')) { $_POST['loadall'] = "reload"; } } //LOAD SAVED SURVEY if (isset($_POST['loadall']) && $_POST['loadall'] == "reload") { $errormsg = ""; if (!isset($param['loadname']) || $param['loadname'] == null) { $errormsg .= $clang->gT("You did not provide a name") . "<br />\n"; } if (!isset($param['loadpass']) || $param['loadpass'] == null) { $errormsg .= $clang->gT("You did not provide a password") . "<br />\n"; } // if security question answer is incorrect // Not called if scid is set in GET params (when using email save/reload reminder URL) if (function_exists("ImageCreate") && isCaptchaEnabled('saveandloadscreen', $thissurvey['usecaptcha'])) { if ((!isset($_POST['loadsecurity']) || !isset($_SESSION['survey_' . $surveyid]['secanswer']) || $_POST['loadsecurity'] != $_SESSION['survey_' . $surveyid]['secanswer']) && !isset($_GET['scid'])) { $errormsg .= $clang->gT("The answer to the security question is incorrect.") . "<br />\n"; } } // Load session before loading the values from the saved data if (isset($_GET['loadall'])) { buildsurveysession($surveyid); } $_SESSION['survey_' . $surveyid]['holdname'] = $param['loadname']; //Session variable used to load answers every page. $_SESSION['survey_' . $surveyid]['holdpass'] = $param['loadpass']; //Session variable used to load answers every page. if ($errormsg == "") { loadanswers(); } $move = "movenext"; if ($errormsg) { $_POST['loadall'] = $clang->gT("Load unfinished survey"); } } //Allow loading of saved survey if (isset($_POST['loadall']) && $_POST['loadall'] == $clang->gT("Load unfinished survey")) { $redata = compact(array_keys(get_defined_vars())); Yii::import("application.libraries.Load_answers"); $tmp = new Load_answers(); $tmp->run($redata); } //Check if TOKEN is used for EVERY PAGE //This function fixes a bug where users able to submit two surveys/votes //by checking that the token has not been used at each page displayed. // bypass only this check at first page (Step=0) because // this check is done in buildsurveysession and error message // could be more interresting there (takes into accound captcha if used) if ($tokensexist == 1 && isset($token) && $token && isset($_SESSION['survey_' . $surveyid]['step']) && $_SESSION['survey_' . $surveyid]['step'] > 0 && tableExists("tokens_{$surveyid}}}")) { //check if tokens actually haven't been already used $areTokensUsed = usedTokens(trim(strip_tags(returnGlobal('token'))), $surveyid); // check if token actually does exist // check also if it is allowed to change survey after completion if ($thissurvey['alloweditaftercompletion'] == 'Y') { $sQuery = "SELECT * FROM {{tokens_" . $surveyid . "}} WHERE token='" . $token . "'"; } else { $sQuery = "SELECT * FROM {{tokens_" . $surveyid . "}} WHERE token='" . $token . "' AND (completed = 'N' or completed='')"; } $aRow = Yii::app()->db->createCommand($sQuery)->queryRow(); $tokendata = $aRow; if (!$aRow || $areTokensUsed && $thissurvey['alloweditaftercompletion'] != 'Y' && !$previewmode) { sendCacheHeaders(); doHeader(); //TOKEN DOESN'T EXIST OR HAS ALREADY BEEN USED. EXPLAIN PROBLEM AND EXIT $redata = compact(array_keys(get_defined_vars())); $this->_printTemplateContent($thistpl . '/startpage.pstpl', $redata, __LINE__); $this->_printTemplateContent($thistpl . '/survey.pstpl', $redata, __LINE__); $asMessage = array(null, $clang->gT("This is a controlled survey. You need a valid token to participate."), sprintf($clang->gT("For further information please contact %s"), $thissurvey['adminname'] . " (<a href='mailto:{$thissurvey['adminemail']}'>" . "{$thissurvey['adminemail']}</a>)")); $this->_niceExit($redata, __LINE__, $thistpl, $asMessage, true); } } if ($tokensexist == 1 && isset($token) && $token && tableExists("{{tokens_" . $surveyid . "}}") && !$previewmode) { // check also if it is allowed to change survey after completion if ($thissurvey['alloweditaftercompletion'] == 'Y') { $tkquery = "SELECT * FROM {{tokens_" . $surveyid . "}} WHERE token='" . $token . "'"; } else { $tkquery = "SELECT * FROM {{tokens_" . $surveyid . "}} WHERE token='" . $token . "' AND (completed = 'N' or completed='')"; } $tkresult = dbExecuteAssoc($tkquery); //Checked $tokendata = $tkresult->read(); $tkresult->close(); //Close the result in case there are more result rows, we are only interested in one and don't want unbuffered query errors if (isset($tokendata['validfrom']) && (trim($tokendata['validfrom']) != '' && $tokendata['validfrom'] > dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust)) || isset($tokendata['validuntil']) && (trim($tokendata['validuntil']) != '' && $tokendata['validuntil'] < dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust))) { sendCacheHeaders(); doHeader(); //TOKEN DOESN'T EXIST OR HAS ALREADY BEEN USED. EXPLAIN PROBLEM AND EXIT $redata = compact(array_keys(get_defined_vars())); $this->_printTemplateContent($thistpl . '/startpage.pstpl', $redata, __LINE__); $this->_printTemplateContent($thistpl . '/survey.pstpl', $redata, __LINE__); $asMessage = array(null, $clang->gT("We are sorry but you are not allowed to enter this survey."), $clang->gT("Your token seems to be valid but can be used only during a certain time period."), sprintf($clang->gT("For further information please contact %s"), $thissurvey['adminname'] . " (<a href='mailto:{$thissurvey['adminemail']}'>" . "{$thissurvey['adminemail']}</a>)")); $this->_niceExit($redata, __LINE__, $thistpl, $asMessage, true); } } //Clear session and remove the incomplete response if requested. if (isset($move) && $move == "clearall") { // delete the response but only if not already completed $s_lang = $_SESSION['survey_' . $surveyid]['s_lang']; if (isset($_SESSION['survey_' . $surveyid]['srid']) && !Survey_dynamic::model($surveyid)->isCompleted($_SESSION['survey_' . $surveyid]['srid'])) { // delete the response but only if not already completed $result = dbExecuteAssoc('DELETE FROM {{survey_' . $surveyid . '}} WHERE id=' . $_SESSION['survey_' . $surveyid]['srid'] . " AND submitdate IS NULL"); if ($result->count() > 0) { // Using count() here *should* be okay for MSSQL because it is a delete statement // find out if there are any fuqt questions - checked $fieldmap = createFieldMap($surveyid, 'short', false, false, $s_lang); foreach ($fieldmap as $field) { if ($field['type'] == "|" && !strpos($field['fieldname'], "_filecount")) { if (!isset($qid)) { $qid = array(); } $qid[] = $field['fieldname']; } } // if yes, extract the response json to those questions if (isset($qid)) { $query = "SELECT * FROM {{survey_" . $surveyid . "}} WHERE id=" . $_SESSION['survey_' . $surveyid]['srid']; $result = dbExecuteAssoc($query); foreach ($result->readAll() as $row) { foreach ($qid as $question) { $json = $row[$question]; if ($json == "" || $json == NULL) { continue; } // decode them $phparray = json_decode($json); foreach ($phparray as $metadata) { $target = Yii::app()->getConfig("uploaddir") . "/surveys/" . $surveyid . "/files/"; // delete those files unlink($target . $metadata->filename); } } } } // done deleting uploaded files } // also delete a record from saved_control when there is one dbExecuteAssoc('DELETE FROM {{saved_control}} WHERE srid=' . $_SESSION['survey_' . $surveyid]['srid'] . ' AND sid=' . $surveyid); } killSurveySession($surveyid); sendCacheHeaders(); doHeader(); $redata = compact(array_keys(get_defined_vars())); $this->_printTemplateContent($thistpl . '/startpage.pstpl', $redata, __LINE__); echo "\n\n<!-- JAVASCRIPT FOR CONDITIONAL QUESTIONS -->\n" . "\t<script type='text/javascript'>\n" . "\t<!--\n" . "function checkconditions(value, name, type, evt_type)\n" . "\t{\n" . "\t}\n" . "\t//-->\n" . "\t</script>\n\n"; //Present the clear all page using clearall.pstpl template $this->_printTemplateContent($thistpl . '/clearall.pstpl', $redata, __LINE__); $this->_printTemplateContent($thistpl . '/endpage.pstpl', $redata, __LINE__); doFooter(); exit; } //Check to see if a refering URL has been captured. if (!isset($_SESSION['survey_' . $surveyid]['refurl'])) { $_SESSION['survey_' . $surveyid]['refurl'] = GetReferringUrl(); // do not overwrite refurl } // Let's do this only if // - a saved answer record hasn't been loaded through the saved feature // - the survey is not anonymous // - the survey is active // - a token information has been provided // - the survey is setup to allow token-response-persistence if (!isset($_SESSION['survey_' . $surveyid]['srid']) && $thissurvey['anonymized'] == "N" && $thissurvey['active'] == "Y" && isset($token) && $token != '') { // load previous answers if any (dataentry with nosubmit) $sQuery = "SELECT id,submitdate,lastpage FROM {$thissurvey['tablename']} WHERE {$thissurvey['tablename']}.token='{$token}' order by id desc"; $aRow = Yii::app()->db->createCommand($sQuery)->queryRow(); if ($aRow) { if ($aRow['submitdate'] == '' && $thissurvey['tokenanswerspersistence'] == 'Y' || $aRow['submitdate'] != '' && $thissurvey['alloweditaftercompletion'] == 'Y') { $_SESSION['survey_' . $surveyid]['srid'] = $aRow['id']; if (!is_null($aRow['lastpage']) && $aRow['submitdate'] == '') { $_SESSION['survey_' . $surveyid]['LEMtokenResume'] = true; $_SESSION['survey_' . $surveyid]['step'] = $aRow['lastpage']; } } buildsurveysession($surveyid); loadanswers(); } } // Preview action : Preview right already tested before if ($previewmode) { // Unset all SESSION: be sure to have the last version unset($_SESSION['fieldmap-' . $surveyid . $clang->langcode]); // Needed by createFieldMap: else fieldmap can be outdated unset($_SESSION['survey_' . $surveyid]); if ($param['action'] == 'previewgroup') { $thissurvey['format'] = 'G'; } elseif ($param['action'] == 'previewquestion') { $thissurvey['format'] = 'S'; } buildsurveysession($surveyid, true); } sendCacheHeaders(); //Send local variables to the appropriate survey type unset($redata); $redata = compact(array_keys(get_defined_vars())); Yii::import('application.helpers.SurveyRuntimeHelper'); $tmp = new SurveyRuntimeHelper(); $tmp->run($surveyid, $redata); if (isset($_POST['saveall']) || isset($flashmessage)) { echo "<script type='text/javascript'> \$(document).ready( function() { alert('" . $clang->gT("Your responses were successfully saved.", "js") . "');}) </script>"; } }