/** * 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); } }
/** * Construction of replacement array, actually doing it with redata * * @param $aQuestionQanda : array from qanda helper * @return aray of replacement for question.psptl **/ public static function getQuestionReplacement($aQuestionQanda) { // Get the default replacement and set empty value by default $aReplacement = array("QID" => "", "SGQ" => "", "AID" => "", "QUESTION_CODE" => "", "QUESTION_NUMBER" => "", "QUESTION" => "", "QUESTION_TEXT" => "", "QUESTIONHELP" => "", "QUESTIONHELPPLAINTEXT" => "", "QUESTION_CLASS" => "", "QUESTION_MAN_CLASS" => "", "QUESTION_INPUT_ERROR_CLASS" => "", "ANSWER" => "", "QUESTION_HELP" => "", "QUESTION_VALID_MESSAGE" => "", "QUESTION_FILE_VALID_MESSAGE" => "", "QUESTION_MAN_MESSAGE" => "", "QUESTION_MANDATORY" => "", "QUESTION_ESSENTIALS" => ""); if (!is_array($aQuestionQanda) || empty($aQuestionQanda[0])) { return $aReplacement; } $iQid = $aQuestionQanda[4]; $lemQuestionInfo = LimeExpressionManager::GetQuestionStatus($iQid); $iSurveyId = Yii::app()->getConfig('surveyID'); // Or : by SGQA of question ? by Question::model($iQid)->sid; $oSurveyId = Survey::model()->findByPk($iSurveyId); $sType = $lemQuestionInfo['info']['type']; // Core value : not replaced $aReplacement['QID'] = $iQid; $aReplacement['GID'] = $aQuestionQanda[6]; // Not sure for aleatory : it's the real gid or the updated gid ? We need original gid or updated gid ? $aReplacement['SGQ'] = $aQuestionQanda[7]; $aReplacement['AID'] = isset($aQuestionQanda[0]['aid']) ? $aQuestionQanda[0]['aid'] : ""; $aReplacement['QUESTION_CODE'] = $aReplacement['QUESTION_NUMBER'] = ""; $sCode = $aQuestionQanda[5]; $iNumber = $aQuestionQanda[0]['number']; switch (Yii::app()->getConfig('showqnumcode')) { case 'both': $aReplacement['QUESTION_CODE'] = $sCode; $aReplacement['QUESTION_NUMBER'] = $iNumber; break; case 'number': $aReplacement['QUESTION_NUMBER'] = $iNumber; break; case 'number': $aReplacement['QUESTION_CODE'] = $sCode; break; case 'choose': default: switch ($oSurveyId->showqnumcode) { case 'B': // Both $aReplacement['QUESTION_CODE'] = $sCode; $aReplacement['QUESTION_NUMBER'] = $iNumber; break; case 'N': $aReplacement['QUESTION_NUMBER'] = $iNumber; break; case 'C': $aReplacement['QUESTION_CODE'] = $sCode; break; case 'X': default: break; } break; } $aReplacement['QUESTION'] = $aQuestionQanda[0]['all']; // Deprecated : only used in old template (very old) // Core value : user text $aReplacement['QUESTION_TEXT'] = $aQuestionQanda[0]['text']; $aReplacement['QUESTIONHELP'] = $lemQuestionInfo['info']['help']; // User help // To be moved in a extra plugin : QUESTIONHELP img adding $sTemplateDir = Template::model()->getTemplatePath($oSurveyId->template); $sTemplateUrl = Template::model()->getTemplateURL($oSurveyId->template); if (flattenText($aReplacement['QUESTIONHELP'], true, true) != '') { $aReplacement['QUESTIONHELP'] = Yii::app()->getController()->renderPartial('/survey/system/questionhelp/questionhelp', array('questionHelp' => $aReplacement['QUESTIONHELP']), true); } // Core value :the classes $aReplacement['QUESTION_CLASS'] = Question::getQuestionClass($sType); //get additional question classes from question attribute $aQuestionAttributes = getQuestionAttributeValues($aQuestionQanda[4]); //add additional classes if (isset($aQuestionAttributes['cssclass'])) { $aReplacement['QUESTION_CLASS'] .= " " . $aQuestionAttributes['cssclass']; } $aMandatoryClass = array(); if ($lemQuestionInfo['info']['mandatory'] == 'Y') { $aMandatoryClass[] = 'mandatory'; } if ($lemQuestionInfo['anyUnanswered'] && $_SESSION['survey_' . $iSurveyId]['maxstep'] != $_SESSION['survey_' . $iSurveyId]['step']) { $aMandatoryClass[] = 'missing'; } $aReplacement['QUESTION_MAN_CLASS'] = !empty($aMandatoryClass) ? " " . implode(" ", $aMandatoryClass) : ""; $aReplacement['QUESTION_INPUT_ERROR_CLASS'] = $aQuestionQanda[0]['input_error_class']; // Core value : LS text : EM and not $aReplacement['ANSWER'] = $aQuestionQanda[1]; $aReplacement['QUESTION_HELP'] = $aQuestionQanda[0]['help']; // Core help only, not EM $aReplacement['QUESTION_VALID_MESSAGE'] = $aQuestionQanda[0]['valid_message']; // $lemQuestionInfo['validTip'] $aReplacement['QUESTION_FILE_VALID_MESSAGE'] = $aQuestionQanda[0]['file_valid_message']; // $lemQuestionInfo['??'] $aReplacement['QUESTION_MAN_MESSAGE'] = $aQuestionQanda[0]['man_message']; $aReplacement['QUESTION_MANDATORY'] = $aQuestionQanda[0]['mandatory']; // For QUESTION_ESSENTIALS $aHtmlOptions = array(); if (!$lemQuestionInfo['relevant'] || $lemQuestionInfo['hidden']) { $aHtmlOptions['style'] = 'display: none;'; } // Launch the event $event = new PluginEvent('beforeQuestionRender'); // Some helper $event->set('surveyId', $iSurveyId); $event->set('type', $sType); $event->set('code', $sCode); $event->set('qid', $iQid); $event->set('gid', $aReplacement['GID']); // User text $event->set('text', $aReplacement['QUESTION_TEXT']); $event->set('questionhelp', $aReplacement['QUESTIONHELP']); // The classes $event->set('class', $aReplacement['QUESTION_CLASS']); $event->set('man_class', $aReplacement['QUESTION_MAN_CLASS']); $event->set('input_error_class', $aReplacement['QUESTION_INPUT_ERROR_CLASS']); // LS core text $event->set('answers', $aReplacement['ANSWER']); $event->set('help', $aReplacement['QUESTION_HELP']); $event->set('man_message', $aReplacement['QUESTION_MAN_MESSAGE']); $event->set('valid_message', $aReplacement['QUESTION_VALID_MESSAGE']); $event->set('file_valid_message', $aReplacement['QUESTION_FILE_VALID_MESSAGE']); // htmlOptions for container $event->set('aHtmlOptions', $aHtmlOptions); App()->getPluginManager()->dispatchEvent($event); // User text $aReplacement['QUESTION_TEXT'] = $event->get('text'); $aReplacement['QUESTIONHELP'] = $event->get('questionhelp'); $aReplacement['QUESTIONHELPPLAINTEXT'] = strip_tags(addslashes($aReplacement['QUESTIONHELP'])); // The classes $aReplacement['QUESTION_CLASS'] = $event->get('class'); $aReplacement['QUESTION_MAN_CLASS'] = $event->get('man_class'); $aReplacement['QUESTION_INPUT_ERROR_CLASS'] = $event->get('input_error_class'); // LS core text $aReplacement['ANSWER'] = $event->get('answers'); $aReplacement['QUESTION_HELP'] = $event->get('help'); $aReplacement['QUESTION_MAN_MESSAGE'] = $event->get('man_message'); $aReplacement['QUESTION_VALID_MESSAGE'] = $event->get('valid_message'); $aReplacement['QUESTION_FILE_VALID_MESSAGE'] = $event->get('file_valid_message'); $aReplacement['QUESTION_MANDATORY'] = $event->get('mandatory', $aReplacement['QUESTION_MANDATORY']); // Always add id for QUESTION_ESSENTIALS $aHtmlOptions['id'] = "question{$iQid}"; $aReplacement['QUESTION_ESSENTIALS'] = CHtml::renderAttributes($aHtmlOptions); return $aReplacement; }
function do_multiplenumeric($ia) { global $thissurvey; $extraclass = ""; $checkconditionFunction = "fixnum_checkconditions"; $aQuestionAttributes = getQuestionAttributeValues($ia[0]); $answer = ''; $sSeparator = getRadixPointData($thissurvey['surveyls_numberformat']); $sSeparator = $sSeparator['separator']; //Must turn on the "numbers only javascript" $extraclass .= " numberonly"; if ($aQuestionAttributes['thousands_separator'] == 1) { App()->clientScript->registerPackage('jquery-price-format'); App()->clientScript->registerScriptFile('scripts/numerical_input.js'); $extraclass .= " thousandsseparator"; } if (intval(trim($aQuestionAttributes['maximum_chars'])) > 0) { // Only maxlength attribute, use textarea[maxlength] jquery selector for textarea $maximum_chars = intval(trim($aQuestionAttributes['maximum_chars'])); $maxlength = "maxlength='{$maximum_chars}' "; $extraclass .= " maxchars maxchars-" . $maximum_chars; } else { $maxlength = " maxlength='25' "; } if (trim($aQuestionAttributes['prefix'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']]) != '') { $prefix = $aQuestionAttributes['prefix'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']]; $extraclass .= " withprefix"; } else { $prefix = ''; } if (trim($aQuestionAttributes['suffix'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']]) != '') { $suffix = $aQuestionAttributes['suffix'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']]; $extraclass .= " withsuffix"; } else { $suffix = ''; } if ($thissurvey['nokeyboard'] == 'Y') { includeKeypad(); $kpclass = "num-keypad"; $extraclass .= " keypad"; } else { $kpclass = ""; } $numbersonly_slider = ''; // DEPRECATED if (trim($aQuestionAttributes['text_input_width']) != '') { $tiwidth = $aQuestionAttributes['text_input_width']; $extraclass .= " inputwidth" . trim($aQuestionAttributes['text_input_width']); } else { $tiwidth = 10; } $prefixclass = "numeric"; if ($aQuestionAttributes['slider_layout'] == 1) { $prefixclass = "slider"; $slider_layout = true; $extraclass .= " withslider"; $slider_step = trim(LimeExpressionManager::ProcessString("{{$aQuestionAttributes['slider_accuracy']}}", $ia[0], array(), false, 1, 1, false, false, true)); $slider_step = is_numeric($slider_step) ? $slider_step : 1; $slider_min = trim(LimeExpressionManager::ProcessString("{{$aQuestionAttributes['slider_min']}}", $ia[0], array(), false, 1, 1, false, false, true)); $slider_mintext = $slider_min = is_numeric($slider_min) ? $slider_min : 0; $slider_max = trim(LimeExpressionManager::ProcessString("{{$aQuestionAttributes['slider_max']}}", $ia[0], array(), false, 1, 1, false, false, true)); $slider_maxtext = $slider_max = is_numeric($slider_max) ? $slider_max : 100; $slider_default = trim(LimeExpressionManager::ProcessString("{{$aQuestionAttributes['slider_default']}}", $ia[0], array(), false, 1, 1, false, false, true)); $slider_default = is_numeric($slider_default) ? $slider_default : ""; if ($slider_default == '' && $aQuestionAttributes['slider_middlestart'] == 1) { $slider_middlestart = intval(($slider_max + $slider_min) / 2); } else { $slider_middlestart = ''; } $slider_separator = trim($aQuestionAttributes['slider_separator']) != '' ? $aQuestionAttributes['slider_separator'] : ""; $slider_reset = $aQuestionAttributes['slider_reset'] ? 1 : 0; } else { $slider_layout = false; } $hidetip = $aQuestionAttributes['hide_tip']; if ($aQuestionAttributes['random_order'] == 1) { $ansquery = "SELECT * FROM {{questions}} WHERE parent_qid={$ia['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 language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "' ORDER BY question_order"; } $ansresult = dbExecuteAssoc($ansquery); //Checked $aSubquestions = $ansresult->readAll(); $anscount = count($aSubquestions) * 2; $fn = 1; $answer_main = ''; if ($anscount == 0) { $inputnames = array(); $answer_main .= ' <li>' . gT('Error: This question has no answers.') . "</li>\n"; } else { foreach ($aSubquestions as $ansrow) { $myfname = $ia[1] . $ansrow['title']; if ($ansrow['question'] == "") { $ansrow['question'] = " "; } if ($slider_layout === false || $slider_separator == '') { $theanswer = $ansrow['question']; $sliderleft = ''; $sliderright = ''; } else { $aAnswer = explode($slider_separator, $ansrow['question']); $theanswer = isset($aAnswer[0]) ? $aAnswer[0] : ""; $sliderleft = isset($aAnswer[1]) ? $aAnswer[1] : ""; $sliderright = isset($aAnswer[2]) ? $aAnswer[2] : ""; $sliderleft = "<div class=\"slider_lefttext\">{$sliderleft}</div>"; $sliderright = "<div class=\"slider_righttext\">{$sliderright}</div>"; } // color code missing mandatory questions red if ($ia[6] == 'Y' && $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname] === '') { $theanswer = "<span class='errormandatory'>{$theanswer}</span>"; } list($htmltbody2, $hiddenfield) = return_array_filter_strings($ia, $aQuestionAttributes, $thissurvey, $ansrow, $myfname, '', $myfname, "li", "question-item answer-item text-item numeric-item" . $extraclass); $answer_main .= "\t{$htmltbody2}\n"; $answer_main .= "<label for=\"answer{$myfname}\" class=\"{$prefixclass}-label\">{$theanswer}</label>\n"; $sSeparator = getRadixPointData($thissurvey['surveyls_numberformat']); $sSeparator = $sSeparator['separator']; $answer_main .= "{$sliderleft}<span class=\"input\">\n\t" . $prefix . "\n\t<input class=\"text {$kpclass}\" type=\"text\" size=\"" . $tiwidth . "\" name=\"" . $myfname . "\" id=\"answer" . $myfname . "\" title=\"" . gT('Only numbers may be entered in this field.') . "\" value=\""; if (isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname])) { $dispVal = $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname]; if (strpos($dispVal, ".")) { $dispVal = rtrim(rtrim($dispVal, "0"), "."); } $dispVal = str_replace('.', $sSeparator, $dispVal); $answer_main .= $dispVal; } $answer_main .= '" onkeyup="' . $checkconditionFunction . '(this.value, this.name, this.type);" ' . " {$maxlength} />\n\t" . $suffix . "\n</span>{$sliderright}\n\t</li>\n"; $fn++; $inputnames[] = $myfname; } if (trim($aQuestionAttributes['equals_num_value']) != '' || trim($aQuestionAttributes['min_num_value']) != '' || trim($aQuestionAttributes['max_num_value']) != '') { $qinfo = LimeExpressionManager::GetQuestionStatus($ia[0]); if (trim($aQuestionAttributes['equals_num_value']) != '') { $answer_main .= "\t<li class='multiplenumerichelp help-item'>\n" . "<span class=\"label\">" . gT('Remaining: ') . "</span>\n" . "<span id=\"remainingvalue_{$ia[0]}\" class=\"dynamic_remaining\">{$prefix}\n" . "{" . $qinfo['sumRemainingEqn'] . "}\n" . "{$suffix}</span>\n" . "\t</li>\n"; } $answer_main .= "\t<li class='multiplenumerichelp help-item'>\n" . "<span class=\"label\">" . gT('Total: ') . "</span>\n" . "<span id=\"totalvalue_{$ia[0]}\" class=\"dynamic_sum\">{$prefix}\n" . "{" . $qinfo['sumEqn'] . "}\n" . "{$suffix}</span>\n" . "\t</li>\n"; } $answer .= "<ul class=\"subquestions-list questions-list text-list {$prefixclass}-list\">\n" . $answer_main . "</ul>\n"; } if ($aQuestionAttributes['slider_layout'] == 1) { Yii::app()->getClientScript()->registerScriptFile(Yii::app()->getConfig('generalscripts') . "numeric-slider.js"); Yii::app()->getClientScript()->registerCssFile(Yii::app()->getConfig('publicstyleurl') . "numeric-slider.css"); if ($slider_default != "") { $slider_startvalue = $slider_default; $slider_displaycallout = 1; } elseif ($slider_middlestart != '') { $slider_startvalue = $slider_middlestart; $slider_displaycallout = 0; } else { $slider_startvalue = 'NULL'; $slider_displaycallout = 0; } $slider_showminmax = $aQuestionAttributes['slider_showminmax'] == 1 ? 1 : 0; //some var for slider $aJsLang = array('reset' => gT('Reset'), 'tip' => gT('Please click and drag the slider handles to enter your answer.')); $aJsVar = array('slider_showminmax' => $slider_showminmax, 'slider_min' => $slider_min, 'slider_mintext' => $slider_mintext, 'slider_max' => $slider_max, 'slider_maxtext' => $slider_maxtext, 'slider_step' => $slider_step, 'slider_startvalue' => $slider_startvalue, 'slider_displaycallout' => $slider_displaycallout, 'slider_prefix' => $prefix, 'slider_suffix' => $suffix, 'slider_reset' => $slider_reset, 'lang' => $aJsLang); $answer .= "<script type='text/javascript'><!--\n" . " doNumericSlider({$ia[0]}," . ls_json_encode($aJsVar) . ");\n" . " //--></script>"; } $sSeparator = getRadixPointData($thissurvey['surveyls_numberformat']); $sSeparator = $sSeparator['separator']; return array($answer, $inputnames); }
/** * Show printable survey */ function index($surveyid, $lang = null) { $surveyid = sanitize_int($surveyid); if (!Permission::model()->hasSurveyPermission($surveyid, 'surveycontent', 'read')) { $aData['surveyid'] = $surveyid; App()->getClientScript()->registerPackage('jquery-superfish'); $message['title'] = gT('Access denied!'); $message['message'] = gT('You do not have sufficient rights to access this page.'); $message['class'] = "error"; $this->_renderWrappedTemplate('survey', array("message" => $message), $aData); } else { $aSurveyInfo = getSurveyInfo($surveyid, $lang); if (!$aSurveyInfo) { $this->getController()->error('Invalid survey ID'); } SetSurveyLanguage($surveyid, $lang); $sLanguageCode = App()->language; $templatename = $aSurveyInfo['template']; $welcome = $aSurveyInfo['surveyls_welcometext']; $end = $aSurveyInfo['surveyls_endtext']; $surveyname = $aSurveyInfo['surveyls_title']; $surveydesc = $aSurveyInfo['surveyls_description']; $surveyactive = $aSurveyInfo['active']; $surveytable = "{{survey_" . $aSurveyInfo['sid'] . "}}"; $surveyexpirydate = $aSurveyInfo['expires']; $surveyfaxto = $aSurveyInfo['faxto']; $dateformattype = $aSurveyInfo['surveyls_dateformat']; Yii::app()->loadHelper('surveytranslator'); if (!is_null($surveyexpirydate)) { $dformat = getDateFormatData($dateformattype); $dformat = $dformat['phpdate']; $expirytimestamp = strtotime($surveyexpirydate); $expirytimeofday_h = date('H', $expirytimestamp); $expirytimeofday_m = date('i', $expirytimestamp); $surveyexpirydate = date($dformat, $expirytimestamp); if (!empty($expirytimeofday_h) || !empty($expirytimeofday_m)) { $surveyexpirydate .= ' – ' . $expirytimeofday_h . ':' . $expirytimeofday_m; } sprintf(gT("Please submit by %s"), $surveyexpirydate); } else { $surveyexpirydate = ''; } //Fix $templatename : control if print_survey.pstpl exist if (is_file(getTemplatePath($templatename) . DIRECTORY_SEPARATOR . 'print_survey.pstpl')) { $templatename = $templatename; // Change nothing } elseif (is_file(getTemplatePath(Yii::app()->getConfig("defaulttemplate")) . DIRECTORY_SEPARATOR . 'print_survey.pstpl')) { $templatename = Yii::app()->getConfig("defaulttemplate"); } else { $templatename = "default"; } $sFullTemplatePath = getTemplatePath($templatename) . DIRECTORY_SEPARATOR; $sFullTemplateUrl = getTemplateURL($templatename) . "/"; define('PRINT_TEMPLATE_DIR', $sFullTemplatePath, true); define('PRINT_TEMPLATE_URL', $sFullTemplateUrl, true); LimeExpressionManager::StartSurvey($surveyid, 'survey', NULL, false, LEM_PRETTY_PRINT_ALL_SYNTAX); $moveResult = LimeExpressionManager::NavigateForwards(); $condition = "sid = '{$surveyid}' AND language = '{$sLanguageCode}'"; $degresult = QuestionGroup::model()->getAllGroups($condition, array('group_order')); //xiao, if (!isset($surveyfaxto) || !$surveyfaxto and isset($surveyfaxnumber)) { $surveyfaxto = $surveyfaxnumber; //Use system fax number if none is set in survey. } $headelements = getPrintableHeader(); //if $showsgqacode is enabled at config.php show table name for reference $showsgqacode = Yii::app()->getConfig("showsgqacode"); if (isset($showsgqacode) && $showsgqacode == true) { $surveyname = $surveyname . "<br />[" . gT('Database') . " " . gT('table') . ": {$surveytable}]"; } else { $surveyname = $surveyname; } $survey_output = array('SITENAME' => Yii::app()->getConfig("sitename"), 'SURVEYNAME' => $surveyname, 'SURVEYDESCRIPTION' => $surveydesc, 'WELCOME' => $welcome, 'END' => $end, 'THEREAREXQUESTIONS' => 0, 'SUBMIT_TEXT' => gT("Submit Your Survey."), 'SUBMIT_BY' => $surveyexpirydate, 'THANKS' => gT("Thank you for completing this survey."), 'HEADELEMENTS' => $headelements, 'TEMPLATEURL' => PRINT_TEMPLATE_URL, 'FAXTO' => $surveyfaxto, 'PRIVACY' => '', 'GROUPS' => ''); $survey_output['FAX_TO'] = ''; if (!empty($surveyfaxto) && $surveyfaxto != '000-00000000') { $survey_output['FAX_TO'] = gT("Please fax your completed survey to:") . " {$surveyfaxto}"; } $total_questions = 0; $mapquestionsNumbers = array(); $answertext = ''; // otherwise can throw an error on line 1617 $fieldmap = createFieldMap($surveyid, 'full', false, false, $sLanguageCode); // ========================================================= // START doin the business: foreach ($degresult->readAll() as $degrow) { // --------------------------------------------------- // START doing groups $deqresult = Question::model()->getQuestions($surveyid, $degrow['gid'], $sLanguageCode, 0, '"I"'); $deqrows = array(); //Create an empty array in case FetchRow does not return any rows foreach ($deqresult->readAll() as $deqrow) { $deqrows[] = $deqrow; } // Get table output into array // Perform a case insensitive natural sort on group name then question title of a multidimensional array usort($deqrows, 'groupOrderThenQuestionOrder'); if ($degrow['description']) { $group_desc = $degrow['description']; } else { $group_desc = ''; } $group = array('GROUPNAME' => $degrow['group_name'], 'GROUPDESCRIPTION' => $group_desc, 'QUESTIONS' => ''); // A group can have only hidden questions. In that case you don't want to see the group's header/description either. $bGroupHasVisibleQuestions = false; $gid = $degrow['gid']; //Alternate bgcolor for different groups if (!isset($group['ODD_EVEN']) || $group['ODD_EVEN'] == ' g-row-even') { $group['ODD_EVEN'] = ' g-row-odd'; } else { $group['ODD_EVEN'] = ' g-row-even'; } //Loop through questions foreach ($deqrows as $deqrow) { // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // START doing questions $qidattributes = getQuestionAttributeValues($deqrow['qid'], $deqrow['type']); if ($qidattributes['hidden'] == 1 && $deqrow['type'] != '*') { continue; } $bGroupHasVisibleQuestions = true; //GET ANY CONDITIONS THAT APPLY TO THIS QUESTION $printablesurveyoutput = ''; $sExplanation = ''; //reset conditions explanation $s = 0; // TMSW Condition->Relevance: show relevance instead of this whole section to create $explanation $scenarioresult = Condition::model()->getScenarios($deqrow['qid']); $scenarioresult = $scenarioresult->readAll(); //Loop through distinct scenarios, thus grouping them together. foreach ($scenarioresult as $scenariorow) { if ($s == 0 && count($scenarioresult) > 1) { $sExplanation .= '<p class="scenario">' . " -------- Scenario {$scenariorow['scenario']} --------</p>\n\n"; } if ($s > 0) { $sExplanation .= '<p class="scenario">' . ' -------- ' . gT("or") . " Scenario {$scenariorow['scenario']} --------</p>\n\n"; } $x = 0; $conditions1 = "qid={$deqrow['qid']} AND scenario={$scenariorow['scenario']}"; $distinctresult = Condition::model()->getSomeConditions(array('cqid', 'method', 'cfieldname'), $conditions1, array('cqid'), array('cqid', 'method', 'cfieldname')); //Loop through each condition for a particular scenario. foreach ($distinctresult->readAll() as $distinctrow) { $condition = "qid = '{$distinctrow['cqid']}' AND parent_qid = 0 AND language = '{$sLanguageCode}'"; $subresult = Question::model()->find($condition); if ($x > 0) { $sExplanation .= ' <em class="scenario-and-separator">' . gT('and') . '</em> '; } if (trim($distinctrow['method']) == '') { $distinctrow['method'] = '=='; } if ($distinctrow['cqid']) { // cqid != 0 ==> previous answer match if ($distinctrow['method'] == '==') { $sExplanation .= gT("Answer was") . " "; } elseif ($distinctrow['method'] == '!=') { $sExplanation .= gT("Answer was NOT") . " "; } elseif ($distinctrow['method'] == '<') { $sExplanation .= gT("Answer was less than") . " "; } elseif ($distinctrow['method'] == '<=') { $sExplanation .= gT("Answer was less than or equal to") . " "; } elseif ($distinctrow['method'] == '>=') { $sExplanation .= gT("Answer was greater than or equal to") . " "; } elseif ($distinctrow['method'] == '>') { $sExplanation .= gT("Answer was greater than") . " "; } elseif ($distinctrow['method'] == 'RX') { $sExplanation .= gT("Answer matched (regexp)") . " "; } else { $sExplanation .= gT("Answer was") . " "; } } if (!$distinctrow['cqid']) { // cqid == 0 ==> token attribute match $tokenData = getTokenFieldsAndNames($surveyid); preg_match('/^{TOKEN:([^}]*)}$/', $distinctrow['cfieldname'], $extractedTokenAttr); $sExplanation .= "Your " . $tokenData[strtolower($extractedTokenAttr[1])]['description'] . " "; if ($distinctrow['method'] == '==') { $sExplanation .= gT("is") . " "; } elseif ($distinctrow['method'] == '!=') { $sExplanation .= gT("is NOT") . " "; } elseif ($distinctrow['method'] == '<') { $sExplanation .= gT("is less than") . " "; } elseif ($distinctrow['method'] == '<=') { $sExplanation .= gT("is less than or equal to") . " "; } elseif ($distinctrow['method'] == '>=') { $sExplanation .= gT("is greater than or equal to") . " "; } elseif ($distinctrow['method'] == '>') { $sExplanation .= gT("is greater than") . " "; } elseif ($distinctrow['method'] == 'RX') { $sExplanation .= gT("is matched (regexp)") . " "; } else { $sExplanation .= gT("is") . " "; } $answer_section = ' ' . $distinctrow['value'] . ' '; } $conresult = Condition::model()->getConditionsQuestions($distinctrow['cqid'], $deqrow['qid'], $scenariorow['scenario'], $sLanguageCode); $conditions = array(); foreach ($conresult->readAll() as $conrow) { $postans = ""; $value = $conrow['value']; switch ($conrow['type']) { case "Y": switch ($conrow['value']) { case "Y": $conditions[] = gT("Yes"); break; case "N": $conditions[] = gT("No"); break; } break; case "G": switch ($conrow['value']) { case "M": $conditions[] = gT("Male"); break; case "F": $conditions[] = gT("Female"); break; } // switch break; case "A": case "B": case ":": case ";": case "5": $conditions[] = $conrow['value']; break; case "C": switch ($conrow['value']) { case "Y": $conditions[] = gT("Yes"); break; case "U": $conditions[] = gT("Uncertain"); break; case "N": $conditions[] = gT("No"); break; } // switch break; case "E": switch ($conrow['value']) { case "I": $conditions[] = gT("Increase"); break; case "D": $conditions[] = gT("Decrease"); break; case "S": $conditions[] = gT("Same"); break; } case "1": $labelIndex = preg_match("/^[^#]+#([01]{1})\$/", $conrow['cfieldname']); if ($labelIndex == 0) { // TIBO $condition = "qid='{$conrow['cqid']}' AND code='{$conrow['value']}' AND scale_id=0 AND language='{$sLanguageCode}'"; $fresult = Answer::model()->getAllRecords($condition); foreach ($fresult->readAll() as $frow) { $postans = $frow['answer']; $conditions[] = $frow['answer']; } // while } elseif ($labelIndex == 1) { $condition = "qid='{$conrow['cqid']}' AND code='{$conrow['value']}' AND scale_id=1 AND language='{$sLanguageCode}'"; $fresult = Answer::model()->getAllRecords($condition); foreach ($fresult->readAll() as $frow) { $postans = $frow['answer']; $conditions[] = $frow['answer']; } // while } break; case "L": case "!": case "O": case "R": $condition = "qid='{$conrow['cqid']}' AND code='{$conrow['value']}' AND language='{$sLanguageCode}'"; $ansresult = Answer::model()->findAll($condition); foreach ($ansresult as $ansrow) { $conditions[] = $ansrow['answer']; } if ($conrow['value'] == "-oth-") { $conditions[] = gT("Other"); } $conditions = array_unique($conditions); break; case "M": case "P": $condition = " parent_qid='{$conrow['cqid']}' AND title='{$conrow['value']}' AND language='{$sLanguageCode}'"; $ansresult = Question::model()->findAll($condition); foreach ($ansresult as $ansrow) { $conditions[] = $ansrow['question']; } $conditions = array_unique($conditions); break; case "N": case "K": $conditions[] = $value; break; case "F": case "H": default: $value = substr($conrow['cfieldname'], strpos($conrow['cfieldname'], "X" . $conrow['cqid']) + strlen("X" . $conrow['cqid']), strlen($conrow['cfieldname'])); $condition = " qid='{$conrow['cqid']}' AND code='{$conrow['value']}' AND language='{$sLanguageCode}'"; $fresult = Answer::model()->getAllRecords($condition); foreach ($fresult->readAll() as $frow) { $postans = $frow['answer']; $conditions[] = $frow['answer']; } // while break; } // switch // Now let's complete the answer text with the answer_section $answer_section = ""; switch ($conrow['type']) { case "A": case "B": case "C": case "E": case "F": case "H": case "K": $thiscquestion = $fieldmap[$conrow['cfieldname']]; $condition = "parent_qid='{$conrow['cqid']}' AND title='{$thiscquestion['aid']}' AND language='{$sLanguageCode}'"; $ansresult = Question::model()->findAll($condition); foreach ($ansresult as $ansrow) { $answer_section = " (" . $ansrow['question'] . ")"; } break; case "1": // dual: (Label 1), (Label 2) $labelIndex = substr($conrow['cfieldname'], -1); $thiscquestion = $fieldmap[$conrow['cfieldname']]; $condition = "parent_qid='{$conrow['cqid']}' AND title='{$thiscquestion['aid']}' AND language='{$sLanguageCode}'"; $ansresult = Question::model()->findAll($condition); $cqidattributes = getQuestionAttributeValues($conrow['cqid']); if ($labelIndex == 0) { if (trim($cqidattributes['dualscale_headerA'][$sLanguageCode]) != '') { $header = gT($cqidattributes['dualscale_headerA'][$sLanguageCode]); } else { $header = '1'; } } elseif ($labelIndex == 1) { if (trim($cqidattributes['dualscale_headerB'][$sLanguageCode]) != '') { $header = gT($cqidattributes['dualscale_headerB'][$sLanguageCode]); } else { $header = '2'; } } foreach ($ansresult as $ansrow) { $answer_section = " (" . $ansrow->question . " " . sprintf(gT("Label %s"), $header) . ")"; } break; case ":": case ";": //multi flexi: ( answer [label] ) $thiscquestion = $fieldmap[$conrow['cfieldname']]; $condition = "parent_qid='{$conrow['cqid']}' AND title='{$thiscquestion['aid']}' AND language='{$sLanguageCode}'"; $ansresult = Question::model()->findAll($condition); foreach ($ansresult as $ansrow) { $condition = "qid = '{$conrow['cqid']}' AND code = '{$conrow['value']}' AND language= '{$sLanguageCode}'"; $fresult = Answer::model()->findAll($condition); foreach ($fresult as $frow) { //$conditions[]=$frow['title']; $answer_section = " (" . $ansrow->question . "[" . $frow['answer'] . "])"; } // while } break; case "R": // (Rank 1), (Rank 2)... TIBO $thiscquestion = $fieldmap[$conrow['cfieldname']]; $rankid = $thiscquestion['aid']; $answer_section = " (" . gT("RANK") . " {$rankid})"; break; default: // nothing to add break; } } if (count($conditions) > 1) { $sExplanation .= "'" . implode("' <em class='scenario-or-separator'>" . gT("or") . "</em> '", $conditions) . "'"; } elseif (count($conditions) == 1) { $sExplanation .= "'" . $conditions[0] . "'"; } unset($conditions); // Following line commented out because answer_section was lost, but is required for some question types //$explanation .= " ".gT("to question")." '".$mapquestionsNumbers[$distinctrow['cqid']]."' $answer_section "; if ($distinctrow['cqid']) { $sExplanation .= " <span class='scenario-at-separator'>" . gT("at question") . "</span> '" . $mapquestionsNumbers[$distinctrow['cqid']] . " [" . $subresult['title'] . "]' (" . strip_tags($subresult['question']) . "{$answer_section})"; } else { $sExplanation .= " " . $distinctrow['value']; } //$distinctrow $x++; } $s++; } $qinfo = LimeExpressionManager::GetQuestionStatus($deqrow['qid']); $relevance = trim($qinfo['info']['relevance']); $sEquation = $qinfo['relEqn']; if (trim($relevance) != '' && trim($relevance) != '1') { if (isset($qidattributes['printable_help'][$sLanguageCode]) && $qidattributes['printable_help'][$sLanguageCode] != '') { $sExplanation = $qidattributes['printable_help'][$sLanguageCode]; } elseif ($sExplanation == '') { $sExplanation = $sEquation; $sEquation = ' '; // No need to show it twice } $sExplanation = "<b>" . gT('Only answer this question if the following conditions are met:') . "</b><br/> " . $sExplanation; if (Yii::app()->getConfig('showrelevance')) { $sExplanation .= "<span class='printable_equation'><br>" . $sEquation . "</span>"; } } else { $sExplanation = ''; } ++$total_questions; //TIBO map question qid to their q number $mapquestionsNumbers[$deqrow['qid']] = $total_questions; //END OF GETTING CONDITIONS $qid = $deqrow['qid']; $fieldname = "{$surveyid}" . "X" . "{$gid}" . "X" . "{$qid}"; if (isset($showsgqacode) && $showsgqacode == true) { $deqrow['question'] = $deqrow['question'] . "<br />" . gT("ID:") . " {$fieldname} <br />" . gT("Question code:") . " " . $deqrow['title']; } $question = array('QUESTION_NUMBER' => $total_questions, 'QUESTION_CODE' => $deqrow['title'], 'QUESTION_TEXT' => preg_replace('/(?:<br ?\\/?>|<\\/(?:p|h[1-6])>)$/is', '', $deqrow['question']), 'QUESTION_SCENARIO' => $sExplanation, 'QUESTION_MANDATORY' => '', 'QUESTION_ID' => $deqrow['qid'], 'QUESTION_CLASS' => getQuestionClass($deqrow['type']), 'QUESTION_TYPE_HELP' => $qinfo['validTip'], 'QUESTION_MAN_MESSAGE' => '', 'QUESTION_VALID_MESSAGE' => '', 'QUESTION_FILE_VALID_MESSAGE' => '', 'QUESTIONHELP' => '', 'ANSWER' => ''); $showqnumcode = Yii::app()->getConfig('showqnumcode'); if ($showqnumcode == 'choose' && ($aSurveyInfo['showqnumcode'] == 'N' || $aSurveyInfo['showqnumcode'] == 'X') || $showqnumcode == 'number' || $showqnumcode == 'none') { $question['QUESTION_CODE'] = ''; } if ($showqnumcode == 'choose' && ($aSurveyInfo['showqnumcode'] == 'C' || $aSurveyInfo['showqnumcode'] == 'X') || $showqnumcode == 'code' || $showqnumcode == 'none') { $question['QUESTION_NUMBER'] = ''; } if ($question['QUESTION_TYPE_HELP'] != "") { $question['QUESTION_TYPE_HELP'] .= "<br />\n"; } if ($deqrow['mandatory'] == 'Y') { $question['QUESTION_MANDATORY'] = gT('*'); $question['QUESTION_CLASS'] .= ' mandatory'; } //DIFFERENT TYPES OF DATA FIELD HERE if ($deqrow['help']) { $question['QUESTIONHELP'] = $deqrow['help']; } if (!empty($qidattributes['page_break'])) { $question['QUESTION_CLASS'] .= ' breakbefore '; } if (isset($qidattributes['maximum_chars']) && $qidattributes['maximum_chars'] != '') { $question['QUESTION_CLASS'] = "max-chars-{$qidattributes['maximum_chars']} " . $question['QUESTION_CLASS']; } switch ($deqrow['type']) { // ================================================================== case "5": //5 POINT CHOICE $question['QUESTION_TYPE_HELP'] .= gT('Please choose *only one* of the following:'); $question['ANSWER'] .= "\n\t<ul>\n"; for ($i = 1; $i <= 5; $i++) { $question['ANSWER'] .= "\t\t<li>\n\t\t\t" . self::_input_type_image('radio', $i) . "\n\t\t\t{$i} " . self::_addsgqacode("({$i})") . "\n\t\t</li>\n"; } $question['ANSWER'] .= "\t</ul>\n"; break; // ================================================================== // ================================================================== case "D": //DATE $question['QUESTION_TYPE_HELP'] .= gT('Please enter a date:'); $question['ANSWER'] .= "\t" . self::_input_type_image('text', $question['QUESTION_TYPE_HELP'], 30, 1); break; // ================================================================== // ================================================================== case "G": //GENDER $question['QUESTION_TYPE_HELP'] .= gT("Please choose *only one* of the following:"); $question['ANSWER'] .= "\n\t<ul>\n"; $question['ANSWER'] .= "\t\t<li>\n\t\t\t" . self::_input_type_image('radio', gT("Female")) . "\n\t\t\t" . gT("Female") . " " . self::_addsgqacode("(F)") . "\n\t\t</li>\n"; $question['ANSWER'] .= "\t\t<li>\n\t\t\t" . self::_input_type_image('radio', gT("Male")) . "\n\t\t\t" . gT("Male") . " " . self::_addsgqacode("(M)") . "\n\t\t</li>\n"; $question['ANSWER'] .= "\t</ul>\n"; break; // ================================================================== // ================================================================== case "L": //LIST drop-down/radio-button list // ================================================================== //LIST drop-down/radio-button list // ================================================================== case "!": //List - dropdown if (isset($qidattributes['display_columns']) && trim($qidattributes['display_columns']) != '') { $dcols = $qidattributes['display_columns']; } else { $dcols = 0; } if (isset($qidattributes['category_separator']) && trim($qidattributes['category_separator']) != '') { $optCategorySeparator = $qidattributes['category_separator']; } else { unset($optCategorySeparator); } $question['QUESTION_TYPE_HELP'] .= gT("Please choose *only one* of the following:"); $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $sLanguageCode, $surveyid); $dearesult = Answer::model()->getAllRecords(" qid='{$deqrow['qid']}' AND language='{$sLanguageCode}' ", array('sortorder', 'answer')); $dearesult = $dearesult->readAll(); $deacount = count($dearesult); if ($deqrow['other'] == "Y") { $deacount++; } $wrapper = setupColumns(0, $deacount); $question['ANSWER'] = $wrapper['whole-start']; $rowcounter = 0; $colcounter = 1; foreach ($dearesult as $dearow) { if (isset($optCategorySeparator)) { list($category, $answer) = explode($optCategorySeparator, $dearow['answer']); if ($category != '') { $dearow['answer'] = "({$category}) {$answer} " . self::_addsgqacode("(" . $dearow['code'] . ")"); } else { $dearow['answer'] = $answer . self::_addsgqacode(" (" . $dearow['code'] . ")"); } $question['ANSWER'] .= "\t" . $wrapper['item-start'] . "\t\t" . self::_input_type_image('radio', $dearow['answer']) . "\n\t\t\t" . $dearow['answer'] . "\n" . $wrapper['item-end']; } else { $question['ANSWER'] .= "\t" . $wrapper['item-start'] . "\t\t" . self::_input_type_image('radio', $dearow['answer']) . "\n\t\t\t" . $dearow['answer'] . self::_addsgqacode(" (" . $dearow['code'] . ")") . "\n" . $wrapper['item-end']; } ++$rowcounter; if ($rowcounter == $wrapper['maxrows'] && $colcounter < $wrapper['cols']) { if ($colcounter == $wrapper['cols'] - 1) { $question['ANSWER'] .= $wrapper['col-devide-last']; } else { $question['ANSWER'] .= $wrapper['col-devide']; } $rowcounter = 0; ++$colcounter; } } if ($deqrow['other'] == 'Y') { if (trim($qidattributes["other_replace_text"][$sLanguageCode]) == '') { $qidattributes["other_replace_text"][$sLanguageCode] = gT("Other"); } // $printablesurveyoutput .="\t".$wrapper['item-start']."\t\t".self::_input_type_image('radio' , gT("Other"))."\n\t\t\t".gT("Other")."\n\t\t\t<input type='text' size='30' readonly='readonly' />\n".$wrapper['item-end']; $question['ANSWER'] .= $wrapper['item-start-other'] . self::_input_type_image('radio', gT($qidattributes["other_replace_text"][$sLanguageCode])) . ' ' . gT($qidattributes["other_replace_text"][$sLanguageCode]) . self::_addsgqacode(" (-oth-)") . "\n\t\t\t" . self::_input_type_image('other') . self::_addsgqacode(" (" . $deqrow['sid'] . "X" . $deqrow['gid'] . "X" . $deqrow['qid'] . "other)") . "\n" . $wrapper['item-end']; } $question['ANSWER'] .= $wrapper['whole-end']; //Let's break the presentation into columns. break; // ================================================================== // ================================================================== case "O": //LIST WITH COMMENT $question['QUESTION_TYPE_HELP'] .= gT("Please choose *only one* of the following:"); $dearesult = Answer::model()->getAllRecords(" qid='{$deqrow['qid']}' AND language='{$sLanguageCode}'", array('sortorder', 'answer')); $question['ANSWER'] = "\t<ul>\n"; foreach ($dearesult->readAll() as $dearow) { $question['ANSWER'] .= "\t\t<li>\n\t\t\t" . self::_input_type_image('radio', $dearow['answer']) . "\n\t\t\t" . $dearow['answer'] . self::_addsgqacode(" (" . $dearow['code'] . ")") . "\n\t\t</li>\n"; } $question['ANSWER'] .= "\t</ul>\n"; $question['ANSWER'] .= "\t<p class=\"comment\">\n\t\t" . gT("Make a comment on your choice here:") . "\n"; $question['ANSWER'] .= "\t\t" . self::_input_type_image('textarea', gT("Make a comment on your choice here:"), 50, 8) . self::_addsgqacode(" (" . $deqrow['sid'] . "X" . $deqrow['gid'] . "X" . $deqrow['qid'] . "comment)") . "\n\t</p>\n"; break; // ================================================================== // ================================================================== case "R": //RANKING Type Question $rearesult = Answer::model()->getAllRecords(" qid='{$deqrow['qid']}' AND language='{$sLanguageCode}'", array('sortorder', 'answer')); $rearesult = $rearesult->readAll(); $reacount = count($rearesult); $question['QUESTION_TYPE_HELP'] .= gT("Please number each box in order of preference from 1 to") . " {$reacount}"; $question['QUESTION_TYPE_HELP'] .= self::_min_max_answers_help($qidattributes, $sLanguageCode, $surveyid); $question['ANSWER'] = "\n<ul>\n"; foreach ($rearesult as $rearow) { $question['ANSWER'] .= "\t<li>\n\t" . self::_input_type_image('rank', '', 4, 1) . "\n\t\t " . $rearow['answer'] . self::_addsgqacode(" (" . $fieldname . $rearow['code'] . ")") . "\n\t</li>\n"; } $question['ANSWER'] .= "\n</ul>\n"; break; // ================================================================== // ================================================================== case "M": //Multiple choice (Quite tricky really!) if (trim($qidattributes['display_columns']) != '') { $dcols = $qidattributes['display_columns']; } else { $dcols = 0; } $question['QUESTION_TYPE_HELP'] .= gT("Please choose *all* that apply:"); $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $sLanguageCode, $surveyid); $mearesult = Question::model()->getAllRecords(" parent_qid='{$deqrow['qid']}' AND language='{$sLanguageCode}' ", array('question_order')); $mearesult = $mearesult->readAll(); $meacount = count($mearesult); if ($deqrow['other'] == 'Y') { $meacount++; } $wrapper = setupColumns($dcols, $meacount); $question['ANSWER'] = $wrapper['whole-start']; $rowcounter = 0; $colcounter = 1; foreach ($mearesult as $mearow) { $question['ANSWER'] .= $wrapper['item-start'] . self::_input_type_image('checkbox', $mearow['question']) . "\n\t\t" . $mearow['question'] . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . ") ") . $wrapper['item-end']; ++$rowcounter; if ($rowcounter == $wrapper['maxrows'] && $colcounter < $wrapper['cols']) { if ($colcounter == $wrapper['cols'] - 1) { $question['ANSWER'] .= $wrapper['col-devide-last']; } else { $question['ANSWER'] .= $wrapper['col-devide']; } $rowcounter = 0; ++$colcounter; } } if ($deqrow['other'] == "Y") { if (trim($qidattributes['other_replace_text'][$sLanguageCode]) == '') { $qidattributes["other_replace_text"][$sLanguageCode] = "Other"; } if (!isset($mearow['answer'])) { $mearow['answer'] = ""; } $question['ANSWER'] .= $wrapper['item-start-other'] . self::_input_type_image('checkbox', $mearow['answer']) . gT($qidattributes["other_replace_text"][$sLanguageCode]) . ":\n\t\t" . self::_input_type_image('other') . self::_addsgqacode(" (" . $fieldname . "other) ") . $wrapper['item-end']; } $question['ANSWER'] .= $wrapper['whole-end']; // } break; // ================================================================== // ================================================================== case "P": //Multiple choice with comments $question['QUESTION_TYPE_HELP'] .= gT("Please choose all that apply and provide a comment:"); $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $sLanguageCode, $surveyid); $mearesult = Question::model()->getAllRecords("parent_qid='{$deqrow['qid']}' AND language='{$sLanguageCode}'", array('question_order')); // $printablesurveyoutput .="\t\t\t<u>".gT("Please choose all that apply and provide a comment:")."</u><br />\n"; $j = 0; $longest_string = 0; foreach ($mearesult->readAll() as $mearow) { $longest_string = longestString($mearow['question'], $longest_string); $question['ANSWER'] .= "\t<li><span>\n\t\t" . self::_input_type_image('checkbox', $mearow['question']) . $mearow['question'] . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . ") ") . "</span>\n\t\t" . self::_input_type_image('text', 'comment box', 60) . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . "comment) ") . "\n\t</li>\n"; $j++; } if ($deqrow['other'] == "Y") { $question['ANSWER'] .= "\t<li class=\"other\">\n\t\t<div class=\"other-replacetext\">" . gT('Other:') . self::_input_type_image('other', '', 1) . "</div>" . self::_input_type_image('othercomment', 'comment box', 50) . self::_addsgqacode(" (" . $fieldname . "other) ") . "\n\t</li>\n"; $j++; } $question['ANSWER'] = "\n<ul>\n" . $question['ANSWER'] . "</ul>\n"; break; // ================================================================== // ================================================================== case "Q": //MULTIPLE SHORT TEXT $width = 60; // ================================================================== // ================================================================== case "K": //MULTIPLE NUMERICAL $question['QUESTION_TYPE_HELP'] = ""; $width = isset($width) ? $width : 16; // if (!empty($qidattributes['equals_num_value'])) // { // $question['QUESTION_TYPE_HELP'] .= "* ".sprintf(gT('Total of all entries must equal %d'),$qidattributes['equals_num_value'])."<br />\n"; // } // if (!empty($qidattributes['max_num_value'])) // { // $question['QUESTION_TYPE_HELP'] .= sprintf(gT('Total of all entries must not exceed %d'), $qidattributes['max_num_value'])."<br />\n"; // } // if (!empty($qidattributes['min_num_value'])) // { // $question['QUESTION_TYPE_HELP'] .= sprintf(gT('Total of all entries must be at least %s'),$qidattributes['min_num_value'])."<br />\n"; // } $question['QUESTION_TYPE_HELP'] .= gT("Please write your answer(s) here:"); $longest_string = 0; $mearesult = Question::model()->getAllRecords("parent_qid='{$deqrow['qid']}' AND language='{$sLanguageCode}'", array('question_order')); foreach ($mearesult->readAll() as $mearow) { $longest_string = longestString($mearow['question'], $longest_string); if (isset($qidattributes['slider_layout']) && $qidattributes['slider_layout'] == 1) { $mearow['question'] = explode(':', $mearow['question']); $mearow['question'] = $mearow['question'][0]; } $question['ANSWER'] .= "\t<li>\n\t\t<span>" . $mearow['question'] . "</span>\n\t\t" . self::_input_type_image('text', $mearow['question'], $width) . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . ") ") . "\n\t</li>\n"; } $question['ANSWER'] = "\n<ul>\n" . $question['ANSWER'] . "</ul>\n"; break; // ================================================================== // ================================================================== case "S": //SHORT TEXT $question['QUESTION_TYPE_HELP'] .= gT("Please write your answer here:"); $question['ANSWER'] = self::_input_type_image('text', $question['QUESTION_TYPE_HELP'], 50); break; // ================================================================== // ================================================================== case "T": //LONG TEXT $question['QUESTION_TYPE_HELP'] .= gT("Please write your answer here:"); $question['ANSWER'] = self::_input_type_image('textarea', $question['QUESTION_TYPE_HELP'], '100%', 8); break; // ================================================================== // ================================================================== case "U": //HUGE TEXT $question['QUESTION_TYPE_HELP'] .= gT("Please write your answer here:"); $question['ANSWER'] = self::_input_type_image('textarea', $question['QUESTION_TYPE_HELP'], '100%', 30); break; // ================================================================== // ================================================================== case "N": //NUMERICAL $prefix = ""; $suffix = ""; if ($qidattributes['prefix'][$sLanguageCode] != "") { $prefix = $qidattributes['prefix'][$sLanguageCode]; } if ($qidattributes['suffix'][$sLanguageCode] != "") { $suffix = $qidattributes['suffix'][$sLanguageCode]; } $question['QUESTION_TYPE_HELP'] .= gT("Please write your answer here:"); $question['ANSWER'] = "<ul>\n\t<li>\n\t\t<span>{$prefix}</span>\n\t\t" . self::_input_type_image('text', $question['QUESTION_TYPE_HELP'], 20) . "\n\t\t<span>{$suffix}</span>\n\t\t</li>\n\t</ul>"; break; // ================================================================== // ================================================================== case "Y": //YES/NO $question['QUESTION_TYPE_HELP'] .= gT("Please choose *only one* of the following:"); $question['ANSWER'] = "\n<ul>\n\t<li>\n\t\t" . self::_input_type_image('radio', gT('Yes')) . "\n\t\t" . gT('Yes') . self::_addsgqacode(" (Y)") . "\n\t</li>\n"; $question['ANSWER'] .= "\n\t<li>\n\t\t" . self::_input_type_image('radio', gT('No')) . "\n\t\t" . gT('No') . self::_addsgqacode(" (N)") . "\n\t</li>\n</ul>\n"; break; // ================================================================== // ================================================================== case "A": //ARRAY (5 POINT CHOICE) $condition = "parent_qid = '{$deqrow['qid']}' AND language= '{$sLanguageCode}'"; $question['QUESTION_TYPE_HELP'] .= gT("Please choose the appropriate response for each item:"); $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $sLanguageCode, $surveyid); $question['ANSWER'] = "\n <table>\n <thead>\n <tr>\n <td> </td>\n <th style='font-family:Arial,helvetica,sans-serif;font-weight:normal;'>1 " . self::_addsgqacode(" (1)") . "</th>\n <th style='font-family:Arial,helvetica,sans-serif;font-weight:normal;'>2 " . self::_addsgqacode(" (2)") . "</th>\n <th style='font-family:Arial,helvetica,sans-serif;font-weight:normal;'>3 " . self::_addsgqacode(" (3)") . "</th>\n <th style='font-family:Arial,helvetica,sans-serif;font-weight:normal;'>4 " . self::_addsgqacode(" (4)") . "</th>\n <th style='font-family:Arial,helvetica,sans-serif;font-weight:normal;'>5" . self::_addsgqacode(" (5)") . "</th>\n </tr>\n </thead>\n <tbody>"; $j = 0; $rowclass = 'array1'; $mearesult = Question::model()->getAllRecords($condition, array('question_order')); foreach ($mearesult->readAll() as $mearow) { $question['ANSWER'] .= "\t\t<tr class=\"{$rowclass}\">\n"; $rowclass = alternation($rowclass, 'row'); //semantic differential question type? if (strpos($mearow['question'], '|')) { $answertext = substr($mearow['question'], 0, strpos($mearow['question'], '|')) . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . ")") . " "; } else { $answertext = $mearow['question'] . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . ")"); } $question['ANSWER'] .= "\t\t\t<th class=\"answertext\">{$answertext}</th>\n"; for ($i = 1; $i <= 5; $i++) { $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio', $i) . "</td>\n"; } $answertext .= $mearow['question']; //semantic differential question type? if (strpos($mearow['question'], '|')) { $answertext2 = substr($mearow['question'], strpos($mearow['question'], '|') + 1); $question['ANSWER'] .= "\t\t\t<th class=\"answertextright\">{$answertext2}</td>\n"; } $question['ANSWER'] .= "\t\t</tr>\n"; $j++; } $question['ANSWER'] .= "\t</tbody>\n</table>\n"; break; // ================================================================== // ================================================================== case "B": //ARRAY (10 POINT CHOICE) $question['QUESTION_TYPE_HELP'] .= gT("Please choose the appropriate response for each item:"); $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $sLanguageCode, $surveyid); $question['ANSWER'] .= "\n<table>\n\t<thead>\n\t\t<tr>\n\t\t\t<td> </td>\n"; for ($i = 1; $i <= 10; $i++) { $question['ANSWER'] .= "\t\t\t<th>{$i}" . self::_addsgqacode(" ({$i})") . "</th>\n"; } $question['ANSWER'] .= "\t</thead>\n\n\t<tbody>\n"; $j = 0; $rowclass = 'array1'; $mearesult = Question::model()->getAllRecords(" parent_qid='{$deqrow['qid']}' AND language='{$sLanguageCode}' ", array('question_order')); foreach ($mearesult->readAll() as $mearow) { $question['ANSWER'] .= "\t\t<tr class=\"{$rowclass}\">\n\t\t\t<th class=\"answertext\">{$mearow['question']}" . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . ")") . "</th>\n"; $rowclass = alternation($rowclass, 'row'); for ($i = 1; $i <= 10; $i++) { $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio', $i) . "</td>\n"; } $question['ANSWER'] .= "\t\t</tr>\n"; $j++; } $question['ANSWER'] .= "\t</tbody>\n</table>\n"; break; // ================================================================== // ================================================================== case "C": //ARRAY (YES/UNCERTAIN/NO) $question['QUESTION_TYPE_HELP'] .= gT("Please choose the appropriate response for each item:"); $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $sLanguageCode, $surveyid); $question['ANSWER'] = ' <table> <thead> <tr> <td> </td> <th>' . gT("Yes") . self::_addsgqacode(" (Y)") . '</th> <th>' . gT("Uncertain") . self::_addsgqacode(" (U)") . '</th> <th>' . gT("No") . self::_addsgqacode(" (N)") . '</th> </tr> </thead> <tbody> '; $j = 0; $rowclass = 'array1'; $mearesult = Question::model()->getAllRecords(" parent_qid='{$deqrow['qid']}' AND language='{$sLanguageCode}' ", array('question_order')); foreach ($mearesult->readAll() as $mearow) { $question['ANSWER'] .= "\t\t<tr class=\"{$rowclass}\">\n"; $question['ANSWER'] .= "\t\t\t<th class=\"answertext\">{$mearow['question']}" . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . ")") . "</th>\n"; $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio', gT("Yes")) . "</td>\n"; $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio', gT("Uncertain")) . "</td>\n"; $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio', gT("No")) . "</td>\n"; $question['ANSWER'] .= "\t\t</tr>\n"; $j++; $rowclass = alternation($rowclass, 'row'); } $question['ANSWER'] .= "\t</tbody>\n</table>\n"; break; case "E": //ARRAY (Increase/Same/Decrease) $question['QUESTION_TYPE_HELP'] .= gT("Please choose the appropriate response for each item:"); $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $sLanguageCode, $surveyid); $question['ANSWER'] = ' <table> <thead> <tr> <td> </td> <th>' . gT("Increase") . self::_addsgqacode(" (I)") . '</th> <th>' . gT("Same") . self::_addsgqacode(" (S)") . '</th> <th>' . gT("Decrease") . self::_addsgqacode(" (D)") . '</th> </tr> </thead> <tbody> '; $j = 0; $rowclass = 'array1'; $mearesult = Question::model()->getAllRecords(" parent_qid='{$deqrow['qid']}' AND language='{$sLanguageCode}' ", array('question_order')); foreach ($mearesult->readAll() as $mearow) { $question['ANSWER'] .= "\t\t<tr class=\"{$rowclass}\">\n"; $question['ANSWER'] .= "\t\t\t<th class=\"answertext\">{$mearow['question']}" . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . ")") . "</th>\n"; $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio', gT("Increase")) . "</td>\n"; $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio', gT("Same")) . "</td>\n"; $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio', gT("Decrease")) . "</td>\n"; $question['ANSWER'] .= "\t\t</tr>\n"; $j++; $rowclass = alternation($rowclass, 'row'); } $question['ANSWER'] .= "\t</tbody>\n</table>\n"; break; // ================================================================== // ================================================================== case ":": //ARRAY (Multi Flexible) (Numbers) $headstyle = "style='padding-left: 20px; padding-right: 7px'"; 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']) == '') { $minvalue = 1; $maxvalue = 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) { $checkboxlayout = true; } else { $checkboxlayout = false; } $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $sLanguageCode, $surveyid); $question['ANSWER'] .= "\n<table>\n\t<thead>\n\t\t<tr>\n\t\t\t<td> </td>\n"; $fresult = Question::model()->getAllRecords(" parent_qid='{$deqrow['qid']}' and scale_id=1 AND language='{$sLanguageCode}' ", array('question_order')); $fresult = $fresult->readAll(); $fcount = count($fresult); $fwidth = "120"; $i = 0; //array to temporary store X axis question codes $xaxisarray = array(); foreach ($fresult as $frow) { $question['ANSWER'] .= "\t\t\t<th>{$frow['question']}</th>\n"; $i++; //add current question code $xaxisarray[$i] = $frow['title']; } $question['ANSWER'] .= "\t\t</tr>\n\t</thead>\n\n\t<tbody>\n"; $a = 1; //Counter for pdfoutput $rowclass = 'array1'; $mearesult = Question::model()->getAllRecords(" parent_qid='{$deqrow['qid']}' and scale_id=0 AND language='{$sLanguageCode}' ", array('question_order')); $result = $mearesult->readAll(); foreach ($result as $frow) { $question['ANSWER'] .= "\t<tr class=\"{$rowclass}\">\n"; $rowclass = alternation($rowclass, 'row'); $answertext = $frow['question']; if (strpos($answertext, '|')) { $answertext = substr($answertext, 0, strpos($answertext, '|')); } $question['ANSWER'] .= "\t\t\t\t\t<th class=\"answertext\">{$answertext}</th>\n"; //$printablesurveyoutput .="\t\t\t\t\t<td>"; for ($i = 1; $i <= $fcount; $i++) { $question['ANSWER'] .= "\t\t\t<td>\n"; if ($checkboxlayout === false) { $question['ANSWER'] .= "\t\t\t\t" . self::_input_type_image('text', '', 4) . self::_addsgqacode(" (" . $fieldname . $frow['title'] . "_" . $xaxisarray[$i] . ") ") . "\n"; } else { $question['ANSWER'] .= "\t\t\t\t" . self::_input_type_image('checkbox') . self::_addsgqacode(" (" . $fieldname . $frow['title'] . "_" . $xaxisarray[$i] . ") ") . "\n"; } $question['ANSWER'] .= "\t\t\t</td>\n"; } $answertext = $frow['question']; if (strpos($answertext, '|')) { $answertext = substr($answertext, strpos($answertext, '|') + 1); $question['ANSWER'] .= "\t\t\t<th class=\"answertextright\">{$answertext}</th>\n"; } $question['ANSWER'] .= "\t\t</tr>\n"; $a++; } $question['ANSWER'] .= "\t</tbody>\n</table>\n"; break; // ================================================================== // ================================================================== case ";": //ARRAY (Multi Flexible) (text) $headstyle = "style='padding-left: 20px; padding-right: 7px'"; $mearesult = Question::model()->getAllRecords(" parent_qid='{$deqrow['qid']}' AND scale_id=0 AND language='{$sLanguageCode}' ", array('question_order')); $mearesult = $mearesult->readAll(); $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $sLanguageCode, $surveyid); $question['ANSWER'] .= "\n<table>\n\t<thead>\n\t\t<tr>\n\t\t\t<td> </td>\n"; $fresult = Question::model()->getAllRecords(" parent_qid='{$deqrow['qid']}' AND scale_id=1 AND language='{$sLanguageCode}' ", array('question_order')); $fresult = $fresult->readAll(); $fcount = count($fresult); $fwidth = "120"; $i = 0; //array to temporary store X axis question codes $xaxisarray = array(); foreach ($fresult as $frow) { $question['ANSWER'] .= "\t\t\t<th>{$frow['question']}</th>\n"; $i++; //add current question code $xaxisarray[$i] = $frow['title']; } $question['ANSWER'] .= "\t\t</tr>\n\t</thead>\n\n<tbody>\n"; $a = 1; $rowclass = 'array1'; foreach ($mearesult as $mearow) { $question['ANSWER'] .= "\t\t<tr class=\"{$rowclass}\">\n"; $rowclass = alternation($rowclass, 'row'); $answertext = $mearow['question']; if (strpos($answertext, '|')) { $answertext = substr($answertext, 0, strpos($answertext, '|')); } $question['ANSWER'] .= "\t\t\t<th class=\"answertext\">{$answertext}</th>\n"; for ($i = 1; $i <= $fcount; $i++) { $question['ANSWER'] .= "\t\t\t<td>\n"; $question['ANSWER'] .= "\t\t\t\t" . self::_input_type_image('text', '', 23) . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . "_" . $xaxisarray[$i] . ") ") . "\n"; $question['ANSWER'] .= "\t\t\t</td>\n"; } $answertext = $mearow['question']; if (strpos($answertext, '|')) { $answertext = substr($answertext, strpos($answertext, '|') + 1); $question['ANSWER'] .= "\t\t\t\t<th class=\"answertextright\">{$answertext}</th>\n"; } $question['ANSWER'] .= "\t\t</tr>\n"; $a++; } $question['ANSWER'] .= "\t</tbody>\n</table>\n"; break; // ================================================================== // ================================================================== case "F": //ARRAY (Flexible Labels) $question['QUESTION_TYPE_HELP'] .= gT("Please choose the appropriate response for each item:"); $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $sLanguageCode, $surveyid); $fresult = Answer::model()->getAllRecords(" scale_id=0 AND qid='{$deqrow['qid']}' AND language='{$sLanguageCode}'", array('sortorder', 'code')); $fresult = $fresult->readAll(); $fcount = count($fresult); $fwidth = "120"; $i = 1; $column_headings = array(); foreach ($fresult as $frow) { $column_headings[] = $frow['answer'] . self::_addsgqacode(" (" . $frow['code'] . ")"); } if (trim($qidattributes['answer_width']) != '') { $iAnswerWidth = 100 - $qidattributes['answer_width']; } else { $iAnswerWidth = 80; } if (count($column_headings) > 0) { $col_width = round($iAnswerWidth / count($column_headings)); } else { $heading = ''; } $question['ANSWER'] .= "\n<table>\n\t<thead>\n\t\t<tr>\n"; $question['ANSWER'] .= "\t\t\t<td> </td>\n"; foreach ($column_headings as $heading) { $question['ANSWER'] .= "\t\t\t<th style=\"width:{$col_width}%;\">{$heading}</th>\n"; } $i++; $question['ANSWER'] .= "\t\t</tr>\n\t</thead>\n\n\t<tbody>\n"; $counter = 1; $rowclass = 'array1'; $mearesult = Question::model()->getAllRecords(" parent_qid='{$deqrow['qid']}' AND language='{$sLanguageCode}' ", array('question_order')); foreach ($mearesult->readAll() as $mearow) { $question['ANSWER'] .= "\t\t<tr class=\"{$rowclass}\">\n"; $rowclass = alternation($rowclass, 'row'); if (trim($answertext) == '') { $answertext = ' '; } //semantic differential question type? if (strpos($mearow['question'], '|')) { $answertext = substr($mearow['question'], 0, strpos($mearow['question'], '|')) . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . ")") . " "; } else { $answertext = $mearow['question'] . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . ")"); } if (trim($qidattributes['answer_width']) != '') { $sInsertStyle = ' style="width:' . $qidattributes['answer_width'] . '%" '; } else { $sInsertStyle = ''; } $question['ANSWER'] .= "\t\t\t<th {$sInsertStyle} class=\"answertext\">{$answertext}</th>\n"; for ($i = 1; $i <= $fcount; $i++) { $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio') . "</td>\n"; } $counter++; $answertext = $mearow['question']; //semantic differential question type? if (strpos($mearow['question'], '|')) { $answertext2 = substr($mearow['question'], strpos($mearow['question'], '|') + 1); $question['ANSWER'] .= "\t\t\t<th class=\"answertextright\">{$answertext2}</th>\n"; } $question['ANSWER'] .= "\t\t</tr>\n"; } $question['ANSWER'] .= "\t</tbody>\n</table>\n"; break; // ================================================================== // ================================================================== case "1": //ARRAY (Flexible Labels) multi scale $leftheader = $qidattributes['dualscale_headerA'][$sLanguageCode]; $rightheader = $qidattributes['dualscale_headerB'][$sLanguageCode]; $headstyle = 'style="padding-left: 20px; padding-right: 7px"'; $question['QUESTION_TYPE_HELP'] .= gT("Please choose the appropriate response for each item:"); $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $sLanguageCode, $surveyid); $question['ANSWER'] .= "\n<table>\n\t<thead>\n"; $condition = "qid= '{$deqrow['qid']}' AND language= '{$sLanguageCode}' AND scale_id=0"; $fresult = Answer::model()->getAllRecords($condition, array('sortorder', 'code')); $fresult = $fresult->readAll(); $fcount = count($fresult); $fwidth = "120"; $l1 = 0; $printablesurveyoutput2 = "\t\t\t<td> </td>\n"; $myheader2 = ''; foreach ($fresult as $frow) { $printablesurveyoutput2 .= "\t\t\t<th>{$frow['answer']}" . self::_addsgqacode(" (" . $frow['code'] . ")") . "</th>\n"; $myheader2 .= "<td></td>"; $l1++; } // second scale $printablesurveyoutput2 .= "\t\t\t<td> </td>\n"; //$fquery1 = "SELECT * FROM {{answers}} WHERE qid='{$deqrow['qid']}' AND language='{$sLanguageCode}' AND scale_id=1 ORDER BY sortorder, code"; // $fresult1 = Yii::app()->db->createCommand($fquery1)->query(); $fresult1 = Answer::model()->getAllRecords(" qid='{$deqrow['qid']}' AND language='{$sLanguageCode}' AND scale_id=1 ", array('sortorder', 'code')); $fresult1 = $fresult1->readAll(); $fcount1 = count($fresult1); $fwidth = "120"; $l2 = 0; //array to temporary store second scale question codes $scale2array = array(); foreach ($fresult1 as $frow1) { $printablesurveyoutput2 .= "\t\t\t<th>{$frow1['answer']}" . self::_addsgqacode(" (" . $frow1['code'] . ")") . "</th>\n"; //add current question code $scale2array[$l2] = $frow1['code']; $l2++; } // build header if needed if ($leftheader != '' || $rightheader != '') { $myheader = "\t\t\t<td> </td>"; $myheader .= "\t\t\t<th colspan=\"" . $l1 . "\">{$leftheader}</th>\n"; if ($rightheader != '') { // $myheader .= "\t\t\t\t\t" .$myheader2; $myheader .= "\t\t\t<td> </td>"; $myheader .= "\t\t\t<th colspan=\"" . $l2 . "\">{$rightheader}</td>\n"; } $myheader .= "\t\t\t\t</tr>\n"; } else { $myheader = ''; } $question['ANSWER'] .= $myheader . "\t\t</tr>\n\n\t\t<tr>\n"; $question['ANSWER'] .= $printablesurveyoutput2; $question['ANSWER'] .= "\t\t</tr>\n\t</thead>\n\n\t<tbody>\n"; $rowclass = 'array1'; //counter for each subquestion $sqcounter = 0; $mearesult = Question::model()->getAllRecords(" parent_qid={$deqrow['qid']} AND language='{$sLanguageCode}' ", array('question_order')); foreach ($mearesult->readAll() as $mearow) { $question['ANSWER'] .= "\t\t<tr class=\"{$rowclass}\">\n"; $rowclass = alternation($rowclass, 'row'); $answertext = $mearow['question'] . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . "#0) / (" . $fieldname . $mearow['title'] . "#1)"); if (strpos($answertext, '|')) { $answertext = substr($answertext, 0, strpos($answertext, '|')); } $question['ANSWER'] .= "\t\t\t<th class=\"answertext\">{$answertext}</th>\n"; for ($i = 1; $i <= $fcount; $i++) { $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio') . "</td>\n"; } $question['ANSWER'] .= "\t\t\t<td> </td>\n"; for ($i = 1; $i <= $fcount1; $i++) { $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio') . "</td>\n"; } $answertext = $mearow['question']; if (strpos($answertext, '|')) { $answertext = substr($answertext, strpos($answertext, '|') + 1); $question['ANSWER'] .= "\t\t\t<th class=\"answertextright\">{$answertext}</th>\n"; } $question['ANSWER'] .= "\t\t</tr>\n"; //increase subquestion counter $sqcounter++; } $question['ANSWER'] .= "\t</tbody>\n</table>\n"; break; // ================================================================== // ================================================================== case "H": //ARRAY (Flexible Labels) by Column //$headstyle="style='border-left-style: solid; border-left-width: 1px; border-left-color: #AAAAAA'"; $headstyle = "style='padding-left: 20px; padding-right: 7px'"; $condition = "parent_qid= '{$deqrow['qid']}' AND language= '{$sLanguageCode}'"; $fresult = Question::model()->getAllRecords($condition, array('question_order', 'title')); $fresult = $fresult->readAll(); $question['QUESTION_TYPE_HELP'] .= gT("Please choose the appropriate response for each item:"); $question['ANSWER'] .= "\n<table>\n\t<thead>\n\t\t<tr>\n\t\t\t<td> </td>\n"; $fcount = count($fresult); $fwidth = "120"; $i = 0; foreach ($fresult as $frow) { $question['ANSWER'] .= "\t\t\t<th>{$frow['question']}" . self::_addsgqacode(" (" . $fieldname . $frow['title'] . ")") . "</th>\n"; $i++; } $question['ANSWER'] .= "\t\t</tr>\n\t</thead>\n\n\t<tbody>\n"; $a = 1; $rowclass = 'array1'; $mearesult = Answer::model()->getAllRecords(" qid='{$deqrow['qid']}' AND scale_id=0 AND language='{$sLanguageCode}' ", array('sortorder', 'code')); foreach ($mearesult->readAll() as $mearow) { //$_POST['type']=$type; $question['ANSWER'] .= "\t\t<tr class=\"{$rowclass}\">\n"; $rowclass = alternation($rowclass, 'row'); $question['ANSWER'] .= "\t\t\t<th class=\"answertext\">{$mearow['answer']}" . self::_addsgqacode(" (" . $mearow['code'] . ")") . "</th>\n"; //$printablesurveyoutput .="\t\t\t\t\t<td>"; for ($i = 1; $i <= $fcount; $i++) { $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio') . "</td>\n"; } //$printablesurveyoutput .="\t\t\t\t\t</tr></table></td>\n"; $question['ANSWER'] .= "\t\t</tr>\n"; $a++; } $question['ANSWER'] .= "\t</tbody>\n</table>\n"; break; case "|": // File Upload $question['QUESTION_TYPE_HELP'] .= "Kindly attach the aforementioned documents along with the survey"; break; // === END SWITCH =================================================== } $question['QUESTION_TYPE_HELP'] = self::_star_replace($question['QUESTION_TYPE_HELP']); $group['QUESTIONS'] .= self::_populate_template('question', $question); } if ($bGroupHasVisibleQuestions) { $survey_output['GROUPS'] .= self::_populate_template('group', $group); } } $survey_output['THEREAREXQUESTIONS'] = str_replace('{NUMBEROFQUESTIONS}', $total_questions, gT('There are {NUMBEROFQUESTIONS} questions in this survey')); // START recursive tag stripping. // PHP 5.1.0 introduced the count parameter for preg_replace() and thus allows this procedure to run with only one regular expression. // Previous version of PHP needs two regular expressions to do the same thing and thus will run a bit slower. $server_is_newer = version_compare(PHP_VERSION, '5.1.0', '>'); $rounds = 0; while ($rounds < 1) { $replace_count = 0; if ($server_is_newer) { $survey_output['GROUPS'] = preg_replace(array('/<td>(?: | | )?<\\/td>/isU', '/<th[^>]*>(?: | | )?<\\/th>/isU', '/<([^ >]+)[^>]*>(?: | |\\r\\n|\\n\\r|\\n|\\r|\\t| )*<\\/\\1>/isU'), array('[[EMPTY-TABLE-CELL]]', '[[EMPTY-TABLE-CELL-HEADER]]', ''), $survey_output['GROUPS'], -1, $replace_count); } else { $survey_output['GROUPS'] = preg_replace(array('/<td>(?: | | )?<\\/td>/isU', '/<th[^>]*>(?: | | )?<\\/th>/isU', '/<([^ >]+)[^>]*>(?: | |\\r\\n|\\n\\r|\\n|\\r|\\t| )*<\\/\\1>/isU'), array('[[EMPTY-TABLE-CELL]]', '[[EMPTY-TABLE-CELL-HEADER]]', ''), $survey_output['GROUPS']); $replace_count = preg_match('/<([^ >]+)[^>]*>(?: | |\\r\\n|\\n\\r|\\n|\\r|\\t| )*<\\/\\1>/isU', $survey_output['GROUPS']); } if ($replace_count == 0) { ++$rounds; $survey_output['GROUPS'] = preg_replace(array('/\\[\\[EMPTY-TABLE-CELL\\]\\]/', '/\\[\\[EMPTY-TABLE-CELL-HEADER\\]\\]/', '/\\n(?:\\t*\\n)+/'), array('<td> </td>', '<th> </th>', "\n"), $survey_output['GROUPS']); } } $survey_output['GROUPS'] = preg_replace('/(<div[^>]*>){NOTEMPTY}(<\\/div>)/', '\\1 \\2', $survey_output['GROUPS']); // END recursive empty tag stripping. echo self::_populate_template('survey', $survey_output); } // End print }
/** * Load preview of a question screen. * * @access public * @param int $surveyid * @param int $qid * @param string $lang * @return void */ public function preview($surveyid, $qid, $lang = null) { $surveyid = sanitize_int($surveyid); $qid = sanitize_int($qid); $LEMdebugLevel = 0; Yii::app()->loadHelper("qanda"); Yii::app()->loadHelper("surveytranslator"); if (empty($surveyid)) { $this->getController()->error('No Survey ID provided'); } if (empty($qid)) { $this->getController()->error('No Question ID provided'); } if (empty($lang)) { $language = Survey::model()->findByPk($surveyid)->language; } else { $language = $lang; } if (!isset(Yii::app()->session['step'])) { Yii::app()->session['step'] = 0; } if (!isset(Yii::app()->session['prevstep'])) { Yii::app()->session['prevstep'] = 0; } if (!isset(Yii::app()->session['maxstep'])) { Yii::app()->session['maxstep'] = 0; } // Use $_SESSION instead of $this->session for frontend features. $_SESSION['survey_' . $surveyid]['s_lang'] = $language; $_SESSION['survey_' . $surveyid]['fieldmap'] = createFieldMap($surveyid, 'full', true, $qid, $language); // Prefill question/answer from defaultvalues foreach ($_SESSION['survey_' . $surveyid]['fieldmap'] as $field) { if (isset($field['defaultvalue'])) { $_SESSION['survey_' . $surveyid][$field['fieldname']] = $field['defaultvalue']; } } $clang = new limesurvey_lang($language); $thissurvey = getSurveyInfo($surveyid); setNoAnswerMode($thissurvey); Yii::app()->session['dateformats'] = getDateFormatData($thissurvey['surveyls_dateformat']); $qrows = Questions::model()->findByAttributes(array('sid' => $surveyid, 'qid' => $qid, 'language' => $language))->getAttributes(); $ia = array(0 => $qid, 1 => $surveyid . 'X' . $qrows['gid'] . 'X' . $qid, 2 => $qrows['title'], 3 => $qrows['question'], 4 => $qrows['type'], 5 => $qrows['gid'], 6 => $qrows['mandatory'], 7 => 'N', 8 => 'N'); $radix = getRadixPointData($thissurvey['surveyls_numberformat']); $radix = $radix['seperator']; $surveyOptions = array('radix' => $radix, 'tempdir' => Yii::app()->getConfig('tempdir')); LimeExpressionManager::StartSurvey($surveyid, 'question', $surveyOptions, false, $LEMdebugLevel); $qseq = LimeExpressionManager::GetQuestionSeq($qid); $moveResult = LimeExpressionManager::JumpTo($qseq + 1, true, false, true); $answers = retrieveAnswers($ia, $surveyid); if (!$thissurvey['template']) { $thistpl = getTemplatePath(Yii::app()->getConfig('defaulttemplate')); } else { $thistpl = getTemplatePath(validateTemplateDir($thissurvey['template'])); } doHeader(); $showQuestion = "\$('#question{$qid}').show();"; $dummy_js = <<<EOD <script type='text/javascript'> <!-- LEMradix='{$radix}'; var numRegex = new RegExp('[^-' + LEMradix + '0-9]','g'); var intRegex = new RegExp('[^-0-9]','g'); function fixnum_checkconditions(value, name, type, evt_type, intonly) { newval = new String(value); if (typeof intonly !=='undefined' && intonly==1) { newval = newval.replace(intRegex,''); } else { newval = newval.replace(numRegex,''); } if (LEMradix === ',') { newval = newval.split(',').join('.'); } if (newval != '-' && newval != '.' && newval != '-.' && newval != parseFloat(newval)) { newval = ''; } displayVal = newval; if (LEMradix === ',') { displayVal = displayVal.split('.').join(','); } if (name.match(/other\$/)) { \$('#answer'+name+'text').val(displayVal); } \$('#answer'+name).val(displayVal); if (typeof evt_type === 'undefined') { evt_type = 'onchange'; } checkconditions(newval, name, type, evt_type); } function checkconditions(value, name, type, evt_type) { if (typeof evt_type === 'undefined') { evt_type = 'onchange'; } if (type == 'radio' || type == 'select-one') { var hiddenformname='java'+name; document.getElementById(hiddenformname).value=value; } else if (type == 'checkbox') { if (document.getElementById('answer'+name).checked) { \$('#java'+name).val('Y'); } else { \$('#java'+name).val(''); } } else if (type == 'text' && name.match(/other\$/) && typeof document.getElementById('java'+name) !== 'undefined' && document.getElementById('java'+name) != null) { \$('#java'+name).val(value); } ExprMgr_process_relevance_and_tailoring(evt_type,name,type); {$showQuestion} } \$(document).ready(function() { {$showQuestion} }); \$(document).change(function() { {$showQuestion} }); \$(document).bind('keydown',function(e) { if (e.keyCode == 9) { {$showQuestion} return true; } return true; }); // --> </script> EOD; $answer = $answers[0][1]; // $help = $answers[0][2]; $qinfo = LimeExpressionManager::GetQuestionStatus($qid); $help = $qinfo['info']['help']; $question = $answers[0][0]; $question['code'] = $answers[0][5]; $question['class'] = getQuestionClass($qrows['type']); $question['essentials'] = 'id="question' . $qrows['qid'] . '"'; $question['sgq'] = $ia[1]; $question['aid'] = 'unknown'; $question['sqid'] = 'unknown'; if ($qrows['mandatory'] == 'Y') { $question['man_class'] = ' mandatory'; } else { $question['man_class'] = ''; } $redata = compact(array_keys(get_defined_vars())); $content = templatereplace(file_get_contents("{$thistpl}/startpage.pstpl"), array(), $redata); $content .= CHtml::form('index.php', 'post', array('id' => "limesurvey", 'name' => "limesurvey", 'autocomplete' => 'off')); $content .= templatereplace(file_get_contents("{$thistpl}/startgroup.pstpl"), array(), $redata); $question_template = file_get_contents("{$thistpl}/question.pstpl"); // the following has been added for backwards compatiblity. if (substr_count($question_template, '{QUESTION_ESSENTIALS}') > 0) { // LS 1.87 and newer templates $content .= "\n" . templatereplace($question_template, array(), $redata, 'Unspecified', false, $qid) . "\n"; } else { // LS 1.86 and older templates $content .= '<div ' . $question['essentials'] . ' class="' . $question['class'] . $question['man_class'] . '">'; $content .= "\n" . templatereplace($question_template, array(), $redata, 'Unspecified', false, $qid) . "\n"; $content .= "\n\t</div>\n"; } $content .= templatereplace(file_get_contents("{$thistpl}/endgroup.pstpl"), array(), $redata) . $dummy_js; LimeExpressionManager::FinishProcessingGroup(); $content .= LimeExpressionManager::GetRelevanceAndTailoringJavaScript(); $content .= '<p> </form>'; $content .= templatereplace(file_get_contents("{$thistpl}/endpage.pstpl"), array(), $redata); LimeExpressionManager::FinishProcessingPage(); echo $content; if ($LEMdebugLevel >= 1) { echo LimeExpressionManager::GetDebugTimingMessage(); } if ($LEMdebugLevel >= 2) { echo "<table><tr><td align='left'><b>Group/Question Validation Results:</b>" . $moveResult['message'] . "</td></tr></table>\n"; } echo "</html>\n"; exit; }
function do_multiplenumeric($ia) { global $thissurvey; $extraclass = ""; $checkconditionFunction = "fixnum_checkconditions"; $aQuestionAttributes = QuestionAttribute::model()->getQuestionAttributes($ia[0]); $answer = ''; $sSeparator = getRadixPointData($thissurvey['surveyls_numberformat']); $sSeparator = $sSeparator['separator']; $extraclass .= " numberonly"; //Must turn on the "numbers only javascript" if (intval(trim($aQuestionAttributes['maximum_chars'])) > 0) { $maximum_chars = intval(trim($aQuestionAttributes['maximum_chars'])); // Only maxlength attribute, use textarea[maxlength] jquery selector for textarea $maxlength = "maxlength='{$maximum_chars}' "; $extraclass .= " maxchars maxchars-" . $maximum_chars; } else { $maxlength = " maxlength='25' "; } if (trim($aQuestionAttributes['prefix'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']]) != '') { $prefix = $aQuestionAttributes['prefix'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']]; $extraclass .= " withprefix"; } else { $prefix = ''; } if (trim($aQuestionAttributes['suffix'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']]) != '') { $suffix = $aQuestionAttributes['suffix'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']]; $extraclass .= " withsuffix"; } else { $suffix = ''; } $kpclass = testKeypad($thissurvey['nokeyboard']); // Virtual keyboard (probably obsolete today) $numbersonly_slider = ''; // DEPRECATED if (trim($aQuestionAttributes['text_input_width']) != '') { $tiwidth = $aQuestionAttributes['text_input_width']; $col = $aQuestionAttributes['text_input_width'] <= 12 ? $aQuestionAttributes['text_input_width'] : 12; //$extraclass .= " col-sm-".trim($col); } else { $tiwidth = 6; } $prefixclass = "numeric"; if ($aQuestionAttributes['slider_layout'] == 1) { $prefixclass = "slider"; $slider_layout = true; $extraclass .= " withslider"; $slider_step = trim(LimeExpressionManager::ProcessString("{{$aQuestionAttributes['slider_accuracy']}}", $ia[0], array(), false, 1, 1, false, false, true)); $slider_step = is_numeric($slider_step) ? $slider_step : 1; $slider_min = trim(LimeExpressionManager::ProcessString("{{$aQuestionAttributes['slider_min']}}", $ia[0], array(), false, 1, 1, false, false, true)); $slider_mintext = $slider_min = is_numeric($slider_min) ? $slider_min : 0; $slider_max = trim(LimeExpressionManager::ProcessString("{{$aQuestionAttributes['slider_max']}}", $ia[0], array(), false, 1, 1, false, false, true)); $slider_maxtext = $slider_max = is_numeric($slider_max) ? $slider_max : 100; $slider_default = trim(LimeExpressionManager::ProcessString("{{$aQuestionAttributes['slider_default']}}", $ia[0], array(), false, 1, 1, false, false, true)); $slider_default = is_numeric($slider_default) ? $slider_default : ""; $slider_orientation = trim($aQuestionAttributes['slider_orientation']) == 0 ? 'horizontal' : 'vertical'; $slider_custom_handle = trim($aQuestionAttributes['slider_custom_handle']); switch (trim($aQuestionAttributes['slider_handle'])) { case 0: $slider_handle = 'round'; break; case 1: $slider_handle = 'square'; break; case 2: $slider_handle = 'triangle'; break; case 3: $slider_handle = 'custom'; break; } if ($slider_default == '' && $aQuestionAttributes['slider_middlestart'] == 1) { $slider_middlestart = intval(($slider_max + $slider_min) / 2); } else { $slider_middlestart = ''; } $slider_separator = trim($aQuestionAttributes['slider_separator']) != '' ? $aQuestionAttributes['slider_separator'] : ""; $slider_reset = $aQuestionAttributes['slider_reset'] ? 1 : 0; // If the slider reset is ON, slider should be max 10 columns if ($slider_reset) { $tiwidth = $tiwidth < 10 ? $tiwidth : 10; } } else { $slider_layout = false; $slider_step = ''; $slider_min = ''; $slider_mintext = ''; $slider_max = ''; $slider_maxtext = ''; $slider_default = null; $slider_orientation = ''; $slider_handle = ''; $slider_custom_handle = ''; $slider_separator = ''; $slider_reset = 0; $slider_startvalue = ''; $slider_displaycallout = ''; } $hidetip = $aQuestionAttributes['hide_tip']; if ($aQuestionAttributes['random_order'] == 1) { $ansquery = "SELECT * FROM {{questions}} WHERE parent_qid={$ia['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 language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "' ORDER BY question_order"; } $ansresult = dbExecuteAssoc($ansquery); //Checked $aSubquestions = $ansresult->readAll(); $anscount = count($aSubquestions) * 2; $fn = 1; $sRows = ""; $answer_main = ''; $inputnames = array(); if ($anscount == 0) { $noanswer = true; $answer = doRender('/survey/questions/multiplenumeric/empty', array(), true); } else { foreach ($aSubquestions as $ansrow) { $labelText = $ansrow['question']; $myfname = $ia[1] . $ansrow['title']; if ($ansrow['question'] == "") { $ansrow['question'] = " "; } if ($slider_layout === false || $slider_separator == '') { $theanswer = $ansrow['question']; $sliders = false; } else { $aAnswer = explode($slider_separator, $ansrow['question']); $theanswer = isset($aAnswer[0]) ? $aAnswer[0] : ""; $labelText = $theanswer; $sliderleft = isset($aAnswer[1]) ? $aAnswer[1] : ""; $sliderright = isset($aAnswer[2]) ? $aAnswer[2] : ""; $sliders = true; } $aAnswer = isset($aAnswer) ? $aAnswer : ''; $sliderleft = isset($sliderleft) ? $sliderleft : ""; $sliderright = isset($sliderright) ? $sliderright : ""; // color code missing mandatory questions red $alert = ''; if ($_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['step'] != $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['maxstep'] || $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['step'] == $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['prevstep']) { if ($ia[6] == 'Y' && $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname] === '') { $alert = true; } } //list($htmltbody2, $hiddenfield)=return_array_filter_strings($ia, $aQuestionAttributes, $thissurvey, $ansrow, $myfname, '', $myfname, "div","form-group question-item answer-item text-item numeric-item".$extraclass); $sDisplayStyle = return_display_style($ia, $aQuestionAttributes, $thissurvey, $myfname); // TODO : check why it's done here a second time $sSeparator = getRadixPointData($thissurvey['surveyls_numberformat']); $sSeparator = $sSeparator['separator']; // The value of the slider depends on many possible different parameters, by order of priority : // 1. The value stored in the session // 2. Else the default Answer (set by EM and stored in session, so same case than 1) // 3. Else the init value // 4. Else the middle start // 5. If no value at all, or if middle start, the "user no action" is recorded as null in the database // For bootstrap slider, the value can't be NULL so we set it by default to the slider minimum value. // The old behaviour of "null" value (corresponding to user no action) is implemented via $slider_user_no_action // It could be used to show a temporary "No Answer" checkbox (hidden when user touch the slider) // Most of this javascript is here to handle the fact that bootstrapSlider need numerical value in the input // It can't accept "NULL" nor anyother thousand separator than "." (else it become a string) // See : https://github.com/LimeSurvey/LimeSurvey/blob/master/scripts/bootstrap-slider.js#l1453-l1461 // If the bootstrapSlider were updated, most of this javascript would not be necessary. $sValue = null; if (App()->request->getPost('slider_user_no_action_' . $myfname)) { $slider_user_no_action = App()->request->getPost('slider_user_no_action_' . $myfname); } else { $slider_user_no_action = 1; // value stored in _SESSION if (isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname])) { $sValue = $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname]; $slider_user_no_action = 0; } elseif ($slider_default != "") { $sValue = $slider_default; $slider_user_no_action = 0; } elseif (isset($slider_middlestart) && $slider_middlestart != '') { $sValue = $slider_middlestart; } } $sUnformatedValue = $sValue; if (strpos($sValue, ".")) { $sValue = rtrim(rtrim($sValue, "0"), "."); $sValue = str_replace('.', $sSeparator, $sValue); } if (trim($aQuestionAttributes['num_value_int_only']) == 1) { $extraclass .= " integeronly"; $answertypeclass = " integeronly"; $integeronly = 1; } else { $answertypeclass = ""; $integeronly = 0; } if (!$sliders) { $sRows .= doRender('/survey/questions/multiplenumeric/rows/input/answer_row', array('qid' => $ia[0], 'extraclass' => $extraclass, 'answertypeclass' => $answertypeclass, 'sDisplayStyle' => $sDisplayStyle, 'kpclass' => $kpclass, 'alert' => $alert, 'theanswer' => $theanswer, 'labelname' => 'answer' . $myfname, 'prefixclass' => $prefixclass, 'prefix' => $prefix, 'suffix' => $suffix, 'tiwidth' => $tiwidth, 'myfname' => $myfname, 'dispVal' => $sValue, 'maxlength' => $maxlength, 'labelText' => $labelText, 'checkconditionFunction' => $checkconditionFunction . '(this.value, this.name, this.type, \'onchange\',' . $integeronly . ')', 'integeronly' => $integeronly), true); } else { $sRows .= doRender('/survey/questions/multiplenumeric/rows/sliders/answer_row', array('qid' => $ia[0], 'extraclass' => $extraclass, 'sDisplayStyle' => $sDisplayStyle, 'kpclass' => $kpclass, 'alert' => $alert, 'theanswer' => $theanswer, 'labelname' => 'answer' . $myfname, 'prefixclass' => $prefixclass, 'sliders' => $sliders, 'sliderleft' => $sliderleft, 'sliderright' => $sliderright, 'prefix' => $prefix, 'suffix' => $suffix, 'tiwidth' => $tiwidth, 'myfname' => $myfname, 'dispVal' => $sValue, 'maxlength' => $maxlength, 'labelText' => $labelText, 'checkconditionFunction' => $checkconditionFunction . '(this.value, this.name, this.type)', 'slider_orientation' => $slider_orientation, 'slider_step' => $slider_step, 'slider_min' => $slider_min, 'slider_mintext' => $slider_mintext, 'slider_max' => $slider_max, 'slider_maxtext' => $slider_maxtext, 'slider_default' => $slider_default, 'slider_handle' => isset($slider_handle) ? $slider_handle : '', 'slider_reset' => $slider_reset, 'slider_custom_handle' => $slider_custom_handle, 'slider_user_no_action' => $slider_user_no_action, 'slider_showminmax' => $aQuestionAttributes['slider_showminmax'], 'sSeparator' => $sSeparator, 'sUnformatedValue' => $sUnformatedValue), true); } $fn++; $inputnames[] = $myfname; } $displaytotal = false; $equals_num_value = false; if (trim($aQuestionAttributes['equals_num_value']) != '' || trim($aQuestionAttributes['min_num_value']) != '' || trim($aQuestionAttributes['max_num_value']) != '') { $qinfo = LimeExpressionManager::GetQuestionStatus($ia[0]); if (trim($aQuestionAttributes['equals_num_value']) != '') { $equals_num_value = true; } $displaytotal = true; } // TODO: Slider and multiple-numeric input should really be two different question types $templateFile = $sliders ? 'answer' : 'answer_input'; $answer = doRender('/survey/questions/multiplenumeric/' . $templateFile, array('sRows' => $sRows, 'prefixclass' => $prefixclass, 'equals_num_value' => $equals_num_value, 'id' => $ia[0], 'prefix' => $prefix, 'suffix' => $suffix, 'sumRemainingEqn' => isset($qinfo) ? $qinfo['sumRemainingEqn'] : '', 'displaytotal' => $displaytotal, 'sumEqn' => isset($qinfo) ? $qinfo['sumEqn'] : '', 'prefix' => $prefix), true); } if ($aQuestionAttributes['slider_layout'] == 1) { Yii::app()->getClientScript()->registerScriptFile(App()->baseUrl . "/third_party/bootstrap-slider/bootstrap-slider.js"); } $sSeparator = getRadixPointData($thissurvey['surveyls_numberformat']); $sSeparator = $sSeparator['separator']; return array($answer, $inputnames); }
/** * Main function * * @param mixed $surveyid * @param mixed $args */ function run($surveyid, $args) { global $errormsg; extract($args); $LEMsessid = 'survey_' . $surveyid; $sTemplatePath = getTemplatePath(Yii::app()->getConfig("defaulttemplate")) . DIRECTORY_SEPARATOR; if (isset($_SESSION['survey_' . $surveyid]['templatepath'])) { $sTemplatePath = $_SESSION['survey_' . $surveyid]['templatepath']; } // $LEMdebugLevel - customizable debugging for Lime Expression Manager $LEMdebugLevel = 0; // LEM_DEBUG_TIMING; // (LEM_DEBUG_TIMING + LEM_DEBUG_VALIDATION_SUMMARY + LEM_DEBUG_VALIDATION_DETAIL); $LEMskipReprocessing = false; // true if used GetLastMoveResult to avoid generation of unneeded extra JavaScript switch ($thissurvey['format']) { case "A": //All in one $surveyMode = 'survey'; break; default: case "S": //One at a time $surveyMode = 'question'; break; case "G": //Group at a time $surveyMode = 'group'; break; } $radix = getRadixPointData($thissurvey['surveyls_numberformat']); $radix = $radix['seperator']; $surveyOptions = array('active' => $thissurvey['active'] == 'Y', 'allowsave' => $thissurvey['allowsave'] == 'Y', 'anonymized' => $thissurvey['anonymized'] != 'N', 'assessments' => $thissurvey['assessments'] == 'Y', 'datestamp' => $thissurvey['datestamp'] == 'Y', 'hyperlinkSyntaxHighlighting' => ($LEMdebugLevel & LEM_DEBUG_VALIDATION_SUMMARY) == LEM_DEBUG_VALIDATION_SUMMARY, 'ipaddr' => $thissurvey['ipaddr'] == 'Y', 'radix' => $radix, 'refurl' => $thissurvey['refurl'] == "Y" ? $_SESSION[$LEMsessid]['refurl'] : NULL, 'savetimings' => $thissurvey['savetimings'] == "Y", 'surveyls_dateformat' => isset($thissurvey['surveyls_dateformat']) ? $thissurvey['surveyls_dateformat'] : 1, 'startlanguage' => isset($clang->langcode) ? $clang->langcode : $thissurvey['language'], 'target' => Yii::app()->getConfig('uploaddir') . DIRECTORY_SEPARATOR . 'surveys' . DIRECTORY_SEPARATOR . $thissurvey['sid'] . DIRECTORY_SEPARATOR . 'files' . DIRECTORY_SEPARATOR, 'tempdir' => Yii::app()->getConfig('tempdir') . DIRECTORY_SEPARATOR, 'timeadjust' => isset($timeadjust) ? $timeadjust : 0, 'token' => isset($clienttoken) ? $clienttoken : NULL); //Security Checked: POST, GET, SESSION, REQUEST, returnGlobal, DB $previewgrp = false; if ($surveyMode == 'group' && isset($param['action']) && $param['action'] == 'previewgroup') { $previewgrp = true; } $previewquestion = false; if ($surveyMode == 'question' && isset($param['action']) && $param['action'] == 'previewquestion') { $previewquestion = true; } // if (isset($param['newtest']) && $param['newtest'] == "Y") // setcookie("limesurvey_timers", "0"); //@todo fix - sometimes results in headers already sent error $show_empty_group = false; if ($previewgrp || $previewquestion) { $_SESSION[$LEMsessid]['prevstep'] = 1; $_SESSION[$LEMsessid]['maxstep'] = 0; } else { //RUN THIS IF THIS IS THE FIRST TIME , OR THE FIRST PAGE ######################################## if (!isset($_SESSION[$LEMsessid]['step'])) { buildsurveysession($surveyid); $sTemplatePath = $_SESSION[$LEMsessid]['templatepath']; if ($surveyid != LimeExpressionManager::getLEMsurveyId()) { LimeExpressionManager::SetDirtyFlag(); } LimeExpressionManager::StartSurvey($surveyid, $surveyMode, $surveyOptions, false, $LEMdebugLevel); $_SESSION[$LEMsessid]['step'] = 0; if ($surveyMode == 'survey') { $move = "movenext"; // to force a call to NavigateForwards() } elseif (isset($thissurvey['showwelcome']) && $thissurvey['showwelcome'] == 'N') { $move = "movenext"; $_SESSION[$LEMsessid]['step'] = 1; } } else { if ($surveyid != LimeExpressionManager::getLEMsurveyId()) { LimeExpressionManager::StartSurvey($surveyid, $surveyMode, $surveyOptions, false, $LEMdebugLevel); LimeExpressionManager::JumpTo($_SESSION[$LEMsessid]['step'], false, false); } } $totalquestions = $_SESSION['survey_' . $surveyid]['totalquestions']; if (!isset($_SESSION[$LEMsessid]['totalsteps'])) { $_SESSION[$LEMsessid]['totalsteps'] = 0; } if (!isset($_SESSION[$LEMsessid]['maxstep'])) { $_SESSION[$LEMsessid]['maxstep'] = 0; } if (isset($_SESSION[$LEMsessid]['LEMpostKey']) && isset($_POST['LEMpostKey']) && $_POST['LEMpostKey'] != $_SESSION[$LEMsessid]['LEMpostKey']) { // then trying to resubmit (e.g. Next, Previous, Submit) from a cached copy of the page // Does not try to save anything from the page to the database $moveResult = LimeExpressionManager::GetLastMoveResult(true); if (isset($_POST['thisstep']) && isset($moveResult['seq']) && $_POST['thisstep'] == $moveResult['seq']) { // then pressing F5 or otherwise refreshing the current page, which is OK $LEMskipReprocessing = true; $move = "movenext"; // so will re-display the survey } else { // trying to use browser back buttons, which may be disallowed if no 'previous' button is present $LEMskipReprocessing = true; $move = "movenext"; // so will re-display the survey $invalidLastPage = true; $vpopup = "<script type=\"text/javascript\">\n\n <!--\n \$(document).ready(function(){\n alert(\"" . $clang->gT("Please use the LimeSurvey navigation buttons or index. It appears you attempted to use the browser back button to re-submit a page.", "js") . "\");});\n //-->\n\n </script>\n"; } } if (!(isset($_POST['saveall']) || isset($_POST['saveprompt']) || isset($_POST['loadall']) || isset($_GET['sid']) || $LEMskipReprocessing || isset($move) && preg_match('/^changelang_/', $move))) { $_SESSION[$LEMsessid]['prevstep'] = $_SESSION[$LEMsessid]['step']; } if (!isset($_SESSION[$LEMsessid]['prevstep'])) { $_SESSION[$LEMsessid]['prevstep'] = -1; // this only happens on re-load } if (isset($_SESSION[$LEMsessid]['LEMtokenResume'])) { LimeExpressionManager::StartSurvey($thissurvey['sid'], $surveyMode, $surveyOptions, false, $LEMdebugLevel); $moveResult = LimeExpressionManager::JumpTo($_SESSION[$LEMsessid]['step'], false, false); // if late in the survey, will re-validate contents, which may be overkill unset($_SESSION[$LEMsessid]['LEMtokenResume']); } else { if (!$LEMskipReprocessing) { //Move current step ########################################################################### if (isset($move) && $move == 'moveprev' && ($thissurvey['allowprev'] == 'Y' || $thissurvey['allowjumps'] == 'Y')) { $moveResult = LimeExpressionManager::NavigateBackwards(); if ($moveResult['at_start']) { $_SESSION[$LEMsessid]['step'] = 0; unset($moveResult); // so display welcome page again } } if (isset($move) && $move == "movenext") { $moveResult = LimeExpressionManager::NavigateForwards(); } if (isset($move) && $move == 'movesubmit') { if ($surveyMode == 'survey') { $moveResult = LimeExpressionManager::NavigateForwards(); } else { // may be submitting from the navigation bar, in which case need to process all intervening questions // in order to update equations and ensure there are no intervening relevant mandatory or relevant invalid questions $moveResult = LimeExpressionManager::JumpTo($_SESSION[$LEMsessid]['totalsteps'] + 1, false); } } if (isset($move) && preg_match('/^changelang_/', $move)) { // jump to current step using new language, processing POST values $moveResult = LimeExpressionManager::JumpTo($_SESSION[$LEMsessid]['step'], false, true, false, true); // do process the POST data } if (isset($move) && isNumericInt($move) && $thissurvey['allowjumps'] == 'Y') { $move = (int) $move; if ($move > 0 && ($move <= $_SESSION[$LEMsessid]['step'] || isset($_SESSION[$LEMsessid]['maxstep']) && $move <= $_SESSION[$LEMsessid]['maxstep'])) { $moveResult = LimeExpressionManager::JumpTo($move, false); } } if (!isset($moveResult) && !($surveyMode != 'survey' && $_SESSION[$LEMsessid]['step'] == 0)) { // Just in case not set via any other means, but don't do this if it is the welcome page $moveResult = LimeExpressionManager::GetLastMoveResult(true); $LEMskipReprocessing = true; } } } if (isset($moveResult)) { if ($moveResult['finished'] == true) { $move = 'movesubmit'; } else { $_SESSION[$LEMsessid]['step'] = $moveResult['seq'] + 1; // step is index base 1 $stepInfo = LimeExpressionManager::GetStepIndexInfo($moveResult['seq']); } if ($move == "movesubmit" && $moveResult['finished'] == false) { // then there are errors, so don't finalize the survey $move = "movenext"; // so will re-display the survey $invalidLastPage = true; } } // We do not keep the participant session anymore when the same browser is used to answer a second time a survey (let's think of a library PC for instance). // Previously we used to keep the session and redirect the user to the // submit page. if ($surveyMode != 'survey' && $_SESSION[$LEMsessid]['step'] == 0) { $_SESSION[$LEMsessid]['test'] = time(); display_first_page(); exit; } //CHECK IF ALL MANDATORY QUESTIONS HAVE BEEN ANSWERED ############################################ //First, see if we are moving backwards or doing a Save so far, and its OK not to check: if (isset($move) && ($move == "moveprev" || is_int($move) && $_SESSION[$LEMsessid]['prevstep'] == $_SESSION[$LEMsessid]['maxstep'] || $_SESSION[$LEMsessid]['prevstep'] == $_SESSION[$LEMsessid]['step']) || isset($_POST['saveall']) && $_POST['saveall'] == $clang->gT("Save your responses so far")) { if (Yii::app()->getConfig('allowmandbackwards') == 1) { $backok = "Y"; } else { $backok = "N"; } } else { $backok = "N"; // NA, since not moving backwards } // TODO FIXME if ($thissurvey['active'] == "Y") { Yii::import("application.libraries.Save"); $cSave = new Save(); } if ($thissurvey['active'] == "Y" && isset($_POST['saveall'])) { // must do this here to process the POSTed values $moveResult = LimeExpressionManager::JumpTo($_SESSION[$LEMsessid]['step'], false); // by jumping to current step, saves data so far $cSave->showsaveform(); // generates a form and exits, awaiting input } if ($thissurvey['active'] == "Y" && isset($_POST['saveprompt'])) { // The response from the save form // CREATE SAVED CONTROL RECORD USING SAVE FORM INFORMATION $flashmessage = $cSave->savedcontrol(); if (isset($errormsg) && $errormsg != "") { $cSave->showsaveform(); // reshow the form if there is an error } $moveResult = LimeExpressionManager::GetLastMoveResult(true); $LEMskipReprocessing = true; // TODO - does this work automatically for token answer persistence? Used to be savedsilent() } //Now, we check mandatory questions if necessary //CHECK IF ALL CONDITIONAL MANDATORY QUESTIONS THAT APPLY HAVE BEEN ANSWERED global $notanswered; if (isset($moveResult) && !$moveResult['finished']) { $unansweredSQList = $moveResult['unansweredSQs']; if (strlen($unansweredSQList) > 0 && $backok != "N") { $notanswered = explode('|', $unansweredSQList); } else { $notanswered = array(); } //CHECK INPUT $invalidSQList = $moveResult['invalidSQs']; if (strlen($invalidSQList) > 0 && $backok != "N") { $notvalidated = explode('|', $invalidSQList); } else { $notvalidated = array(); } } // CHECK UPLOADED FILES // TMSW - Move this into LEM::NavigateForwards? $filenotvalidated = checkUploadedFileValidity($surveyid, $move, $backok); //SEE IF THIS GROUP SHOULD DISPLAY $show_empty_group = false; if ($_SESSION[$LEMsessid]['step'] == 0) { $show_empty_group = true; } $redata = compact(array_keys(get_defined_vars())); //SUBMIT ############################################################################### if (isset($move) && $move == "movesubmit") { // setcookie("limesurvey_timers", "", time() - 3600); // remove the timers cookies //@todo fix - sometimes results in headers already sent error if ($thissurvey['refurl'] == "Y") { if (!in_array("refurl", $_SESSION[$LEMsessid]['insertarray'])) { $_SESSION[$LEMsessid]['insertarray'][] = "refurl"; } } resetTimers(); //Before doing the "templatereplace()" function, check the $thissurvey['url'] //field for limereplace stuff, and do transformations! $thissurvey['surveyls_url'] = passthruReplace($thissurvey['surveyls_url'], $thissurvey); $thissurvey['surveyls_url'] = templatereplace($thissurvey['surveyls_url'], $thissurvey); // to do INSERTANS substitutions //END PAGE - COMMIT CHANGES TO DATABASE if ($thissurvey['active'] != "Y") { if ($thissurvey['assessments'] == "Y") { $assessments = doAssessment($surveyid); } sendCacheHeaders(); doHeader(); echo templatereplace(file_get_contents($sTemplatePath . "startpage.pstpl"), array(), $redata); //Check for assessments if ($thissurvey['assessments'] == "Y" && $assessments) { echo templatereplace(file_get_contents($sTemplatePath . "assessment.pstpl"), array(), $redata); } // fetch all filenames from $_SESSIONS['files'] and delete them all // from the /upload/tmp/ directory /* echo "<pre>";print_r($_SESSION);echo "</pre>"; for($i = 1; isset($_SESSION[$LEMsessid]['files'][$i]); $i++) { unlink('upload/tmp/'.$_SESSION[$LEMsessid]['files'][$i]['filename']); } */ // can't kill session before end message, otherwise INSERTANS doesn't work. $completed = templatereplace($thissurvey['surveyls_endtext']); $completed .= "<br /><strong><font size='2' color='red'>" . $clang->gT("Did Not Save") . "</font></strong><br /><br />\n\n"; $completed .= $clang->gT("Your survey responses have not been recorded. This survey is not yet active.") . "<br /><br />\n"; if ($thissurvey['printanswers'] == 'Y') { // 'Clear all' link is only relevant for survey with printanswers enabled // in other cases the session is cleared at submit time $completed .= "<a href='" . Yii::app()->getController()->createUrl("survey/index/sid/{$surveyid}/move/clearall") . "'>" . $clang->gT("Clear Responses") . "</a><br /><br />\n"; } } else { if ($thissurvey['usecookie'] == "Y" && $tokensexist != 1) { setcookie("LS_" . $surveyid . "_STATUS", "COMPLETE", time() + 31536000); //Cookie will expire in 365 days } $content = ''; $content .= templatereplace(file_get_contents($sTemplatePath . "startpage.pstpl"), array(), $redata); //Check for assessments if ($thissurvey['assessments'] == "Y") { $assessments = doAssessment($surveyid); if ($assessments) { $content .= templatereplace(file_get_contents($sTemplatePath . "assessment.pstpl"), array(), $redata); } } //Update the token if needed and send a confirmation email if (isset($clienttoken) && $clienttoken) { submittokens(); } //Send notifications sendSubmitNotifications($surveyid); $content = ''; $content .= templatereplace(file_get_contents($sTemplatePath . "startpage.pstpl"), array(), $redata); //echo $thissurvey['url']; //Check for assessments if ($thissurvey['assessments'] == "Y") { $assessments = doAssessment($surveyid); if ($assessments) { $content .= templatereplace(file_get_contents($sTemplatePath . "assessment.pstpl"), array(), $redata); } } if (trim(strip_tags($thissurvey['surveyls_endtext'])) == '') { $completed = "<br /><span class='success'>" . $clang->gT("Thank you!") . "</span><br /><br />\n\n" . $clang->gT("Your survey responses have been recorded.") . "<br /><br />\n"; } else { $completed = templatereplace($thissurvey['surveyls_endtext']); } // Link to Print Answer Preview ********** if ($thissurvey['printanswers'] == 'Y') { $url = Yii::app()->getController()->createUrl("printanswers/view/surveyid/{$surveyid}"); $completed .= "<br /><br />" . "<a class='printlink' href='{$url}' target='_blank'>" . $clang->gT("Print your answers.") . "</a><br />\n"; } //***************************************** if ($thissurvey['publicstatistics'] == 'Y' && $thissurvey['printanswers'] == 'Y') { $completed .= '<br />' . $clang->gT("or"); } // Link to Public statistics ********** if ($thissurvey['publicstatistics'] == 'Y') { $url = Yii::app()->getController()->createUrl("statistics_user/action/surveyid/{$surveyid}/language/" . $_SESSION[$LEMsessid]['s_lang']); $completed .= "<br /><br />" . "<a class='publicstatisticslink' href='{$url}' target='_blank'>" . $clang->gT("View the statistics for this survey.") . "</a><br />\n"; } //***************************************** $_SESSION[$LEMsessid]['finished'] = true; $_SESSION[$LEMsessid]['sid'] = $surveyid; sendCacheHeaders(); if (isset($thissurvey['autoredirect']) && $thissurvey['autoredirect'] == "Y" && $thissurvey['surveyls_url']) { //Automatically redirect the page to the "url" setting for the survey header("Location: {$thissurvey['surveyls_url']}"); } doHeader(); echo $content; } $redata['completed'] = $completed; echo templatereplace(file_get_contents($sTemplatePath . "completed.pstpl"), array('completed' => $completed), $redata); echo "\n<br />\n"; if (($LEMdebugLevel & LEM_DEBUG_TIMING) == LEM_DEBUG_TIMING) { echo LimeExpressionManager::GetDebugTimingMessage(); } if (($LEMdebugLevel & LEM_DEBUG_VALIDATION_SUMMARY) == LEM_DEBUG_VALIDATION_SUMMARY) { echo "<table><tr><td align='left'><b>Group/Question Validation Results:</b>" . $moveResult['message'] . "</td></tr></table>\n"; } echo templatereplace(file_get_contents($sTemplatePath . "endpage.pstpl")); doFooter(); // The session cannot be killed until the page is completely rendered if ($thissurvey['printanswers'] != 'Y') { killSurveySession($surveyid); } exit; } } $redata = compact(array_keys(get_defined_vars())); // IF GOT THIS FAR, THEN DISPLAY THE ACTIVE GROUP OF QUESTIONSs //SEE IF $surveyid EXISTS #################################################################### if ($surveyExists < 1) { //SURVEY DOES NOT EXIST. POLITELY EXIT. echo templatereplace(file_get_contents($sTemplatePath . "startpage.pstpl"), array(), $redata); echo "\t<center><br />\n"; echo "\t" . $clang->gT("Sorry. There is no matching survey.") . "<br /></center> \n"; echo templatereplace(file_get_contents($sTemplatePath . "endpage.pstpl"), array(), $redata); doFooter(); exit; } createFieldMap($surveyid, 'full', false, false, $_SESSION[$LEMsessid]['s_lang']); //GET GROUP DETAILS if ($surveyMode == 'group' && $previewgrp) { // setcookie("limesurvey_timers", "0"); //@todo fix - sometimes results in headers already sent error $_gid = sanitize_int($param['gid']); LimeExpressionManager::StartSurvey($thissurvey['sid'], 'group', $surveyOptions, false, $LEMdebugLevel); $gseq = LimeExpressionManager::GetGroupSeq($_gid); if ($gseq == -1) { echo $clang->gT('Invalid group number for this survey: ') . $_gid; exit; } $moveResult = LimeExpressionManager::JumpTo($gseq + 1, true); if (is_null($moveResult)) { echo $clang->gT('This group contains no questions. You must add questions to this group before you can preview it'); exit; } if (isset($moveResult)) { $_SESSION[$LEMsessid]['step'] = $moveResult['seq'] + 1; // step is index base 1? } $stepInfo = LimeExpressionManager::GetStepIndexInfo($moveResult['seq']); $gid = $stepInfo['gid']; $groupname = $stepInfo['gname']; $groupdescription = $stepInfo['gtext']; } else { if ($show_empty_group || !isset($_SESSION[$LEMsessid]['grouplist'])) { $gid = -1; // Make sure the gid is unused. This will assure that the foreach (fieldarray as ia) has no effect. $groupname = $clang->gT("Submit your answers"); $groupdescription = $clang->gT("There are no more questions. Please press the <Submit> button to finish this survey."); } else { if ($surveyMode != 'survey') { if ($previewquestion) { $_qid = sanitize_int($param['qid']); LimeExpressionManager::StartSurvey($surveyid, 'question', $surveyOptions, false, $LEMdebugLevel); $qSec = LimeExpressionManager::GetQuestionSeq($_qid); $moveResult = LimeExpressionManager::JumpTo($qSec + 1, true, false, true); $stepInfo = LimeExpressionManager::GetStepIndexInfo($moveResult['seq']); } else { $stepInfo = LimeExpressionManager::GetStepIndexInfo($moveResult['seq']); } $gid = $stepInfo['gid']; $groupname = $stepInfo['gname']; $groupdescription = $stepInfo['gtext']; } } } if ($previewquestion) { $_SESSION[$LEMsessid]['step'] = 0; //maybe unset it after the question has been displayed? } if ($_SESSION[$LEMsessid]['step'] > $_SESSION[$LEMsessid]['maxstep']) { $_SESSION[$LEMsessid]['maxstep'] = $_SESSION[$LEMsessid]['step']; } // If the survey uses answer persistence and a srid is registered in SESSION // then loadanswers from this srid /* Only survey mode used this - should all? if ($thissurvey['tokenanswerspersistence'] == 'Y' && $thissurvey['anonymized'] == "N" && isset($_SESSION[$LEMsessid]['srid']) && $thissurvey['active'] == "Y") { loadanswers(); } */ //****************************************************************************************************** //PRESENT SURVEY //****************************************************************************************************** $okToShowErrors = !$previewgrp && (isset($invalidLastPage) || $_SESSION[$LEMsessid]['prevstep'] == $_SESSION[$LEMsessid]['step']); Yii::app()->getController()->loadHelper('qanda'); setNoAnswerMode($thissurvey); //Iterate through the questions about to be displayed: $inputnames = array(); foreach ($_SESSION[$LEMsessid]['grouplist'] as $gl) { $gid = $gl[0]; $qnumber = 0; if ($surveyMode != 'survey') { $onlyThisGID = $stepInfo['gid']; if ($onlyThisGID != $gid) { continue; } } // TMSW - could iterate through LEM::currentQset instead foreach ($_SESSION[$LEMsessid]['fieldarray'] as $key => $ia) { ++$qnumber; $ia[9] = $qnumber; // incremental question count; if (isset($ia[10]) && $ia[10] == $gid || !isset($ia[10]) && $ia[5] == $gid) { if ($surveyMode == 'question' && $ia[0] != $stepInfo['qid']) { continue; } $qidattributes = getQuestionAttributeValues($ia[0], $ia[4]); if ($ia[4] != '*' && ($qidattributes === false || !isset($qidattributes['hidden']) || $qidattributes['hidden'] == 1)) { continue; } //Get the answers/inputnames // TMSW - can content of retrieveAnswers() be provided by LEM? Review scope of what it provides. // TODO - retrieveAnswers is slow - queries database separately for each question. May be fixed in _CI or _YII ports, so ignore for now list($plus_qanda, $plus_inputnames) = retrieveAnswers($ia, $surveyid); if ($plus_qanda) { $plus_qanda[] = $ia[4]; $plus_qanda[] = $ia[6]; // adds madatory identifyer for adding mandatory class to question wrapping div $qanda[] = $plus_qanda; } if ($plus_inputnames) { $inputnames = addtoarray_single($inputnames, $plus_inputnames); } //Display the "mandatory" popup if necessary // TMSW - get question-level error messages - don't call **_popup() directly if ($okToShowErrors && $stepInfo['mandViolation']) { list($mandatorypopup, $popup) = mandatory_popup($ia, $notanswered); } //Display the "validation" popup if necessary if ($okToShowErrors && !$stepInfo['valid']) { list($validationpopup, $vpopup) = validation_popup($ia, $notvalidated); } // Display the "file validation" popup if necessary if ($okToShowErrors && isset($filenotvalidated)) { list($filevalidationpopup, $fpopup) = file_validation_popup($ia, $filenotvalidated); } } if ($ia[4] == "|") { $upload_file = TRUE; } } //end iteration } if ($surveyMode != 'survey' && isset($thissurvey['showprogress']) && $thissurvey['showprogress'] == 'Y') { if ($show_empty_group) { $percentcomplete = makegraph($_SESSION[$LEMsessid]['totalsteps'] + 1, $_SESSION[$LEMsessid]['totalsteps']); } else { $percentcomplete = makegraph($_SESSION[$LEMsessid]['step'], $_SESSION[$LEMsessid]['totalsteps']); } } if (!(isset($languagechanger) && strlen($languagechanger) > 0) && function_exists('makeLanguageChangerSurvey')) { $languagechanger = makeLanguageChangerSurvey($_SESSION[$LEMsessid]['s_lang']); } //READ TEMPLATES, INSERT DATA AND PRESENT PAGE sendCacheHeaders(); doHeader(); $redata = compact(array_keys(get_defined_vars())); echo templatereplace(file_get_contents($sTemplatePath . "startpage.pstpl"), array(), $redata); //popup need jquery if (isset($popup)) { echo $popup; } if (isset($vpopup)) { echo $vpopup; } if (isset($fpopup)) { echo $fpopup; } //ALTER PAGE CLASS TO PROVIDE WHOLE-PAGE ALTERNATION if ($surveyMode != 'survey' && $_SESSION[$LEMsessid]['step'] != $_SESSION[$LEMsessid]['prevstep'] || isset($_SESSION[$LEMsessid]['stepno']) && $_SESSION[$LEMsessid]['stepno'] % 2) { if (!isset($_SESSION[$LEMsessid]['stepno'])) { $_SESSION[$LEMsessid]['stepno'] = 0; } if ($_SESSION[$LEMsessid]['step'] != $_SESSION[$LEMsessid]['prevstep']) { ++$_SESSION[$LEMsessid]['stepno']; } if ($_SESSION[$LEMsessid]['stepno'] % 2) { echo "<script type=\"text/javascript\">\n" . " \$(\"body\").addClass(\"page-odd\");\n" . "</script>\n"; } } $hiddenfieldnames = implode("|", $inputnames); if (isset($upload_file) && $upload_file) { echo CHtml::form(array("survey/index"), 'post', array('enctype' => 'multipart/form-data', 'id' => 'limesurvey', 'name' => 'limesurvey', 'autocomplete' => 'off')) . "\n\n <!-- INPUT NAMES -->\n <input type='hidden' name='fieldnames' value='{$hiddenfieldnames}' id='fieldnames' />\n"; } else { echo CHtml::form(array("survey/index"), 'post', array('id' => 'limesurvey', 'name' => 'limesurvey', 'autocomplete' => 'off')) . "\n\n <!-- INPUT NAMES -->\n <input type='hidden' name='fieldnames' value='{$hiddenfieldnames}' id='fieldnames' />\n"; } echo sDefaultSubmitHandler(); // <-- END FEATURE - SAVE if ($surveyMode == 'survey') { if (isset($thissurvey['showwelcome']) && $thissurvey['showwelcome'] == 'N') { //Hide the welcome screen if explicitly set } else { echo templatereplace(file_get_contents($sTemplatePath . "welcome.pstpl"), array(), $redata) . "\n"; } if ($thissurvey['anonymized'] == "Y") { echo templatereplace(file_get_contents($sTemplatePath . "privacy.pstpl"), array(), $redata) . "\n"; } } // <-- START THE SURVEY --> if ($surveyMode != 'survey') { echo templatereplace(file_get_contents($sTemplatePath . "survey.pstpl"), array(), $redata); } // the runonce element has been changed from a hidden to a text/display:none one // in order to workaround an not-reproduced issue #4453 (lemeur) echo "<input type='text' id='runonce' value='0' style='display: none;'/>\n <!-- JAVASCRIPT FOR CONDITIONAL QUESTIONS -->\n <script type='text/javascript'>\n <!--\n"; echo "var LEMradix='" . $radix . "';\n"; echo "var numRegex = new RegExp('[^-' + LEMradix + '0-9]','g');\n"; echo "var intRegex = new RegExp('[^-0-9]','g');\n"; print <<<END function fixnum_checkconditions(value, name, type, evt_type, intonly) { newval = new String(value); if (typeof intonly !=='undefined' && intonly==1) { newval = newval.replace(intRegex,''); } else { newval = newval.replace(numRegex,''); } if (LEMradix === ',') { newval = newval.split(',').join('.'); } if (newval != '-' && newval != '.' && newval != '-.' && newval != parseFloat(newval)) { newval = ''; } displayVal = newval; if (LEMradix === ',') { displayVal = displayVal.split('.').join(','); } if (name.match(/other\$/)) { \$('#answer'+name+'text').val(displayVal); } \$('#answer'+name).val(displayVal); if (typeof evt_type === 'undefined') { evt_type = 'onchange'; } checkconditions(newval, name, type, evt_type); } function checkconditions(value, name, type, evt_type) { if (typeof evt_type === 'undefined') { evt_type = 'onchange'; } if (type == 'radio' || type == 'select-one') { \$('#java'+name).val(value); } else if (type == 'checkbox') { if (\$('#answer'+name).is(':checked')) { \$('#java'+name).val('Y'); } else { \$('#java'+name).val(''); } } else if (type == 'text' && name.match(/other\$/)) { \$('#java'+name).val(value); } ExprMgr_process_relevance_and_tailoring(evt_type,name,type); END; if ($previewgrp) { // force the group to be visible, even if irrelevant - will not always work print <<<END \$('#relevanceG' + LEMgseq).val(1); \$(document).ready(function() { \$('#group-' + LEMgseq).show(); }); \$(document).change(function() { \$('#group-' + LEMgseq).show(); }); \$(document).bind('keydown',function(e) { if (e.keyCode == 9) { \$('#group-' + LEMgseq).show(); return true; } return true; }); END; } print <<<END } // --> </script> END; //Display the "mandatory" message on page if necessary if (isset($showpopups) && $showpopups == 0 && $stepInfo['mandViolation'] && $okToShowErrors) { echo "<p><span class='errormandatory'>" . $clang->gT("One or more mandatory questions have not been answered. You cannot proceed until these have been completed.") . "</span></p>"; } //Display the "validation" message on page if necessary if (isset($showpopups) && $showpopups == 0 && !$stepInfo['valid'] && $okToShowErrors) { echo "<p><span class='errormandatory'>" . $clang->gT("One or more questions have not been answered in a valid manner. You cannot proceed until these answers are valid.") . "</span></p>"; } //Display the "file validation" message on page if necessary if (isset($showpopups) && $showpopups == 0 && isset($filenotvalidated) && $filenotvalidated == true && $okToShowErrors) { echo "<p><span class='errormandatory'>" . $clang->gT("One or more uploaded files are not in proper format/size. You cannot proceed until these files are valid.") . "</span></p>"; } $_gseq = -1; foreach ($_SESSION[$LEMsessid]['grouplist'] as $gl) { $gid = $gl[0]; ++$_gseq; $groupname = $gl[1]; $groupdescription = $gl[2]; if ($surveyMode != 'survey' && $gid != $onlyThisGID) { continue; } $redata = compact(array_keys(get_defined_vars())); echo "\n\n<!-- START THE GROUP -->\n"; echo "\n\n<div id='group-{$_gseq}'"; $gnoshow = LimeExpressionManager::GroupIsIrrelevantOrHidden($_gseq); if ($gnoshow && !$previewgrp) { echo " style='display: none;'"; } echo ">\n"; echo templatereplace(file_get_contents($sTemplatePath . "startgroup.pstpl"), array(), $redata); echo "\n"; if (!$previewquestion) { echo templatereplace(file_get_contents($sTemplatePath . "groupdescription.pstpl"), array(), $redata); } echo "\n"; echo "\n\n<!-- PRESENT THE QUESTIONS -->\n"; foreach ($qanda as $qa) { if ($gid != $qa[6]) { continue; } $qid = $qa[4]; $qinfo = LimeExpressionManager::GetQuestionStatus($qid); $lastgrouparray = explode("X", $qa[7]); $lastgroup = $lastgrouparray[0] . "X" . $lastgrouparray[1]; // id of the last group, derived from question id $lastanswer = $qa[7]; $q_class = getQuestionClass($qinfo['info']['type']); $man_class = ''; if ($qinfo['info']['mandatory'] == 'Y') { $man_class .= ' mandatory'; } if ($qinfo['anyUnanswered'] && $_SESSION[$LEMsessid]['maxstep'] != $_SESSION[$LEMsessid]['step']) { $man_class .= ' missing'; } $n_q_display = ''; if ($qinfo['hidden'] && $qinfo['info']['type'] != '*') { continue; // skip this one } if (!$qinfo['relevant'] || $qinfo['hidden'] && $qinfo['info']['type'] == '*') { $n_q_display = ' style="display: none;"'; } $question = $qa[0]; //=================================================================== // The following four variables offer the templating system the // capacity to fully control the HTML output for questions making the // above echo redundant if desired. $question['essentials'] = 'id="question' . $qa[4] . '"' . $n_q_display; $question['class'] = $q_class; $question['man_class'] = $man_class; $question['code'] = $qa[5]; $question['sgq'] = $qa[7]; $question['aid'] = !empty($qinfo['info']['aid']) ? $qinfo['info']['aid'] : 0; $question['sqid'] = !empty($qinfo['info']['sqid']) ? $qinfo['info']['sqid'] : 0; $question['type'] = $qinfo['info']['type']; //=================================================================== $answer = $qa[1]; $help = $qinfo['info']['help']; // $qa[2]; $redata = compact(array_keys(get_defined_vars())); $question_template = file_get_contents($sTemplatePath . 'question.pstpl'); if (preg_match('/\\{QUESTION_ESSENTIALS\\}/', $question_template) === false || preg_match('/\\{QUESTION_CLASS\\}/', $question_template) === false) { // if {QUESTION_ESSENTIALS} is present in the template but not {QUESTION_CLASS} remove it because you don't want id="" and display="" duplicated. $question_template = str_replace('{QUESTION_ESSENTIALS}', '', $question_template); $question_template = str_replace('{QUESTION_CLASS}', '', $question_template); echo ' <!-- NEW QUESTION --> <div id="question' . $qa[4] . '" class="' . $q_class . $man_class . '"' . $n_q_display . '>'; echo templatereplace($question_template, array(), $redata, false, false, $qa[4]); echo '</div>'; } else { // TMSW - eventually refactor so that only substitutes the QUESTION_** fields - doesn't need full power of template replace // TMSW - also, want to return a string, and call templatereplace once on that result string once all done. echo templatereplace($question_template, array(), $redata, false, false, $qa[4]); } } if ($surveyMode == 'group') { echo "<input type='hidden' name='lastgroup' value='{$lastgroup}' id='lastgroup' />\n"; // for counting the time spent on each group } if ($surveyMode == 'question') { echo "<input type='hidden' name='lastanswer' value='{$lastanswer}' id='lastanswer' />\n"; } echo "\n\n<!-- END THE GROUP -->\n"; echo templatereplace(file_get_contents($sTemplatePath . "endgroup.pstpl"), array(), $redata); echo "\n\n</div>\n"; } LimeExpressionManager::FinishProcessingGroup($LEMskipReprocessing); echo LimeExpressionManager::GetRelevanceAndTailoringJavaScript(); LimeExpressionManager::FinishProcessingPage(); if (!$previewgrp && !$previewquestion) { $navigator = surveymover(); //This gets globalised in the templatereplace function $redata = compact(array_keys(get_defined_vars())); echo "\n\n<!-- PRESENT THE NAVIGATOR -->\n"; echo templatereplace(file_get_contents($sTemplatePath . "navigator.pstpl"), array(), $redata); echo "\n"; if ($thissurvey['active'] != "Y") { echo "<p style='text-align:center' class='error'>" . $clang->gT("This survey is currently not active. You will not be able to save your responses.") . "</p>\n"; } if ($surveyMode != 'survey' && $thissurvey['allowjumps'] == 'Y') { echo "\n\n<!-- PRESENT THE INDEX -->\n"; echo '<div id="index"><div class="container"><h2>' . $clang->gT("Question index") . '</h2>'; $stepIndex = LimeExpressionManager::GetStepIndexInfo(); $lastGseq = -1; $gseq = -1; $grel = true; for ($v = 0, $n = 0; $n != $_SESSION[$LEMsessid]['maxstep']; ++$n) { if (!isset($stepIndex[$n])) { continue; // this is an invalid group - skip it } $stepInfo = $stepIndex[$n]; if ($surveyMode == 'question') { if ($lastGseq != $stepInfo['gseq']) { // show the group label ++$gseq; $g = $_SESSION[$LEMsessid]['grouplist'][$gseq]; $grel = !LimeExpressionManager::GroupIsIrrelevantOrHidden($gseq); if ($grel) { $gtitle = LimeExpressionManager::ProcessString($g[1]); echo '<h3>' . flattenText($gtitle) . "</h3>"; } $lastGseq = $stepInfo['gseq']; } if (!$grel || !$stepInfo['show']) { continue; } $q = $_SESSION[$LEMsessid]['fieldarray'][$n]; } else { ++$gseq; if (!$stepInfo['show']) { continue; } $g = $_SESSION[$LEMsessid]['grouplist'][$gseq]; } if ($surveyMode == 'group') { $indexlabel = LimeExpressionManager::ProcessString($g[1]); } else { $indexlabel = LimeExpressionManager::ProcessString($q[3]); } $sText = $surveyMode == 'group' ? flattenText($indexlabel) : flattenText($indexlabel); $bGAnsw = !$stepInfo['anyUnanswered']; ++$v; $class = $n == $_SESSION[$LEMsessid]['step'] - 1 ? 'current' : ($bGAnsw ? 'answer' : 'missing'); if ($v % 2) { $class .= " odd"; } $s = $n + 1; echo "<div class=\"row {$class}\" onclick=\"javascript:document.limesurvey.move.value = '{$s}'; document.limesurvey.submit();\"><span class=\"hdr\">{$v}</span><span title=\"{$sText}\">{$sText}</span></div>"; } if ($_SESSION[$LEMsessid]['maxstep'] == $_SESSION[$LEMsessid]['totalsteps']) { echo "<input class='submit' type='submit' accesskey='l' onclick=\"javascript:document.limesurvey.move.value = 'movesubmit';\" value=' " . $clang->gT("Submit") . " ' name='move2' />\n"; } echo '</div></div>'; /* Can be replaced by php or in global js */ echo "<script type=\"text/javascript\">\n" . " \$(\".outerframe\").addClass(\"withindex\");\n" . " var idx = \$(\"#index\");\n" . " var row = \$(\"#index .row.current\");\n" . " idx.scrollTop(row.position().top - idx.height() / 2 - row.height() / 2);\n" . "</script>\n"; echo "\n"; } echo "<input type='hidden' name='thisstep' value='{$_SESSION[$LEMsessid]['step']}' id='thisstep' />\n"; echo "<input type='hidden' name='sid' value='{$surveyid}' id='sid' />\n"; echo "<input type='hidden' name='start_time' value='" . time() . "' id='start_time' />\n"; $_SESSION[$LEMsessid]['LEMpostKey'] = mt_rand(); echo "<input type='hidden' name='LEMpostKey' value='{$_SESSION[$LEMsessid]['LEMpostKey']}' id='LEMpostKey' />\n"; if (isset($token) && !empty($token)) { echo "\n<input type='hidden' name='token' value='{$token}' id='token' />\n"; } } if (($LEMdebugLevel & LEM_DEBUG_TIMING) == LEM_DEBUG_TIMING) { echo LimeExpressionManager::GetDebugTimingMessage(); } if (($LEMdebugLevel & LEM_DEBUG_VALIDATION_SUMMARY) == LEM_DEBUG_VALIDATION_SUMMARY) { echo "<table><tr><td align='left'><b>Group/Question Validation Results:</b>" . $moveResult['message'] . "</td></tr></table>\n"; } echo "</form>\n"; echo templatereplace(file_get_contents($sTemplatePath . "endpage.pstpl"), array(), $redata); echo "\n"; doFooter(); }
/** * Main function * * @param mixed $surveyid * @param mixed $args */ function run($surveyid, $args) { global $errormsg; extract($args); if (!$thissurvey) { $thissurvey = getSurveyInfo($surveyid); } $LEMsessid = 'survey_' . $surveyid; $this->setJavascriptVar($surveyid, isset($clang->langcode) ? $clang->langcode : $thissurvey['language']); $sTemplatePath = getTemplatePath(Yii::app()->getConfig("defaulttemplate")) . DIRECTORY_SEPARATOR; if (isset($_SESSION['survey_' . $surveyid]['templatepath'])) { $sTemplatePath = $_SESSION['survey_' . $surveyid]['templatepath']; } // $LEMdebugLevel - customizable debugging for Lime Expression Manager $LEMdebugLevel = 0; // LEM_DEBUG_TIMING; // (LEM_DEBUG_TIMING + LEM_DEBUG_VALIDATION_SUMMARY + LEM_DEBUG_VALIDATION_DETAIL); $LEMskipReprocessing = false; // true if used GetLastMoveResult to avoid generation of unneeded extra JavaScript switch ($thissurvey['format']) { case "A": //All in one $surveyMode = 'survey'; break; default: case "S": //One at a time $surveyMode = 'question'; break; case "G": //Group at a time $surveyMode = 'group'; break; } $radix = getRadixPointData($thissurvey['surveyls_numberformat']); $radix = $radix['separator']; $surveyOptions = array('active' => $thissurvey['active'] == 'Y', 'allowsave' => $thissurvey['allowsave'] == 'Y', 'anonymized' => $thissurvey['anonymized'] != 'N', 'assessments' => $thissurvey['assessments'] == 'Y', 'datestamp' => $thissurvey['datestamp'] == 'Y', 'deletenonvalues' => Yii::app()->getConfig('deletenonvalues'), 'hyperlinkSyntaxHighlighting' => ($LEMdebugLevel & LEM_DEBUG_VALIDATION_SUMMARY) == LEM_DEBUG_VALIDATION_SUMMARY, 'ipaddr' => $thissurvey['ipaddr'] == 'Y', 'radix' => $radix, 'refurl' => $thissurvey['refurl'] == "Y" && isset($_SESSION[$LEMsessid]['refurl']) ? $_SESSION[$LEMsessid]['refurl'] : NULL, 'savetimings' => $thissurvey['savetimings'] == "Y", 'surveyls_dateformat' => isset($thissurvey['surveyls_dateformat']) ? $thissurvey['surveyls_dateformat'] : 1, 'startlanguage' => isset($clang->langcode) ? $clang->langcode : $thissurvey['language'], 'target' => Yii::app()->getConfig('uploaddir') . DIRECTORY_SEPARATOR . 'surveys' . DIRECTORY_SEPARATOR . $thissurvey['sid'] . DIRECTORY_SEPARATOR . 'files' . DIRECTORY_SEPARATOR, 'tempdir' => Yii::app()->getConfig('tempdir') . DIRECTORY_SEPARATOR, 'timeadjust' => isset($timeadjust) ? $timeadjust : 0, 'token' => isset($clienttoken) ? $clienttoken : NULL); //Security Checked: POST, GET, SESSION, REQUEST, returnGlobal, DB $previewgrp = false; if ($surveyMode == 'group' && isset($param['action']) && $param['action'] == 'previewgroup') { $previewgrp = true; } $previewquestion = false; if ($surveyMode == 'question' && isset($param['action']) && $param['action'] == 'previewquestion') { $previewquestion = true; } // if (isset($param['newtest']) && $param['newtest'] == "Y") // setcookie("limesurvey_timers", "0"); //@todo fix - sometimes results in headers already sent error $show_empty_group = false; if ($previewgrp || $previewquestion) { $_SESSION[$LEMsessid]['prevstep'] = 2; $_SESSION[$LEMsessid]['maxstep'] = 0; } else { //RUN THIS IF THIS IS THE FIRST TIME , OR THE FIRST PAGE ######################################## if (!isset($_SESSION[$LEMsessid]['step'])) { buildsurveysession($surveyid); $sTemplatePath = $_SESSION[$LEMsessid]['templatepath']; if ($surveyid != LimeExpressionManager::getLEMsurveyId()) { LimeExpressionManager::SetDirtyFlag(); } LimeExpressionManager::StartSurvey($surveyid, $surveyMode, $surveyOptions, false, $LEMdebugLevel); $_SESSION[$LEMsessid]['step'] = 0; if ($surveyMode == 'survey') { LimeExpressionManager::JumpTo(1, false, false, true); } elseif (isset($thissurvey['showwelcome']) && $thissurvey['showwelcome'] == 'N') { $moveResult = LimeExpressionManager::JumpTo(1, false, false, true); $_SESSION[$LEMsessid]['step'] = 1; } } elseif ($surveyid != LimeExpressionManager::getLEMsurveyId()) { LimeExpressionManager::StartSurvey($surveyid, $surveyMode, $surveyOptions, false, $LEMdebugLevel); LimeExpressionManager::JumpTo($_SESSION[$LEMsessid]['step'], false, false); } $totalquestions = $_SESSION['survey_' . $surveyid]['totalquestions']; if (!isset($_SESSION[$LEMsessid]['totalsteps'])) { $_SESSION[$LEMsessid]['totalsteps'] = 0; } if (!isset($_SESSION[$LEMsessid]['maxstep'])) { $_SESSION[$LEMsessid]['maxstep'] = 0; } if (isset($_SESSION[$LEMsessid]['LEMpostKey']) && isset($_POST['LEMpostKey']) && $_POST['LEMpostKey'] != $_SESSION[$LEMsessid]['LEMpostKey']) { // then trying to resubmit (e.g. Next, Previous, Submit) from a cached copy of the page // Does not try to save anything from the page to the database $moveResult = LimeExpressionManager::GetLastMoveResult(true); if (isset($_POST['thisstep']) && isset($moveResult['seq']) && $_POST['thisstep'] == $moveResult['seq']) { // then pressing F5 or otherwise refreshing the current page, which is OK $LEMskipReprocessing = true; $move = "movenext"; // so will re-display the survey } else { // trying to use browser back buttons, which may be disallowed if no 'previous' button is present $LEMskipReprocessing = true; $move = "movenext"; // so will re-display the survey $invalidLastPage = true; $backpopup = $clang->gT("Please use the LimeSurvey navigation buttons or index. It appears you attempted to use the browser back button to re-submit a page."); } } if (isset($move) && $move == "clearcancel") { $moveResult = LimeExpressionManager::JumpTo($_SESSION[$LEMsessid]['step'], false, true, false, true); //$backpopup=$clang->gT("Clear all need confirmation."); } if (!(isset($_POST['saveall']) || isset($_POST['saveprompt']) || isset($_GET['sid']) || $LEMskipReprocessing || isset($move) && preg_match('/^changelang_/', $move))) { $_SESSION[$LEMsessid]['prevstep'] = $_SESSION[$LEMsessid]['step']; } if (!isset($_SESSION[$LEMsessid]['prevstep'])) { $_SESSION[$LEMsessid]['prevstep'] = -1; // this only happens on re-load } if (isset($_SESSION[$LEMsessid]['LEMtokenResume'])) { LimeExpressionManager::StartSurvey($thissurvey['sid'], $surveyMode, $surveyOptions, false, $LEMdebugLevel); if (isset($_SESSION[$LEMsessid]['maxstep']) && $_SESSION[$LEMsessid]['maxstep'] > $_SESSION[$LEMsessid]['step']) { LimeExpressionManager::JumpTo($_SESSION[$LEMsessid]['maxstep'], false, false); } $moveResult = LimeExpressionManager::JumpTo($_SESSION[$LEMsessid]['step'], false, false); // if late in the survey, will re-validate contents, which may be overkill unset($_SESSION[$LEMsessid]['LEMtokenResume']); } else { if (!$LEMskipReprocessing) { //Move current step ########################################################################### if (isset($move) && $move == 'moveprev' && ($thissurvey['allowprev'] == 'Y' || $thissurvey['questionindex'] > 0)) { $moveResult = LimeExpressionManager::NavigateBackwards(); if ($moveResult['at_start']) { $_SESSION[$LEMsessid]['step'] = 0; unset($moveResult); // so display welcome page again } } if (isset($move) && $move == "movenext") { $moveResult = LimeExpressionManager::NavigateForwards(); } if (isset($move) && $move == 'movesubmit') { if ($surveyMode == 'survey') { $moveResult = LimeExpressionManager::NavigateForwards(); } else { // may be submitting from the navigation bar, in which case need to process all intervening questions // in order to update equations and ensure there are no intervening relevant mandatory or relevant invalid questions $moveResult = LimeExpressionManager::JumpTo($_SESSION[$LEMsessid]['totalsteps'] + 1, false); } } if (isset($move) && $move == 'changelang') { // jump to current step using new language, processing POST values $moveResult = LimeExpressionManager::JumpTo($_SESSION[$LEMsessid]['step'], false, true, true, true); // do process the POST data } if (isset($move) && isNumericInt($move) && $thissurvey['questionindex'] == 1) { $move = (int) $move; if ($move > 0 && ($move <= $_SESSION[$LEMsessid]['step'] || isset($_SESSION[$LEMsessid]['maxstep']) && $move <= $_SESSION[$LEMsessid]['maxstep'])) { $moveResult = LimeExpressionManager::JumpTo($move, false); } } elseif (isset($move) && isNumericInt($move) && $thissurvey['questionindex'] == 2) { $move = (int) $move; $moveResult = LimeExpressionManager::JumpTo($move, false, true, true); } if (!isset($moveResult) && !($surveyMode != 'survey' && $_SESSION[$LEMsessid]['step'] == 0)) { // Just in case not set via any other means, but don't do this if it is the welcome page $moveResult = LimeExpressionManager::GetLastMoveResult(true); $LEMskipReprocessing = true; } } } if (isset($moveResult) && isset($moveResult['seq'])) { // With complete index, we need to revalidate whole group bug #08806. It's actually the only mode where we JumpTo with force if ($moveResult['finished'] == true && $thissurvey['questionindex'] == 2) { //LimeExpressionManager::JumpTo(-1, false, false, true); LimeExpressionManager::StartSurvey($surveyid, $surveyMode, $surveyOptions); $moveResult = LimeExpressionManager::JumpTo($_SESSION[$LEMsessid]['totalsteps'] + 1, false, false, false); // no preview, no save data and NO force if (!$moveResult['mandViolation'] && $moveResult['valid'] && empty($moveResult['invalidSQs'])) { $moveResult['finished'] = true; } } if ($moveResult['finished'] == true) { $move = 'movesubmit'; } else { $_SESSION[$LEMsessid]['step'] = $moveResult['seq'] + 1; // step is index base 1 $stepInfo = LimeExpressionManager::GetStepIndexInfo($moveResult['seq']); } if ($move == "movesubmit" && $moveResult['finished'] == false) { // then there are errors, so don't finalize the survey $move = "movenext"; // so will re-display the survey $invalidLastPage = true; } } // We do not keep the participant session anymore when the same browser is used to answer a second time a survey (let's think of a library PC for instance). // Previously we used to keep the session and redirect the user to the // submit page. if ($surveyMode != 'survey' && $_SESSION[$LEMsessid]['step'] == 0) { $_SESSION[$LEMsessid]['test'] = time(); display_first_page(); Yii::app()->end(); // So we can still see debug messages } // TODO FIXME if ($thissurvey['active'] == "Y") { Yii::import("application.libraries.Save"); $cSave = new Save(); } if ($thissurvey['active'] == "Y" && Yii::app()->request->getPost('saveall')) { $bTokenAnswerPersitance = $thissurvey['tokenanswerspersistence'] == 'Y' && isset($surveyid) && tableExists('tokens_' . $surveyid); // must do this here to process the POSTed values $moveResult = LimeExpressionManager::JumpTo($_SESSION[$LEMsessid]['step'], false); // by jumping to current step, saves data so far if (!isset($_SESSION[$LEMsessid]['scid']) && !$bTokenAnswerPersitance) { $cSave->showsaveform(); // generates a form and exits, awaiting input } else { // Intentional retest of all conditions to be true, to make sure we do have tokens and surveyid // Now update lastpage to $_SESSION[$LEMsessid]['step'] in SurveyDynamic, otherwise we land on // the previous page when we return. $iResponseID = $_SESSION[$LEMsessid]['srid']; $oResponse = SurveyDynamic::model($surveyid)->findByPk($iResponseID); $oResponse->lastpage = $_SESSION[$LEMsessid]['step']; $oResponse->save(); } } if ($thissurvey['active'] == "Y" && Yii::app()->request->getParam('savesubmit')) { // The response from the save form // CREATE SAVED CONTROL RECORD USING SAVE FORM INFORMATION $popup = $cSave->savedcontrol(); if (isset($errormsg) && $errormsg != "") { $cSave->showsaveform(); // reshow the form if there is an error } $moveResult = LimeExpressionManager::GetLastMoveResult(true); $LEMskipReprocessing = true; // TODO - does this work automatically for token answer persistence? Used to be savedsilent() } //Now, we check mandatory questions if necessary //CHECK IF ALL CONDITIONAL MANDATORY QUESTIONS THAT APPLY HAVE BEEN ANSWERED global $notanswered; if (isset($moveResult) && !$moveResult['finished']) { $unansweredSQList = $moveResult['unansweredSQs']; if (strlen($unansweredSQList) > 0) { $notanswered = explode('|', $unansweredSQList); } else { $notanswered = array(); } //CHECK INPUT $invalidSQList = $moveResult['invalidSQs']; if (strlen($invalidSQList) > 0) { $notvalidated = explode('|', $invalidSQList); } else { $notvalidated = array(); } } // CHECK UPLOADED FILES // TMSW - Move this into LEM::NavigateForwards? $filenotvalidated = checkUploadedFileValidity($surveyid, $move); //SEE IF THIS GROUP SHOULD DISPLAY $show_empty_group = false; if ($_SESSION[$LEMsessid]['step'] == 0) { $show_empty_group = true; } $redata = compact(array_keys(get_defined_vars())); //SUBMIT ############################################################################### if (isset($move) && $move == "movesubmit") { // setcookie("limesurvey_timers", "", time() - 3600); // remove the timers cookies //@todo fix - sometimes results in headers already sent error if ($thissurvey['refurl'] == "Y") { if (!in_array("refurl", $_SESSION[$LEMsessid]['insertarray'])) { $_SESSION[$LEMsessid]['insertarray'][] = "refurl"; } } resetTimers(); //Before doing the "templatereplace()" function, check the $thissurvey['url'] //field for limereplace stuff, and do transformations! $thissurvey['surveyls_url'] = passthruReplace($thissurvey['surveyls_url'], $thissurvey); $thissurvey['surveyls_url'] = templatereplace($thissurvey['surveyls_url'], array(), $redata, 'URLReplace', false, NULL, array(), true); // to do INSERTANS substitutions //END PAGE - COMMIT CHANGES TO DATABASE if ($thissurvey['active'] != "Y") { if ($thissurvey['assessments'] == "Y") { $assessments = doAssessment($surveyid); } sendCacheHeaders(); doHeader(); echo templatereplace(file_get_contents($sTemplatePath . "startpage.pstpl"), array(), $redata, 'SubmitStartpageI', false, NULL, array(), true); //Check for assessments if ($thissurvey['assessments'] == "Y" && $assessments) { echo templatereplace(file_get_contents($sTemplatePath . "assessment.pstpl"), array(), $redata, 'SubmitAssessmentI', false, NULL, array(), true); } // fetch all filenames from $_SESSIONS['files'] and delete them all // from the /upload/tmp/ directory /* echo "<pre>";print_r($_SESSION);echo "</pre>"; for($i = 1; isset($_SESSION[$LEMsessid]['files'][$i]); $i++) { unlink('upload/tmp/'.$_SESSION[$LEMsessid]['files'][$i]['filename']); } */ // can't kill session before end message, otherwise INSERTANS doesn't work. $completed = templatereplace($thissurvey['surveyls_endtext'], array(), $redata, 'SubmitEndtextI', false, NULL, array(), true); $completed .= "<br /><strong><font size='2' color='red'>" . $clang->gT("Did Not Save") . "</font></strong><br /><br />\n\n"; $completed .= $clang->gT("Your survey responses have not been recorded. This survey is not yet active.") . "<br /><br />\n"; if ($thissurvey['printanswers'] == 'Y') { // 'Clear all' link is only relevant for survey with printanswers enabled // in other cases the session is cleared at submit time $completed .= "<a href='" . Yii::app()->getController()->createUrl("survey/index/sid/{$surveyid}/move/clearall") . "'>" . $clang->gT("Clear Responses") . "</a><br /><br />\n"; } } else { if ($thissurvey['usecookie'] == "Y" && $tokensexist != 1) { setcookie("LS_" . $surveyid . "_STATUS", "COMPLETE", time() + 31536000); //Cookie will expire in 365 days } $content = ''; $content .= templatereplace(file_get_contents($sTemplatePath . "startpage.pstpl"), array(), $redata, 'SubmitStartpage', false, NULL, array(), true); //Check for assessments if ($thissurvey['assessments'] == "Y") { $assessments = doAssessment($surveyid); if ($assessments) { $content .= templatereplace(file_get_contents($sTemplatePath . "assessment.pstpl"), array(), $redata, 'SubmitAssessment', false, NULL, array(), true); } } //Update the token if needed and send a confirmation email if (isset($_SESSION['survey_' . $surveyid]['token'])) { submittokens(); } //Send notifications sendSubmitNotifications($surveyid); $content = ''; $content .= templatereplace(file_get_contents($sTemplatePath . "startpage.pstpl"), array(), $redata, 'SubmitStartpage', false, NULL, array(), true); //echo $thissurvey['url']; //Check for assessments if ($thissurvey['assessments'] == "Y") { $assessments = doAssessment($surveyid); if ($assessments) { $content .= templatereplace(file_get_contents($sTemplatePath . "assessment.pstpl"), array(), $redata, 'SubmitAssessment', false, NULL, array(), true); } } if (trim(str_replace(array('<p>', '</p>'), '', $thissurvey['surveyls_endtext'])) == '') { $completed = "<br /><span class='success'>" . $clang->gT("Thank you!") . "</span><br /><br />\n\n" . $clang->gT("Your survey responses have been recorded.") . "<br /><br />\n"; } else { $completed = templatereplace($thissurvey['surveyls_endtext'], array(), $redata, 'SubmitAssessment', false, NULL, array(), true); } // Link to Print Answer Preview ********** if ($thissurvey['printanswers'] == 'Y') { $url = Yii::app()->getController()->createUrl("/printanswers/view/surveyid/{$surveyid}"); $completed .= "<br /><br />" . "<a class='printlink' href='{$url}' target='_blank'>" . $clang->gT("Print your answers.") . "</a><br />\n"; } //***************************************** if ($thissurvey['publicstatistics'] == 'Y' && $thissurvey['printanswers'] == 'Y') { $completed .= '<br />' . $clang->gT("or"); } // Link to Public statistics ********** if ($thissurvey['publicstatistics'] == 'Y') { $url = Yii::app()->getController()->createUrl("/statistics_user/action/surveyid/{$surveyid}/language/" . $_SESSION[$LEMsessid]['s_lang']); $completed .= "<br /><br />" . "<a class='publicstatisticslink' href='{$url}' target='_blank'>" . $clang->gT("View the statistics for this survey.") . "</a><br />\n"; } //***************************************** $_SESSION[$LEMsessid]['finished'] = true; $_SESSION[$LEMsessid]['sid'] = $surveyid; sendCacheHeaders(); if (isset($thissurvey['autoredirect']) && $thissurvey['autoredirect'] == "Y" && $thissurvey['surveyls_url']) { //Automatically redirect the page to the "url" setting for the survey header("Location: {$thissurvey['surveyls_url']}"); } doHeader(); echo $content; } $redata['completed'] = $completed; // @todo Remove direct session access. $event = new PluginEvent('afterSurveyComplete'); if (isset($_SESSION[$LEMsessid]['srid'])) { $event->set('responseId', $_SESSION[$LEMsessid]['srid']); } $event->set('surveyId', $surveyid); App()->getPluginManager()->dispatchEvent($event); $blocks = array(); foreach ($event->getAllContent() as $blockData) { /* @var $blockData PluginEventContent */ $blocks[] = CHtml::tag('div', array('id' => $blockData->getCssId(), 'class' => $blockData->getCssClass()), $blockData->getContent()); } $redata['completed'] = implode("\n", $blocks) . "\n" . $redata['completed']; $redata['thissurvey']['surveyls_url'] = $thissurvey['surveyls_url']; echo templatereplace(file_get_contents($sTemplatePath . "completed.pstpl"), array('completed' => $completed), $redata, 'SubmitCompleted', false, NULL, array(), true); echo "\n"; if (($LEMdebugLevel & LEM_DEBUG_TIMING) == LEM_DEBUG_TIMING) { echo LimeExpressionManager::GetDebugTimingMessage(); } if (($LEMdebugLevel & LEM_DEBUG_VALIDATION_SUMMARY) == LEM_DEBUG_VALIDATION_SUMMARY) { echo "<table><tr><td align='left'><b>Group/Question Validation Results:</b>" . $moveResult['message'] . "</td></tr></table>\n"; } echo templatereplace(file_get_contents($sTemplatePath . "endpage.pstpl"), array(), $redata, 'SubmitEndpage', false, NULL, array(), true); doFooter(); // The session cannot be killed until the page is completely rendered if ($thissurvey['printanswers'] != 'Y') { killSurveySession($surveyid); } exit; } } $redata = compact(array_keys(get_defined_vars())); // IF GOT THIS FAR, THEN DISPLAY THE ACTIVE GROUP OF QUESTIONSs //SEE IF $surveyid EXISTS #################################################################### if ($surveyExists < 1) { //SURVEY DOES NOT EXIST. POLITELY EXIT. echo templatereplace(file_get_contents($sTemplatePath . "startpage.pstpl"), array(), $redata); echo "\t<center><br />\n"; echo "\t" . $clang->gT("Sorry. There is no matching survey.") . "<br /></center> \n"; echo templatereplace(file_get_contents($sTemplatePath . "endpage.pstpl"), array(), $redata); doFooter(); exit; } createFieldMap($surveyid, 'full', false, false, $_SESSION[$LEMsessid]['s_lang']); //GET GROUP DETAILS if ($surveyMode == 'group' && $previewgrp) { // setcookie("limesurvey_timers", "0"); //@todo fix - sometimes results in headers already sent error $_gid = sanitize_int($param['gid']); LimeExpressionManager::StartSurvey($thissurvey['sid'], 'group', $surveyOptions, false, $LEMdebugLevel); $gseq = LimeExpressionManager::GetGroupSeq($_gid); if ($gseq == -1) { echo $clang->gT('Invalid group number for this survey: ') . $_gid; exit; } $moveResult = LimeExpressionManager::JumpTo($gseq + 1, true); if (is_null($moveResult)) { echo $clang->gT('This group contains no questions. You must add questions to this group before you can preview it'); exit; } if (isset($moveResult)) { $_SESSION[$LEMsessid]['step'] = $moveResult['seq'] + 1; // step is index base 1? } $stepInfo = LimeExpressionManager::GetStepIndexInfo($moveResult['seq']); $gid = $stepInfo['gid']; $groupname = $stepInfo['gname']; $groupdescription = $stepInfo['gtext']; } else { if ($show_empty_group || !isset($_SESSION[$LEMsessid]['grouplist'])) { $gid = -1; // Make sure the gid is unused. This will assure that the foreach (fieldarray as ia) has no effect. $groupname = $clang->gT("Submit your answers"); $groupdescription = $clang->gT("There are no more questions. Please press the <Submit> button to finish this survey."); } else { if ($surveyMode != 'survey') { if ($previewquestion) { $_qid = sanitize_int($param['qid']); LimeExpressionManager::StartSurvey($surveyid, 'question', $surveyOptions, false, $LEMdebugLevel); $qSec = LimeExpressionManager::GetQuestionSeq($_qid); $moveResult = LimeExpressionManager::JumpTo($qSec + 1, true, false, true); $stepInfo = LimeExpressionManager::GetStepIndexInfo($moveResult['seq']); } else { $stepInfo = LimeExpressionManager::GetStepIndexInfo($moveResult['seq']); } $gid = $stepInfo['gid']; $groupname = $stepInfo['gname']; $groupdescription = $stepInfo['gtext']; } } } if ($previewquestion) { $_SESSION[$LEMsessid]['step'] = 0; //maybe unset it after the question has been displayed? } if ($_SESSION[$LEMsessid]['step'] > $_SESSION[$LEMsessid]['maxstep']) { $_SESSION[$LEMsessid]['maxstep'] = $_SESSION[$LEMsessid]['step']; } // If the survey uses answer persistence and a srid is registered in SESSION // then loadanswers from this srid /* Only survey mode used this - should all? if ($thissurvey['tokenanswerspersistence'] == 'Y' && $thissurvey['anonymized'] == "N" && isset($_SESSION[$LEMsessid]['srid']) && $thissurvey['active'] == "Y") { loadanswers(); } */ //****************************************************************************************************** //PRESENT SURVEY //****************************************************************************************************** $okToShowErrors = !$previewgrp && (isset($invalidLastPage) || $_SESSION[$LEMsessid]['prevstep'] == $_SESSION[$LEMsessid]['step']); Yii::app()->getController()->loadHelper('qanda'); setNoAnswerMode($thissurvey); //Iterate through the questions about to be displayed: $inputnames = array(); foreach ($_SESSION[$LEMsessid]['grouplist'] as $gl) { $gid = $gl['gid']; $qnumber = 0; if ($surveyMode != 'survey') { $onlyThisGID = $stepInfo['gid']; if ($onlyThisGID != $gid) { continue; } } // TMSW - could iterate through LEM::currentQset instead foreach ($_SESSION[$LEMsessid]['fieldarray'] as $key => $ia) { ++$qnumber; $ia[9] = $qnumber; // incremental question count; if (isset($ia[10]) && $ia[10] == $gid || !isset($ia[10]) && $ia[5] == $gid) { if ($surveyMode == 'question' && $ia[0] != $stepInfo['qid']) { continue; } $qidattributes = getQuestionAttributeValues($ia[0], $ia[4]); if ($ia[4] != '*' && ($qidattributes === false || !isset($qidattributes['hidden']) || $qidattributes['hidden'] == 1)) { continue; } //Get the answers/inputnames // TMSW - can content of retrieveAnswers() be provided by LEM? Review scope of what it provides. // TODO - retrieveAnswers is slow - queries database separately for each question. May be fixed in _CI or _YII ports, so ignore for now list($plus_qanda, $plus_inputnames) = retrieveAnswers($ia, $surveyid); if ($plus_qanda) { $plus_qanda[] = $ia[4]; $plus_qanda[] = $ia[6]; // adds madatory identifyer for adding mandatory class to question wrapping div // Add a finalgroup in qa array , needed for random attribute : TODO: find a way to have it in new quanda_helper in 2.1 if (isset($ia[10])) { $plus_qanda['finalgroup'] = $ia[10]; } else { $plus_qanda['finalgroup'] = $ia[5]; } $qanda[] = $plus_qanda; } if ($plus_inputnames) { $inputnames = addtoarray_single($inputnames, $plus_inputnames); } //Display the "mandatory" popup if necessary // TMSW - get question-level error messages - don't call **_popup() directly if ($okToShowErrors && $stepInfo['mandViolation']) { list($mandatorypopup, $popup) = mandatory_popup($ia, $notanswered); } //Display the "validation" popup if necessary if ($okToShowErrors && !$stepInfo['valid']) { list($validationpopup, $vpopup) = validation_popup($ia, $notvalidated); } // Display the "file validation" popup if necessary if ($okToShowErrors && isset($filenotvalidated)) { list($filevalidationpopup, $fpopup) = file_validation_popup($ia, $filenotvalidated); } } if ($ia[4] == "|") { $upload_file = TRUE; } } //end iteration } if ($surveyMode != 'survey' && isset($thissurvey['showprogress']) && $thissurvey['showprogress'] == 'Y') { if ($show_empty_group) { $percentcomplete = makegraph($_SESSION[$LEMsessid]['totalsteps'] + 1, $_SESSION[$LEMsessid]['totalsteps']); } else { $percentcomplete = makegraph($_SESSION[$LEMsessid]['step'], $_SESSION[$LEMsessid]['totalsteps']); } } if (!(isset($languagechanger) && strlen($languagechanger) > 0) && function_exists('makeLanguageChangerSurvey')) { $languagechanger = makeLanguageChangerSurvey($_SESSION[$LEMsessid]['s_lang']); } //READ TEMPLATES, INSERT DATA AND PRESENT PAGE sendCacheHeaders(); doHeader(); $redata = compact(array_keys(get_defined_vars())); echo templatereplace(file_get_contents($sTemplatePath . "startpage.pstpl"), array(), $redata); $aPopup = array(); // We can move this part where we want now if (isset($backpopup)) { $aPopup[] = $backpopup; // If user click reload: no need other popup } else { if (isset($popup)) { $aPopup[] = $popup; } if (isset($vpopup)) { $aPopup[] = $vpopup; } if (isset($fpopup)) { $aPopup[] = $fpopup; } } Yii::app()->clientScript->registerScript("showpopup", "showpopup=" . (int) Yii::app()->getConfig('showpopups') . ";", CClientScript::POS_HEAD); //if(count($aPopup)) Yii::app()->clientScript->registerScript('startPopup', "startPopups=" . json_encode($aPopup) . ";", CClientScript::POS_HEAD); //ALTER PAGE CLASS TO PROVIDE WHOLE-PAGE ALTERNATION if ($surveyMode != 'survey' && $_SESSION[$LEMsessid]['step'] != $_SESSION[$LEMsessid]['prevstep'] || isset($_SESSION[$LEMsessid]['stepno']) && $_SESSION[$LEMsessid]['stepno'] % 2) { if (!isset($_SESSION[$LEMsessid]['stepno'])) { $_SESSION[$LEMsessid]['stepno'] = 0; } if ($_SESSION[$LEMsessid]['step'] != $_SESSION[$LEMsessid]['prevstep']) { ++$_SESSION[$LEMsessid]['stepno']; } if ($_SESSION[$LEMsessid]['stepno'] % 2) { echo "<script type=\"text/javascript\">\n" . " \$(\"body\").addClass(\"page-odd\");\n" . "</script>\n"; } } $hiddenfieldnames = implode("|", $inputnames); if (isset($upload_file) && $upload_file) { echo CHtml::form(array("survey/index"), 'post', array('enctype' => 'multipart/form-data', 'id' => 'limesurvey', 'name' => 'limesurvey', 'autocomplete' => 'off')) . "\n\n <!-- INPUT NAMES -->\n <input type='hidden' name='fieldnames' value='{$hiddenfieldnames}' id='fieldnames' />\n"; } else { echo CHtml::form(array("survey/index"), 'post', array('id' => 'limesurvey', 'name' => 'limesurvey', 'autocomplete' => 'off')) . "\n\n <!-- INPUT NAMES -->\n <input type='hidden' name='fieldnames' value='{$hiddenfieldnames}' id='fieldnames' />\n"; } // <-- END FEATURE - SAVE // The default submit button echo CHtml::htmlButton("default", array('type' => 'submit', 'id' => "defaultbtn", 'value' => "default", 'name' => 'move', 'class' => "submit noview", 'style' => 'display:none')); if ($surveyMode == 'survey') { if (isset($thissurvey['showwelcome']) && $thissurvey['showwelcome'] == 'N') { //Hide the welcome screen if explicitly set } else { echo templatereplace(file_get_contents($sTemplatePath . "welcome.pstpl"), array(), $redata) . "\n"; } if ($thissurvey['anonymized'] == "Y") { echo templatereplace(file_get_contents($sTemplatePath . "privacy.pstpl"), array(), $redata) . "\n"; } } // <-- START THE SURVEY --> if ($surveyMode != 'survey') { echo templatereplace(file_get_contents($sTemplatePath . "survey.pstpl"), array(), $redata); } // runonce element has been changed from a hidden to a text/display:none one. In order to workaround an not-reproduced issue #4453 (lemeur) // We don't need runonce actually (140228): the script was updated and replaced by EM see #08783 (grep show no other runonce) // echo "<input type='text' id='runonce' value='0' style='display: none;'/>"; $showpopups = Yii::app()->getConfig('showpopups'); //Display the "mandatory" message on page if necessary if (!$showpopups && $stepInfo['mandViolation'] && $okToShowErrors) { echo "<p class='errormandatory'>" . $clang->gT("One or more mandatory questions have not been answered. You cannot proceed until these have been completed.") . "</p>"; } //Display the "validation" message on page if necessary if (!$showpopups && !$stepInfo['valid'] && $okToShowErrors) { echo "<p class='errormandatory'>" . $clang->gT("One or more questions have not been answered in a valid manner. You cannot proceed until these answers are valid.") . "</p>"; } //Display the "file validation" message on page if necessary if (!$showpopups && isset($filenotvalidated) && $filenotvalidated == true && $okToShowErrors) { echo "<p class='errormandatory'>" . $clang->gT("One or more uploaded files are not in proper format/size. You cannot proceed until these files are valid.") . "</p>"; } $_gseq = -1; foreach ($_SESSION[$LEMsessid]['grouplist'] as $gl) { $gid = $gl['gid']; ++$_gseq; $groupname = $gl['group_name']; $groupdescription = $gl['description']; if ($surveyMode != 'survey' && $gid != $onlyThisGID) { continue; } $redata = compact(array_keys(get_defined_vars())); Yii::app()->setConfig('gid', $gid); // To be used in templaterplace in whole group. Attention : it's the actual GID (not the GID of the question) echo "\n\n<!-- START THE GROUP -->\n"; echo "\n\n<div id='group-{$_gseq}'"; $gnoshow = LimeExpressionManager::GroupIsIrrelevantOrHidden($_gseq); if ($gnoshow && !$previewgrp) { echo " style='display: none;'"; } echo ">\n"; echo templatereplace(file_get_contents($sTemplatePath . "startgroup.pstpl"), array(), $redata); echo "\n"; if (!$previewquestion) { echo templatereplace(file_get_contents($sTemplatePath . "groupdescription.pstpl"), array(), $redata); } echo "\n"; echo "\n\n<!-- PRESENT THE QUESTIONS -->\n"; foreach ($qanda as $qa) { // Test if finalgroup is in this qid (for all in one survey, else we do only qanda for needed question (in one by one or group by goup) if ($gid != $qa['finalgroup']) { continue; } $qid = $qa[4]; $qinfo = LimeExpressionManager::GetQuestionStatus($qid); $lastgrouparray = explode("X", $qa[7]); $lastgroup = $lastgrouparray[0] . "X" . $lastgrouparray[1]; // id of the last group, derived from question id $lastanswer = $qa[7]; $q_class = getQuestionClass($qinfo['info']['type']); $man_class = ''; if ($qinfo['info']['mandatory'] == 'Y') { $man_class .= ' mandatory'; } if ($qinfo['anyUnanswered'] && $_SESSION[$LEMsessid]['maxstep'] != $_SESSION[$LEMsessid]['step']) { $man_class .= ' missing'; } $n_q_display = ''; if ($qinfo['hidden'] && $qinfo['info']['type'] != '*') { continue; // skip this one } if (!$qinfo['relevant'] || $qinfo['hidden'] && $qinfo['info']['type'] == '*') { $n_q_display = ' style="display: none;"'; } $question = $qa[0]; //=================================================================== // The following four variables offer the templating system the // capacity to fully control the HTML output for questions making the // above echo redundant if desired. $question['essentials'] = 'id="question' . $qa[4] . '"' . $n_q_display; $question['class'] = $q_class; $question['man_class'] = $man_class; $question['code'] = $qa[5]; $question['sgq'] = $qa[7]; $question['aid'] = !empty($qinfo['info']['aid']) ? $qinfo['info']['aid'] : 0; $question['sqid'] = !empty($qinfo['info']['sqid']) ? $qinfo['info']['sqid'] : 0; $question['type'] = $qinfo['info']['type']; //=================================================================== $answer = $qa[1]; $help = $qinfo['info']['help']; // $qa[2]; $redata = compact(array_keys(get_defined_vars())); $question_template = file_get_contents($sTemplatePath . 'question.pstpl'); if (preg_match('/\\{QUESTION_ESSENTIALS\\}/', $question_template) === false || preg_match('/\\{QUESTION_CLASS\\}/', $question_template) === false) { // if {QUESTION_ESSENTIALS} is present in the template but not {QUESTION_CLASS} remove it because you don't want id="" and display="" duplicated. $question_template = str_replace('{QUESTION_ESSENTIALS}', '', $question_template); $question_template = str_replace('{QUESTION_CLASS}', '', $question_template); echo ' <!-- NEW QUESTION --> <div id="question' . $qa[4] . '" class="' . $q_class . $man_class . '"' . $n_q_display . '>'; echo templatereplace($question_template, array(), $redata, false, false, $qa[4]); echo '</div>'; } else { // TMSW - eventually refactor so that only substitutes the QUESTION_** fields - doesn't need full power of template replace // TMSW - also, want to return a string, and call templatereplace once on that result string once all done. echo templatereplace($question_template, array(), $redata, false, false, $qa[4]); } } if ($surveyMode == 'group') { echo "<input type='hidden' name='lastgroup' value='{$lastgroup}' id='lastgroup' />\n"; // for counting the time spent on each group } if ($surveyMode == 'question') { echo "<input type='hidden' name='lastanswer' value='{$lastanswer}' id='lastanswer' />\n"; } echo "\n\n<!-- END THE GROUP -->\n"; echo templatereplace(file_get_contents($sTemplatePath . "endgroup.pstpl"), array(), $redata); echo "\n\n</div>\n"; Yii::app()->setConfig('gid', ''); } LimeExpressionManager::FinishProcessingGroup($LEMskipReprocessing); echo LimeExpressionManager::GetRelevanceAndTailoringJavaScript(); LimeExpressionManager::FinishProcessingPage(); if (!$previewgrp && !$previewquestion) { $navigator = surveymover(); //This gets globalised in the templatereplace function $redata = compact(array_keys(get_defined_vars())); echo "\n\n<!-- PRESENT THE NAVIGATOR -->\n"; echo templatereplace(file_get_contents($sTemplatePath . "navigator.pstpl"), array(), $redata); echo "\n"; if ($thissurvey['active'] != "Y") { echo "<p style='text-align:center' class='error'>" . $clang->gT("This survey is currently not active. You will not be able to save your responses.") . "</p>\n"; } if ($surveyMode != 'survey' && $thissurvey['questionindex'] == 1) { $this->createIncrementalQuestionIndex($LEMsessid, $surveyMode); } elseif ($surveyMode != 'survey' && $thissurvey['questionindex'] == 2) { $this->createFullQuestionIndex($LEMsessid, $surveyMode); } echo "<input type='hidden' name='thisstep' value='{$_SESSION[$LEMsessid]['step']}' id='thisstep' />\n"; echo "<input type='hidden' name='sid' value='{$surveyid}' id='sid' />\n"; echo "<input type='hidden' name='start_time' value='" . time() . "' id='start_time' />\n"; $_SESSION[$LEMsessid]['LEMpostKey'] = mt_rand(); echo "<input type='hidden' name='LEMpostKey' value='{$_SESSION[$LEMsessid]['LEMpostKey']}' id='LEMpostKey' />\n"; if (isset($token) && !empty($token)) { echo "\n<input type='hidden' name='token' value='{$token}' id='token' />\n"; } } if (($LEMdebugLevel & LEM_DEBUG_TIMING) == LEM_DEBUG_TIMING) { echo LimeExpressionManager::GetDebugTimingMessage(); } if (($LEMdebugLevel & LEM_DEBUG_VALIDATION_SUMMARY) == LEM_DEBUG_VALIDATION_SUMMARY) { echo "<table><tr><td align='left'><b>Group/Question Validation Results:</b>" . $moveResult['message'] . "</td></tr></table>\n"; } echo "</form>\n"; echo templatereplace(file_get_contents($sTemplatePath . "endpage.pstpl"), array(), $redata); echo "\n"; doFooter(); }
function do_multiplenumeric($ia) { global $thissurvey; $extraclass = ""; $checkconditionFunction = "fixnum_checkconditions"; $aQuestionAttributes = QuestionAttribute::model()->getQuestionAttributes($ia[0]); $answer = ''; $sSeparator = getRadixPointData($thissurvey['surveyls_numberformat']); $sSeparator = $sSeparator['separator']; //Must turn on the "numbers only javascript" $extraclass .= " numberonly"; if ($aQuestionAttributes['thousands_separator'] == 1) { App()->clientScript->registerPackage('jquery-price-format'); App()->clientScript->registerScriptFile(Yii::app()->getConfig('generalscripts') . 'numerical_input.js'); $extraclass .= " thousandsseparator"; } if (intval(trim($aQuestionAttributes['maximum_chars'])) > 0) { // Only maxlength attribute, use textarea[maxlength] jquery selector for textarea $maximum_chars = intval(trim($aQuestionAttributes['maximum_chars'])); $maxlength = "maxlength='{$maximum_chars}' "; $extraclass .= " maxchars maxchars-" . $maximum_chars; } else { $maxlength = " maxlength='25' "; } if (trim($aQuestionAttributes['prefix'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']]) != '') { $prefix = $aQuestionAttributes['prefix'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']]; $extraclass .= " withprefix"; } else { $prefix = ''; } if (trim($aQuestionAttributes['suffix'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']]) != '') { $suffix = $aQuestionAttributes['suffix'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']]; $extraclass .= " withsuffix"; } else { $suffix = ''; } if ($thissurvey['nokeyboard'] == 'Y') { includeKeypad(); $kpclass = "num-keypad"; $extraclass .= " keypad"; } else { $kpclass = ""; } $numbersonly_slider = ''; // DEPRECATED if (trim($aQuestionAttributes['text_input_width']) != '') { $tiwidth = $aQuestionAttributes['text_input_width']; //$extraclass .=" inputwidth".trim($aQuestionAttributes['text_input_width']); $col = $aQuestionAttributes['text_input_width'] <= 12 ? $aQuestionAttributes['text_input_width'] : 12; $extraclass .= " col-sm-" . trim($col); } else { $tiwidth = 10; } $prefixclass = "numeric"; if ($aQuestionAttributes['slider_layout'] == 1) { $prefixclass = "slider"; $slider_layout = true; $extraclass .= " withslider"; $slider_step = trim(LimeExpressionManager::ProcessString("{{$aQuestionAttributes['slider_accuracy']}}", $ia[0], array(), false, 1, 1, false, false, true)); $slider_step = is_numeric($slider_step) ? $slider_step : 1; $slider_min = trim(LimeExpressionManager::ProcessString("{{$aQuestionAttributes['slider_min']}}", $ia[0], array(), false, 1, 1, false, false, true)); $slider_mintext = $slider_min = is_numeric($slider_min) ? $slider_min : 0; $slider_max = trim(LimeExpressionManager::ProcessString("{{$aQuestionAttributes['slider_max']}}", $ia[0], array(), false, 1, 1, false, false, true)); $slider_maxtext = $slider_max = is_numeric($slider_max) ? $slider_max : 100; $slider_default = trim(LimeExpressionManager::ProcessString("{{$aQuestionAttributes['slider_default']}}", $ia[0], array(), false, 1, 1, false, false, true)); $slider_default = is_numeric($slider_default) ? $slider_default : ""; $slider_orientation = trim($aQuestionAttributes['slider_orientation']) == 0 ? 'horizontal' : 'vertical'; $slider_custom_handle = trim($aQuestionAttributes['slider_custom_handle']); switch (trim($aQuestionAttributes['slider_handle'])) { case 0: $slider_handle = 'round'; break; case 1: $slider_handle = 'square'; break; case 2: $slider_handle = 'triangle'; break; case 3: $slider_handle = 'custom'; break; } if ($slider_default == '' && $aQuestionAttributes['slider_middlestart'] == 1) { $slider_middlestart = intval(($slider_max + $slider_min) / 2); } else { $slider_middlestart = ''; } $slider_separator = trim($aQuestionAttributes['slider_separator']) != '' ? $aQuestionAttributes['slider_separator'] : ""; $slider_reset = $aQuestionAttributes['slider_reset'] ? 1 : 0; } else { $slider_layout = false; $slider_step = ''; $slider_step = ''; $slider_min = ''; $slider_mintext = ''; $slider_max = ''; $slider_maxtext = ''; $slider_default = ''; $slider_default = ''; $slider_orientation = ''; $slider_handle = ''; $slider_custom_handle = ''; $slider_separator = ''; } $hidetip = $aQuestionAttributes['hide_tip']; if ($aQuestionAttributes['random_order'] == 1) { $ansquery = "SELECT * FROM {{questions}} WHERE parent_qid={$ia['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 language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "' ORDER BY question_order"; } $ansresult = dbExecuteAssoc($ansquery); //Checked $aSubquestions = $ansresult->readAll(); $anscount = count($aSubquestions) * 2; $fn = 1; $answer = Yii::app()->getController()->renderPartial('/survey/questions/multiplenumeric/header', array('prefixclass' => $prefixclass), true); $answer_main = ''; if ($anscount == 0) { $inputnames = array(); $noanswer = true; $answer .= ' <p class="text-danger">' . gT('Error: This question has no answers.') . "</p>\n"; } else { foreach ($aSubquestions as $ansrow) { $myfname = $ia[1] . $ansrow['title']; if ($ansrow['question'] == "") { $ansrow['question'] = " "; } if ($slider_layout === false || $slider_separator == '') { $theanswer = $ansrow['question']; $sliders = false; } else { $aAnswer = explode($slider_separator, $ansrow['question']); $theanswer = isset($aAnswer[0]) ? $aAnswer[0] : ""; $sliderleft = isset($aAnswer[1]) ? $aAnswer[1] : ""; $sliderright = isset($aAnswer[2]) ? $aAnswer[2] : ""; $sliders = true; $sliderright = "<div class=\"slider_righttext\">{$sliderright}</div>"; } $aAnswer = isset($aAnswer) ? $aAnswer : ''; $sliderleft = isset($sliderleft) ? $sliderleft : ""; $sliderright = isset($sliderright) ? $sliderright : ""; // color code missing mandatory questions red $alert = ''; if ($ia[6] == 'Y' && $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname] === '') { $alert = true; } //list($htmltbody2, $hiddenfield)=return_array_filter_strings($ia, $aQuestionAttributes, $thissurvey, $ansrow, $myfname, '', $myfname, "div","form-group question-item answer-item text-item numeric-item".$extraclass); $sDisplayStyle = return_display_style($ia, $aQuestionAttributes, $thissurvey, $myfname); $sSeparator = getRadixPointData($thissurvey['surveyls_numberformat']); $sSeparator = $sSeparator['separator']; $dispVal = ''; if (isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname])) { $dispVal = $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname]; if (strpos($dispVal, ".")) { $dispVal = rtrim(rtrim($dispVal, "0"), "."); } $dispVal = str_replace('.', $sSeparator, $dispVal); } $itemDatas = array('extraclass' => $extraclass, 'sDisplayStyle' => $sDisplayStyle, 'kpclass' => $kpclass, 'alert' => $alert, 'theanswer' => $theanswer, 'labelname' => 'answer' . $myfname, 'prefixclass' => $prefixclass, 'sliders' => $sliders, 'sliderleft' => $sliderleft, 'sliderright' => $sliderright, 'prefix' => $prefix, 'suffix' => $suffix, 'tiwidth' => $tiwidth, 'myfname' => $myfname, 'dispVal' => $dispVal, 'maxlength' => $maxlength, 'labelText' => $ansrow['question'], 'checkconditionFunction' => $checkconditionFunction . '(this.value, this.name, this.type)', 'slider_orientation' => $slider_orientation, 'slider_step' => $slider_step, 'slider_min' => $slider_min, 'slider_mintext' => $slider_mintext, 'slider_max' => $slider_max, 'slider_maxtext' => $slider_maxtext, 'slider_default' => $slider_default, 'slider_handle' => $slider_handle, 'slider_custom_handle' => $slider_custom_handle); $answer .= Yii::app()->getController()->renderPartial('/survey/questions/multiplenumeric/item', $itemDatas, true); $fn++; $inputnames[] = $myfname; } $displaytotal = false; $equals_num_value = false; if (trim($aQuestionAttributes['equals_num_value']) != '' || trim($aQuestionAttributes['min_num_value']) != '' || trim($aQuestionAttributes['max_num_value']) != '') { $qinfo = LimeExpressionManager::GetQuestionStatus($ia[0]); if (trim($aQuestionAttributes['equals_num_value']) != '') { $equals_num_value = true; } $displaytotal = true; } $footerDatas = array('equals_num_value' => $equals_num_value, 'id' => $ia[0], 'prefix' => $prefix, 'suffix' => $suffix, 'sumRemainingEqn' => isset($qinfo) ? $qinfo['sumRemainingEqn'] : '', 'displaytotal' => $displaytotal, 'sumEqn' => isset($qinfo) ? $qinfo['sumEqn'] : ''); $answer .= Yii::app()->getController()->renderPartial('/survey/questions/multiplenumeric/footer', $footerDatas, true); } if ($aQuestionAttributes['slider_layout'] == 1) { Yii::app()->getClientScript()->registerScriptFile(Yii::app()->getConfig('generalscripts') . "bootstrap-slider.js"); Yii::app()->getClientScript()->registerScriptFile(Yii::app()->getConfig('generalscripts') . "numeric-slider.js"); Yii::app()->getClientScript()->registerCssFile(Yii::app()->getConfig('publicstyleurl') . "numeric-slider.css"); if ($slider_default != "") { $slider_startvalue = $slider_default; $slider_displaycallout = 1; } elseif ($slider_middlestart != '') { $slider_startvalue = $slider_middlestart; $slider_displaycallout = 0; } else { $slider_startvalue = 'NULL'; $slider_displaycallout = 0; } $slider_showminmax = $aQuestionAttributes['slider_showminmax'] == 1 ? 1 : 0; //some var for slider $aJsLang = array('reset' => gT('Reset'), 'tip' => gT('Please click and drag the slider handles to enter your answer.')); $aJsVar = array('slider_showminmax' => $slider_showminmax, 'slider_min' => $slider_min, 'slider_mintext' => $slider_mintext, 'slider_max' => $slider_max, 'slider_maxtext' => $slider_maxtext, 'slider_step' => $slider_step, 'slider_startvalue' => $slider_startvalue, 'slider_displaycallout' => $slider_displaycallout, 'slider_prefix' => $prefix, 'slider_suffix' => $suffix, 'slider_reset' => $slider_reset, 'lang' => $aJsLang); /* $answer .= "<script type='text/javascript'><!--\n" . " doNumericSlider({$ia[0]},".ls_json_encode($aJsVar).");\n" . " //--></script>"; */ } $sSeparator = getRadixPointData($thissurvey['surveyls_numberformat']); $sSeparator = $sSeparator['separator']; return array($answer, $inputnames); }
} //Loop through questions foreach ($deqrows as $deqrow) { // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // START doing questions $qidattributes = getQuestionAttributes($deqrow['qid'], $deqrow['type']); if ($qidattributes['hidden'] == 1 && $deqrow['type'] != '*') { continue; } $bGroupHasVisibleQuestions = true; //GET ANY CONDITIONS THAT APPLY TO THIS QUESTION $printablesurveyoutput = ''; $explanation = ''; //reset conditions explanation $s = 0; $qinfo = LimeExpressionManager::GetQuestionStatus($deqrow['qid']); $relevance = trim($qinfo['info']['relevance']); $explanation = $qinfo['relEqn']; if (trim($relevance) != '' && trim($relevance) != '1') { $explanation = "<b>" . $clang->gT('Only answer this question if the following conditions are met:') . "</b>" . "<br/> ° " . $explanation; } else { $explanation = ''; } ++$total_questions; //TIBO map question qid to their q number $mapquestionsNumbers[$deqrow['qid']] = $total_questions; //END OF GETTING CONDITIONS $qid = $deqrow['qid']; $fieldname = "{$surveyid}" . "X" . "{$gid}" . "X" . "{$qid}"; if (isset($showsgqacode) && $showsgqacode == true) { $deqrow['question'] = $deqrow['question'] . "<br />" . $clang->gT("ID:") . " {$fieldname} <br />" . $clang->gT("Question code:") . " " . $deqrow['title'];
/** * 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); } }
function do_multiplenumeric($ia) { global $thissurvey; $clang = Yii::app()->lang; $extraclass = ""; $checkconditionFunction = "fixnum_checkconditions"; $aQuestionAttributes = getQuestionAttributeValues($ia[0], $ia[4]); $answer = ''; $sSeperator = getRadixPointData($thissurvey['surveyls_numberformat']); $sSeperator = $sSeperator['seperator']; //Must turn on the "numbers only javascript" $extraclass .= " numberonly"; if (intval(trim($aQuestionAttributes['maximum_chars'])) > 0) { // Only maxlength attribute, use textarea[maxlength] jquery selector for textarea $maximum_chars = intval(trim($aQuestionAttributes['maximum_chars'])); $maxlength = "maxlength='{$maximum_chars}' "; $extraclass .= " maxchars maxchars-" . $maximum_chars; } else { $maxlength = "25"; } // //EQUALS VALUE // if (trim($aQuestionAttributes['equals_num_value']) != ''){ // $equals_num_value = $aQuestionAttributes['equals_num_value']; // $numbersonlyonblur[]='calculateValue'.$ia[1].'(3)'; // $calculateValue[]=3; // } // elseif (trim($aQuestionAttributes['num_value_equals_sgqa']) != '' && isset($_SESSION[$aQuestionAttributes['num_value_equals_sgqa']])) // { // $equals_num_value = $_SESSION['survey_'.Yii::app()->getConfig('surveyID')][$aQuestionAttributes['num_value_equals_sgqa']]; // $numbersonlyonblur[]='calculateValue'.$ia[1].'(3)'; // $calculateValue[]=3; // } // else // { // $equals_num_value=0; // } // // //MIN VALUE // if (trim($aQuestionAttributes['min_num_value']) != ''){ // $min_num_value = $aQuestionAttributes['min_num_value']; // $numbersonlyonblur[]='calculateValue'.$ia[1].'(2)'; // $calculateValue[]=2; // } // elseif (trim($aQuestionAttributes['min_num_value_sgqa']) != '' && isset($_SESSION[$aQuestionAttributes['min_num_value_sgqa']])){ // $min_num_value = $_SESSION[$aQuestionAttributes['min_num_value_sgqa']]; // $numbersonlyonblur[]='calculateValue'.$ia[1].'(2)'; // $calculateValue[]=2; // } // else // { // $min_num_value=0; // } // // //MAX VALUE // if (trim($aQuestionAttributes['max_num_value']) != ''){ // $max_num_value = $aQuestionAttributes['max_num_value']; // $numbersonlyonblur[]='calculateValue'.$ia[1].'(1)'; // $calculateValue[]=1; // } // elseif (trim($aQuestionAttributes['max_num_value_sgqa']) != '' && isset($_SESSION[$aQuestionAttributes['max_num_value_sgqa']])){ // $max_num_value = $_SESSION['survey_'.Yii::app()->getConfig('surveyID')][$aQuestionAttributes['max_num_value_sgqa']]; // $numbersonlyonblur[]='calculateValue'.$ia[1].'(1)'; // $calculateValue[]=1; // } // else // { // $max_num_value = 0; // } if (trim($aQuestionAttributes['prefix'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']]) != '') { $prefix = $aQuestionAttributes['prefix'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']]; $extraclass .= " withprefix"; } else { $prefix = ''; } if (trim($aQuestionAttributes['suffix'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']]) != '') { $suffix = $aQuestionAttributes['suffix'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']]; $extraclass .= " withsuffix"; } else { $suffix = ''; } if ($thissurvey['nokeyboard'] == 'Y') { includeKeypad(); $kpclass = "num-keypad"; $extraclass .= " keypad"; } else { $kpclass = ""; } /*if(!empty($numbersonlyonblur)) { $numbersonly .= ' onblur="'.implode(';', $numbersonlyonblur).'"'; $numbersonly_slider = implode(';', $numbersonlyonblur); } else { $numbersonly_slider = ''; }*/ $numbersonly_slider = ''; if (trim($aQuestionAttributes['text_input_width']) != '') { $tiwidth = $aQuestionAttributes['text_input_width']; $extraclass .= " inputwidth" . trim($aQuestionAttributes['text_input_width']); } else { $tiwidth = 10; } if ($aQuestionAttributes['slider_layout'] == 1) { header_includes(Yii::app()->getConfig("generalscripts") . 'jquery/lime-slider.js'); $slider_layout = true; $extraclass .= " withslider"; if (trim($aQuestionAttributes['slider_accuracy']) != '') { //$slider_divisor = 1 / $slider_accuracy['value']; $decimnumber = strlen($aQuestionAttributes['slider_accuracy']) - strpos($aQuestionAttributes['slider_accuracy'], '.') - 1; $slider_divisor = pow(10, $decimnumber); $slider_stepping = $aQuestionAttributes['slider_accuracy'] * $slider_divisor; // error_log('acc='.$slider_accuracy['value']." div=$slider_divisor stepping=$slider_stepping"); } else { $slider_divisor = 1; $slider_stepping = 1; } if (trim($aQuestionAttributes['slider_min']) != '') { $slider_mintext = $aQuestionAttributes['slider_min']; $slider_min = $aQuestionAttributes['slider_min'] * $slider_divisor; } else { $slider_mintext = 0; $slider_min = 0; } if (trim($aQuestionAttributes['slider_max']) != '') { $slider_maxtext = $aQuestionAttributes['slider_max']; $slider_max = $aQuestionAttributes['slider_max'] * $slider_divisor; } else { $slider_maxtext = "100"; $slider_max = 100 * $slider_divisor; } if (trim($aQuestionAttributes['slider_default']) != '') { $slider_default = $aQuestionAttributes['slider_default']; } else { $slider_default = ''; } if ($slider_default == '' && $aQuestionAttributes['slider_middlestart'] == 1) { $slider_middlestart = intval(($slider_max + $slider_min) / 2); } else { $slider_middlestart = ''; } if (trim($aQuestionAttributes['slider_separator']) != '') { $slider_separator = $aQuestionAttributes['slider_separator']; } else { $slider_separator = ''; } } else { $slider_layout = false; } $hidetip = $aQuestionAttributes['hide_tip']; if ($slider_layout === true) { $hidetip = 1; } if ($aQuestionAttributes['random_order'] == 1) { $ansquery = "SELECT * FROM {{questions}} WHERE parent_qid={$ia['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 language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "' ORDER BY question_order"; } $ansresult = dbExecuteAssoc($ansquery); //Checked $aSubquestions = $ansresult->readAll(); $anscount = count($aSubquestions) * 2; $fn = 1; $answer_main = ''; if ($anscount == 0) { $inputnames = array(); $answer_main .= ' <li>' . $clang->gT('Error: This question has no answers.') . "</li>\n"; } else { $label_width = 0; foreach ($aSubquestions as $ansrow) { $myfname = $ia[1] . $ansrow['title']; if ($ansrow['question'] == "") { $ansrow['question'] = " "; } if ($slider_layout === false || $slider_separator == '') { $theanswer = $ansrow['question']; $sliderleft = ''; $sliderright = ''; } else { $answer_and_slider_array = explode($slider_separator, $ansrow['question']); if (isset($answer_and_slider_array[0])) { $theanswer = $answer_and_slider_array[0]; } else { $theanswer = ''; } if (isset($answer_and_slider_array[1])) { $sliderleft = $answer_and_slider_array[1]; } else { $sliderleft = ''; } if (isset($answer_and_slider_array[2])) { $sliderright = $answer_and_slider_array[2]; } else { $sliderright = ''; } $sliderleft = "<div class=\"slider_lefttext\">{$sliderleft}</div>"; $sliderright = "<div class=\"slider_righttext\">{$sliderright}</div>"; } // color code missing mandatory questions red if ($ia[6] == 'Y' && ($_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['step'] == $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['prevstep'] || $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['maxstep'] > $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['step']) && $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname] === '') { $theanswer = "<span class='errormandatory'>{$theanswer}</span>"; } list($htmltbody2, $hiddenfield) = return_array_filter_strings($ia, $aQuestionAttributes, $thissurvey, $ansrow, $myfname, '', $myfname, "li", "question-item answer-item text-item numeric-item" . $extraclass); $answer_main .= "\t{$htmltbody2}\n"; if ($slider_layout === false) { $answer_main .= "<label for=\"answer{$myfname}\">{$theanswer}</label>\n"; } else { $answer_main .= "<label for=\"answer{$myfname}\" class=\"slider-label\">{$theanswer}</label>\n"; } if ($label_width < strlen(trim(strip_tags($ansrow['question'])))) { $label_width = strlen(trim(strip_tags($ansrow['question']))); } if ($slider_layout === false) { $sSeperator = getRadixPointData($thissurvey['surveyls_numberformat']); $sSeperator = $sSeperator['seperator']; $answer_main .= "<span class=\"input\">\n\t" . $prefix . "\n\t<input class=\"text {$kpclass}\" type=\"text\" size=\"" . $tiwidth . '" name="' . $myfname . '" id="answer' . $myfname . '" value="'; if (isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname])) { $dispVal = str_replace('.', $sSeperator, $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname]); $answer_main .= $dispVal; } $answer_main .= '" onkeyup="' . $checkconditionFunction . '(this.value, this.name, this.type);" ' . " {$maxlength} />\n\t" . $suffix . "\n</span>\n\t</li>\n"; } else { if ($aQuestionAttributes['slider_showminmax'] == 1) { //$slider_showmin=$slider_min; $slider_showmin = "\t<div id=\"slider-left-{$myfname}\" class=\"slider_showmin\">{$slider_mintext}</div>\n"; $slider_showmax = "\t<div id=\"slider-right-{$myfname}\" class=\"slider_showmax\">{$slider_maxtext}</div>\n"; } else { $slider_showmin = ''; $slider_showmax = ''; } if (isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname]) && $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname] != '') { $slider_startvalue = $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname] * $slider_divisor; $displaycallout_atstart = 1; } elseif ($slider_default != "") { $slider_startvalue = $slider_default * $slider_divisor; $displaycallout_atstart = 1; } elseif ($slider_middlestart != '') { $slider_startvalue = $slider_middlestart; $displaycallout_atstart = 0; } else { $slider_startvalue = 'NULL'; $displaycallout_atstart = 0; } $answer_main .= "{$sliderleft}<div id='container-{$myfname}' class='multinum-slider'>\n" . "\t<input type=\"text\" id=\"slider-modifiedstate-{$myfname}\" value=\"{$displaycallout_atstart}\" style=\"display: none;\" />\n" . "\t<input type=\"text\" id=\"slider-param-min-{$myfname}\" value=\"{$slider_min}\" style=\"display: none;\" />\n" . "\t<input type=\"text\" id=\"slider-param-max-{$myfname}\" value=\"{$slider_max}\" style=\"display: none;\" />\n" . "\t<input type=\"text\" id=\"slider-param-stepping-{$myfname}\" value=\"{$slider_stepping}\" style=\"display: none;\" />\n" . "\t<input type=\"text\" id=\"slider-param-divisor-{$myfname}\" value=\"{$slider_divisor}\" style=\"display: none;\" />\n" . "\t<input type=\"text\" id=\"slider-param-startvalue-{$myfname}\" value='{$slider_startvalue}' style=\"display: none;\" />\n" . "\t<input type=\"text\" id=\"slider-onchange-js-{$myfname}\" value=\"{$numbersonly_slider}\" style=\"display: none;\" />\n" . "\t<input type=\"text\" id=\"slider-prefix-{$myfname}\" value=\"{$prefix}\" style=\"display: none;\" />\n" . "\t<input type=\"text\" id=\"slider-suffix-{$myfname}\" value=\"{$suffix}\" style=\"display: none;\" />\n" . "<div id=\"slider-{$myfname}\" class=\"ui-slider-1\">\n" . $slider_showmin . "<div class=\"slider_callout\" id=\"slider-callout-{$myfname}\"></div>\n" . "<div class=\"ui-slider-handle\" id=\"slider-handle-{$myfname}\"></div>\n" . $slider_showmax . "\t</div>" . "</div>{$sliderright}\n" . "<input class=\"text\" type=\"text\" name=\"{$myfname}\" id=\"answer{$myfname}\" value=\""; if (isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname]) && $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname] != '') { $answer_main .= $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname]; } elseif ($slider_default != "") { $answer_main .= $slider_default; } $answer_main .= "\"/>\n" . "\t</li>\n"; } // $answer .= "\t</tr>\n"; $fn++; $inputnames[] = $myfname; } $question_tip = ''; if ($hidetip == 0) { $question_tip .= '<p class="tip">' . $clang->gT('Only numbers may be entered in these fields') . "</p>\n"; } // if ($max_num_value) // { // $question_tip .= '<p id="max_num_value_'.$ia[1].'" class="tip">'.sprintf($clang->gT('Total of all entries must not exceed %d'), $max_num_value)."</p>\n"; // } // if ($equals_num_value) // { // $question_tip .= '<p id="equals_num_value_'.$ia[1].'" class="tip">'.sprintf($clang->gT('Total of all entries must equal %d'),$equals_num_value)."</p>\n"; // } // if ($min_num_value) // { // $question_tip .= '<p id="min_num_value_'.$ia[1].'" class="tip">'.sprintf($clang->gT('Total of all entries must be at least %s'),$min_num_value)."</p>\n"; // } // // // TMSW TODO // if ($max_num_value || $equals_num_value || $min_num_value) // { // $answer_computed = ''; // if ($equals_num_value) // { // $answer_computed .= "\t<li class='multiplenumerichelp'>\n<label for=\"remainingvalue_{$ia[1]}\">\n\t".$clang->gT('Remaining: ')."\n</label>\n<span>\n\t$prefix\n\t<input size=10 type='text' id=\"remainingvalue_{$ia[1]}\" disabled=\"disabled\" />\n\t$suffix\n</span>\n\t</li>\n"; // } // $answer_computed .= "\t<li class='multiplenumerichelp'>\n<label for=\"totalvalue_{$ia[1]}\">\n\t".$clang->gT('Total: ')."\n</label>\n<span>\n\t$prefix\n\t<input size=10 type=\"text\" id=\"totalvalue_{$ia[1]}\" disabled=\"disabled\" />\n\t$suffix\n</span>\n\t</li>\n"; // $answer_main .= $answer_computed; // } if (trim($aQuestionAttributes['equals_num_value']) != '' || trim($aQuestionAttributes['min_num_value']) != '' || trim($aQuestionAttributes['max_num_value']) != '') { $qinfo = LimeExpressionManager::GetQuestionStatus($ia[0]); if (trim($aQuestionAttributes['equals_num_value']) != '') { $answer_main .= "\t<li class='multiplenumerichelp help-item'>\n" . "<span class=\"label\">" . $clang->gT('Remaining: ') . "</span>\n" . "<span id=\"remainingvalue_{$ia[0]}\" class=\"dynamic_remaining\">{$prefix}\n" . "{" . $qinfo['sumRemainingEqn'] . "}\n" . "{$suffix}</span>\n" . "\t</li>\n"; } $answer_main .= "\t<li class='multiplenumerichelp help-item'>\n" . "<span class=\"label\">" . $clang->gT('Total: ') . "</span>\n" . "<span id=\"totalvalue_{$ia[0]}\" class=\"dynamic_sum\">{$prefix}\n" . "{" . $qinfo['sumEqn'] . "}\n" . "{$suffix}</span>\n" . "\t</li>\n"; } $answer .= $question_tip . "<ul class=\"subquestions-list questions-list text-list numeric-list\">\n" . $answer_main . "</ul>\n"; } //just added these here so its easy to change in one place $errorClass = 'tip problem'; $goodClass = 'tip good'; /* ================================== Style to be applied to all templates. .numeric-multi p.tip.error { color: #f00; } .numeric-multi p.tip.good { color: #0f0; } */ $sSeperator = getRadixPointData($thissurvey['surveyls_numberformat']); $sSeperator = $sSeperator['seperator']; // if ($max_num_value || $equals_num_value || $min_num_value) // { //Do value validation // $answer .= '<input type="hidden" name="qattribute_answer[]" value="'.$ia[1]."\" />\n"; // $answer .= '<input type="hidden" name="qattribute_answer'.$ia[1]."\" />\n"; // // $answer .= "<script type='text/javascript'>\n"; // $answer .= " function calculateValue".$ia[1]."(method) {\n"; // //Make all empty fields 0 (or else calculation won't work // foreach ($inputnames as $inputname) // { // $answer .= " if(document.limesurvey.answer".$inputname.".value == '') { document.limesurvey.answer".$inputname.".value = 0; }\n"; // $javainputnames[]="parseInt(parseFloat((document.limesurvey.answer".$inputname.".value).split(',').join('.'))*1000)"; // } // $answer .= " bob = eval('document.limesurvey.qattribute_answer".$ia[1]."');\n"; // $answer .= " totalvalue_".$ia[1]."=("; // $answer .= implode(" + ", $javainputnames); // $answer .= ")/1000;\n"; // $answer .= " $('#totalvalue_{$ia[1]}').val((parseFloat(totalvalue_{$ia[1]})+'').split('.').join('{$sSeperator}'));\n"; // $answer .= " var ua = navigator.appVersion.indexOf('MSIE');\n"; // $answer .= " var ieAtt = ua != -1 ? 'className' : 'class';\n"; // $answer .= " switch(method)\n"; // $answer .= " {\n"; // $answer .= " case 1:\n"; // $answer .= " if (totalvalue_".$ia[1]." > $max_num_value)\n"; // $answer .= " {\n"; // $answer .= " bob.value = '".$clang->gT("Answer is invalid. The total of all entries should not add up to more than ").$max_num_value."';\n"; // $answer .= " document.getElementById('totalvalue_{$ia[1]}').setAttribute(ieAtt,'" . $errorClass . "');\n"; // $answer .= " document.getElementById('max_num_value_{$ia[1]}').setAttribute(ieAtt,'" . $errorClass . "');\n"; // $answer .= " }\n"; // $answer .= " else\n"; // $answer .= " {\n"; // $answer .= " if (bob.value == '' || bob.value == '".$clang->gT("Answer is invalid. The total of all entries should not add up to more than ").$max_num_value."')\n"; // $answer .= " {\n"; // $answer .= " bob.value = '';\n"; // // $answer .= " document.getElementById('totalvalue_{$ia[1]}').style.color='black';\n"; // $answer .= " document.getElementById('totalvalue_{$ia[1]}').setAttribute(ieAtt,'" . $goodClass . "');\n"; // $answer .= " }\n"; // // $answer .= " document.getElementById('max_num_value_{$ia[1]}').style.color='black';\n"; // $answer .= " document.getElementById('max_num_value_{$ia[1]}').setAttribute(ieAtt,'" . $goodClass . "');\n"; // $answer .= " }\n"; // $answer .= " break;\n"; // $answer .= " case 2:\n"; // $answer .= " if (totalvalue_".$ia[1]." < $min_num_value)\n"; // $answer .= " {\n"; // $answer .= " bob.value = '".sprintf($clang->gT("Answer is invalid. The total of all entries should add up to at least %s.",'js'),$min_num_value)."';\n"; // // $answer .= " document.getElementById('totalvalue_".$ia[1]."').style.color='red';\n"; // // $answer .= " document.getElementById('min_num_value_".$ia[1]."').style.color='red';\n"; // $answer .= " document.getElementById('totalvalue_".$ia[1]."').setAttribute(ieAtt,'" . $errorClass . "');\n"; // $answer .= " document.getElementById('min_num_value_".$ia[1]."').setAttribute(ieAtt,'" . $errorClass . "');\n"; // $answer .= " }\n"; // $answer .= " else\n"; // $answer .= " {\n"; // $answer .= " if (bob.value == '' || bob.value == '".sprintf($clang->gT("Answer is invalid. The total of all entries should add up to at least %s.",'js'),$min_num_value)."')\n"; // $answer .= " {\n"; // $answer .= " bob.value = '';\n"; // // $answer .= " document.getElementById('totalvalue_".$ia[1]."').style.color='black';\n"; // $answer .= " document.getElementById('totalvalue_".$ia[1]."').setAttribute(ieAtt,'" . $goodClass . "');\n"; // $answer .= " }\n"; // // $answer .= " document.getElementById('min_num_value_".$ia[1]."').style.color='black';\n"; // $answer .= " document.getElementById('min_num_value_".$ia[1]."').setAttribute(ieAtt,'" . $goodClass . "');\n"; // $answer .= " }\n"; // $answer .= " break;\n"; // $answer .= " case 3:\n"; // $answer .= " remainingvalue = (parseInt(parseFloat($equals_num_value)*1000) - parseInt(parseFloat(totalvalue_".$ia[1].")*1000))/1000;\n"; // $answer .= " document.getElementById('remainingvalue_".$ia[1]."').value=remainingvalue;\n"; // $answer .= " if (totalvalue_".$ia[1]." == $equals_num_value)\n"; // $answer .= " {\n"; // $answer .= " if (bob.value == '' || bob.value == '".$clang->gT("Answer is invalid. The total of all entries should not add up to more than ").$equals_num_value."')\n"; // $answer .= " {\n"; // $answer .= " bob.value = '';\n"; // // $answer .= " document.getElementById('totalvalue_".$ia[1]."').style.color='black';\n"; // // $answer .= " document.getElementById('equals_num_value_".$ia[1]."').style.color='black';\n"; // $answer .= " document.getElementById('totalvalue_".$ia[1]."').setAttribute(ieAtt,'" . $goodClass . "');\n"; // $answer .= " document.getElementById('equals_num_value_".$ia[1]."').setAttribute(ieAtt,'" . $goodClass . "');\n"; // $answer .= " }\n"; // $answer .= " }\n"; // $answer .= " else\n"; // $answer .= " {\n"; // $answer .= " bob.value = '".$clang->gT("Answer is invalid. The total of all entries should not add up to more than ").$equals_num_value."';\n"; // // $answer .= " document.getElementById('totalvalue_".$ia[1]."').style.color='red';\n"; // // $answer .= " document.getElementById('equals_num_value_".$ia[1]."').style.color='red';\n"; // $answer .= " document.getElementById('totalvalue_".$ia[1]."').setAttribute(ieAtt,'" . $errorClass . "');\n"; // $answer .= " document.getElementById('equals_num_value_".$ia[1]."').setAttribute(ieAtt,'" . $errorClass . "');\n"; // $answer .= " }\n"; // $answer .= " break;\n"; // $answer .= " }\n"; // $answer .= " }\n"; // foreach($calculateValue as $cValue) // { // $answer .= " calculateValue".$ia[1]."($cValue);\n"; // } // $answer .= "</script>\n"; // // } return array($answer, $inputnames); }
} echo ">\n"; echo templatereplace(file_get_contents("{$thistpl}/startgroup.pstpl")); echo "\n"; if ($groupdescription) { echo templatereplace(file_get_contents("{$thistpl}/groupdescription.pstpl")); } echo "\n"; echo "\n\n<!-- PRESENT THE QUESTIONS -->\n"; $i = 0; foreach ($qanda as $qa) { if ($gid != $qa[6]) { continue; } $qid = $qa[4]; $qinfo = LimeExpressionManager::GetQuestionStatus($qid); $lastgrouparray = explode("X", $qa[7]); $lastgroup = $lastgrouparray[0] . "X" . $lastgrouparray[1]; // id of the last group, derived from question id $lastanswer = $qa[7]; $q_class = question_class($qinfo['info']['type']); $man_class = ''; if ($qinfo['info']['mandatory'] == 'Y') { $man_class .= ' mandatory'; } if ($qinfo['anyUnanswered'] && $_SESSION['maxstep'] != $_SESSION['step']) { $man_class .= ' missing'; } $n_q_display = ''; if ($qinfo['hidden'] && $qinfo['info']['type'] != '*') { continue;
function do_multiplenumeric($ia) { global $dbprefix, $clang, $js_header_includes, $css_header_includes, $thissurvey; $checkconditionFunction = "fixnum_checkconditions"; $qidattributes = getQuestionAttributes($ia[0], $ia[4]); $answer = ''; $sSeperator = getRadixPointData($thissurvey['surveyls_numberformat']); $sSeperator = $sSeperator['seperator']; $numbersonly = ''; // 'onkeypress="inputField = event.srcElement ? event.srcElement : event.target || event.currentTarget; if (inputField.value.indexOf(\''.$sSeperator.'\')>0 && String.fromCharCode(getkey(event))==\''.$sSeperator.'\') return false; return goodchars(event,\'-0123456789'.$sSeperator.'\')"'; if (intval(trim($qidattributes['maximum_chars'])) > 0) { // Only maxlength attribute, use textarea[maxlength] jquery selector for textarea $maximum_chars = intval(trim($qidattributes['maximum_chars'])); $maxlength = "maxlength='{$maximum_chars}' "; } else { $maxlength = "maxlength='25'"; } if (trim($qidattributes['prefix']) != '') { $prefix = $qidattributes['prefix']; } else { $prefix = ''; } if (trim($qidattributes['suffix']) != '') { $suffix = $qidattributes['suffix']; } else { $suffix = ''; } if ($thissurvey['nokeyboard'] == 'Y') { vIncludeKeypad(); $kpclass = "num-keypad"; } else { $kpclass = ""; } if (!empty($numbersonlyonblur)) { $numbersonly .= ' onblur="' . implode(';', $numbersonlyonblur) . '"'; $numbersonly_slider = implode(';', $numbersonlyonblur); } else { $numbersonly_slider = ''; } if (trim($qidattributes['text_input_width']) != '') { $tiwidth = $qidattributes['text_input_width']; } else { $tiwidth = 10; } if ($qidattributes['slider_layout'] == 1) { $slider_layout = true; $css_header_includes[] = '/scripts/jquery/css/start/jquery-ui.css'; if (trim($qidattributes['slider_accuracy']) != '') { //$slider_divisor = 1 / $slider_accuracy['value']; $decimnumber = strlen($qidattributes['slider_accuracy']) - strpos($qidattributes['slider_accuracy'], '.') - 1; $slider_divisor = pow(10, $decimnumber); $slider_stepping = $qidattributes['slider_accuracy'] * $slider_divisor; // error_log('acc='.$slider_accuracy['value']." div=$slider_divisor stepping=$slider_stepping"); } else { $slider_divisor = 1; $slider_stepping = 1; } if (trim($qidattributes['slider_min']) != '') { $slider_mintext = $qidattributes['slider_min']; $slider_min = $qidattributes['slider_min'] * $slider_divisor; } else { $slider_mintext = 0; $slider_min = 0; } if (trim($qidattributes['slider_max']) != '') { $slider_maxtext = $qidattributes['slider_max']; $slider_max = $qidattributes['slider_max'] * $slider_divisor; } else { $slider_maxtext = "100"; $slider_max = 100 * $slider_divisor; } if (trim($qidattributes['slider_default']) != '') { $slider_default = $qidattributes['slider_default']; } else { $slider_default = ''; } if ($slider_default == '' && $qidattributes['slider_middlestart'] == 1) { $slider_middlestart = intval(($slider_max + $slider_min) / 2); } else { $slider_middlestart = ''; } if (trim($qidattributes['slider_separator']) != '') { $slider_separator = $qidattributes['slider_separator']; } else { $slider_separator = ''; } } else { $slider_layout = false; } $hidetip = $qidattributes['hide_tip']; if ($slider_layout === true) { $hidetip = 1; } if ($qidattributes['random_order'] == 1) { $ansquery = "SELECT * FROM {$dbprefix}questions WHERE parent_qid={$ia['0']} AND language='" . $_SESSION['s_lang'] . "' ORDER BY " . db_random(); } else { $ansquery = "SELECT * FROM {$dbprefix}questions WHERE parent_qid={$ia['0']} AND language='" . $_SESSION['s_lang'] . "' ORDER BY question_order"; } $ansresult = db_execute_assoc($ansquery); //Checked $anscount = $ansresult->RecordCount() * 2; //$answer .= "\t<input type='hidden' name='MULTI$ia[1]' value='$anscount'>\n"; $fn = 1; $answer_main = ''; if ($anscount == 0) { $inputnames = array(); $answer_main .= ' <li>' . $clang->gT('Error: This question has no answers.') . "</li>\n"; } else { $label_width = 0; while ($ansrow = $ansresult->FetchRow()) { $myfname = $ia[1] . $ansrow['title']; if ($ansrow['question'] == "") { $ansrow['question'] = " "; } if ($slider_layout === false || $slider_separator == '') { $theanswer = $ansrow['question']; $sliderleft = ''; $sliderright = ''; } else { $answer_and_slider_array = explode($slider_separator, $ansrow['question']); if (isset($answer_and_slider_array[0])) { $theanswer = $answer_and_slider_array[0]; } else { $theanswer = ""; } if (isset($answer_and_slider_array[1])) { $sliderleft = $answer_and_slider_array[1]; } else { $sliderleft = ""; } if (isset($answer_and_slider_array[2])) { $sliderright = $answer_and_slider_array[2]; } else { $sliderright = ""; } $sliderleft = "<div class=\"slider_lefttext\">{$sliderleft}</div>"; $sliderright = "<div class=\"slider_righttext\">{$sliderright}</div>"; } // color code missing mandatory questions red if ($ia[6] == 'Y' && ($_SESSION['step'] == $_SESSION['prevstep'] || $_SESSION['maxstep'] > $_SESSION['step']) && $_SESSION[$myfname] == '') { $theanswer = "<span class='errormandatory'>{$theanswer}</span>"; } list($htmltbody2, $hiddenfield) = return_array_filter_strings($ia, $qidattributes, $thissurvey, $ansrow, $myfname, '', $myfname, "li"); $answer_main .= "\t{$htmltbody2}\n"; if ($slider_layout === false) { $answer_main .= "<label for=\"answer{$myfname}\">{$theanswer}</label>\n"; } else { $answer_main .= "<label for=\"answer{$myfname}\" class=\"slider-label\">{$theanswer}</label>\n"; } if ($label_width < strlen(trim(strip_tags($ansrow['question'])))) { $label_width = strlen(trim(strip_tags($ansrow['question']))); } if ($slider_layout === false) { $sSeperator = getRadixPointData($thissurvey['surveyls_numberformat']); $sSeperator = $sSeperator['seperator']; $answer_main .= "<span class=\"input\">\n\t" . $prefix . "\n\t<input class=\"text {$kpclass}\" type=\"text\" size=\"" . $tiwidth . '" name="' . $myfname . '" id="answer' . $myfname . '" value="'; if (isset($_SESSION[$myfname])) { $dispVal = str_replace('.', $sSeperator, $_SESSION[$myfname]); $answer_main .= $dispVal; } $answer_main .= '" onkeyup="' . $checkconditionFunction . '(this.value, this.name, this.type);" ' . " {$numbersonly} {$maxlength} />\n\t" . $suffix . "\n</span>\n\t</li>\n"; } else { if ($qidattributes['slider_showminmax'] == 1) { //$slider_showmin=$slider_min; $slider_showmin = "\t<div id=\"slider-left-{$myfname}\" class=\"slider_showmin\">{$slider_mintext}</div>\n"; $slider_showmax = "\t<div id=\"slider-right-{$myfname}\" class=\"slider_showmax\">{$slider_maxtext}</div>\n"; } else { $slider_showmin = ''; $slider_showmax = ''; } $js_header_includes[] = '/scripts/jquery/lime-slider.js'; if (isset($_SESSION[$myfname]) && $_SESSION[$myfname] != '') { $slider_startvalue = $_SESSION[$myfname] * $slider_divisor; $displaycallout_atstart = 1; } elseif ($slider_default != "") { $slider_startvalue = $slider_default * $slider_divisor; $displaycallout_atstart = 1; } elseif ($slider_middlestart != '') { $slider_startvalue = $slider_middlestart; $displaycallout_atstart = 0; } else { $slider_startvalue = 'NULL'; $displaycallout_atstart = 0; } $answer_main .= "{$sliderleft}<div id='container-{$myfname}' class='multinum-slider'>\n" . "\t<input type=\"text\" id=\"slider-modifiedstate-{$myfname}\" value=\"{$displaycallout_atstart}\" style=\"display: none;\" />\n" . "\t<input type=\"text\" id=\"slider-param-min-{$myfname}\" value=\"{$slider_min}\" style=\"display: none;\" />\n" . "\t<input type=\"text\" id=\"slider-param-max-{$myfname}\" value=\"{$slider_max}\" style=\"display: none;\" />\n" . "\t<input type=\"text\" id=\"slider-param-stepping-{$myfname}\" value=\"{$slider_stepping}\" style=\"display: none;\" />\n" . "\t<input type=\"text\" id=\"slider-param-divisor-{$myfname}\" value=\"{$slider_divisor}\" style=\"display: none;\" />\n" . "\t<input type=\"text\" id=\"slider-param-startvalue-{$myfname}\" value='{$slider_startvalue}' style=\"display: none;\" />\n" . "\t<input type=\"text\" id=\"slider-onchange-js-{$myfname}\" value=\"{$numbersonly_slider}\" style=\"display: none;\" />\n" . "\t<input type=\"text\" id=\"slider-prefix-{$myfname}\" value=\"{$prefix}\" style=\"display: none;\" />\n" . "\t<input type=\"text\" id=\"slider-suffix-{$myfname}\" value=\"{$suffix}\" style=\"display: none;\" />\n" . "<div id=\"slider-{$myfname}\" class=\"ui-slider-1\">\n" . $slider_showmin . "<div class=\"slider_callout\" id=\"slider-callout-{$myfname}\"></div>\n" . "<div class=\"ui-slider-handle\" id=\"slider-handle-{$myfname}\"></div>\n"; $answer_main .= "<input class=\"text\" type=\"text\" name=\"{$myfname}\" id=\"answer{$myfname}\" value=\""; if (isset($_SESSION[$myfname]) && $_SESSION[$myfname] != '') { $answer_main .= $_SESSION[$myfname]; } elseif ($slider_default != "") { $answer_main .= $slider_default; } $answer_main .= "\"/>\n"; $answer_main .= $slider_showmax . "\t</div>" . "</div>{$sliderright}\n"; $answer_main .= "\t</li>\n"; } // $answer .= "\t</tr>\n"; $fn++; $inputnames[] = $myfname; } $question_tip = ''; if ($hidetip == 0) { $question_tip .= '<p class="tip">' . $clang->gT('Only numbers may be entered in these fields') . "</p>\n"; } if (trim($qidattributes['equals_num_value']) != '' || trim($qidattributes['min_num_value']) != '' || trim($qidattributes['max_num_value']) != '') { $qinfo = LimeExpressionManager::GetQuestionStatus($ia[0]); if (trim($qidattributes['equals_num_value']) != '') { $answer_main .= "\t<li class='multiplenumerichelp'>\n" . "<label for=\"remainingvalue_{$ia[0]}\">" . $clang->gT('Remaining: ') . "</label>\n" . "<span id=\"remainingvalue_{$ia[0]}\" class=\"dynamic_remaining\">{$prefix}\n" . "{" . $qinfo['sumRemainingEqn'] . "}\n" . "{$suffix}</span>\n" . "\t</li>\n"; } $answer_main .= "\t<li class='multiplenumerichelp'>\n" . "<label for=\"totalvalue_{$ia[0]}\">" . $clang->gT('Total: ') . "</label>\n" . "<span id=\"totalvalue_{$ia[0]}\" class=\"dynamic_sum\">{$prefix}\n" . "{" . $qinfo['sumEqn'] . "}\n" . "{$suffix}</span>\n" . "\t</li>\n"; } $answer .= $question_tip . "<ul>\n" . $answer_main . "</ul>\n"; } //just added these here so its easy to change in one place $errorClass = 'tip problem'; $goodClass = 'tip good'; /* ================================== Style to be applied to all templates. .numeric-multi p.tip.error { color: #f00; } .numeric-multi p.tip.good { color: #0f0; } */ $sSeperator = getRadixPointData($thissurvey['surveyls_numberformat']); $sSeperator = $sSeperator['seperator']; return array($answer, $inputnames); }