/** * 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); global $oTemplate; $sTemplatePath = $oTemplate->path; $sTemplateViewPath = $oTemplate->viewPath; //$sTemplatePath=getTemplatePath(Yii::app()->getConfig("defaulttemplate")).DIRECTORY_SEPARATOR; // TODO : check if necessary : /* 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(App()->language) ? App()->language : $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); //TODO : check if necessary //$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::NavigateForwards(); //$_SESSION[$LEMsessid]['step']=1; } } elseif ($surveyid != LimeExpressionManager::getLEMsurveyId()) { $_SESSION[$LEMsessid]['step'] = $_SESSION[$LEMsessid]['step'] < 0 ? 0 : $_SESSION[$LEMsessid]['step']; //$_SESSION[$LEMsessid]['step'] can not be less than 0, fix it always #09772 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 = 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=gT("Clear all need confirmation."); } if (isset($move)) { if (!in_array($move, array("clearall", "changelang", "saveall", "reload"))) { $_SESSION[$LEMsessid]['prevstep'] = $_SESSION[$LEMsessid]['step']; } else { // Accepted $move without error $_SESSION[$LEMsessid]['prevstep'] = $move; } } else { //$_SESSION[$LEMsessid]['prevstep'] = $_SESSION[$LEMsessid]['step']-1; // Is this needed ? } if (!isset($_SESSION[$LEMsessid]['prevstep'])) { $_SESSION[$LEMsessid]['prevstep'] = $_SESSION[$LEMsessid]['step'] - 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 if ($thissurvey['questionindex'] == 2) { // Must : save actual page , review whole before set finished to true (see #09906), index==1 seems to don't need it : (don't force move) LimeExpressionManager::StartSurvey($surveyid, $surveyMode, $surveyOptions); } $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 && $move != 'movesubmit' && $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($sTemplateViewPath . "startpage.pstpl"), array(), $redata, 'SubmitStartpageI', false, NULL, array(), true); //Check for assessments if ($thissurvey['assessments'] == "Y" && $assessments) { echo templatereplace(file_get_contents($sTemplateViewPath . "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'>" . gT("Did Not Save") . "</font></strong><br /><br />\n\n"; $completed .= 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") . "'>" . 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($sTemplateViewPath . "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($sTemplateViewPath . "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($sTemplateViewPath . "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($sTemplateViewPath . "assessment.pstpl"), array(), $redata, 'SubmitAssessment', false, NULL, array(), true); } } if (trim(str_replace(array('<p>', '</p>'), '', $thissurvey['surveyls_endtext'])) == '') { $completed = "<br /><span class='success'>" . gT("Thank you!") . "</span><br /><br />\n\n" . 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'>" . gT("Print your answers.") . "</a><br />\n"; } //***************************************** if ($thissurvey['publicstatistics'] == 'Y' && $thissurvey['printanswers'] == 'Y') { $completed .= '<br />' . 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'>" . 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($sTemplateViewPath . "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($sTemplateViewPath . "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($sTemplateViewPath . "startpage.pstpl"), array(), $redata); echo "\t<center><br />\n"; echo "\t" . gT("Sorry. There is no matching survey.") . "<br /></center> \n"; echo templatereplace(file_get_contents($sTemplateViewPath . "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 gT('Invalid group number for this survey: ') . $_gid; exit; } $moveResult = LimeExpressionManager::JumpTo($gseq + 1, true); if (is_null($moveResult)) { echo 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 = gT("Submit your answers"); $groupdescription = 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 //// To diplay one question, all the questions are processed ? 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]); 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(); /** * Question Index */ $aQuestionindexbuttons = null; $aQuestionindexbuttonsmenu = null; if (!$previewgrp && !$previewquestion) { if ($surveyMode != 'survey' && $thissurvey['questionindex'] == 1) { //$aQuestionindex = $this->createIncrementalQuestionIndex($LEMsessid, $surveyMode); $aQuestionindexmenu = $this->createIncrementalQuestionIndexMenu($LEMsessid, $surveyMode); } elseif ($surveyMode != 'survey' && $thissurvey['questionindex'] == 2) { //$aQuestionindex = $this->createFullQuestionIndex($LEMsessid, $surveyMode); $aQuestionindexmenu = $this->createFullQuestionIndexMenu($LEMsessid, $surveyMode); } //$questionindex = (isset($aQuestionindex['menulist']))?$aQuestionindex['menulist']:''; $questionindexmenu = isset($aQuestionindexmenu['menulist']) ? $aQuestionindexmenu['menulist'] : ''; //$aQuestionindexbuttons = (isset($aQuestionindex['buttons']))?$aQuestionindex['buttons']:''; $aQuestionindexbuttonsmenu = isset($aQuestionindexmenu['buttons']) ? $aQuestionindexmenu['buttons'] : ''; } ///////////////////////////////// // First call to templatereplace echo "<!-- SurveyRunTimeHelper -->"; $redata = compact(array_keys(get_defined_vars())); echo templatereplace(file_get_contents($sTemplateViewPath . "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", "sid" => $surveyid), 'post', array('enctype' => 'multipart/form-data', 'id' => 'limesurvey', 'name' => 'limesurvey', 'autocomplete' => 'off', 'class' => 'survey-form-container surveyRunTimeUploadFile')) . "\n\n <!-- INPUT NAMES -->\n <input type='hidden' name='fieldnames' value='{$hiddenfieldnames}' id='fieldnames' />\n"; } else { echo CHtml::form(array("/survey/index", "sid" => $surveyid), 'post', array('id' => 'limesurvey', 'name' => 'limesurvey', 'autocomplete' => 'off', 'class' => 'survey-form-container surveyRunTime')) . "\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($sTemplateViewPath . "welcome.pstpl"), array(), $redata) . "\n"; } if ($thissurvey['anonymized'] == "Y") { echo templatereplace(file_get_contents($sTemplateViewPath . "privacy.pstpl"), array(), $redata) . "\n"; } } // <-- START THE SURVEY --> if ($surveyMode != 'survey') { echo templatereplace(file_get_contents($sTemplateViewPath . "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 alert alert-danger' role='alert'>" . 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 alert alert-danger' role='alert'>" . 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 alert alert-danger' role='alert'>" . 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 (in SurveyRunTime ) -->\n"; echo "\n\n<div id='group-{$_gseq}'"; $gnoshow = LimeExpressionManager::GroupIsIrrelevantOrHidden($_gseq); if ($gnoshow && !$previewgrp) { echo " style='display: none;'"; } echo " class='row'>\n"; echo templatereplace(file_get_contents($sTemplateViewPath . "startgroup.pstpl"), array(), $redata); echo "\n"; if (!$previewquestion && trim($redata['groupdescription']) == "") { echo templatereplace(file_get_contents($sTemplateViewPath . "groupdescription.pstpl"), array(), $redata); } echo "\n"; echo "\n\n<!-- PRESENT THE QUESTIONS (in SurveyRunTime ) -->\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]; $n_q_display = ''; if ($qinfo['hidden'] && $qinfo['info']['type'] != '*') { continue; // skip this one } $aReplacement = array(); $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['sgq'] = $qa[7]; $question['aid'] = !empty($qinfo['info']['aid']) ? $qinfo['info']['aid'] : 0; $question['sqid'] = !empty($qinfo['info']['sqid']) ? $qinfo['info']['sqid'] : 0; //=================================================================== $question_template = file_get_contents($sTemplateViewPath . 'question.pstpl'); // Fix old template : can we remove it ? Old template are surely already broken by another issue 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); $question_template = "<div {QUESTION_ESSENTIALS} class='{QUESTION_CLASS} {QUESTION_MAN_CLASS} {QUESTION_INPUT_ERROR_CLASS}'" . $question_template . "</div>"; } $redata = compact(array_keys(get_defined_vars())); $aQuestionReplacement = $this->getQuestionReplacement($qa); echo templatereplace($question_template, $aQuestionReplacement, $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($sTemplateViewPath . "endgroup.pstpl"), array(), $redata); echo "\n\n</div>\n"; Yii::app()->setConfig('gid', ''); } LimeExpressionManager::FinishProcessingGroup($LEMskipReprocessing); echo LimeExpressionManager::GetRelevanceAndTailoringJavaScript(); LimeExpressionManager::FinishProcessingPage(); /** * Navigator */ if (!$previewgrp && !$previewquestion) { $aNavigator = surveymover(); $moveprevbutton = $aNavigator['sMovePrevButton']; $movenextbutton = $aNavigator['sMoveNextButton']; $navigator = $moveprevbutton . ' ' . $movenextbutton; $redata = compact(array_keys(get_defined_vars())); echo "\n\n<!-- PRESENT THE NAVIGATOR -->\n"; echo templatereplace(file_get_contents($sTemplateViewPath . "navigator.pstpl"), array(), $redata); echo "\n"; if ($thissurvey['active'] != "Y") { echo "<p style='text-align:center' class='error'>" . 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); $this->createIncrementalQuestionIndexMenu($LEMsessid, $surveyMode); } elseif ($surveyMode != 'survey' && $thissurvey['questionindex'] == 2) { $this->createFullQuestionIndex($LEMsessid, $surveyMode); $this->createFullQuestionIndexMenu($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($sTemplateViewPath . "endpage.pstpl"), array(), $redata); echo "\n"; doFooter(); }
/** * 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); } }
private function _showReorderForm($iSurveyID) { // Prepare data for the view $sBaseLanguage = Survey::model()->findByPk($iSurveyID)->language; LimeExpressionManager::StartSurvey($iSurveyID, 'survey'); LimeExpressionManager::StartProcessingPage(true, Yii::app()->baseUrl); $aGrouplist = QuestionGroup::model()->getGroups($iSurveyID); $initializedReplacementFields = false; foreach ($aGrouplist as $iGID => $aGroup) { LimeExpressionManager::StartProcessingGroup($aGroup['gid'], false, $iSurveyID); if (!$initializedReplacementFields) { templatereplace("{SITENAME}"); // Hack to ensure the EM sets values of LimeReplacementFields $initializedReplacementFields = true; } $oQuestionData = Question::model()->getQuestions($iSurveyID, $aGroup['gid'], $sBaseLanguage); $qs = array(); $junk = array(); foreach ($oQuestionData->readAll() as $q) { $relevance = $q['relevance'] == '' ? 1 : $q['relevance']; $question = '[{' . $relevance . '}] ' . $q['question']; LimeExpressionManager::ProcessString($question, $q['qid']); $q['question'] = LimeExpressionManager::GetLastPrettyPrintExpression(); $q['gid'] = $aGroup['gid']; $qs[] = $q; } $aGrouplist[$iGID]['questions'] = $qs; LimeExpressionManager::FinishProcessingGroup(); } LimeExpressionManager::FinishProcessingPage(); $aData['aGroupsAndQuestions'] = $aGrouplist; $aData['surveyid'] = $iSurveyID; $this->_renderWrappedTemplate('survey', 'organizeGroupsAndQuestions_view', $aData); }
/** * printanswers::view() * View answers at the end of a survey in one place. To export as pdf, set 'usepdfexport' = 1 in lsconfig.php and $printableexport='pdf'. * @param mixed $surveyid * @param bool $printableexport * @return */ function actionView($surveyid, $printableexport = FALSE) { Yii::app()->loadHelper("frontend"); Yii::import('application.libraries.admin.pdf'); $iSurveyID = (int) $surveyid; $sExportType = $printableexport; Yii::app()->loadHelper('database'); if (isset($_SESSION['survey_' . $iSurveyID]['sid'])) { $iSurveyID = $_SESSION['survey_' . $iSurveyID]['sid']; } else { //die('Invalid survey/session'); } // Get the survey inforamtion // Set the language for dispay if (isset($_SESSION['survey_' . $iSurveyID]['s_lang'])) { $sLanguage = $_SESSION['survey_' . $iSurveyID]['s_lang']; } elseif (Survey::model()->findByPk($iSurveyID)) { $sLanguage = Survey::model()->findByPk($iSurveyID)->language; } else { $iSurveyID = 0; $sLanguage = Yii::app()->getConfig("defaultlang"); } $clang = SetSurveyLanguage($iSurveyID, $sLanguage); $aSurveyInfo = getSurveyInfo($iSurveyID, $sLanguage); //SET THE TEMPLATE DIRECTORY if (!isset($aSurveyInfo['templatedir']) || !$aSurveyInfo['templatedir']) { $aSurveyInfo['templatedir'] = Yii::app()->getConfig('defaulttemplate'); } $sTemplate = validateTemplateDir($aSurveyInfo['templatedir']); //Survey is not finished or don't exist if (!isset($_SESSION['survey_' . $iSurveyID]['finished']) || !isset($_SESSION['survey_' . $iSurveyID]['srid'])) { sendCacheHeaders(); doHeader(); echo templatereplace(file_get_contents(getTemplatePath($sTemplate) . '/startpage.pstpl'), array()); echo "<center><br />\n" . "\t<font color='RED'><strong>" . $clang->gT("Error") . "</strong></font><br />\n" . "\t" . $clang->gT("We are sorry but your session has expired.") . "<br />" . $clang->gT("Either you have been inactive for too long, you have cookies disabled for your browser, or there were problems with your connection.") . "<br />\n" . "\t" . sprintf($clang->gT("Please contact %s ( %s ) for further assistance."), Yii::app()->getConfig("siteadminname"), Yii::app()->getConfig("siteadminemail")) . "\n" . "</center><br />\n"; echo templatereplace(file_get_contents(getTemplatePath($sTemplate) . '/endpage.pstpl'), array()); doFooter(); exit; } //Fin session time out $sSRID = $_SESSION['survey_' . $iSurveyID]['srid']; //I want to see the answers with this id //Ensure script is not run directly, avoid path disclosure //if (!isset($rootdir) || isset($_REQUEST['$rootdir'])) {die( "browse - Cannot run this script directly");} if ($aSurveyInfo['printanswers'] == 'N') { die; //Die quietly if print answers is not permitted } //CHECK IF SURVEY IS ACTIVATED AND EXISTS $sSurveyName = $aSurveyInfo['surveyls_title']; $sAnonymized = $aSurveyInfo['anonymized']; //OK. IF WE GOT THIS FAR, THEN THE SURVEY EXISTS AND IT IS ACTIVE, SO LETS GET TO WORK. //SHOW HEADER $sOutput = CHtml::form(array("printanswers/view/surveyid/{$iSurveyID}/printableexport/pdf"), 'post') . "<center><input type='submit' value='" . $clang->gT("PDF export") . "'id=\"exportbutton\"/><input type='hidden' name='printableexport' /></center></form>"; if ($sExportType == 'pdf') { //require (Yii::app()->getConfig('rootdir').'/application/config/tcpdf.php'); Yii::import('application.libraries.admin.pdf', true); Yii::import('application.helpers.pdfHelper'); $aPdfLanguageSettings = pdfHelper::getPdfLanguageSettings($clang->langcode); $oPDF = new pdf(); $oPDF->SetTitle($clang->gT("Survey name (ID)", 'unescaped') . ": {$sSurveyName} ({$iSurveyID})"); $oPDF->SetSubject($sSurveyName); $oPDF->SetDisplayMode('fullpage', 'two'); $oPDF->setLanguageArray($aPdfLanguageSettings['lg']); $oPDF->setHeaderFont(array($aPdfLanguageSettings['pdffont'], '', PDF_FONT_SIZE_MAIN)); $oPDF->setFooterFont(array($aPdfLanguageSettings['pdffont'], '', PDF_FONT_SIZE_DATA)); $oPDF->SetFont($aPdfLanguageSettings['pdffont'], '', $aPdfLanguageSettings['pdffontsize']); $oPDF->AddPage(); $oPDF->titleintopdf($clang->gT("Survey name (ID)", 'unescaped') . ": {$sSurveyName} ({$iSurveyID})"); } $sOutput .= "\t<div class='printouttitle'><strong>" . $clang->gT("Survey name (ID):") . "</strong> {$sSurveyName} ({$iSurveyID})</div><p> \n"; LimeExpressionManager::StartProcessingPage(true); // means that all variables are on the same page // Since all data are loaded, and don't need JavaScript, pretend all from Group 1 LimeExpressionManager::StartProcessingGroup(1, $aSurveyInfo['anonymized'] != "N", $iSurveyID); $printanswershonorsconditions = Yii::app()->getConfig('printanswershonorsconditions'); $aFullResponseTable = getFullResponseTable($iSurveyID, $sSRID, $sLanguage, $printanswershonorsconditions); //Get the fieldmap @TODO: do we need to filter out some fields? if ($aSurveyInfo['datestamp'] != "Y" || $sAnonymized == 'Y') { unset($aFullResponseTable['submitdate']); } else { unset($aFullResponseTable['id']); } unset($aFullResponseTable['token']); unset($aFullResponseTable['lastpage']); unset($aFullResponseTable['startlanguage']); unset($aFullResponseTable['datestamp']); unset($aFullResponseTable['startdate']); $sOutput .= "<table class='printouttable' >\n"; foreach ($aFullResponseTable as $sFieldname => $fname) { if (substr($sFieldname, 0, 4) == 'gid_') { $sOutput .= "\t<tr class='printanswersgroup'><td colspan='2'>{$fname[0]}</td></tr>\n"; } elseif (substr($sFieldname, 0, 4) == 'qid_') { $sOutput .= "\t<tr class='printanswersquestionhead'><td colspan='2'>{$fname[0]}</td></tr>\n"; } elseif ($sFieldname == 'submitdate') { if ($sAnonymized != 'Y') { $sOutput .= "\t<tr class='printanswersquestion'><td>{$fname[0]} {$fname[1]} {$sFieldname}</td><td class='printanswersanswertext'>{$fname[2]}</td></tr>"; } } else { $sOutput .= "\t<tr class='printanswersquestion'><td>{$fname[0]} {$fname[1]}</td><td class='printanswersanswertext'>" . flattenText($fname[2]) . "</td></tr>"; } } $sOutput .= "</table>\n"; $sData['thissurvey'] = $aSurveyInfo; $sOutput = templatereplace($sOutput, array(), $sData, '', $aSurveyInfo['anonymized'] == "Y", NULL, array(), true); // Do a static replacement if ($sExportType == 'pdf') { $oPDF->writeHTML($sOutput); header("Pragma: public"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); $sExportFileName = sanitize_filename($sSurveyName); $oPDF->Output($sExportFileName . "-" . $iSurveyID . ".pdf", "D"); } else { ob_start(function ($buffer, $phase) { App()->getClientScript()->render($buffer); App()->getClientScript()->reset(); return $buffer; }); ob_implicit_flush(false); sendCacheHeaders(); doHeader(); echo templatereplace(file_get_contents(getTemplatePath($sTemplate) . '/startpage.pstpl'), array(), $sData); echo templatereplace(file_get_contents(getTemplatePath($sTemplate) . '/printanswers.pstpl'), array('ANSWERTABLE' => $sOutput), $sData); echo templatereplace(file_get_contents(getTemplatePath($sTemplate) . '/endpage.pstpl'), array(), $sData); echo "</body></html>"; ob_flush(); } LimeExpressionManager::FinishProcessingGroup(); LimeExpressionManager::FinishProcessingPage(); }
/** * 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(); }
/** * 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; }
/** * printanswers::view() * View answers at the end of a survey in one place. To export as pdf, set 'usepdfexport' = 1 in lsconfig.php and $printableexport='pdf'. * @param mixed $surveyid * @param bool $printableexport * @return */ function actionView($surveyid, $printableexport = FALSE) { global $siteadminname, $siteadminemail; Yii::app()->loadHelper("frontend"); Yii::import('application.libraries.admin.pdf'); $surveyid = (int) $surveyid; Yii::app()->loadHelper('database'); if (isset($_SESSION['survey_' . $surveyid]['sid'])) { $surveyid = $_SESSION['survey_' . $surveyid]['sid']; } else { die('Invalid survey/session'); } //Debut session time out if (!isset($_SESSION['survey_' . $surveyid]['finished']) || !isset($_SESSION['survey_' . $surveyid]['srid'])) { //require_once($rootdir.'/classes/core/language.php'); $baselang = Survey::model()->findByPk($surveyid)->language; Yii::import('application.libraries.Limesurvey_lang', true); $clang = new Limesurvey_lang($baselang); //A nice exit sendCacheHeaders(); doHeader(); echo templatereplace(file_get_contents(getTemplatePath(validateTemplateDir("default")) . "/startpage.pstpl"), array(), array()); echo "<center><br />\n" . "\t<font color='RED'><strong>" . $clang->gT("Error") . "</strong></font><br />\n" . "\t" . $clang->gT("We are sorry but your session has expired.") . "<br />" . $clang->gT("Either you have been inactive for too long, you have cookies disabled for your browser, or there were problems with your connection.") . "<br />\n" . "\t" . sprintf($clang->gT("Please contact %s ( %s ) for further assistance."), $siteadminname, $siteadminemail) . "\n" . "</center><br />\n"; echo templatereplace(file_get_contents(getTemplatePath(validateTemplateDir("default")) . "/endpage.pstpl"), array(), array()); doFooter(); exit; } //Fin session time out $id = $_SESSION['survey_' . $surveyid]['srid']; //I want to see the answers with this id $clang = $_SESSION['survey_' . $surveyid]['s_lang']; //Ensure script is not run directly, avoid path disclosure //if (!isset($rootdir) || isset($_REQUEST['$rootdir'])) {die( "browse - Cannot run this script directly");} // Set the language for dispay //require_once($rootdir.'/classes/core/language.php'); // has been secured if (isset($_SESSION['survey_' . $surveyid]['s_lang'])) { $clang = SetSurveyLanguage($surveyid, $_SESSION['survey_' . $surveyid]['s_lang']); $language = $_SESSION['survey_' . $surveyid]['s_lang']; } else { $language = Survey::model()->findByPk($surveyid)->language; $clang = SetSurveyLanguage($surveyid, $language); } // Get the survey inforamtion $thissurvey = getSurveyInfo($surveyid, $language); //SET THE TEMPLATE DIRECTORY if (!isset($thissurvey['templatedir']) || !$thissurvey['templatedir']) { $thistpl = validateTemplateDir("default"); } else { $thistpl = validateTemplateDir($thissurvey['templatedir']); } if ($thissurvey['printanswers'] == 'N') { die; //Die quietly if print answers is not permitted } //CHECK IF SURVEY IS ACTIVATED AND EXISTS $surveytable = "{{survey_{$surveyid}}}"; $surveyname = $thissurvey['surveyls_title']; $anonymized = $thissurvey['anonymized']; //OK. IF WE GOT THIS FAR, THEN THE SURVEY EXISTS AND IT IS ACTIVE, SO LETS GET TO WORK. //SHOW HEADER $printoutput = ''; $printoutput .= "<form action='" . Yii::app()->getController()->createUrl('printanswers/view/surveyid/' . $surveyid . '/printableexport/pdf') . "' method='post'>\n<center><input type='submit' value='" . $clang->gT("PDF export") . "'id=\"exportbutton\"/><input type='hidden' name='printableexport' /></center></form>"; if ($printableexport == 'pdf') { require Yii::app()->getConfig('rootdir') . '/application/config/tcpdf.php'; Yii::import('application.libraries.admin.pdf', true); $pdf = new pdf(); $pdf->setConfig($tcpdf); //$pdf->SetFont($pdfdefaultfont,'',$pdffontsize); $pdf->AddPage(); //$pdf->titleintopdf($clang->gT("Survey name (ID)",'unescaped').": {$surveyname} ({$surveyid})"); $pdf->SetTitle($clang->gT("Survey name (ID)", 'unescaped') . ": {$surveyname} ({$surveyid})"); } $printoutput .= "\t<div class='printouttitle'><strong>" . $clang->gT("Survey name (ID):") . "</strong> {$surveyname} ({$surveyid})</div><p> \n"; LimeExpressionManager::StartProcessingPage(true); // means that all variables are on the same page // Since all data are loaded, and don't need JavaScript, pretend all from Group 1 LimeExpressionManager::StartProcessingGroup(1, $thissurvey['anonymized'] != "N", $surveyid); $aFullResponseTable = getFullResponseTable($surveyid, $id, $language, true); //Get the fieldmap @TODO: do we need to filter out some fields? unset($aFullResponseTable['id']); unset($aFullResponseTable['token']); unset($aFullResponseTable['lastpage']); unset($aFullResponseTable['startlanguage']); unset($aFullResponseTable['datestamp']); unset($aFullResponseTable['startdate']); $printoutput .= "<table class='printouttable' >\n"; if ($printableexport == 'pdf') { $pdf->intopdf($clang->gT("Question", 'unescaped') . ": " . $clang->gT("Your answer", 'unescaped')); } $oldgid = 0; $oldqid = 0; foreach ($aFullResponseTable as $sFieldname => $fname) { if (substr($sFieldname, 0, 4) == 'gid_') { if ($printableexport) { $pdf->intopdf(flattenText($fname[0], false, true)); $pdf->ln(2); } else { $printoutput .= "\t<tr class='printanswersgroup'><td colspan='2'>{$fname[0]}</td></tr>\n"; } } elseif (substr($sFieldname, 0, 4) == 'qid_') { if ($printableexport == 'pdf') { $pdf->intopdf(flattenText($fname[0] . $fname[1], false, true) . ": " . $fname[2]); $pdf->ln(2); } else { $printoutput .= "\t<tr class='printanswersquestionhead'><td colspan='2'>{$fname[0]}</td></tr>\n"; } } elseif ($sFieldname == 'submitdate') { if ($anonymized != 'Y') { if ($printableexport == 'pdf') { $pdf->intopdf(flattenText($fname[0] . $fname[1], false, true) . ": " . $fname[2]); $pdf->ln(2); } else { $printoutput .= "\t<tr class='printanswersquestion'><td>{$fname[0]} {$fname[1]} {$sFieldname}</td><td class='printanswersanswertext'>{$fname[2]}</td></tr>"; } } } else { if ($printableexport == 'pdf') { $pdf->intopdf(flattenText($fname[0] . $fname[1], false, true) . ": " . $fname[2]); $pdf->ln(2); } else { $printoutput .= "\t<tr class='printanswersquestion'><td>{$fname[0]} {$fname[1]}</td><td class='printanswersanswertext'>{$fname[2]}</td></tr>"; } } } $printoutput .= "</table>\n"; if ($printableexport == 'pdf') { header("Pragma: public"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); $sExportFileName = sanitize_filename($surveyname); $pdf->Output($sExportFileName . "-" . $surveyid . ".pdf", "D"); } //Display the page with user answers if (!$printableexport) { sendCacheHeaders(); doHeader(); echo templatereplace(file_get_contents(getTemplatePath($thistpl) . '/startpage.pstpl')); echo templatereplace(file_get_contents(getTemplatePath($thistpl) . '/printanswers.pstpl'), array('ANSWERTABLE' => $printoutput)); echo templatereplace(file_get_contents(getTemplatePath($thistpl) . '/endpage.pstpl')); echo "</body></html>"; } LimeExpressionManager::FinishProcessingGroup(); LimeExpressionManager::FinishProcessingPage(); }
/** * Unit test Relevance using a simplified syntax to represent questions. */ static function UnitTestRelevance() { // Tests: varName~relevance~inputType~message $tests = <<<EOT name~1~text~What is your name? age~1~text~How old are you (must be 16-80)? badage~1~expr~{badage=((age<16) || (age>80))} agestop~!is_empty(age) && ((age<16) || (age>80))~message~Sorry, {name}, you are too {if((age<16),'young',if((age>80),'old','middle-aged'))} for this test. kids~!((age<16) || (age>80))~yesno~Do you have children (Y/N)? kidsO~!is_empty(kids) && !(kids=='Y' or kids=='N')~message~Please answer the question about whether you have children with 'Y' or 'N'. wantsKids~kids=='N'~yesno~Do you hope to have kids some day (Y/N)? wantsKidsY~wantsKids=='Y'~message~{name}, I hope you are able to have children some day! wantsKidsN~wantsKids=='N'~message~{name}, I hope you have a wonderfully fulfilling life! wantsKidsO~!is_empty(wantsKids) && !(wantsKids=='Y' or wantsKids=='N')~message~Please answer the question about whether you want children with 'Y' or 'N'. parents~1~expr~{parents = (!badage && kids=='Y')} numKids~kids=='Y'~text~How many children do you have? numKidsValidation~parents and strlen(numKids) > 0 and numKids <= 0~message~{name}, please check your entries. You said you do have children, {numKids} of them, which makes no sense. kid1~numKids >= 1~text~How old is your first child? kid2~numKids >= 2~text~How old is your second child? kid3~numKids >= 3~text~How old is your third child? kid4~numKids >= 4~text~How old is your fourth child? kid5~numKids >= 5~text~How old is your fifth child? sumage~1~expr~{sumage=sum(kid1.NAOK,kid2.NAOK,kid3.NAOK,kid4.NAOK,kid5.NAOK)} report~numKids > 0~message~{name}, you said you are {age} and that you have {numKids} kids. The sum of ages of your first {min(numKids,5)} kids is {sumage}. EOT; $vars = array(); $varsNAOK = array(); $varSeq = array(); $testArgs = array(); $argInfo = array(); LimeExpressionManager::SetDirtyFlag(); $LEM =& LimeExpressionManager::singleton(); LimeExpressionManager::StartProcessingPage(true); LimeExpressionManager::StartProcessingGroup(1); // pretending this is group 1 // collect variables $i = 0; foreach (explode("\n", $tests) as $test) { $args = explode("~", $test); $type = $args[1] == 'expr' ? '*' : $args[1] == 'message' ? 'X' : 'S'; $vars[$args[0]] = array('sgqa' => $args[0], 'code' => '', 'jsName' => 'java' . $args[0], 'jsName_on' => 'java' . $args[0], 'readWrite' => 'Y', 'type' => $type, 'relevanceStatus' => '1', 'gid' => 1, 'gseq' => 1, 'qseq' => $i, 'qid' => $i); $varSeq[] = $args[0]; $testArgs[] = $args; $LEM->questionId2questionSeq[$i] = $i; $LEM->questionId2groupSeq[$i] = 1; $LEM->questionSeq2relevance[$i] = array('relevance' => htmlspecialchars(preg_replace('/[[:space:]]/', ' ', $args[1]), ENT_QUOTES), 'qid' => $i, 'qseq' => $i, 'gseq' => 1, 'jsResultVar' => 'java' . $args[0], 'type' => $type, 'hidden' => false, 'gid' => 1); ++$i; } $LEM->knownVars = $vars; $LEM->gRelInfo[1] = array('gid' => 1, 'gseq' => 1, 'eqn' => '', 'result' => 1, 'numJsVars' => 0, 'relevancejs' => '', 'relevanceVars' => '', 'prettyPrint' => ''); $LEM->ProcessAllNeededRelevance(); // collect relevance $alias2varName = array(); $varNameAttr = array(); for ($i = 0; $i < count($testArgs); ++$i) { $testArg = $testArgs[$i]; $var = $testArg[0]; $rel = LimeExpressionManager::QuestionIsRelevant($i); $question = LimeExpressionManager::ProcessString($testArg[3], $i, NULL, true, 1, 1); $jsVarName = 'java' . str_replace('#', '_', $testArg[0]); $argInfo[] = array('num' => $i, 'name' => $jsVarName, 'sgqa' => $testArg[0], 'type' => $testArg[2], 'question' => $question, 'relevance' => $testArg[1], 'relevanceStatus' => $rel); $alias2varName[$var] = array('jsName' => $jsVarName, 'jsPart' => "'" . $var . "':'" . $jsVarName . "'"); $alias2varName[$jsVarName] = array('jsName' => $jsVarName, 'jsPart' => "'" . $jsVarName . "':'" . $jsVarName . "'"); $varNameAttr[$jsVarName] = "'" . $jsVarName . "':{" . "'jsName':'" . $jsVarName . "','jsName_on':'" . $jsVarName . "','sgqa':'" . substr($jsVarName, 4) . "','qid':" . $i . ",'gid':" . 1 . "}"; } $LEM->alias2varName = $alias2varName; $LEM->varNameAttr = $varNameAttr; LimeExpressionManager::FinishProcessingGroup(); LimeExpressionManager::FinishProcessingPage(); print <<<EOD <script type='text/javascript'> <!-- var LEMradix='.'; function checkconditions(value, name, type, evt_type) { if (typeof evt_type === 'undefined') { evt_type = 'onchange'; } ExprMgr_process_relevance_and_tailoring(evt_type,name,type); } // --> </script> EOD; print LimeExpressionManager::GetRelevanceAndTailoringJavaScript(); // Print Table of questions print "<h3>This is a test of dynamic relevance.</h3>"; print "Enter your name and age, and try all the permutations of answers to whether you have or want children.<br />\n"; print "Note how the text and sum of ages changes dynamically; that prior answers are remembered; and that irrelevant values are not included in the sum of ages.<br />"; print "<table class='table' border='1'><tr><td>"; foreach ($argInfo as $arg) { $rel = LimeExpressionManager::QuestionIsRelevant($arg['num']); print "<div id='question" . $arg['num'] . ($rel ? "'" : "' style='display: none'") . ">\n"; print "<input type='hidden' id='display" . $arg['num'] . "' name='" . $arg['num'] . "' value='" . ($rel ? 'on' : '') . "'/>\n"; if ($arg['type'] == 'expr') { // Hack for testing purposes - rather than using LimeSurvey internals to store the results of equations, process them via a hidden <div> print "<div style='display: none' id='hack_" . $arg['name'] . "'>" . $arg['question']; print "<input type='hidden' id='" . $arg['name'] . "' name='" . $arg['name'] . "' value=''/></div>\n"; } else { print "<table class='table' border='1' width='100%'>\n<tr>\n<td>[Q" . $arg['num'] . "] " . $arg['question'] . "</td>\n"; switch ($arg['type']) { case 'yesno': case 'text': print "<td><input type='text' id='" . $arg['name'] . "' name='" . $arg['sgqa'] . "' value='' onchange='checkconditions(this.value, this.name, this.type)'/></td>\n"; break; case 'message': print "<input type='hidden' id='" . $arg['name'] . "' name='" . $arg['sgqa'] . "' value=''/>\n"; break; } print "</tr>\n</table>\n"; } print "</div>\n"; } print "</table>"; LimeExpressionManager::SetDirtyFlag(); // so subsequent tests don't try to access these variables }
/** * printanswers::view() * View answers at the end of a survey in one place. To export as pdf, set 'usepdfexport' = 1 in lsconfig.php and $printableexport='pdf'. * @param mixed $surveyid * @param bool $printableexport * @return */ function actionView($surveyid, $printableexport = FALSE) { Yii::app()->loadHelper("frontend"); Yii::import('application.libraries.admin.pdf'); $iSurveyID = (int) $surveyid; $sExportType = $printableexport; Yii::app()->loadHelper('database'); if (isset($_SESSION['survey_' . $iSurveyID]['sid'])) { $iSurveyID = $_SESSION['survey_' . $iSurveyID]['sid']; } else { //die('Invalid survey/session'); } // Get the survey inforamtion // Set the language for dispay if (isset($_SESSION['survey_' . $iSurveyID]['s_lang'])) { $sLanguage = $_SESSION['survey_' . $iSurveyID]['s_lang']; } elseif (Survey::model()->findByPk($iSurveyID)) { $sLanguage = Survey::model()->findByPk($iSurveyID)->language; } else { $iSurveyID = 0; $sLanguage = Yii::app()->getConfig("defaultlang"); } SetSurveyLanguage($iSurveyID, $sLanguage); $aSurveyInfo = getSurveyInfo($iSurveyID, $sLanguage); $oTemplate = Template::model()->getInstance(null, $iSurveyID); //Survey is not finished or don't exist if (!isset($_SESSION['survey_' . $iSurveyID]['finished']) || !isset($_SESSION['survey_' . $iSurveyID]['srid'])) { sendCacheHeaders(); doHeader(); /// $oTemplate is a global variable defined in controller/survey/index echo templatereplace(file_get_contents($oTemplate->viewPath . '/startpage.pstpl'), array()); echo "<center><br />\n" . "\t<font color='RED'><strong>" . gT("Error") . "</strong></font><br />\n" . "\t" . gT("We are sorry but your session has expired.") . "<br />" . gT("Either you have been inactive for too long, you have cookies disabled for your browser, or there were problems with your connection.") . "<br />\n" . "\t" . sprintf(gT("Please contact %s ( %s ) for further assistance."), Yii::app()->getConfig("siteadminname"), Yii::app()->getConfig("siteadminemail")) . "\n" . "</center><br />\n"; echo templatereplace(file_get_contents($oTemplate->viewPath . '/endpage.pstpl'), array()); doFooter(); exit; } //Fin session time out $sSRID = $_SESSION['survey_' . $iSurveyID]['srid']; //I want to see the answers with this id //Ensure script is not run directly, avoid path disclosure //if (!isset($rootdir) || isset($_REQUEST['$rootdir'])) {die( "browse - Cannot run this script directly");} //Ensure Participants printAnswer setting is set to true or that the logged user have read permissions over the responses. if ($aSurveyInfo['printanswers'] == 'N' && !Permission::model()->hasSurveyPermission($iSurveyID, 'responses', 'read')) { throw new CHttpException(401, 'You are not allowed to print answers.'); } //CHECK IF SURVEY IS ACTIVATED AND EXISTS $sSurveyName = $aSurveyInfo['surveyls_title']; $sAnonymized = $aSurveyInfo['anonymized']; //OK. IF WE GOT THIS FAR, THEN THE SURVEY EXISTS AND IT IS ACTIVE, SO LETS GET TO WORK. //SHOW HEADER if ($sExportType != 'pdf') { $sOutput = CHtml::form(array("printanswers/view/surveyid/{$iSurveyID}/printableexport/pdf"), 'post') . "<center><input class='btn btn-default' type='submit' value='" . gT("PDF export") . "'id=\"exportbutton\"/><input type='hidden' name='printableexport' /></center></form>"; $sOutput .= "\t<div class='printouttitle'><strong>" . gT("Survey name (ID):") . "</strong> {$sSurveyName} ({$iSurveyID})</div><p> \n"; LimeExpressionManager::StartProcessingPage(true); // means that all variables are on the same page // Since all data are loaded, and don't need JavaScript, pretend all from Group 1 LimeExpressionManager::StartProcessingGroup(1, $aSurveyInfo['anonymized'] != "N", $iSurveyID); $printanswershonorsconditions = Yii::app()->getConfig('printanswershonorsconditions'); $aFullResponseTable = getFullResponseTable($iSurveyID, $sSRID, $sLanguage, $printanswershonorsconditions); //Get the fieldmap @TODO: do we need to filter out some fields? if ($aSurveyInfo['datestamp'] != "Y" || $sAnonymized == 'Y') { unset($aFullResponseTable['submitdate']); } else { unset($aFullResponseTable['id']); } unset($aFullResponseTable['token']); unset($aFullResponseTable['lastpage']); unset($aFullResponseTable['startlanguage']); unset($aFullResponseTable['datestamp']); unset($aFullResponseTable['startdate']); $sOutput .= "<table class='printouttable' >\n"; foreach ($aFullResponseTable as $sFieldname => $fname) { if (substr($sFieldname, 0, 4) == 'gid_') { $sOutput .= "\t<tr class='printanswersgroup'><td colspan='2'>{$fname[0]}</td></tr>\n"; $sOutput .= "\t<tr class='printanswersgroupdesc'><td colspan='2'>{$fname[1]}</td></tr>\n"; } elseif ($sFieldname == 'submitdate') { if ($sAnonymized != 'Y') { $sOutput .= "\t<tr class='printanswersquestion'><td>{$fname[0]} {$fname[1]} {$sFieldname}</td><td class='printanswersanswertext'>{$fname[2]}</td></tr>"; } } elseif (substr($sFieldname, 0, 4) != 'qid_') { $sOutput .= "\t<tr class='printanswersquestion'><td>{$fname[0]} {$fname[1]}</td><td class='printanswersanswertext'>" . flattenText($fname[2]) . "</td></tr>"; } } $sOutput .= "</table>\n"; $sData['thissurvey'] = $aSurveyInfo; $sOutput = templatereplace($sOutput, array(), $sData, '', $aSurveyInfo['anonymized'] == "Y", NULL, array(), true); // Do a static replacement ob_start(function ($buffer, $phase) { App()->getClientScript()->render($buffer); App()->getClientScript()->reset(); return $buffer; }); ob_implicit_flush(false); sendCacheHeaders(); doHeader(); echo templatereplace(file_get_contents($oTemplate->viewPath . '/startpage.pstpl'), array(), $sData); echo templatereplace(file_get_contents($oTemplate->viewPath . '/printanswers.pstpl'), array('ANSWERTABLE' => $sOutput), $sData); echo templatereplace(file_get_contents($oTemplate->viewPath . '/endpage.pstpl'), array(), $sData); echo "</body></html>"; ob_flush(); } if ($sExportType == 'pdf') { // Get images for TCPDF from template directory define('K_PATH_IMAGES', getTemplatePath($aSurveyInfo['template']) . DIRECTORY_SEPARATOR); Yii::import('application.libraries.admin.pdf', true); Yii::import('application.helpers.pdfHelper'); $aPdfLanguageSettings = pdfHelper::getPdfLanguageSettings(App()->language); $oPDF = new pdf(); $sDefaultHeaderString = $sSurveyName . " (" . gT("ID", 'unescaped') . ":" . $iSurveyID . ")"; $oPDF->initAnswerPDF($aSurveyInfo, $aPdfLanguageSettings, Yii::app()->getConfig('sitename'), $sSurveyName, $sDefaultHeaderString); LimeExpressionManager::StartProcessingPage(true); // means that all variables are on the same page // Since all data are loaded, and don't need JavaScript, pretend all from Group 1 LimeExpressionManager::StartProcessingGroup(1, $aSurveyInfo['anonymized'] != "N", $iSurveyID); $printanswershonorsconditions = Yii::app()->getConfig('printanswershonorsconditions'); $aFullResponseTable = getFullResponseTable($iSurveyID, $sSRID, $sLanguage, $printanswershonorsconditions); //Get the fieldmap @TODO: do we need to filter out some fields? if ($aSurveyInfo['datestamp'] != "Y" || $sAnonymized == 'Y') { unset($aFullResponseTable['submitdate']); } else { unset($aFullResponseTable['id']); } unset($aFullResponseTable['token']); unset($aFullResponseTable['lastpage']); unset($aFullResponseTable['startlanguage']); unset($aFullResponseTable['datestamp']); unset($aFullResponseTable['startdate']); foreach ($aFullResponseTable as $sFieldname => $fname) { if (substr($sFieldname, 0, 4) == 'gid_') { $oPDF->addGidAnswer($fname[0], $fname[1]); } elseif ($sFieldname == 'submitdate') { if ($sAnonymized != 'Y') { $oPDF->addAnswer($fname[0] . " " . $fname[1], $fname[2]); } } elseif (substr($sFieldname, 0, 4) != 'qid_') { $oPDF->addAnswer($fname[0] . " " . $fname[1], $fname[2]); } } header("Pragma: public"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); $sExportFileName = sanitize_filename($sSurveyName); $oPDF->Output($sExportFileName . "-" . $iSurveyID . ".pdf", "D"); } LimeExpressionManager::FinishProcessingGroup(); LimeExpressionManager::FinishProcessingPage(); }
/** * 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); } }
} else { $question['man_class'] = ''; } $content = templatereplace(file_get_contents("{$thistpl}/startpage.pstpl")); $content .= '<form method="post" action="index.php" id="limesurvey" name="limesurvey" autocomplete="off">'; $content .= templatereplace(file_get_contents("{$thistpl}/startgroup.pstpl")); $question_template = file_get_contents("{$thistpl}/question.pstpl"); if (substr_count($question_template, '{QUESTION_ESSENTIALS}') > 0) { // LS 1.87 and newer templates $content .= "\n" . templatereplace($question_template, NULL, 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, NULL, false, $qid) . "\n"; $content .= "\n\t</div>\n"; } $content .= templatereplace(file_get_contents("{$thistpl}/endgroup.pstpl")) . $dummy_js; LimeExpressionManager::FinishProcessingGroup(); $content .= LimeExpressionManager::GetRelevanceAndTailoringJavaScript(); $content .= '<p> </form>'; 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"; } $content .= templatereplace(file_get_contents("{$thistpl}/endpage.pstpl")); echo "</html>\n"; exit;
/** * Show the form for Organize question groups/questions * * @todo Change function name to _showOrganizeGroupsAndQuestions? * @param int $iSurveyID * @return void */ private function _showReorderForm($iSurveyID) { $surveyinfo = Survey::model()->findByPk($iSurveyID)->surveyinfo; $aData['title_bar']['title'] = $surveyinfo['surveyls_title'] . "(" . gT("ID") . ":" . $iSurveyID . ")"; // Prepare data for the view $sBaseLanguage = Survey::model()->findByPk($iSurveyID)->language; LimeExpressionManager::StartSurvey($iSurveyID, 'survey'); LimeExpressionManager::StartProcessingPage(true, Yii::app()->baseUrl); $aGrouplist = QuestionGroup::model()->getGroups($iSurveyID); $initializedReplacementFields = false; $aData['organizebar']['savebuttonright'] = true; //$aData['organizebar']['returnbutton']['url'] = $this->getController()->createUrl("admin/survey/sa/view/", array('surveyid' => $iSurveyID)); //$aData['organizebar']['returnbutton']['text'] = gT('Return to survey summary'); foreach ($aGrouplist as $iGID => $aGroup) { LimeExpressionManager::StartProcessingGroup($aGroup['gid'], false, $iSurveyID); if (!$initializedReplacementFields) { templatereplace("{SITENAME}"); // Hack to ensure the EM sets values of LimeReplacementFields $initializedReplacementFields = true; } $oQuestionData = Question::model()->getQuestions($iSurveyID, $aGroup['gid'], $sBaseLanguage); $qs = array(); $junk = array(); foreach ($oQuestionData->readAll() as $q) { $relevance = $q['relevance'] == '' ? 1 : $q['relevance']; $question = '[{' . $relevance . '}] ' . $q['question']; LimeExpressionManager::ProcessString($question, $q['qid']); $q['question'] = viewHelper::stripTagsEM(LimeExpressionManager::GetLastPrettyPrintExpression()); $q['gid'] = $aGroup['gid']; $qs[] = $q; } $aGrouplist[$iGID]['questions'] = $qs; LimeExpressionManager::FinishProcessingGroup(); } LimeExpressionManager::FinishProcessingPage(); $aData['aGroupsAndQuestions'] = $aGrouplist; $aData['surveyid'] = $iSurveyID; $this->_renderWrappedTemplate('survey', 'organizeGroupsAndQuestions_view', $aData); }
echo templatereplace($question_template, NULL, 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("{$thistpl}/endgroup.pstpl")); echo "\n\n</div>\n"; } } LimeExpressionManager::FinishProcessingGroup($LEMskipReprocessing); echo LimeExpressionManager::GetRelevanceAndTailoringJavaScript(); LimeExpressionManager::FinishProcessingPage(); if (!$previewgrp) { $navigator = surveymover(); //This gets globalised in the templatereplace function echo "\n\n<!-- PRESENT THE NAVIGATOR -->\n"; echo templatereplace(file_get_contents("{$thistpl}/navigator.pstpl")); 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();