</td>
        </tr>
        <?php 
}
?>
    <?php 
if (trim($qrrow['relevance']) != '') {
    ?>
        <tr>
            <td><?php 
    $clang->eT("Relevance equation:");
    ?>
</td>
            <td>
                <?php 
    LimeExpressionManager::ProcessString("{" . $qrrow['relevance'] . "}", $qid);
    // tests Relevance equation so can pretty-print it
    echo LimeExpressionManager::GetLastPrettyPrintExpression();
    ?>
            </td>
        </tr>
        <?php 
}
?>
    <?php 
$sCurrentCategory = '';
foreach ($advancedsettings as $aAdvancedSetting) {
    ?>
        <tr>
            <td><?php 
    echo $aAdvancedSetting['caption'];
Exemplo n.º 2
0
 /**
  * Evaluates an expression via Expression Manager
  * Uses the current context.
  * @param string $expression
  * @return string
  */
 public function EMevaluateExpression($expression)
 {
     $result = LimeExpressionManager::ProcessString($expression);
     return $result;
 }
Exemplo n.º 3
0
    /**
     * 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>&nbsp;\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();
    }
 /**
  * This event is fired by when a response is submitted
  * available for a survey.
  * @param PluginEvent $event
  */
 public function afterSurveyComplete()
 {
     // This method will send a notification email
     $event = $this->getEvent();
     $surveyId = $event->get('surveyId');
     // Only process the afterSurveyComplete if the plugin is Enabled for this survey and if the survey is Active
     if ($this->get('emailCount', 'Survey', $surveyId) < 1 || Survey::model()->findByPk($surveyId)->active != "Y") {
         // leave gracefully
         return true;
     }
     // Retrieve response and survey properties
     $responseId = $event->get('responseId');
     $response = $this->pluginManager->getAPI()->getResponse($surveyId, $responseId);
     $sitename = $this->pluginManager->getAPI()->getConfigKey('sitename');
     $surveyInfo = getSurveyInfo($surveyId);
     $adminemail = $surveyInfo['adminemail'];
     $bounce_email = $surveyInfo['bounce_email'];
     $isHtmlEmail = $surveyInfo['htmlemail'] == 'Y';
     $baseLang = $surveyInfo['language'];
     for ($i = 1; $i <= $this->get('emailCount', 'Survey', $surveyId); $i++) {
         // Let's check if there is at least a valid destination email address
         $aTo = array();
         $aAttachTo = array();
         $aDestEmail = explode(';', $this->pluginManager->getAPI()->EMevaluateExpression($this->get('emailDestinations_' . $i, 'Survey', $surveyId)));
         $aDestEmail = array_map('trim', $aDestEmail);
         $aUploadQuestions = explode(';', $this->pluginManager->getAPI()->EMevaluateExpression($this->get('emailAttachFiles_' . $i, 'Survey', $surveyId)));
         $aUploadQuestions = array_map('trim', $aUploadQuestions);
         // prepare an array of valid destination email addresses
         foreach ($aDestEmail as $destemail) {
             if (validateEmailAddress($destemail)) {
                 $aTo[] = $destemail;
             }
         }
         // prepare an array of valid attached files from upload-questions
         foreach ($aUploadQuestions as $uploadQuestion) {
             $sgqa = 0;
             $qtype = '';
             if (isset($response[$uploadQuestion])) {
                 // get SGQA code from question-code. Ther might be a better way to do this though...
                 $sgqa = $this->pluginManager->getAPI()->EMevaluateExpression('{' . $uploadQuestion . '.sgqa}');
                 $qtype = $this->pluginManager->getAPI()->EMevaluateExpression('{' . $uploadQuestion . '.type}');
             }
             // Only add the file if question is relevant
             if ($sgqa != 0 && $qtype == "|" && \LimeExpressionManager::QuestionIsRelevant($sgqa)) {
                 $aFiles = json_decode($response[$uploadQuestion]);
                 if (!is_null($aFiles) && is_array($aFiles)) {
                     foreach ($aFiles as $file) {
                         if (property_exists($file, 'name') && property_exists($file, 'filename')) {
                             $name = $file->name;
                             $filename = $file->filename;
                             $aAttachTo[] = array(0 => $this->pluginManager->getAPI()->getConfigKey('uploaddir') . "/surveys/{$surveyId}/files/" . $filename, 1 => $name);
                         }
                     }
                 }
             }
         }
         if (count($aTo) >= 1) {
             // Retrieve the language to use for the notification email
             $emailLang = $this->get('emailLang_' . $i, 'Survey', $surveyId);
             if ($emailLang == '--') {
                 // in this case let's select the language used when submitting the response
                 $emailLang = $response['startlanguage'];
             }
             $subjectTemplate = $this->get("emailSubject_{$i}_{$emailLang}", 'Survey', $surveyId);
             if ($subjectTemplate == "") {
                 // If subject is not translated, use subject and body from the baseLang
                 $emailLang = $baseLang;
                 $subjectTemplate = $this->get("emailSubject_{$i}_{$emailLang}", 'Survey', $surveyId);
             }
             // Process the email subject and body through ExpressionManager
             $subject = $this->pluginManager->getAPI()->EMevaluateExpression($subjectTemplate);
             // Prepare an {ANSWERTABLE} variable
             if ($surveyInfo['datestamp'] == 'N') {
                 //$aFilteredFields=array('id', 'submitdate', 'lastpage', 'startlanguage');
                 // Let's filter submitdate if survey is not datestampped
                 $aFilteredFields = array('submitdate');
             } else {
                 //$aFilteredFields=array('id', 'lastpage', 'startlanguage');
                 $aFilteredFields = array();
             }
             $replacementfields = array('ANSWERTABLE' => $this->translateAnswerTable($surveyId, $responseId, $emailLang, $isHtmlEmail, $aFilteredFields));
             // Process emailBody through EM and replace {ANSWERTABLE}
             $body = \LimeExpressionManager::ProcessString($this->get("emailBody_{$i}_{$emailLang}", 'Survey', $surveyId), NULL, $replacementfields);
             // At last it's time to send the email
             SendEmailMessage($body, $subject, $aTo, $adminemail, $sitename, $isHtmlEmail, $bounce_email, $aAttachTo);
         }
         // END BLOCK 'if' aTo[] not emtpy
     }
     // END BLOCK 'for' emailCount
 }
Exemplo n.º 5
0
function ReplaceFields($text, $fieldsarray, $bReplaceInsertans = true, $staticReplace = true)
{
    if ($bReplaceInsertans) {
        $replacements = array();
        foreach ($fieldsarray as $key => $value) {
            $replacements[substr($key, 1, -1)] = $value;
        }
        $text = LimeExpressionManager::ProcessString($text, NULL, $replacements, false, 2, 1, false, false, $staticReplace);
    } else {
        foreach ($fieldsarray as $key => $value) {
            $text = str_replace($key, $value, $text);
        }
    }
    return $text;
}
Exemplo n.º 6
0
function do_ranking($ia)
{
    global $dbprefix, $imageurl, $clang, $thissurvey, $showpopups;
    $checkconditionFunction = "checkconditions";
    $qidattributes = getQuestionAttributes($ia[0], $ia[4]);
    $answer = "";
    if ($qidattributes['random_order'] == 1) {
        $ansquery = "SELECT * FROM {$dbprefix}answers WHERE qid={$ia['0']} AND language='" . $_SESSION['s_lang'] . "' and scale_id=0 ORDER BY " . db_random();
    } else {
        $ansquery = "SELECT * FROM {$dbprefix}answers WHERE qid={$ia['0']} AND language='" . $_SESSION['s_lang'] . "' and scale_id=0 ORDER BY sortorder, answer";
    }
    $ansresult = db_execute_assoc($ansquery);
    //Checked
    $anscount = $ansresult->RecordCount();
    if (trim($qidattributes["max_answers"]) != '') {
        $max_answers = trim($qidattributes["max_answers"]);
        $max_ans_val = LimeExpressionManager::ProcessString('{' . $max_answers . '}', $ia[0]);
        if (!is_numeric($max_ans_val)) {
            $max_ans_val = $anscount;
        }
    } else {
        $max_answers = $anscount;
        $max_ans_val = $anscount;
    }
    if (trim($qidattributes["min_answers"]) != '') {
        $min_answers = trim($qidattributes["min_answers"]);
    } else {
        $min_answers = 0;
    }
    $answer .= "\t<script type='text/javascript'>\n" . "\t<!--\n" . "function rankthis_{$ia[0]}(\$code, \$value)\n" . "\t{\n" . "\t\$index=document.getElementById('CHOICES_{$ia[0]}').selectedIndex;\n" . "\tvar _maxans = \$.trim(LEMstrip_tags(\$('#RANK_{$ia[0]}_maxans').html()));\n" . "\tvar _minans = \$.trim(LEMstrip_tags(\$('#RANK_{$ia[0]}_minans').html()));\n" . "\tvar maxval = (LEMempty(_maxans) ? {$anscount} : Math.floor(_maxans));\n" . "\tif (({$anscount} - document.getElementById('CHOICES_{$ia[0]}').options.length) >= maxval) {\n" . "\t\tdocument.getElementById('CHOICES_{$ia[0]}').disabled=true;\n" . "\t\tdocument.getElementById('CHOICES_{$ia[0]}').selectedIndex=-1;\n" . "\t\treturn true;\n" . "\t}\n" . "\tfor (i=1; i<=maxval; i++)\n" . "{\n" . "\$b=i;\n" . "\$b += '';\n" . "\$inputname=\"RANK_{$ia[0]}\"+\$b;\n" . "\$hiddenname=\"fvalue_{$ia[0]}\"+\$b;\n" . "\$cutname=\"cut_{$ia[0]}\"+i;\n" . "document.getElementById(\$cutname).style.display='none';\n" . "if (!document.getElementById(\$inputname).value)\n" . "\t{\n" . "\t\t\t\t\t\t\tdocument.getElementById(\$inputname).value=\$value;\n" . "\t\t\t\t\t\t\tdocument.getElementById(\$hiddenname).value=\$code;\n" . "\t\t\t\t\t\t\tdocument.getElementById(\$cutname).style.display='';\n" . "\t\t\t\t\t\t\tfor (var b=document.getElementById('CHOICES_{$ia[0]}').options.length-1; b>=0; b--)\n" . "\t\t\t\t\t\t\t\t{\n" . "\t\t\t\t\t\t\t\tif (document.getElementById('CHOICES_{$ia[0]}').options[b].value == \$code)\n" . "\t\t\t\t\t\t\t\t\t{\n" . "\t\t\t\t\t\t\t\t\tdocument.getElementById('CHOICES_{$ia[0]}').options[b] = null;\n" . "\t\t\t\t\t\t\t\t\t}\n" . "\t\t\t\t\t\t\t\t}\n" . "\t\t\t\t\t\t\ti=maxval;\n" . "\t\t\t\t\t\t\t}\n" . "\t\t\t\t\t\t}\n" . "\t\t\t\t\tif (document.getElementById('CHOICES_{$ia[0]}').options.length == ({$anscount} - maxval))\n" . "\t\t\t\t\t\t{\n" . "\t\t\t\t\t\tdocument.getElementById('CHOICES_{$ia[0]}').disabled=true;\n" . "\t\t\t\t\t\t}\n" . "\t\t\t\t\tdocument.getElementById('CHOICES_{$ia[0]}').selectedIndex=-1;\n" . "\t\t\t\t\t{$checkconditionFunction}(\$code);\n" . "\t\t\t\t\t}\n" . "\t\t\t\tfunction deletethis_{$ia[0]}(\$text, \$value, \$name, \$thisname)\n" . "\t\t\t\t\t{\n" . "\t\t\t\t\tvar qid='{$ia[0]}';\n" . "\t\t\t\t\tvar lngth=qid.length+4;\n" . "\t\t\t\t\tvar cutindex=\$thisname.substring(lngth, \$thisname.length);\n" . "\t\t\t\t\tcutindex=parseFloat(cutindex);\n" . "\t\t\t\t\tdocument.getElementById(\$name).value='';\n" . "\t\t\t\t\tdocument.getElementById(\$thisname).style.display='none';\n" . "\t\t\t\t\tif (cutindex > 1)\n" . "\t\t\t\t\t\t{\n" . "\t\t\t\t\t\t\$cut1name=\"cut_{$ia[0]}\"+(cutindex-1);\n" . "\t\t\t\t\t\t\$cut2name=\"fvalue_{$ia[0]}\"+(cutindex);\n" . "\t\t\t\t\t\tdocument.getElementById(\$cut1name).style.display='';\n" . "\t\t\t\t\t\tdocument.getElementById(\$cut2name).value='';\n" . "\t\t\t\t\t\t}\n" . "\t\t\t\t\telse\n" . "\t\t\t\t\t\t{\n" . "\t\t\t\t\t\t\$cut2name=\"fvalue_{$ia[0]}\"+(cutindex);\n" . "\t\t\t\t\t\tdocument.getElementById(\$cut2name).value='';\n" . "\t\t\t\t\t\t}\n" . "\t\t\t\t\tvar i=document.getElementById('CHOICES_{$ia[0]}').options.length;\n" . "\t\t\t\t\tdocument.getElementById('CHOICES_{$ia[0]}').options[i] = new Option(\$text, \$value);\n" . "\t\t\t\t\tif (document.getElementById('CHOICES_{$ia[0]}').options.length > 0)\n" . "\t\t\t\t\t\t{\n" . "\t\t\t\t\t\tdocument.getElementById('CHOICES_{$ia[0]}').disabled=false;\n" . "\t\t\t\t\t\t}\n" . "\t\t\t\t\t{$checkconditionFunction}('');\n" . "\t\t\t\t\t}\n" . "\t\t\t//-->\n" . "\t\t\t</script>\n";
    unset($answers);
    //unset($inputnames);
    unset($chosen);
    $ranklist = "";
    while ($ansrow = $ansresult->FetchRow()) {
        $answers[] = array($ansrow['code'], $ansrow['answer']);
    }
    $existing = 0;
    for ($i = 1; $i <= $anscount; $i++) {
        $myfname = $ia[1] . $i;
        if (isset($_SESSION[$myfname]) && $_SESSION[$myfname]) {
            $existing++;
        }
    }
    for ($i = 1; $i <= floor($max_ans_val); $i++) {
        $myfname = $ia[1] . $i;
        if (isset($_SESSION[$myfname]) && $_SESSION[$myfname]) {
            foreach ($answers as $ans) {
                if ($ans[0] == $_SESSION[$myfname]) {
                    $thiscode = $ans[0];
                    $thistext = $ans[1];
                }
            }
        }
        $ranklist .= "\t<tr><td class=\"position\">&nbsp;<label for='RANK_{$ia[0]}{$i}'>" . "{$i}:&nbsp;</label></td><td class=\"item\"><input class=\"text\" type=\"text\" name=\"RANK_{$ia[0]}{$i}\" id=\"RANK_{$ia[0]}{$i}\"";
        if (isset($_SESSION[$myfname]) && $_SESSION[$myfname]) {
            $ranklist .= " value='";
            $ranklist .= htmlspecialchars($thistext, ENT_QUOTES);
            $ranklist .= "'";
        }
        $ranklist .= " onfocus=\"this.blur()\" />\n";
        $ranklist .= "<input type=\"hidden\" name=\"{$myfname}\" id=\"fvalue_{$ia[0]}{$i}\" value='";
        $chosen[] = "";
        //create array
        if (isset($_SESSION[$myfname]) && $_SESSION[$myfname]) {
            $ranklist .= $thiscode;
            $chosen[] = array($thiscode, $thistext);
        }
        $ranklist .= "' />\n";
        $ranklist .= "<img src=\"{$imageurl}/cut.gif\" alt=\"" . $clang->gT("Remove this item") . "\" title=\"" . $clang->gT("Remove this item") . "\" ";
        if ($i != $existing) {
            $ranklist .= "style=\"display:none\"";
        }
        $ranklist .= " id=\"cut_{$ia[0]}{$i}\" onclick=\"deletethis_{$ia[0]}(document.getElementById('RANK_{$ia[0]}{$i}').value, document.getElementById('fvalue_{$ia[0]}{$i}').value, document.getElementById('RANK_{$ia[0]}{$i}').name, this.id)\" /><br />\n";
        $inputnames[] = $myfname;
        $ranklist .= "</td></tr>\n";
    }
    $maxselectlength = 0;
    $choicelist = "<select size=\"{$anscount}\" name=\"CHOICES_{$ia[0]}\" ";
    if (isset($choicewidth)) {
        $choicelist .= $choicewidth;
    }
    $choicelist .= " id=\"CHOICES_{$ia[0]}\" onchange=\"if (this.options.length>0 && this.selectedIndex<0) { this.options[this.options.length-1].selected=true; }; rankthis_{$ia[0]}(this.options[this.selectedIndex].value, this.options[this.selectedIndex].text)\" class=\"select\">\n";
    foreach ($answers as $ans) {
        if (!in_array($ans, $chosen)) {
            $choicelist .= "\t\t\t\t\t\t\t<option id='javatbd{$ia[1]}{$ans[0]}' value='{$ans[0]}'>{$ans[1]}</option>\n";
        }
        if (strlen($ans[1]) > $maxselectlength) {
            $maxselectlength = strlen($ans[1]);
        }
    }
    $choicelist .= "</select>\n";
    $answer .= "\t<table border='0' cellspacing='0' class='rank'>\n" . "<tr>\n" . "\t<td align='left' valign='top' class='rank label'>\n" . "<strong>&nbsp;&nbsp;<label for='CHOICES_{$ia[0]}'>" . $clang->gT("Your Choices") . ":</label></strong><br />\n" . "&nbsp;" . $choicelist . "\t&nbsp;</td>\n";
    $maxselectlength = $maxselectlength + 2;
    if ($maxselectlength > 60) {
        $maxselectlength = 60;
    }
    $ranklist = str_replace("<input class=\"text\"", "<input size='{$maxselectlength}' class='text'", $ranklist);
    $answer .= "\t<td style=\"text-align:left; white-space:nowrap;\" class='rank output'>\n" . "\t<table border='0' cellspacing='1' cellpadding='0'>\n" . "\t<tr><td></td><td><strong>" . $clang->gT("Your Ranking") . ":</strong>" . "<div style='display:none' id='RANK_{$ia[0]}_maxans'>{" . $max_answers . "}</div>" . "<div style='display:none' id='RANK_{$ia[0]}_minans'>{" . $min_answers . "}</div>" . "</td></tr>\n";
    $answer .= $ranklist . "\t</table>\n" . "\t</td>\n" . "</tr>\n" . "<tr>\n" . "\t<td colspan='2' class='rank helptext'><font size='1'>\n" . "" . $clang->gT("Click on the scissors next to each item on the right to remove the last entry in your ranked list") . "\t</font size='1'></td>\n" . "</tr>\n" . "\t</table>\n";
    return array($answer, $inputnames);
}
Exemplo n.º 7
0
function do_multiplenumeric($ia)
{
    global $thissurvey;
    $extraclass = "";
    $checkconditionFunction = "fixnum_checkconditions";
    $aQuestionAttributes = QuestionAttribute::model()->getQuestionAttributes($ia[0]);
    $answer = '';
    $sSeparator = getRadixPointData($thissurvey['surveyls_numberformat']);
    $sSeparator = $sSeparator['separator'];
    //Must turn on the "numbers only javascript"
    $extraclass .= " numberonly";
    if ($aQuestionAttributes['thousands_separator'] == 1) {
        App()->clientScript->registerPackage('jquery-price-format');
        App()->clientScript->registerScriptFile(Yii::app()->getConfig('generalscripts') . 'numerical_input.js');
        $extraclass .= " thousandsseparator";
    }
    if (intval(trim($aQuestionAttributes['maximum_chars'])) > 0) {
        // Only maxlength attribute, use textarea[maxlength] jquery selector for textarea
        $maximum_chars = intval(trim($aQuestionAttributes['maximum_chars']));
        $maxlength = "maxlength='{$maximum_chars}' ";
        $extraclass .= " maxchars maxchars-" . $maximum_chars;
    } else {
        $maxlength = " maxlength='25' ";
    }
    if (trim($aQuestionAttributes['prefix'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']]) != '') {
        $prefix = $aQuestionAttributes['prefix'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']];
        $extraclass .= " withprefix";
    } else {
        $prefix = '';
    }
    if (trim($aQuestionAttributes['suffix'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']]) != '') {
        $suffix = $aQuestionAttributes['suffix'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']];
        $extraclass .= " withsuffix";
    } else {
        $suffix = '';
    }
    if ($thissurvey['nokeyboard'] == 'Y') {
        includeKeypad();
        $kpclass = "num-keypad";
        $extraclass .= " keypad";
    } else {
        $kpclass = "";
    }
    $numbersonly_slider = '';
    // DEPRECATED
    if (trim($aQuestionAttributes['text_input_width']) != '') {
        $tiwidth = $aQuestionAttributes['text_input_width'];
        //$extraclass .=" inputwidth".trim($aQuestionAttributes['text_input_width']);
        $col = $aQuestionAttributes['text_input_width'] <= 12 ? $aQuestionAttributes['text_input_width'] : 12;
        $extraclass .= " col-sm-" . trim($col);
    } else {
        $tiwidth = 10;
    }
    $prefixclass = "numeric";
    if ($aQuestionAttributes['slider_layout'] == 1) {
        $prefixclass = "slider";
        $slider_layout = true;
        $extraclass .= " withslider";
        $slider_step = trim(LimeExpressionManager::ProcessString("{{$aQuestionAttributes['slider_accuracy']}}", $ia[0], array(), false, 1, 1, false, false, true));
        $slider_step = is_numeric($slider_step) ? $slider_step : 1;
        $slider_min = trim(LimeExpressionManager::ProcessString("{{$aQuestionAttributes['slider_min']}}", $ia[0], array(), false, 1, 1, false, false, true));
        $slider_mintext = $slider_min = is_numeric($slider_min) ? $slider_min : 0;
        $slider_max = trim(LimeExpressionManager::ProcessString("{{$aQuestionAttributes['slider_max']}}", $ia[0], array(), false, 1, 1, false, false, true));
        $slider_maxtext = $slider_max = is_numeric($slider_max) ? $slider_max : 100;
        $slider_default = trim(LimeExpressionManager::ProcessString("{{$aQuestionAttributes['slider_default']}}", $ia[0], array(), false, 1, 1, false, false, true));
        $slider_default = is_numeric($slider_default) ? $slider_default : "";
        $slider_orientation = trim($aQuestionAttributes['slider_orientation']) == 0 ? 'horizontal' : 'vertical';
        $slider_custom_handle = trim($aQuestionAttributes['slider_custom_handle']);
        switch (trim($aQuestionAttributes['slider_handle'])) {
            case 0:
                $slider_handle = 'round';
                break;
            case 1:
                $slider_handle = 'square';
                break;
            case 2:
                $slider_handle = 'triangle';
                break;
            case 3:
                $slider_handle = 'custom';
                break;
        }
        if ($slider_default == '' && $aQuestionAttributes['slider_middlestart'] == 1) {
            $slider_middlestart = intval(($slider_max + $slider_min) / 2);
        } else {
            $slider_middlestart = '';
        }
        $slider_separator = trim($aQuestionAttributes['slider_separator']) != '' ? $aQuestionAttributes['slider_separator'] : "";
        $slider_reset = $aQuestionAttributes['slider_reset'] ? 1 : 0;
    } else {
        $slider_layout = false;
        $slider_step = '';
        $slider_step = '';
        $slider_min = '';
        $slider_mintext = '';
        $slider_max = '';
        $slider_maxtext = '';
        $slider_default = '';
        $slider_default = '';
        $slider_orientation = '';
        $slider_handle = '';
        $slider_custom_handle = '';
        $slider_separator = '';
    }
    $hidetip = $aQuestionAttributes['hide_tip'];
    if ($aQuestionAttributes['random_order'] == 1) {
        $ansquery = "SELECT * FROM {{questions}} WHERE parent_qid={$ia['0']}  AND language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "' ORDER BY " . dbRandom();
    } else {
        $ansquery = "SELECT * FROM {{questions}} WHERE parent_qid={$ia['0']}  AND language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "' ORDER BY question_order";
    }
    $ansresult = dbExecuteAssoc($ansquery);
    //Checked
    $aSubquestions = $ansresult->readAll();
    $anscount = count($aSubquestions) * 2;
    $fn = 1;
    $answer = Yii::app()->getController()->renderPartial('/survey/questions/multiplenumeric/header', array('prefixclass' => $prefixclass), true);
    $answer_main = '';
    if ($anscount == 0) {
        $inputnames = array();
        $noanswer = true;
        $answer .= '    <p class="text-danger">' . gT('Error: This question has no answers.') . "</p>\n";
    } else {
        foreach ($aSubquestions as $ansrow) {
            $myfname = $ia[1] . $ansrow['title'];
            if ($ansrow['question'] == "") {
                $ansrow['question'] = "&nbsp;";
            }
            if ($slider_layout === false || $slider_separator == '') {
                $theanswer = $ansrow['question'];
                $sliders = false;
            } else {
                $aAnswer = explode($slider_separator, $ansrow['question']);
                $theanswer = isset($aAnswer[0]) ? $aAnswer[0] : "";
                $sliderleft = isset($aAnswer[1]) ? $aAnswer[1] : "";
                $sliderright = isset($aAnswer[2]) ? $aAnswer[2] : "";
                $sliders = true;
                $sliderright = "<div class=\"slider_righttext\">{$sliderright}</div>";
            }
            $aAnswer = isset($aAnswer) ? $aAnswer : '';
            $sliderleft = isset($sliderleft) ? $sliderleft : "";
            $sliderright = isset($sliderright) ? $sliderright : "";
            // color code missing mandatory questions red
            $alert = '';
            if ($ia[6] == 'Y' && $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname] === '') {
                $alert = true;
            }
            //list($htmltbody2, $hiddenfield)=return_array_filter_strings($ia, $aQuestionAttributes, $thissurvey, $ansrow, $myfname, '', $myfname, "div","form-group question-item answer-item text-item numeric-item".$extraclass);
            $sDisplayStyle = return_display_style($ia, $aQuestionAttributes, $thissurvey, $myfname);
            $sSeparator = getRadixPointData($thissurvey['surveyls_numberformat']);
            $sSeparator = $sSeparator['separator'];
            $dispVal = '';
            if (isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname])) {
                $dispVal = $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname];
                if (strpos($dispVal, ".")) {
                    $dispVal = rtrim(rtrim($dispVal, "0"), ".");
                }
                $dispVal = str_replace('.', $sSeparator, $dispVal);
            }
            $itemDatas = array('extraclass' => $extraclass, 'sDisplayStyle' => $sDisplayStyle, 'kpclass' => $kpclass, 'alert' => $alert, 'theanswer' => $theanswer, 'labelname' => 'answer' . $myfname, 'prefixclass' => $prefixclass, 'sliders' => $sliders, 'sliderleft' => $sliderleft, 'sliderright' => $sliderright, 'prefix' => $prefix, 'suffix' => $suffix, 'tiwidth' => $tiwidth, 'myfname' => $myfname, 'dispVal' => $dispVal, 'maxlength' => $maxlength, 'labelText' => $ansrow['question'], 'checkconditionFunction' => $checkconditionFunction . '(this.value, this.name, this.type)', 'slider_orientation' => $slider_orientation, 'slider_step' => $slider_step, 'slider_min' => $slider_min, 'slider_mintext' => $slider_mintext, 'slider_max' => $slider_max, 'slider_maxtext' => $slider_maxtext, 'slider_default' => $slider_default, 'slider_handle' => $slider_handle, 'slider_custom_handle' => $slider_custom_handle);
            $answer .= Yii::app()->getController()->renderPartial('/survey/questions/multiplenumeric/item', $itemDatas, true);
            $fn++;
            $inputnames[] = $myfname;
        }
        $displaytotal = false;
        $equals_num_value = false;
        if (trim($aQuestionAttributes['equals_num_value']) != '' || trim($aQuestionAttributes['min_num_value']) != '' || trim($aQuestionAttributes['max_num_value']) != '') {
            $qinfo = LimeExpressionManager::GetQuestionStatus($ia[0]);
            if (trim($aQuestionAttributes['equals_num_value']) != '') {
                $equals_num_value = true;
            }
            $displaytotal = true;
        }
        $footerDatas = array('equals_num_value' => $equals_num_value, 'id' => $ia[0], 'prefix' => $prefix, 'suffix' => $suffix, 'sumRemainingEqn' => isset($qinfo) ? $qinfo['sumRemainingEqn'] : '', 'displaytotal' => $displaytotal, 'sumEqn' => isset($qinfo) ? $qinfo['sumEqn'] : '');
        $answer .= Yii::app()->getController()->renderPartial('/survey/questions/multiplenumeric/footer', $footerDatas, true);
    }
    if ($aQuestionAttributes['slider_layout'] == 1) {
        Yii::app()->getClientScript()->registerScriptFile(Yii::app()->getConfig('generalscripts') . "bootstrap-slider.js");
        Yii::app()->getClientScript()->registerScriptFile(Yii::app()->getConfig('generalscripts') . "numeric-slider.js");
        Yii::app()->getClientScript()->registerCssFile(Yii::app()->getConfig('publicstyleurl') . "numeric-slider.css");
        if ($slider_default != "") {
            $slider_startvalue = $slider_default;
            $slider_displaycallout = 1;
        } elseif ($slider_middlestart != '') {
            $slider_startvalue = $slider_middlestart;
            $slider_displaycallout = 0;
        } else {
            $slider_startvalue = 'NULL';
            $slider_displaycallout = 0;
        }
        $slider_showminmax = $aQuestionAttributes['slider_showminmax'] == 1 ? 1 : 0;
        //some var for slider
        $aJsLang = array('reset' => gT('Reset'), 'tip' => gT('Please click and drag the slider handles to enter your answer.'));
        $aJsVar = array('slider_showminmax' => $slider_showminmax, 'slider_min' => $slider_min, 'slider_mintext' => $slider_mintext, 'slider_max' => $slider_max, 'slider_maxtext' => $slider_maxtext, 'slider_step' => $slider_step, 'slider_startvalue' => $slider_startvalue, 'slider_displaycallout' => $slider_displaycallout, 'slider_prefix' => $prefix, 'slider_suffix' => $suffix, 'slider_reset' => $slider_reset, 'lang' => $aJsLang);
        /*
        $answer .= "<script type='text/javascript'><!--\n"
                    . " doNumericSlider({$ia[0]},".ls_json_encode($aJsVar).");\n"
                    . " //--></script>";
        */
    }
    $sSeparator = getRadixPointData($thissurvey['surveyls_numberformat']);
    $sSeparator = $sSeparator['separator'];
    return array($answer, $inputnames);
}
Exemplo n.º 8
0
 protected function createIncrementalQuestionIndex($LEMsessid, $surveyMode)
 {
     echo "\n\n<!-- PRESENT THE INDEX -->\n";
     echo '<div id="index"><div class="container" id="indexcontainer"><h2>' . 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['group_name']);
                     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['group_name']);
             $sButtonText = gT('Go to this group');
         } else {
             $indexlabel = LimeExpressionManager::ProcessString($q[3]);
             $sButtonText = gT('Go to this question');
         }
         $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}\">";
         echo "<span class=\"hdr\">{$v}</span>";
         echo "<span title=\"{$sText}\">{$sText}</span>";
         echo CHtml::htmlButton($sButtonText, array('type' => 'submit', 'value' => $s, 'name' => 'move', 'class' => 'jshide'));
         echo "</div>";
     }
     if ($_SESSION[$LEMsessid]['maxstep'] == $_SESSION[$LEMsessid]['totalsteps']) {
         echo CHtml::htmlButton(gT('Submit'), array('type' => 'submit', 'value' => 'movesubmit', 'name' => 'move', 'class' => 'submit button'));
     }
     echo '</div></div>';
     App()->getClientScript()->registerScript('manageIndex', "manageIndex()\n", CClientScript::POS_END);
 }
Exemplo n.º 9
0
 /**
  * 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);
 }
Exemplo n.º 10
0
 /**
  * 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);
     }
 }
Exemplo n.º 11
0
            $minipos++;
        }
        $orderquestions .= "</select>\n";
        $orderquestions .= "\t<input style='float:right;";
        if ($i == 0) {
            $orderquestions .= "visibility:hidden;";
        }
        $orderquestions .= "' type='image' src='{$imageurl}/up.png' name='btnup_{$i}' onclick=\"\$('#sortorder').val('{$oqarray[$i]['question_order']}');\$('#questionordermethod').val('up');\" " . $updisabled . "/>\n";
        if ($i < $questioncount - 1) {
            // Fill the sortorder hiddenfield so we know what field is moved down
            $orderquestions .= "\t<input type='image' src='{$imageurl}/down.png' style='float:right;' name='btndown_{$i}' onclick=\"\$('#sortorder').val('{$oqarray[$i]['question_order']}');\$('#questionordermethod').val('down')\" " . $downdisabled . "/>\n";
        }
        $orderquestions .= "<a href='admin.php?sid={$surveyid}&amp;gid={$gid}&amp;qid={$oqarray[$i]['qid']}' title='" . $clang->gT("View Question") . "'>" . $oqarray[$i]['title'] . "</a>: ";
        $relevance = $oqarray[$i]['relevance'] == '' ? 1 : $oqarray[$i]['relevance'];
        $showme = '[{' . $relevance . '}] ' . $oqarray[$i]['question'];
        LimeExpressionManager::ProcessString($showme, $oqarray[$i]['qid']);
        $orderquestions .= FlattenText(LimeExpressionManager::GetLastPrettyPrintExpression(), false, 'UTF-8', true, true);
        $orderquestions .= "</li>\n";
    }
    $orderquestions .= "</ul>\n" . "<input type='hidden' name='questionmovefrom' />\n" . "<input type='hidden' name='questionordermethod' id='questionordermethod' />\n" . "<input type='hidden' name='questionmoveto' />\n" . "\t<input type='hidden' id='sortorder' name='sortorder' />" . "\t<input type='hidden' name='action' value='orderquestions' />" . "</form>";
    $orderquestions .= "<br />";
    LimeExpressionManager::FinishProcessingGroup();
    LimeExpressionManager::FinishProcessingPage();
}
function questionjavascript($type)
{
    $newquestionoutput = "<script type='text/javascript'>\n" . "if (navigator.userAgent.indexOf(\"Gecko\") != -1)\n" . "window.addEventListener(\"load\", init_gecko_select_hack, false);\n";
    $jc = 0;
    $newquestionoutput .= "\tvar qtypes = new Array();\n";
    $newquestionoutput .= "\tvar qnames = new Array();\n\n";
    $newquestionoutput .= "\tvar qhelp = new Array();\n\n";
Exemplo n.º 12
0
/**
 * This function replaces keywords in a text and is mainly intended for templates
 * If you use this functions put your replacement strings into the $replacements variable
 * instead of using global variables
 * NOTE - Don't do any embedded replacements in this function.  Create the array of replacement values and
 * they will be done in batch at the end
 *
 * @param string $line Text to search in
 * @param array $replacements Array of replacements:  Array( <stringtosearch>=><stringtoreplacewith>, where <stringtosearch> is NOT surrounded with curly braces
 * @param boolean $anonymized Determines if token data is being used or just replaced with blanks
 * @return string  Text with replaced strings
 */
function templatereplace($line, $replacements = array(), $anonymized = false, $questionNum = NULL)
{
    global $surveylist, $sitename, $clienttoken, $rooturl;
    global $thissurvey, $imageurl, $defaulttemplate;
    global $percentcomplete, $move;
    global $groupname, $groupdescription;
    global $question;
    global $showxquestions, $showgroupinfo, $showqnumcode;
    global $answer, $navigator;
    global $help, $surveyformat;
    global $completed, $register_errormsg;
    global $privacy, $surveyid;
    global $publicurl, $templatedir, $token;
    global $assessments, $s_lang;
    global $errormsg, $clang;
    global $saved_id;
    global $totalBoilerplatequestions, $relativeurl;
    global $languagechanger;
    global $captchapath, $loadname;
    // lets sanitize the survey template
    if (isset($thissurvey['templatedir'])) {
        $_templatename = $thissurvey['templatedir'];
    } else {
        $_templatename = $defaulttemplate;
    }
    #    $_templatename = validate_templatedir($_templatename); // Not needed: sGetTemplateURL and sgetTemplatePath do validation
    // create absolute template URL and template dir vars
    $_templateurl = sGetTemplateURL($_templatename) . '/';
    $templatedir = sgetTemplatePath($_templatename);
    $interviewer = returnglobal('interviewer');
    if (!empty($interviewer) || isset($_SESSION['interviewer']) && $_SESSION['interviewer'] == true) {
        $interviewer = true;
        $_SESSION['interviewer'] = true;
    } else {
        $interviewer = false;
    }
    if (stripos($line, "</head>")) {
        //queXS Addition
        $textfocus = "";
        if ($interviewer) {
            $textfocus = '<script type="text/javascript">
		$(document).ready(function()
		{
	        	$(".text").focus();
		        $(".textarea").focus();
		});
		</script>';
        }
        $line = str_ireplace("</head>", "<script type=\"text/javascript\" src=\"{$rooturl}/scripts/survey_runtime.js\"></script>\n" . "{$textfocus}\n" . use_firebug() . "\t</head>", $line);
    }
    // Get some vars : move elsewhere ?
    // surveyformat
    if (isset($thissurvey['format'])) {
        $surveyformat = str_replace(array("A", "S", "G"), array("allinone", "questionbyquestion", "groupbygroup"), $thissurvey['format']);
    } else {
        $surveyformat = "";
    }
    /*if (isset($thissurvey['allowjumps']) && $thissurvey['allowjumps']=="Y" && $surveyformat!="allinone" && (isset($_SESSION['step']) && $_SESSION['step']>0)){
          $surveyformat .= " withindex";
      }*/
    if (isset($thissurvey['showprogress']) && $thissurvey['showprogress'] == "Y") {
        $surveyformat .= " showprogress";
    }
    if (isset($thissurvey['showqnumcode'])) {
        $surveyformat .= " showqnumcode-" . $thissurvey['showqnumcode'];
    }
    // real survey contact
    if (isset($surveylist['contact'])) {
        $_surveycontact = $surveylist['contact'];
    } elseif (isset($thissurvey['admin']) && $thissurvey['admin'] != "") {
        $_surveycontact = sprintf($clang->gT("Please contact %s ( %s ) for further assistance."), $thissurvey['admin'], $thissurvey['adminemail']);
    } else {
        $_surveycontact = "";
    }
    // If there are non-bracketed replacements to be made do so above this line.
    // Only continue in this routine if there are bracketed items to replace {}
    if (strpos($line, "{") === false) {
        return LimeExpressionManager::ProcessString($line, $questionNum, NULL, false, 1, 1, true);
    }
    if ($showgroupinfo == 'both' || $showgroupinfo == 'name' || $showgroupinfo == 'choose' && !isset($thissurvey['showgroupinfo']) || $showgroupinfo == 'choose' && $thissurvey['showgroupinfo'] == 'B' || $showgroupinfo == 'choose' && $thissurvey['showgroupinfo'] == 'N') {
        $_groupname = $groupname;
    } else {
        $_groupname = '';
    }
    if ($showgroupinfo == 'both' || $showgroupinfo == 'description' || $showgroupinfo == 'choose' && !isset($thissurvey['showgroupinfo']) || $showgroupinfo == 'choose' && $thissurvey['showgroupinfo'] == 'B' || $showgroupinfo == 'choose' && $thissurvey['showgroupinfo'] == 'D') {
        $_groupdescription = $groupdescription;
    } else {
        $_groupdescription = '';
    }
    if (is_array($question)) {
        $_question = $question['all'];
        $_question_text = $question['text'];
        $_question_help = $question['help'];
        $_question_mandatory = $question['mandatory'];
        $_question_man_message = $question['man_message'];
        $_question_valid_message = $question['valid_message'];
        $_question_file_valid_message = $question['file_valid_message'];
        if (isset($question['sgq'])) {
            $_question_sgq = $question['sgq'];
            $_parts = explode('X', $_question_sgq);
            $_question_gid = $_parts[1];
        } else {
            $_question_sgq = '';
            $_question_gid = '';
        }
        $_question_essentials = $question['essentials'];
        $_question_class = $question['class'];
        $_question_man_class = $question['man_class'];
        $_question_input_error_class = $question['input_error_class'];
        $_aid = isset($question['aid']) ? $question['aid'] : '';
        $_sqid = isset($question['sqid']) ? $question['sqid'] : '';
        $_question_type = isset($question['type']) ? $question['type'] : '';
    } else {
        $_question = $question;
        $_question_text = '';
        $_question_help = '';
        $_question_mandatory = '';
        $_question_man_message = '';
        $_question_valid_message = '';
        $_question_file_valid_message = '';
        $_question_gid = '';
        $_question_sgq = '';
        $_question_essentials = '';
        $_question_class = '';
        $_question_man_class = '';
        $_question_input_error_class = '';
        $_aid = '';
        $_sqid = '';
        $_question_type = '';
    }
    global $answer_id;
    if ($_question_type == '*') {
        $_question_text = '<div class="em_equation">' . $_question_text . '</div>';
    }
    if ($showqnumcode == 'both' || $showqnumcode == 'number' || $showqnumcode == 'choose' && !isset($thissurvey['showqnumcode']) || $showqnumcode == 'choose' && $thissurvey['showqnumcode'] == 'B' || $showqnumcode == 'choose' && $thissurvey['showqnumcode'] == 'N') {
        $_question_number = $question['number'];
    } else {
        $_question_number = '';
    }
    if ($showqnumcode == 'both' || $showqnumcode == 'code' || $showqnumcode == 'choose' && !isset($thissurvey['showqnumcode']) || $showqnumcode == 'choose' && $thissurvey['showqnumcode'] == 'B' || $showqnumcode == 'choose' && $thissurvey['showqnumcode'] == 'C') {
        $_question_code = $question['code'];
    } else {
        $_question_code = '';
    }
    if (isset($_SESSION['therearexquestions'])) {
        $_totalquestionsAsked = $_SESSION['therearexquestions'] - $totalBoilerplatequestions;
    } else {
        $_totalquestionsAsked = 0;
    }
    if ($showxquestions == 'show' || $showxquestions == 'choose' && !isset($thissurvey['showxquestions']) || $showxquestions == 'choose' && $thissurvey['showxquestions'] == 'Y') {
        if ($_totalquestionsAsked < 1) {
            $_therearexquestions = $clang->gT("There are no questions in this survey");
            // Singular
        } elseif ($_totalquestionsAsked == 1) {
            $_therearexquestions = $clang->gT("There is 1 question in this survey");
            //Singular
        } else {
            $_therearexquestions = $clang->gT("There are {NUMBEROFQUESTIONS} questions in this survey.");
            //Note this line MUST be before {NUMBEROFQUESTIONS}
        }
    } else {
        $_therearexquestions = '';
    }
    if (isset($token)) {
        $_token = $token;
    } elseif (isset($clienttoken)) {
        $_token = htmlentities($clienttoken, ENT_QUOTES, 'UTF-8');
    } else {
        $_token = '';
    }
    if (isset($thissurvey['surveyls_dateformat'])) {
        $dateformatdetails = getDateFormatData($thissurvey['surveyls_dateformat']);
    } else {
        $dateformatdetails = getDateFormatData();
    }
    if (isset($thissurvey['expiry'])) {
        $_datetimeobj = new Date_Time_Converter($thissurvey['expiry'], "Y-m-d");
        $_dateoutput = $_datetimeobj->convert($dateformatdetails['phpdate']);
    } else {
        $_dateoutput = '-';
    }
    $_submitbutton = "<input class='submit' type='submit' value=' " . $clang->gT("Submit") . " ' name='move2' onclick=\"javascript:document.limesurvey.move.value = 'movesubmit';\" />";
    if (isset($thissurvey['surveyls_url']) and $thissurvey['surveyls_url'] != "") {
        if (trim($thissurvey['surveyls_urldescription']) != '') {
            $_linkreplace = "<a href='{$thissurvey['surveyls_url']}'>{$thissurvey['surveyls_urldescription']}</a>";
        } else {
            $_linkreplace = "<a href='{$thissurvey['surveyls_url']}'>{$thissurvey['surveyls_url']}</a>";
        }
    } else {
        $_linkreplace = '';
    }
    if (isset($clienttoken)) {
        $token = $clienttoken;
    } else {
        $token = '';
    }
    if (!isset($_SESSION['s_lang'])) {
        $_s_lang = 'en';
    } else {
        $_s_lang = $_SESSION['s_lang'];
    }
    // CLEARALL
    if ($surveyid && !isCompleted($surveyid, $saved_id)) {
        $_clearall = "<input type='button' name='clearallbtn' value='" . $clang->gT("Exit and Clear Survey") . "' class='clearall' " . "onclick=\"if (confirm('" . $clang->gT("Are you sure you want to clear all your responses?", 'js') . "')) {\nwindow.open('{$publicurl}/index.php?sid={$surveyid}&amp;move=clearall&amp;lang=" . $_s_lang;
        if (returnglobal('token')) {
            $_clearall .= "&amp;token={$_token}";
        }
        $_clearall .= "', '_self')}\" />";
    } else {
        $_clearall = "";
        // This survey are already completed or surveyid not set, then don't have access to clearallbtn
    }
    if (isset($_SESSION['datestamp'])) {
        $_datestamp = $_SESSION['datestamp'];
    } else {
        $_datestamp = '-';
    }
    //Set up save/load feature
    if (isset($thissurvey['allowsave']) and $thissurvey['allowsave'] == "Y") {
        // Find out if the user has any saved data
        if ($thissurvey['format'] == 'A') {
            if ($thissurvey['tokenanswerspersistence'] != 'Y' || !tableExists('tokens_' . $surveyid)) {
                $_saveall = "\t\t\t<input type='button' name='loadall' value='" . $clang->gT("Load Unfinished Survey") . "' class='saveall' onclick=\"javascript:addHiddenField(document.getElementById('limesurvey'),'loadall',this.value);document.getElementById('limesurvey').submit();\" " . ($thissurvey['active'] != "Y" ? "disabled='disabled'" : "") . "/>" . "\n\t\t\t<input type='button' name='saveallbtn' value='" . $clang->gT("Resume Later") . "' class='saveall' onclick=\"javascript:document.limesurvey.move.value = this.value;addHiddenField(document.getElementById('limesurvey'),'saveall',this.value);document.getElementById('limesurvey').submit();\" " . ($thissurvey['active'] != "Y" ? "disabled='disabled'" : "") . "/>";
                // Show Save So Far button
            } else {
                $_saveall = "\t\t\t<input type='button' name='saveallbtn' value='" . $clang->gT("Resume Later") . "' class='saveall' onclick=\"javascript:document.limesurvey.move.value = this.value;addHiddenField(document.getElementById('limesurvey'),'saveall',this.value);document.getElementById('limesurvey').submit();\" " . ($thissurvey['active'] != "Y" ? "disabled='disabled'" : "") . "/>";
                // Show Save So Far button
            }
        } elseif (!isset($_SESSION['step']) || !$_SESSION['step']) {
            //First page, show LOAD
            if ($thissurvey['tokenanswerspersistence'] != 'Y' || !tableExists('tokens_' . $surveyid)) {
                $_saveall = "\t\t\t<input type='button' name='loadall' value='" . $clang->gT("Load Unfinished Survey") . "' class='saveall' onclick=\"javascript:addHiddenField(document.getElementById('limesurvey'),'loadall',this.value);document.getElementById('limesurvey').submit();\" " . ($thissurvey['active'] != "Y" ? "disabled='disabled'" : "") . "/>";
            } else {
                $_saveall = '';
            }
        } elseif (isset($_SESSION['scid']) && (isset($move) && $move == "movelast")) {
            //Already saved and on Submit Page, dont show Save So Far button
            $_saveall = '';
        } else {
            $_saveall = "<input type='button' name='saveallbtn' value='" . $clang->gT("Resume Later") . "' class='saveall' onclick=\"javascript:document.limesurvey.move.value = this.value;addHiddenField(document.getElementById('limesurvey'),'saveall',this.value);document.getElementById('limesurvey').submit();\" " . ($thissurvey['active'] != "Y" ? "disabled='disabled'" : "") . "/>";
            // Show Save So Far button
        }
    } else {
        $_saveall = "";
    }
    $_templatecss = "<link rel='stylesheet' type='text/css' href='{$_templateurl}template.css' />\n";
    if (getLanguageRTL($clang->langcode)) {
        $_templatecss .= "<link rel='stylesheet' type='text/css' href='{$_templateurl}template-rtl.css' />\n";
    }
    if (FlattenText($help, true) != '') {
        if (!isset($helpicon)) {
            if (file_exists($templatedir . '/help.gif')) {
                $helpicon = $_templateurl . 'help.gif';
            } elseif (file_exists($templatedir . '/help.png')) {
                $helpicon = $_templateurl . 'help.png';
            } else {
                $helpicon = $imageurl . "/help.gif";
            }
        }
        $_questionhelp = "<img src='{$helpicon}' alt='Help' align='left' />" . $help;
    } else {
        $_questionhelp = $help;
    }
    if (isset($thissurvey['allowprev']) && $thissurvey['allowprev'] == "N") {
        $_strreview = "";
    } else {
        $_strreview = $clang->gT("If you want to check any of the answers you have made, and/or change them, you can do that now by clicking on the [<< prev] button and browsing through your responses.");
    }
    if (isset($thissurvey['active']) and $thissurvey['active'] == "N") {
        $_restart = "<a href='{$publicurl}/index.php?sid={$surveyid}&amp;newtest=Y";
        if (isset($s_lang) && $s_lang != '') {
            $_restart .= "&amp;lang=" . $s_lang;
        }
        $_restart .= "'>" . $clang->gT("Restart this Survey") . "</a>";
    } else {
        $restart_extra = "";
        $restart_token = returnglobal('token');
        if (!empty($restart_token)) {
            $restart_extra .= "&amp;token=" . urlencode($restart_token);
        } else {
            $restart_extra = "&amp;newtest=Y";
        }
        if (!empty($_GET['lang'])) {
            $restart_extra .= "&amp;lang=" . returnglobal('lang');
        }
        $_restart = "<a href='{$publicurl}/index.php?sid={$surveyid}" . $restart_extra . "'>" . $clang->gT("Restart this Survey") . "</a>";
    }
    if (isset($thissurvey['anonymized']) && $thissurvey['anonymized'] == 'Y') {
        $_savealert = $clang->gT("To remain anonymous please use a pseudonym as your username, also an email address is not required.");
    } else {
        $_savealert = "";
    }
    $_return_to_survey = "<a href='{$relativeurl}/index.php?sid={$surveyid}";
    if (returnglobal('token')) {
        $_return_to_survey .= "&amp;token=" . urlencode(trim(sanitize_xss_string(strip_tags(returnglobal('token')))));
    }
    $_return_to_survey .= "'>" . $clang->gT("Return To Survey") . "</a>";
    $_saveform = "<table><tr><td align='right'>" . $clang->gT("Name") . ":</td><td><input type='text' name='savename' value='";
    if (isset($_POST['savename'])) {
        $_saveform .= html_escape(auto_unescape($_POST['savename']));
    }
    $_saveform .= "' /></td></tr>\n" . "<tr><td align='right'>" . $clang->gT("Password") . ":</td><td><input type='password' name='savepass' value='";
    if (isset($_POST['savepass'])) {
        $_saveform .= html_escape(auto_unescape($_POST['savepass']));
    }
    $_saveform .= "' /></td></tr>\n" . "<tr><td align='right'>" . $clang->gT("Repeat Password") . ":</td><td><input type='password' name='savepass2' value='";
    if (isset($_POST['savepass2'])) {
        $_saveform .= html_escape(auto_unescape($_POST['savepass2']));
    }
    $_saveform .= "' /></td></tr>\n" . "<tr><td align='right'>" . $clang->gT("Your Email") . ":</td><td><input type='text' name='saveemail' value='";
    if (isset($_POST['saveemail'])) {
        $_saveform .= html_escape(auto_unescape($_POST['saveemail']));
    }
    $_saveform .= "' /></td></tr>\n";
    if (isset($thissurvey['usecaptcha']) && function_exists("ImageCreate") && captcha_enabled('saveandloadscreen', $thissurvey['usecaptcha'])) {
        $_saveform .= "<tr><td align='right'>" . $clang->gT("Security Question") . ":</td><td><table><tr><td valign='middle'><img src='{$captchapath}verification.php?sid={$surveyid}' alt='' /></td><td valign='middle' style='text-align:left'><input type='text' size='5' maxlength='3' name='loadsecurity' value='' /></td></tr></table></td></tr>\n";
    }
    $_saveform .= "<tr><td align='right'></td><td></td></tr>\n" . "<tr><td></td><td><input type='submit'  id='savebutton' name='savesubmit' value='" . $clang->gT("Save Now") . "' /></td></tr>\n" . "</table>";
    $_loadform = "<table><tr><td align='right'>" . $clang->gT("Saved name") . ":</td><td><input type='text' name='loadname' value='";
    if ($loadname) {
        $_loadform .= html_escape(auto_unescape($loadname));
    }
    $_loadform .= "' /></td></tr>\n" . "<tr><td align='right'>" . $clang->gT("Password") . ":</td><td><input type='password' name='loadpass' value='";
    if (isset($loadpass)) {
        $_loadform .= html_escape(auto_unescape($loadpass));
    }
    $_loadform .= "' /></td></tr>\n";
    if (isset($thissurvey['usecaptcha']) && function_exists("ImageCreate") && captcha_enabled('saveandloadscreen', $thissurvey['usecaptcha'])) {
        $_loadform .= "<tr><td align='right'>" . $clang->gT("Security Question") . ":</td><td><table><tr><td valign='middle'><img src='{$captchapath}verification.php?sid={$surveyid}' alt='' /></td><td valign='middle'><input type='text' size='5' maxlength='3' name='loadsecurity' value='' alt=''/></td></tr></table></td></tr>\n";
    }
    $_loadform .= "<tr><td align='right'></td><td></td></tr>\n" . "<tr><td></td><td><input type='submit' id='loadbutton' value='" . $clang->gT("Load Now") . "' /></td></tr></table>\n";
    $_registerform = "<form method='post' action='{$publicurl}/register.php'>\n";
    if (!isset($_REQUEST['lang'])) {
        $_reglang = GetBaseLanguageFromSurveyID($surveyid);
    } else {
        $_reglang = returnglobal('lang');
    }
    $_registerform .= "<input type='hidden' name='lang' value='" . $_reglang . "' />\n";
    $_registerform .= "<input type='hidden' name='sid' value='{$surveyid}' id='sid' />\n";
    $_registerform .= "<table class='register' summary='Registrationform'>\n" . "<tr><td align='right'>" . $clang->gT("First name") . ":</td>" . "<td align='left'><input class='text' type='text' name='register_firstname'";
    if (isset($_POST['register_firstname'])) {
        $_registerform .= " value='" . htmlentities(returnglobal('register_firstname'), ENT_QUOTES, 'UTF-8') . "'";
    }
    $_registerform .= " /></td></tr>" . "<tr><td align='right'>" . $clang->gT("Last name") . ":</td>\n" . "<td align='left'><input class='text' type='text' name='register_lastname'";
    if (isset($_POST['register_lastname'])) {
        $_registerform .= " value='" . htmlentities(returnglobal('register_lastname'), ENT_QUOTES, 'UTF-8') . "'";
    }
    $_registerform .= " /></td></tr>\n" . "<tr><td align='right'>" . $clang->gT("Email address") . ":</td>\n" . "<td align='left'><input class='text' type='text' name='register_email'";
    if (isset($_POST['register_email'])) {
        $_registerform .= " value='" . htmlentities(returnglobal('register_email'), ENT_QUOTES, 'UTF-8') . "'";
    }
    $_registerform .= " /></td></tr>\n";
    if (isset($thissurvey['usecaptcha']) && function_exists("ImageCreate") && captcha_enabled('registrationscreen', $thissurvey['usecaptcha'])) {
        $_registerform .= "<tr><td align='right'>" . $clang->gT("Security Question") . ":</td><td><table><tr><td valign='middle'><img src='{$captchapath}verification.php?sid={$surveyid}' alt='' /></td><td valign='middle'><input type='text' size='5' maxlength='3' name='loadsecurity' value='' /></td></tr></table></td></tr>\n";
    }
    /*      if(isset($thissurvey['attribute1']) && $thissurvey['attribute1'])
             {
             $_registerform .= "<tr><td align='right'>".$thissurvey['attribute1'].":</td>\n"
             ."<td align='left'><input class='text' type='text' name='register_attribute1'";
             if (isset($_POST['register_attribute1']))
             {
             $_registerform .= " value='".htmlentities(returnglobal('register_attribute1'),ENT_QUOTES,'UTF-8')."'";
             }
             $_registerform .= " /></td></tr>\n";
             }
             if(isset($thissurvey['attribute2']) && $thissurvey['attribute2'])
             {
             $_registerform .= "<tr><td align='right'>".$thissurvey['attribute2'].":</td>\n"
             ."<td align='left'><input class='text' type='text' name='register_attribute2'";
             if (isset($_POST['register_attribute2']))
             {
             $_registerform .= " value='".htmlentities(returnglobal('register_attribute2'),ENT_QUOTES,'UTF-8')."'";
             }
             $_registerform .= " /></td></tr>\n";
          } */
    $_registerform .= "<tr><td></td><td><input id='registercontinue' class='submit' type='submit' value='" . $clang->gT("Continue") . "' />" . "</td></tr>\n" . "</table>\n" . "</form>\n";
    if (!is_null($surveyid) && function_exists('doAssessment')) {
        $assessmentdata = doAssessment($surveyid, true);
        $_assessment_current_total = $assessmentdata['total'];
    } else {
        $_assessment_current_total = '';
    }
    if (isset($thissurvey['googleanalyticsapikey']) && trim($thissurvey['googleanalyticsapikey']) != '') {
        $_googleAnalyticsAPIKey = trim($thissurvey['googleanalyticsapikey']);
    } else {
        $_googleAnalyticsAPIKey = trim(getGlobalSetting('googleanalyticsapikey'));
    }
    $_googleAnalyticsStyle = isset($thissurvey['googleanalyticsstyle']) ? $thissurvey['googleanalyticsstyle'] : '0';
    $_googleAnalyticsJavaScript = '';
    if ($_googleAnalyticsStyle != '' && $_googleAnalyticsStyle != 0 && $_googleAnalyticsAPIKey != '') {
        switch ($_googleAnalyticsStyle) {
            case '1':
                // Default Google Tracking
                $_googleAnalyticsJavaScript = <<<EOD
<script type="text/javascript">
  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', '{$_googleAnalyticsAPIKey}']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();
</script>
EOD;
                break;
            case '2':
                // SurveyName-[SID]/[GSEQ]-GroupName - create custom GSEQ based upon page step
                $moveInfo = LimeExpressionManager::GetLastMoveResult();
                if (is_null($moveInfo)) {
                    $gseq = 'welcome';
                } else {
                    if ($moveInfo['finished']) {
                        $gseq = 'finished';
                    } else {
                        if (isset($moveInfo['at_start']) && $moveInfo['at_start']) {
                            $gseq = 'welcome';
                        } else {
                            if (is_null($_groupname)) {
                                $gseq = 'printanswers';
                            } else {
                                $gseq = $moveInfo['gseq'] + 1;
                            }
                        }
                    }
                }
                $_trackURL = htmlentities($thissurvey['name'] . '-[' . $surveyid . ']/[' . $gseq . ']-' . $_groupname, ENT_QUOTES);
                $_googleAnalyticsJavaScript = <<<EOD
<script type="text/javascript">
  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', '{$_googleAnalyticsAPIKey}']);
  _gaq.push(['_trackPageview','{$_trackURL}']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();
</script>
EOD;
                break;
        }
    }
    $_endtext = '';
    if (isset($thissurvey['surveyls_endtext']) && trim($thissurvey['surveyls_endtext']) != '') {
        $_endtext = $thissurvey['surveyls_endtext'];
    }
    // Set the array of replacement variables here - don't include curly braces
    // Please put any conditional logic above this section.  Here below should just be an alphabetical list of replacement values with no embedded logic.
    $coreReplacements = array();
    $coreReplacements['ACTIVE'] = isset($thissurvey['active']) && !($thissurvey['active'] != "Y");
    $coreReplacements['AID'] = $_aid;
    // global
    $coreReplacements['ANSWER'] = $answer;
    // global
    $coreReplacements['ANSWERSCLEARED'] = $clang->gT("Answers Cleared");
    $coreReplacements['ASSESSMENTS'] = $assessments;
    // global
    $coreReplacements['ASSESSMENT_CURRENT_TOTAL'] = $_assessment_current_total;
    $coreReplacements['ASSESSMENT_HEADING'] = $clang->gT("Your Assessment");
    $coreReplacements['CHECKJAVASCRIPT'] = "<noscript><span class='warningjs'>" . $clang->gT("Caution: JavaScript execution is disabled in your browser. You may not be able to answer all questions in this survey. Please, verify your browser parameters.") . "</span></noscript>";
    $coreReplacements['CLEARALL'] = $_clearall;
    $coreReplacements['CLOSEWINDOW'] = "<a href='javascript:%20self.close()'>" . $clang->gT("Close this window") . "</a>";
    $coreReplacements['COMPLETED'] = $completed;
    // global
    $coreReplacements['DATESTAMP'] = $_datestamp;
    $coreReplacements['ENDTEXT'] = $_endtext;
    $coreReplacements['EXPIRY'] = $_dateoutput;
    $coreReplacements['GID'] = $_question_gid;
    $coreReplacements['GOOGLE_ANALYTICS_API_KEY'] = $_googleAnalyticsAPIKey;
    $coreReplacements['GOOGLE_ANALYTICS_JAVASCRIPT'] = $_googleAnalyticsJavaScript;
    $coreReplacements['GROUPDESCRIPTION'] = $_groupdescription;
    $coreReplacements['GROUPNAME'] = $_groupname;
    $coreReplacements['LANG'] = $clang->getlangcode();
    $coreReplacements['LANGUAGECHANGER'] = $languagechanger;
    // global
    $coreReplacements['LOADERROR'] = $errormsg;
    // global
    $coreReplacements['LOADFORM'] = $_loadform;
    $coreReplacements['LOADHEADING'] = $clang->gT("Load A Previously Saved Survey");
    $coreReplacements['LOADMESSAGE'] = $clang->gT("You can load a survey that you have previously saved from this screen.") . "<br />" . $clang->gT("Type in the 'name' you used to save the survey, and the password.") . "<br />";
    $coreReplacements['NAVIGATOR'] = $navigator;
    // global
    $coreReplacements['NOSURVEYID'] = $surveylist['nosid'];
    // global
    $coreReplacements['NUMBEROFQUESTIONS'] = $_totalquestionsAsked;
    $coreReplacements['PASSTHRULABEL'] = '';
    $coreReplacements['PASSTHRUVALUE'] = '';
    $coreReplacements['PERCENTCOMPLETE'] = $percentcomplete;
    // global
    $coreReplacements['PRIVACY'] = $privacy;
    // global
    $coreReplacements['PRIVACYMESSAGE'] = "<span style='font-weight:bold; font-style: italic;'>" . $clang->gT("A Note On Privacy") . "</span><br />" . $clang->gT("This survey is anonymous.") . "<br />" . $clang->gT("The record kept of your survey responses does not contain any identifying information about you unless a specific question in the survey has asked for this. If you have responded to a survey that used an identifying token to allow you to access the survey, you can rest assured that the identifying token is not kept with your responses. It is managed in a separate database, and will only be updated to indicate that you have (or haven't) completed this survey. There is no way of matching identification tokens with survey responses in this survey.");
    $coreReplacements['QID'] = isset($questionNum) ? $questionNum : '';
    $coreReplacements['QUESTION'] = $_question;
    $coreReplacements['QUESTIONHELP'] = $_questionhelp;
    $coreReplacements['QUESTIONHELPPLAINTEXT'] = strip_tags(addslashes($help));
    // global
    $coreReplacements['QUESTION_CLASS'] = $_question_class;
    $coreReplacements['QUESTION_CODE'] = $_question_code;
    $coreReplacements['QUESTION_ESSENTIALS'] = $_question_essentials;
    $coreReplacements['QUESTION_FILE_VALID_MESSAGE'] = $_question_file_valid_message;
    $coreReplacements['QUESTION_HELP'] = $_question_help;
    $coreReplacements['QUESTION_INPUT_ERROR_CLASS'] = $_question_input_error_class;
    $coreReplacements['QUESTION_MANDATORY'] = $_question_mandatory;
    $coreReplacements['QUESTION_MAN_CLASS'] = $_question_man_class;
    $coreReplacements['QUESTION_MAN_MESSAGE'] = $_question_man_message;
    $coreReplacements['QUESTION_NUMBER'] = $_question_number;
    $coreReplacements['QUESTION_TEXT'] = $_question_text;
    $coreReplacements['QUESTION_VALID_MESSAGE'] = $_question_valid_message;
    $coreReplacements['REGISTERERROR'] = $register_errormsg;
    // global
    $coreReplacements['REGISTERFORM'] = $_registerform;
    $coreReplacements['REGISTERMESSAGE1'] = $clang->gT("You must be registered to complete this survey");
    $coreReplacements['REGISTERMESSAGE2'] = $clang->gT("You may register for this survey if you wish to take part.") . "<br />\n" . $clang->gT("Enter your details below, and an email containing the link to participate in this survey will be sent immediately.");
    $coreReplacements['RESTART'] = $_restart;
    $coreReplacements['RETURNTOSURVEY'] = $_return_to_survey;
    $coreReplacements['SAVE'] = $_saveall;
    $coreReplacements['SAVEALERT'] = $_savealert;
    $coreReplacements['SAVEDID'] = $saved_id;
    // global
    $coreReplacements['SAVEERROR'] = $errormsg;
    // global - same as LOADERROR
    $coreReplacements['SAVEFORM'] = $_saveform;
    $coreReplacements['SAVEHEADING'] = $clang->gT("Save Your Unfinished Survey");
    $coreReplacements['SAVEMESSAGE'] = $clang->gT("Enter a name and password for this survey and click save below.") . "<br />\n" . $clang->gT("Your survey will be saved using that name and password, and can be completed later by logging in with the same name and password.") . "<br /><br />\n" . $clang->gT("If you give an email address, an email containing the details will be sent to you.") . "<br /><br />\n" . $clang->gT("After having clicked the save button you can either close this browser window or continue filling out the survey.");
    $coreReplacements['SGQ'] = $_question_sgq;
    $coreReplacements['SID'] = $surveyid;
    // global
    $coreReplacements['SITENAME'] = $sitename;
    // global
    $coreReplacements['SQID'] = $_sqid;
    // global
    $coreReplacements['SUBMITBUTTON'] = $_submitbutton;
    $coreReplacements['SUBMITCOMPLETE'] = "<strong>" . $clang->gT("Thank you!") . "<br /><br />" . $clang->gT("You have completed answering the questions in this survey.") . "</strong><br /><br />" . $clang->gT("Click on 'Submit' now to complete the process and save your answers.");
    $coreReplacements['SUBMITREVIEW'] = $_strreview;
    $coreReplacements['SURVEYCONTACT'] = $_surveycontact;
    $coreReplacements['SURVEYDESCRIPTION'] = isset($thissurvey['description']) ? $thissurvey['description'] : '';
    $coreReplacements['SURVEYFORMAT'] = $surveyformat;
    // global
    $coreReplacements['SURVEYLANGAGE'] = $clang->langcode;
    // this misspelling is kept for legacy reasons
    $coreReplacements['SURVEYLANGUAGE'] = $clang->langcode;
    $coreReplacements['SURVEYLIST'] = $surveylist['list'];
    // global
    $coreReplacements['SURVEYLISTHEADING'] = $surveylist['listheading'];
    // global
    $coreReplacements['SURVEYNAME'] = $thissurvey['name'];
    // global
    $coreReplacements['TEMPLATECSS'] = $_templatecss;
    $coreReplacements['TEMPLATEURL'] = $_templateurl;
    $coreReplacements['THEREAREXQUESTIONS'] = $_therearexquestions;
    if (!$anonymized) {
        $coreReplacements['TOKEN'] = $_token;
    }
    $coreReplacements['URL'] = $_linkreplace;
    $coreReplacements['WELCOME'] = isset($thissurvey['welcome']) ? $thissurvey['welcome'] : '';
    //queXS Addition
    include_once "quexs.php";
    $coreReplacements['IS_INTERVIEWER'] = $interviewer;
    $coreReplacements = array_merge($coreReplacements, quexs_core_replace());
    if (!is_null($replacements) && is_array($replacements)) {
        $doTheseReplacements = array_merge($coreReplacements, $replacements);
        // so $replacements overrides core values
    } else {
        $doTheseReplacements = $coreReplacements;
    }
    // Now do all of the replacements - In rare cases, need to do 3 deep recursion, that that is default
    $line = LimeExpressionManager::ProcessString($line, $questionNum, $doTheseReplacements, false, 3, 1);
    return $line;
}
function do_date($ia)
{
    global $thissurvey;
    header_includes(Yii::app()->getConfig("generalscripts") . 'date.js', 'js');
    $clang = Yii::app()->lang;
    $aQuestionAttributes = getQuestionAttributeValues($ia[0], $ia[4]);
    $checkconditionFunction = "checkconditions";
    $dateformatdetails = getDateFormatDataForQID($aQuestionAttributes, $thissurvey);
    $numberformatdatat = getRadixPointData($thissurvey['surveyls_numberformat']);
    if (trim($aQuestionAttributes['dropdown_dates']) == 1) {
        if (!empty($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$ia[1]])) {
            $datetimeobj = new Date_Time_Converter($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$ia[1]], "Y-m-d H:i:s");
            $currentyear = $datetimeobj->years;
            $currentmonth = $datetimeobj->months;
            $currentdate = $datetimeobj->days;
            $currenthour = $datetimeobj->hours;
            $currentminute = $datetimeobj->minutes;
        } else {
            $currentdate = '';
            $currentmonth = '';
            $currentyear = '';
            $currenthour = '';
            $currentminute = '';
        }
        $dateorder = preg_split('/([-\\.\\/ :])/', $dateformatdetails['phpdate'], -1, PREG_SPLIT_DELIM_CAPTURE);
        $answer = '<p class="question answer-item dropdown-item date-item">';
        foreach ($dateorder as $datepart) {
            switch ($datepart) {
                // Show day select box
                case 'j':
                case 'd':
                    $answer .= '<label for="day' . $ia[1] . '" class="hide">' . $clang->gT('Day') . '</label><select id="day' . $ia[1] . '" name="day' . $ia[1] . '" class="day">
                    <option value="">' . $clang->gT('Day') . "</option>\n";
                    for ($i = 1; $i <= 31; $i++) {
                        if ($i == $currentdate) {
                            $i_date_selected = SELECTED;
                        } else {
                            $i_date_selected = '';
                        }
                        $answer .= '<option value="' . sprintf('%02d', $i) . '"' . $i_date_selected . '>' . sprintf('%02d', $i) . "</option>\n";
                    }
                    $answer .= '</select>';
                    break;
                    // Show month select box
                // Show month select box
                case 'n':
                case 'm':
                    $answer .= '<label for="month' . $ia[1] . '" class="hide">' . $clang->gT('Month') . '</label><select id="month' . $ia[1] . '" name="month' . $ia[1] . '" class="month">
                    <option value="">' . $clang->gT('Month') . "</option>\n";
                    $montharray = array($clang->gT('Jan'), $clang->gT('Feb'), $clang->gT('Mar'), $clang->gT('Apr'), $clang->gT('May'), $clang->gT('Jun'), $clang->gT('Jul'), $clang->gT('Aug'), $clang->gT('Sep'), $clang->gT('Oct'), $clang->gT('Nov'), $clang->gT('Dec'));
                    for ($i = 1; $i <= 12; $i++) {
                        if ($i == $currentmonth) {
                            $i_date_selected = SELECTED;
                        } else {
                            $i_date_selected = '';
                        }
                        $answer .= '<option value="' . sprintf('%02d', $i) . '"' . $i_date_selected . '>' . $montharray[$i - 1] . '</option>';
                    }
                    $answer .= '</select>';
                    break;
                    // Show year select box
                // Show year select box
                case 'Y':
                    $answer .= '<label for="year' . $ia[1] . '" class="hide">' . $clang->gT('Year') . '</label><select id="year' . $ia[1] . '" name="year' . $ia[1] . '" class="year">
                    <option value="">' . $clang->gT('Year') . '</option>';
                    /*
                     *  New question attributes used only if question attribute
                     * "dropdown_dates" is used (see IF(...) above).
                     *
                     * yearmin = Minimum year value for dropdown list, if not set default is 1900
                     * yearmax = Maximum year value for dropdown list, if not set default is 2020
                     */
                    if (trim($aQuestionAttributes['dropdown_dates_year_min']) != '') {
                        $yearmin = (int) LimeExpressionManager::ProcessString($aQuestionAttributes['dropdown_dates_year_min']);
                    } else {
                        $yearmin = 1900;
                    }
                    if (trim($aQuestionAttributes['dropdown_dates_year_max']) != '') {
                        $yearmax = (int) LimeExpressionManager::ProcessString($aQuestionAttributes['dropdown_dates_year_max']);
                    } else {
                        $yearmax = 2020;
                    }
                    if ($yearmin > $yearmax) {
                        $yearmin = 1900;
                        $yearmax = 2020;
                    }
                    if ($aQuestionAttributes['reverse'] == 1) {
                        $tmp = $yearmin;
                        $yearmin = $yearmax;
                        $yearmax = $tmp;
                        $step = 1;
                        $reverse = true;
                    } else {
                        $step = -1;
                        $reverse = false;
                    }
                    for ($i = $yearmax; $reverse ? $i <= $yearmin : $i >= $yearmin; $i += $step) {
                        if ($i == $currentyear) {
                            $i_date_selected = SELECTED;
                        } else {
                            $i_date_selected = '';
                        }
                        $answer .= '<option value="' . $i . '"' . $i_date_selected . '>' . $i . '</option>';
                    }
                    $answer .= '</select>';
                    break;
                case 'H':
                case 'h':
                case 'g':
                case 'G':
                    $answer .= '<label for="hour' . $ia[1] . '" class="hide">' . $clang->gT('Hour') . '</label><select id="hour' . $ia[1] . '" name="hour' . $ia[1] . '" class="hour"><option value="">' . $clang->gT('Hour') . '</option>';
                    for ($i = 0; $i < 24; $i++) {
                        if ($i === $currenthour) {
                            $i_date_selected = SELECTED;
                        } else {
                            $i_date_selected = '';
                        }
                        if ($datepart == 'H') {
                            $answer .= '<option value="' . $i . '"' . $i_date_selected . '>' . sprintf('%02d', $i) . '</option>';
                        } else {
                            $answer .= '<option value="' . $i . '"' . $i_date_selected . '>' . $i . '</option>';
                        }
                    }
                    $answer .= '</select>';
                    break;
                case 'i':
                    $answer .= '<label for="minute' . $ia[1] . '" class="hide">' . $clang->gT('Minute') . '</label><select id="minute' . $ia[1] . '" name="minute' . $ia[1] . '" class="minute">
                    <option value="">' . $clang->gT('Minute') . '</option>';
                    for ($i = 0; $i < 60; $i += $aQuestionAttributes['dropdown_dates_minute_step']) {
                        if ($i === $currentminute) {
                            $i_date_selected = SELECTED;
                        } else {
                            $i_date_selected = '';
                        }
                        if ($datepart == 'i') {
                            $answer .= '<option value="' . $i . '"' . $i_date_selected . '>' . sprintf('%02d', $i) . '</option>';
                        } else {
                            $answer .= '<option value="' . $i . '"' . $i_date_selected . '>' . $i . '</option>';
                        }
                    }
                    $answer .= '</select>';
                    break;
                default:
                    $answer .= $datepart;
            }
        }
        $answer .= '<input class="text" type="text" size="10" name="' . $ia[1] . '" style="display: none" id="answer' . $ia[1] . '" value="' . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$ia[1]] . '" maxlength="10" alt="' . $clang->gT('Answer') . '" onchange="' . $checkconditionFunction . '(this.value, this.name, this.type)" />
        </p>';
        $answer .= '<input type="hidden" name="qattribute_answer[]" value="' . $ia[1] . '" />
        <input type="hidden" id="qattribute_answer' . $ia[1] . '" name="qattribute_answer' . $ia[1] . '" />
        <input type="hidden" id="dateformat' . $ia[1] . '" value="' . $dateformatdetails['jsdate'] . '"/>';
    } else {
        if ($clang->langcode !== 'en') {
            header_includes(Yii::app()->getConfig("generalscripts") . 'jquery/locale/jquery.ui.datepicker-' . $clang->langcode . '.js');
        }
        // Format the date  for output
        if (trim($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$ia[1]]) != '') {
            $datetimeobj = new Date_Time_Converter($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$ia[1]], "Y-m-d H:i");
            $dateoutput = $datetimeobj->convert($dateformatdetails['phpdate']);
        } else {
            $dateoutput = '';
        }
        if (trim($aQuestionAttributes['dropdown_dates_year_min']) != '') {
            $minyear = $aQuestionAttributes['dropdown_dates_year_min'];
        } else {
            $minyear = '1900';
        }
        if (trim($aQuestionAttributes['dropdown_dates_year_max']) != '') {
            $maxyear = $aQuestionAttributes['dropdown_dates_year_max'];
        } else {
            $maxyear = '2020';
        }
        $goodchars = str_replace(array("m", "d", "y"), "", $dateformatdetails['jsdate']);
        $goodchars = "0123456789" . substr($goodchars, 0, 1);
        $iLength = strlen($dateformatdetails['dateformat']);
        $answer = "<p class='question answer-item text-item date-item'><label for='answer{$ia[1]}' class='hide label'>{$clang->gT('Date picker')}</label>\n        <input class='popupdate' type=\"text\" size=\"{$iLength}\" name=\"{$ia[1]}\" title='" . sprintf($clang->gT('Format: %s'), $dateformatdetails['dateformat']) . "' id=\"answer{$ia[1]}\" value=\"{$dateoutput}\" maxlength=\"{$iLength}\" onkeypress=\"return goodchars(event,'" . $goodchars . "')\" onchange=\"{$checkconditionFunction}(this.value, this.name, this.type)\" />\n        <input  type='hidden' name='dateformat{$ia[1]}' id='dateformat{$ia[1]}' value='{$dateformatdetails['jsdate']}'  />\n        <input  type='hidden' name='datelanguage{$ia[1]}' id='datelanguage{$ia[1]}' value='{$clang->langcode}'  />\n        <input  type='hidden' name='dateyearrange{$ia[1]}' id='dateyearrange{$ia[1]}' value='{$minyear}:{$maxyear}'  />\n\n        </p>";
        if (trim($aQuestionAttributes['hide_tip']) == 1) {
            $answer .= "<p class=\"tip\">" . sprintf($clang->gT('Format: %s'), $dateformatdetails['dateformat']) . "</p>";
        }
    }
    $inputnames[] = $ia[1];
    return array($answer, $inputnames);
}
Exemplo n.º 14
0
function do_date($ia)
{
    global $thissurvey;
    $clang = Yii::app()->lang;
    $aQuestionAttributes = getQuestionAttributeValues($ia[0], $ia[4]);
    $sDateLangvarJS = " translt = {\n         alertInvalidDate: '" . $clang->gT('Date entered is invalid!', 'js') . "',\n         infoCompleteAll: '" . $clang->gT('Please complete all parts of the date!', 'js') . "'\n        };";
    App()->getClientScript()->registerScript("sDateLangvarJS", $sDateLangvarJS, CClientScript::POS_HEAD);
    App()->getClientScript()->registerScriptFile(Yii::app()->getConfig("generalscripts") . 'date.js');
    App()->getClientScript()->registerScriptFile(Yii::app()->getConfig("third_party") . '/jstoolbox/date.js');
    $checkconditionFunction = "checkconditions";
    $dateformatdetails = getDateFormatDataForQID($aQuestionAttributes, $thissurvey);
    $numberformatdatat = getRadixPointData($thissurvey['surveyls_numberformat']);
    $sMindatetailor = '';
    $sMaxdatetailor = '';
    // date_min: Determine whether we have an expression, a full date (YYYY-MM-DD) or only a year(YYYY)
    if (trim($aQuestionAttributes['date_min']) != '') {
        $date_min = $aQuestionAttributes['date_min'];
        if (preg_match("/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])/", $date_min)) {
            $mindate = $date_min;
        } elseif (strlen($date_min) == 4 && $date_min >= 1900 && $date_min <= 2099) {
            // backward compatibility: if only a year is given, add month and day
            $mindate = $date_min . '-01-01';
        } else {
            $mindate = '{' . $aQuestionAttributes['date_min'] . '}';
            // get the LEMtailor ID, remove the span tags
            $sMindatespan = LimeExpressionManager::ProcessString($mindate, $ia[0], NULL, false, 1, 1);
            preg_match("/LEMtailor_Q_[0-9]{1,7}_[0-9]{1,3}/", $sMindatespan, $matches);
            if (isset($matches[0])) {
                $sMindatetailor = $matches[0];
            }
        }
    } else {
        $mindate = '1900-01-01';
    }
    // date_max: Determine whether we have an expression, a full date (YYYY-MM-DD) or only a year(YYYY)
    if (trim($aQuestionAttributes['date_max']) != '') {
        $date_max = $aQuestionAttributes['date_max'];
        if (preg_match("/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])/", $date_max)) {
            $maxdate = $date_max;
        } elseif (strlen($date_max) == 4 && $date_max >= 1900 && $date_max <= 2099) {
            // backward compatibility: if only a year is given, add month and day
            $maxdate = $date_max . '-12-31';
        } else {
            $maxdate = '{' . $aQuestionAttributes['date_max'] . '}';
            // get the LEMtailor ID, remove the span tags
            $sMaxdatespan = LimeExpressionManager::ProcessString($maxdate, $ia[0], NULL, false, 1, 1);
            preg_match("/LEMtailor_Q_[0-9]{1,7}_[0-9]{1,3}/", $sMaxdatespan, $matches);
            if (isset($matches[0])) {
                $sMaxdatetailor = $matches[0];
            }
        }
    } else {
        $maxdate = '2037-12-31';
    }
    if (trim($aQuestionAttributes['dropdown_dates']) == 1) {
        if (!empty($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$ia[1]]) & $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$ia[1]] != 'INVALID') {
            $datetimeobj = new Date_Time_Converter($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$ia[1]], "Y-m-d H:i:s");
            $currentyear = $datetimeobj->years;
            $currentmonth = $datetimeobj->months;
            $currentdate = $datetimeobj->days;
            $currenthour = $datetimeobj->hours;
            $currentminute = $datetimeobj->minutes;
        } else {
            $currentdate = '';
            $currentmonth = '';
            $currentyear = '';
            $currenthour = '';
            $currentminute = '';
        }
        $dateorder = preg_split('/([-\\.\\/ :])/', $dateformatdetails['phpdate'], -1, PREG_SPLIT_DELIM_CAPTURE);
        $answer = '<p class="question answer-item dropdown-item date-item">';
        foreach ($dateorder as $datepart) {
            switch ($datepart) {
                // Show day select box
                case 'j':
                case 'd':
                    $answer .= '<label for="day' . $ia[1] . '" class="hide">' . $clang->gT('Day') . '</label><select id="day' . $ia[1] . '" name="day' . $ia[1] . '" class="day">
                    <option value="">' . $clang->gT('Day') . "</option>\n";
                    for ($i = 1; $i <= 31; $i++) {
                        if ($i == $currentdate) {
                            $i_date_selected = SELECTED;
                        } else {
                            $i_date_selected = '';
                        }
                        $answer .= '<option value="' . sprintf('%02d', $i) . '"' . $i_date_selected . '>' . sprintf('%02d', $i) . "</option>\n";
                    }
                    $answer .= '</select>';
                    break;
                    // Show month select box
                // Show month select box
                case 'n':
                case 'm':
                    $answer .= '<label for="month' . $ia[1] . '" class="hide">' . $clang->gT('Month') . '</label><select id="month' . $ia[1] . '" name="month' . $ia[1] . '" class="month">
                    <option value="">' . $clang->gT('Month') . "</option>\n";
                    switch ((int) trim($aQuestionAttributes['dropdown_dates_month_style'])) {
                        case 0:
                            $montharray = array($clang->gT('Jan'), $clang->gT('Feb'), $clang->gT('Mar'), $clang->gT('Apr'), $clang->gT('May'), $clang->gT('Jun'), $clang->gT('Jul'), $clang->gT('Aug'), $clang->gT('Sep'), $clang->gT('Oct'), $clang->gT('Nov'), $clang->gT('Dec'));
                            break;
                        case 1:
                            $montharray = array($clang->gT('January'), $clang->gT('February'), $clang->gT('March'), $clang->gT('April'), $clang->gT('May'), $clang->gT('June'), $clang->gT('July'), $clang->gT('August'), $clang->gT('September'), $clang->gT('October'), $clang->gT('November'), $clang->gT('December'));
                            break;
                        case 2:
                            $montharray = array('01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12');
                            break;
                    }
                    for ($i = 1; $i <= 12; $i++) {
                        if ($i == $currentmonth) {
                            $i_date_selected = SELECTED;
                        } else {
                            $i_date_selected = '';
                        }
                        $answer .= '<option value="' . sprintf('%02d', $i) . '"' . $i_date_selected . '>' . $montharray[$i - 1] . '</option>';
                    }
                    $answer .= '</select>';
                    break;
                    // Show year select box
                // Show year select box
                case 'y':
                case 'Y':
                    $answer .= '<label for="year' . $ia[1] . '" class="hide">' . $clang->gT('Year') . '</label><select id="year' . $ia[1] . '" name="year' . $ia[1] . '" class="year">
                    <option value="">' . $clang->gT('Year') . '</option>';
                    /*
                     * yearmin = Minimum year value for dropdown list, if not set default is 1900
                     * yearmax = Maximum year value for dropdown list, if not set default is 2037
                     * if full dates (format: YYYY-MM-DD) are given, only the year is used
                     */
                    $yearmin = (int) substr(LimeExpressionManager::ProcessString($mindate), 0, 4);
                    if (!isset($yearmin) || $yearmin == 0) {
                        $yearmin = 1900;
                    }
                    $yearmax = (int) substr(LimeExpressionManager::ProcessString($maxdate), 0, 4);
                    if (!isset($yearmax) || $yearmax == 0) {
                        $yearmax = 2037;
                    }
                    if ($yearmin > $yearmax) {
                        $yearmin = 1900;
                        $yearmax = 2037;
                    }
                    if ($aQuestionAttributes['reverse'] == 1) {
                        $tmp = $yearmin;
                        $yearmin = $yearmax;
                        $yearmax = $tmp;
                        $step = 1;
                        $reverse = true;
                    } else {
                        $step = -1;
                        $reverse = false;
                    }
                    for ($i = $yearmax; $reverse ? $i <= $yearmin : $i >= $yearmin; $i += $step) {
                        if ($i == $currentyear) {
                            $i_date_selected = SELECTED;
                        } else {
                            $i_date_selected = '';
                        }
                        $answer .= '<option value="' . $i . '"' . $i_date_selected . '>' . $i . '</option>';
                    }
                    $answer .= '</select>';
                    break;
                case 'H':
                case 'h':
                case 'g':
                case 'G':
                    $answer .= '<label for="hour' . $ia[1] . '" class="hide">' . $clang->gT('Hour') . '</label><select id="hour' . $ia[1] . '" name="hour' . $ia[1] . '" class="hour"><option value="">' . $clang->gT('Hour') . '</option>';
                    for ($i = 0; $i < 24; $i++) {
                        if ($i === (int) $currenthour && is_numeric($currenthour)) {
                            $i_date_selected = SELECTED;
                        } else {
                            $i_date_selected = '';
                        }
                        if ($datepart == 'H') {
                            $answer .= '<option value="' . $i . '"' . $i_date_selected . '>' . sprintf('%02d', $i) . '</option>';
                        } else {
                            $answer .= '<option value="' . $i . '"' . $i_date_selected . '>' . $i . '</option>';
                        }
                    }
                    $answer .= '</select>';
                    break;
                case 'i':
                    $answer .= '<label for="minute' . $ia[1] . '" class="hide">' . $clang->gT('Minute') . '</label><select id="minute' . $ia[1] . '" name="minute' . $ia[1] . '" class="minute">
                    <option value="">' . $clang->gT('Minute') . '</option>';
                    for ($i = 0; $i < 60; $i += $aQuestionAttributes['dropdown_dates_minute_step']) {
                        if ($i === (int) $currentminute && is_numeric($currentminute)) {
                            $i_date_selected = SELECTED;
                        } else {
                            $i_date_selected = '';
                        }
                        if ($datepart == 'i') {
                            $answer .= '<option value="' . $i . '"' . $i_date_selected . '>' . sprintf('%02d', $i) . '</option>';
                        } else {
                            $answer .= '<option value="' . $i . '"' . $i_date_selected . '>' . $i . '</option>';
                        }
                    }
                    $answer .= '</select>';
                    break;
                default:
                    $answer .= $datepart;
            }
        }
        // Format the date  for output
        $dateoutput = trim($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$ia[1]]);
        if ($dateoutput != '' & $dateoutput != 'INVALID') {
            $datetimeobj = new Date_Time_Converter($dateoutput, "Y-m-d H:i");
            $dateoutput = $datetimeobj->convert($dateformatdetails['phpdate']);
        }
        $answer .= '<input class="text" type="text" size="10" name="' . $ia[1] . '" style="display: none" id="answer' . $ia[1] . '" value="' . htmlspecialchars($dateoutput, ENT_QUOTES, 'utf-8') . '" maxlength="10" alt="' . $clang->gT('Answer') . '" onchange="' . $checkconditionFunction . '(this.value, this.name, this.type)" title="' . sprintf($clang->gT('Date in the format : %s'), $dateformatdetails['dateformat']) . '" />
        </p>';
        $answer .= '
        <input type="hidden" id="qattribute_answer' . $ia[1] . '" name="qattribute_answer' . $ia[1] . '" value="' . $ia[1] . '"/>
        <input type="hidden" id="dateformat' . $ia[1] . '" value="' . $dateformatdetails['jsdate'] . '"/>';
        App()->getClientScript()->registerScript("doDropDownDate{$ia[0]}", "doDropDownDate({$ia[0]});", CClientScript::POS_HEAD);
        // MayDo:
        // add js code to
        //        - fill dropdown boxes according to min/max
        //        - if one datefield box is changed update all others
        //        - would need a LOT of JS
    } else {
        //register timepicker extension
        App()->getClientScript()->registerPackage('jqueryui-timepicker');
        // Locale for datepicker and timpicker extension
        if ($clang->langcode !== 'en') {
            Yii::app()->getClientScript()->registerScriptFile(App()->getConfig('third_party') . "/jqueryui/development-bundle/ui/i18n/jquery.ui.datepicker-{$clang->langcode}.js");
            Yii::app()->getClientScript()->registerScriptFile(App()->getConfig('third_party') . "/jquery-ui-timepicker-addon/i18n/jquery-ui-timepicker-{$clang->langcode}.js");
        }
        // Format the date  for output
        $dateoutput = trim($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$ia[1]]);
        if ($dateoutput != '' & $dateoutput != 'INVALID') {
            $datetimeobj = new Date_Time_Converter($dateoutput, "Y-m-d H:i");
            $dateoutput = $datetimeobj->convert($dateformatdetails['phpdate']);
        }
        $goodchars = str_replace(array("m", "d", "y"), "", $dateformatdetails['jsdate']);
        $goodchars = "0123456789" . substr($goodchars, 0, 1);
        // Max length of date : Get the date of 1999-12-30 at 32:59:59 to be sure to have space with non leading 0 format
        // "+1" makes room for a trailing space in date/time values
        $iLength = strlen(date($dateformatdetails['phpdate'], mktime(23, 59, 59, 12, 30, 1999))) + 1;
        // HTML for date question using datepicker
        $answer = "<p class='question answer-item text-item date-item'><label for='answer{$ia[1]}' class='hide label'>{$clang->gT('Date picker')}</label>\n        <input class='popupdate' type=\"text\" size=\"{$iLength}\" name=\"{$ia[1]}\" title='" . sprintf($clang->gT('Format: %s'), $dateformatdetails['dateformat']) . "' id=\"answer{$ia[1]}\" value=\"{$dateoutput}\" maxlength=\"{$iLength}\" onkeypress=\"return goodchars(event,'" . $goodchars . "')\" onchange=\"{$checkconditionFunction}(this.value, this.name, this.type)\" />\n        <input  type='hidden' name='dateformat{$ia[1]}' id='dateformat{$ia[1]}' value='{$dateformatdetails['jsdate']}'  />\n        <input  type='hidden' name='datelanguage{$ia[1]}' id='datelanguage{$ia[1]}' value='{$clang->langcode}'  />\n        <input  type='hidden' name='datemin{$ia[1]}' id='datemin{$ia[1]}' value=\"{$mindate}\"    />\n        <input  type='hidden' name='datemax{$ia[1]}' id='datemax{$ia[1]}' value=\"{$maxdate}\"   />\n        </p>";
        // adds min and max date as a hidden element to the page so EM creates the needed LEM_tailor_Q_XX sections
        $sHiddenHtml = "";
        if (!empty($sMindatetailor)) {
            $sHiddenHtml .= $sMindatespan;
        }
        if (!empty($sMaxdatetailor)) {
            $sHiddenHtml .= $sMaxdatespan;
        }
        if (!empty($sHiddenHtml)) {
            $answer .= "<div class='hidden nodisplay' style='display:none'>{$sHiddenHtml}</div>";
        }
        // following JS is for setting datepicker limits on-the-fly according to variables given in date_min/max attributes
        // works with full dates (format: YYYY-MM-DD, js not needed), only a year, for backward compatibility (YYYY, js not needed),
        // variable names which refer to another date question or expressions.
        // Actual conversion of date formats is handled in LEMval()
        if (!empty($sMindatetailor) || !empty($sMaxdatetailor)) {
            $answer .= "<script> \n                \$(document).ready(function() {\n                        \$('.popupdate').change(function() {\n                            \n                            ";
            if (!empty($sMindatetailor)) {
                $answer .= " \n                        \$('#datemin{$ia[1]}').attr('value', \n                        document.getElementById('{$sMindatetailor}').innerHTML);\n                    ";
            }
            if (!empty($sMaxdatetailor)) {
                $answer .= "\n                        \$('#datemax{$ia[1]}').attr('value', \n                        document.getElementById('{$sMaxdatetailor}').innerHTML);\n                    ";
            }
            $answer .= "\n                        });\n                    });\n                </script>";
        }
        if (trim($aQuestionAttributes['hide_tip']) == 1) {
            $answer .= "<p class=\"tip\">" . sprintf($clang->gT('Format: %s'), $dateformatdetails['dateformat']) . "</p>";
        }
        //App()->getClientScript()->registerScript("doPopupDate{$ia[0]}","doPopupDate({$ia[0]})",CClientScript::POS_END);// Beter if just afetre answers part
        $answer .= "<script type='text/javascript'>\n" . "  /*<![CDATA[*/\n" . " doPopupDate({$ia[0]});\n" . " /*]]>*/\n" . "</script>\n";
    }
    $inputnames[] = $ia[1];
    return array($answer, $inputnames);
}
Exemplo n.º 15
0
                <?php if ($qrrow['mandatory'] == "Y") { ?>
                    <?php eT("Yes"); ?>
                    <?php } else
                    { ?>
                    <?php eT("No"); ?>

                    <?php } ?>
            </td>
        </tr>
        <?php } ?>
    <?php if (trim($qrrow['relevance']) != '') { ?>
        <tr>
            <td><?php eT("Relevance equation:"); ?></td>
            <td>
                <?php
                    LimeExpressionManager::ProcessString("{" . $qrrow['relevance'] . "}", $qid);    // tests Relevance equation so can pretty-print it
                    echo LimeExpressionManager::GetLastPrettyPrintExpression();
                ?>
            </td>
        </tr>
        <?php } ?>
    <?php
        $sCurrentCategory='';
        foreach ($advancedsettings as $aAdvancedSetting)
        { ?>
        <tr>
            <td><?php echo $aAdvancedSetting['caption'];?>:</td>
            <td><?php
                    if ($aAdvancedSetting['i18n']==false)  echo htmlspecialchars($aAdvancedSetting['value']); else echo htmlspecialchars($aAdvancedSetting[$baselang]['value'])?>
            </td>
        </tr>
Exemplo n.º 16
0
 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);
 }
Exemplo n.º 17
0
function do_multiplenumeric($ia)
{
    global $thissurvey;
    $extraclass = "";
    $checkconditionFunction = "fixnum_checkconditions";
    $aQuestionAttributes = QuestionAttribute::model()->getQuestionAttributes($ia[0]);
    $answer = '';
    $sSeparator = getRadixPointData($thissurvey['surveyls_numberformat']);
    $sSeparator = $sSeparator['separator'];
    $extraclass .= " numberonly";
    //Must turn on the "numbers only javascript"
    if (intval(trim($aQuestionAttributes['maximum_chars'])) > 0) {
        $maximum_chars = intval(trim($aQuestionAttributes['maximum_chars']));
        // Only maxlength attribute, use textarea[maxlength] jquery selector for textarea
        $maxlength = "maxlength='{$maximum_chars}' ";
        $extraclass .= " maxchars maxchars-" . $maximum_chars;
    } else {
        $maxlength = " maxlength='25' ";
    }
    if (trim($aQuestionAttributes['prefix'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']]) != '') {
        $prefix = $aQuestionAttributes['prefix'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']];
        $extraclass .= " withprefix";
    } else {
        $prefix = '';
    }
    if (trim($aQuestionAttributes['suffix'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']]) != '') {
        $suffix = $aQuestionAttributes['suffix'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']];
        $extraclass .= " withsuffix";
    } else {
        $suffix = '';
    }
    $kpclass = testKeypad($thissurvey['nokeyboard']);
    // Virtual keyboard (probably obsolete today)
    $numbersonly_slider = '';
    // DEPRECATED
    if (trim($aQuestionAttributes['text_input_width']) != '') {
        $tiwidth = $aQuestionAttributes['text_input_width'];
        $col = $aQuestionAttributes['text_input_width'] <= 12 ? $aQuestionAttributes['text_input_width'] : 12;
        //$extraclass .= " col-sm-".trim($col);
    } else {
        $tiwidth = 6;
    }
    $prefixclass = "numeric";
    if ($aQuestionAttributes['slider_layout'] == 1) {
        $prefixclass = "slider";
        $slider_layout = true;
        $extraclass .= " withslider";
        $slider_step = trim(LimeExpressionManager::ProcessString("{{$aQuestionAttributes['slider_accuracy']}}", $ia[0], array(), false, 1, 1, false, false, true));
        $slider_step = is_numeric($slider_step) ? $slider_step : 1;
        $slider_min = trim(LimeExpressionManager::ProcessString("{{$aQuestionAttributes['slider_min']}}", $ia[0], array(), false, 1, 1, false, false, true));
        $slider_mintext = $slider_min = is_numeric($slider_min) ? $slider_min : 0;
        $slider_max = trim(LimeExpressionManager::ProcessString("{{$aQuestionAttributes['slider_max']}}", $ia[0], array(), false, 1, 1, false, false, true));
        $slider_maxtext = $slider_max = is_numeric($slider_max) ? $slider_max : 100;
        $slider_default = trim(LimeExpressionManager::ProcessString("{{$aQuestionAttributes['slider_default']}}", $ia[0], array(), false, 1, 1, false, false, true));
        $slider_default = is_numeric($slider_default) ? $slider_default : "";
        $slider_orientation = trim($aQuestionAttributes['slider_orientation']) == 0 ? 'horizontal' : 'vertical';
        $slider_custom_handle = trim($aQuestionAttributes['slider_custom_handle']);
        switch (trim($aQuestionAttributes['slider_handle'])) {
            case 0:
                $slider_handle = 'round';
                break;
            case 1:
                $slider_handle = 'square';
                break;
            case 2:
                $slider_handle = 'triangle';
                break;
            case 3:
                $slider_handle = 'custom';
                break;
        }
        if ($slider_default == '' && $aQuestionAttributes['slider_middlestart'] == 1) {
            $slider_middlestart = intval(($slider_max + $slider_min) / 2);
        } else {
            $slider_middlestart = '';
        }
        $slider_separator = trim($aQuestionAttributes['slider_separator']) != '' ? $aQuestionAttributes['slider_separator'] : "";
        $slider_reset = $aQuestionAttributes['slider_reset'] ? 1 : 0;
        // If the slider reset is ON, slider should be max 10 columns
        if ($slider_reset) {
            $tiwidth = $tiwidth < 10 ? $tiwidth : 10;
        }
    } else {
        $slider_layout = false;
        $slider_step = '';
        $slider_min = '';
        $slider_mintext = '';
        $slider_max = '';
        $slider_maxtext = '';
        $slider_default = null;
        $slider_orientation = '';
        $slider_handle = '';
        $slider_custom_handle = '';
        $slider_separator = '';
        $slider_reset = 0;
        $slider_startvalue = '';
        $slider_displaycallout = '';
    }
    $hidetip = $aQuestionAttributes['hide_tip'];
    if ($aQuestionAttributes['random_order'] == 1) {
        $ansquery = "SELECT * FROM {{questions}} WHERE parent_qid={$ia['0']}  AND language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "' ORDER BY " . dbRandom();
    } else {
        $ansquery = "SELECT * FROM {{questions}} WHERE parent_qid={$ia['0']}  AND language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "' ORDER BY question_order";
    }
    $ansresult = dbExecuteAssoc($ansquery);
    //Checked
    $aSubquestions = $ansresult->readAll();
    $anscount = count($aSubquestions) * 2;
    $fn = 1;
    $sRows = "";
    $answer_main = '';
    $inputnames = array();
    if ($anscount == 0) {
        $noanswer = true;
        $answer = doRender('/survey/questions/multiplenumeric/empty', array(), true);
    } else {
        foreach ($aSubquestions as $ansrow) {
            $labelText = $ansrow['question'];
            $myfname = $ia[1] . $ansrow['title'];
            if ($ansrow['question'] == "") {
                $ansrow['question'] = "&nbsp;";
            }
            if ($slider_layout === false || $slider_separator == '') {
                $theanswer = $ansrow['question'];
                $sliders = false;
            } else {
                $aAnswer = explode($slider_separator, $ansrow['question']);
                $theanswer = isset($aAnswer[0]) ? $aAnswer[0] : "";
                $labelText = $theanswer;
                $sliderleft = isset($aAnswer[1]) ? $aAnswer[1] : "";
                $sliderright = isset($aAnswer[2]) ? $aAnswer[2] : "";
                $sliders = true;
            }
            $aAnswer = isset($aAnswer) ? $aAnswer : '';
            $sliderleft = isset($sliderleft) ? $sliderleft : "";
            $sliderright = isset($sliderright) ? $sliderright : "";
            // color code missing mandatory questions red
            $alert = '';
            if ($_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['step'] != $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['maxstep'] || $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['step'] == $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['prevstep']) {
                if ($ia[6] == 'Y' && $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname] === '') {
                    $alert = true;
                }
            }
            //list($htmltbody2, $hiddenfield)=return_array_filter_strings($ia, $aQuestionAttributes, $thissurvey, $ansrow, $myfname, '', $myfname, "div","form-group question-item answer-item text-item numeric-item".$extraclass);
            $sDisplayStyle = return_display_style($ia, $aQuestionAttributes, $thissurvey, $myfname);
            // TODO : check why it's done here a second time
            $sSeparator = getRadixPointData($thissurvey['surveyls_numberformat']);
            $sSeparator = $sSeparator['separator'];
            // The value of the slider depends on many possible different parameters, by order of priority :
            // 1. The value stored in the session
            // 2. Else the default Answer   (set by EM and stored in session, so same case than 1)
            // 3. Else the init value
            // 4. Else the middle start
            // 5. If no value at all, or if middle start, the "user no action" is recorded as null in the database
            // For bootstrap slider, the value can't be NULL so we set it by default to the slider minimum value.
            // The old behaviour of "null" value (corresponding to user no action) is implemented via $slider_user_no_action
            // It could be used to show a temporary "No Answer" checkbox (hidden when user touch the slider)
            // Most of this javascript is here to handle the fact that bootstrapSlider need numerical value in the input
            // It can't accept "NULL" nor anyother thousand separator than "." (else it become a string)
            // See : https://github.com/LimeSurvey/LimeSurvey/blob/master/scripts/bootstrap-slider.js#l1453-l1461
            // If the bootstrapSlider were updated, most of this javascript would not be necessary.
            $sValue = null;
            if (App()->request->getPost('slider_user_no_action_' . $myfname)) {
                $slider_user_no_action = App()->request->getPost('slider_user_no_action_' . $myfname);
            } else {
                $slider_user_no_action = 1;
                // value stored in _SESSION
                if (isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname])) {
                    $sValue = $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname];
                    $slider_user_no_action = 0;
                } elseif ($slider_default != "") {
                    $sValue = $slider_default;
                    $slider_user_no_action = 0;
                } elseif (isset($slider_middlestart) && $slider_middlestart != '') {
                    $sValue = $slider_middlestart;
                }
            }
            $sUnformatedValue = $sValue;
            if (strpos($sValue, ".")) {
                $sValue = rtrim(rtrim($sValue, "0"), ".");
                $sValue = str_replace('.', $sSeparator, $sValue);
            }
            if (trim($aQuestionAttributes['num_value_int_only']) == 1) {
                $extraclass .= " integeronly";
                $answertypeclass = " integeronly";
                $integeronly = 1;
            } else {
                $answertypeclass = "";
                $integeronly = 0;
            }
            if (!$sliders) {
                $sRows .= doRender('/survey/questions/multiplenumeric/rows/input/answer_row', array('qid' => $ia[0], 'extraclass' => $extraclass, 'answertypeclass' => $answertypeclass, 'sDisplayStyle' => $sDisplayStyle, 'kpclass' => $kpclass, 'alert' => $alert, 'theanswer' => $theanswer, 'labelname' => 'answer' . $myfname, 'prefixclass' => $prefixclass, 'prefix' => $prefix, 'suffix' => $suffix, 'tiwidth' => $tiwidth, 'myfname' => $myfname, 'dispVal' => $sValue, 'maxlength' => $maxlength, 'labelText' => $labelText, 'checkconditionFunction' => $checkconditionFunction . '(this.value, this.name, this.type, \'onchange\',' . $integeronly . ')', 'integeronly' => $integeronly), true);
            } else {
                $sRows .= doRender('/survey/questions/multiplenumeric/rows/sliders/answer_row', array('qid' => $ia[0], 'extraclass' => $extraclass, 'sDisplayStyle' => $sDisplayStyle, 'kpclass' => $kpclass, 'alert' => $alert, 'theanswer' => $theanswer, 'labelname' => 'answer' . $myfname, 'prefixclass' => $prefixclass, 'sliders' => $sliders, 'sliderleft' => $sliderleft, 'sliderright' => $sliderright, 'prefix' => $prefix, 'suffix' => $suffix, 'tiwidth' => $tiwidth, 'myfname' => $myfname, 'dispVal' => $sValue, 'maxlength' => $maxlength, 'labelText' => $labelText, 'checkconditionFunction' => $checkconditionFunction . '(this.value, this.name, this.type)', 'slider_orientation' => $slider_orientation, 'slider_step' => $slider_step, 'slider_min' => $slider_min, 'slider_mintext' => $slider_mintext, 'slider_max' => $slider_max, 'slider_maxtext' => $slider_maxtext, 'slider_default' => $slider_default, 'slider_handle' => isset($slider_handle) ? $slider_handle : '', 'slider_reset' => $slider_reset, 'slider_custom_handle' => $slider_custom_handle, 'slider_user_no_action' => $slider_user_no_action, 'slider_showminmax' => $aQuestionAttributes['slider_showminmax'], 'sSeparator' => $sSeparator, 'sUnformatedValue' => $sUnformatedValue), true);
            }
            $fn++;
            $inputnames[] = $myfname;
        }
        $displaytotal = false;
        $equals_num_value = false;
        if (trim($aQuestionAttributes['equals_num_value']) != '' || trim($aQuestionAttributes['min_num_value']) != '' || trim($aQuestionAttributes['max_num_value']) != '') {
            $qinfo = LimeExpressionManager::GetQuestionStatus($ia[0]);
            if (trim($aQuestionAttributes['equals_num_value']) != '') {
                $equals_num_value = true;
            }
            $displaytotal = true;
        }
        // TODO: Slider and multiple-numeric input should really be two different question types
        $templateFile = $sliders ? 'answer' : 'answer_input';
        $answer = doRender('/survey/questions/multiplenumeric/' . $templateFile, array('sRows' => $sRows, 'prefixclass' => $prefixclass, 'equals_num_value' => $equals_num_value, 'id' => $ia[0], 'prefix' => $prefix, 'suffix' => $suffix, 'sumRemainingEqn' => isset($qinfo) ? $qinfo['sumRemainingEqn'] : '', 'displaytotal' => $displaytotal, 'sumEqn' => isset($qinfo) ? $qinfo['sumEqn'] : '', 'prefix' => $prefix), true);
    }
    if ($aQuestionAttributes['slider_layout'] == 1) {
        Yii::app()->getClientScript()->registerScriptFile(App()->baseUrl . "/third_party/bootstrap-slider/bootstrap-slider.js");
    }
    $sSeparator = getRadixPointData($thissurvey['surveyls_numberformat']);
    $sSeparator = $sSeparator['separator'];
    return array($answer, $inputnames);
}
Exemplo n.º 18
0
function do_multiplenumeric($ia)
{
    global $thissurvey;
    $extraclass = "";
    $checkconditionFunction = "fixnum_checkconditions";
    $aQuestionAttributes = getQuestionAttributeValues($ia[0]);
    $answer = '';
    $sSeparator = getRadixPointData($thissurvey['surveyls_numberformat']);
    $sSeparator = $sSeparator['separator'];
    //Must turn on the "numbers only javascript"
    $extraclass .= " numberonly";
    if ($aQuestionAttributes['thousands_separator'] == 1) {
        App()->clientScript->registerPackage('jquery-price-format');
        App()->clientScript->registerScriptFile('scripts/numerical_input.js');
        $extraclass .= " thousandsseparator";
    }
    if (intval(trim($aQuestionAttributes['maximum_chars'])) > 0) {
        // Only maxlength attribute, use textarea[maxlength] jquery selector for textarea
        $maximum_chars = intval(trim($aQuestionAttributes['maximum_chars']));
        $maxlength = "maxlength='{$maximum_chars}' ";
        $extraclass .= " maxchars maxchars-" . $maximum_chars;
    } else {
        $maxlength = " maxlength='25' ";
    }
    if (trim($aQuestionAttributes['prefix'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']]) != '') {
        $prefix = $aQuestionAttributes['prefix'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']];
        $extraclass .= " withprefix";
    } else {
        $prefix = '';
    }
    if (trim($aQuestionAttributes['suffix'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']]) != '') {
        $suffix = $aQuestionAttributes['suffix'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']];
        $extraclass .= " withsuffix";
    } else {
        $suffix = '';
    }
    if ($thissurvey['nokeyboard'] == 'Y') {
        includeKeypad();
        $kpclass = "num-keypad";
        $extraclass .= " keypad";
    } else {
        $kpclass = "";
    }
    $numbersonly_slider = '';
    // DEPRECATED
    if (trim($aQuestionAttributes['text_input_width']) != '') {
        $tiwidth = $aQuestionAttributes['text_input_width'];
        $extraclass .= " inputwidth" . trim($aQuestionAttributes['text_input_width']);
    } else {
        $tiwidth = 10;
    }
    $prefixclass = "numeric";
    if ($aQuestionAttributes['slider_layout'] == 1) {
        $prefixclass = "slider";
        $slider_layout = true;
        $extraclass .= " withslider";
        $slider_step = trim(LimeExpressionManager::ProcessString("{{$aQuestionAttributes['slider_accuracy']}}", $ia[0], array(), false, 1, 1, false, false, true));
        $slider_step = is_numeric($slider_step) ? $slider_step : 1;
        $slider_min = trim(LimeExpressionManager::ProcessString("{{$aQuestionAttributes['slider_min']}}", $ia[0], array(), false, 1, 1, false, false, true));
        $slider_mintext = $slider_min = is_numeric($slider_min) ? $slider_min : 0;
        $slider_max = trim(LimeExpressionManager::ProcessString("{{$aQuestionAttributes['slider_max']}}", $ia[0], array(), false, 1, 1, false, false, true));
        $slider_maxtext = $slider_max = is_numeric($slider_max) ? $slider_max : 100;
        $slider_default = trim(LimeExpressionManager::ProcessString("{{$aQuestionAttributes['slider_default']}}", $ia[0], array(), false, 1, 1, false, false, true));
        $slider_default = is_numeric($slider_default) ? $slider_default : "";
        if ($slider_default == '' && $aQuestionAttributes['slider_middlestart'] == 1) {
            $slider_middlestart = intval(($slider_max + $slider_min) / 2);
        } else {
            $slider_middlestart = '';
        }
        $slider_separator = trim($aQuestionAttributes['slider_separator']) != '' ? $aQuestionAttributes['slider_separator'] : "";
        $slider_reset = $aQuestionAttributes['slider_reset'] ? 1 : 0;
    } else {
        $slider_layout = false;
    }
    $hidetip = $aQuestionAttributes['hide_tip'];
    if ($aQuestionAttributes['random_order'] == 1) {
        $ansquery = "SELECT * FROM {{questions}} WHERE parent_qid={$ia['0']}  AND language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "' ORDER BY " . dbRandom();
    } else {
        $ansquery = "SELECT * FROM {{questions}} WHERE parent_qid={$ia['0']}  AND language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "' ORDER BY question_order";
    }
    $ansresult = dbExecuteAssoc($ansquery);
    //Checked
    $aSubquestions = $ansresult->readAll();
    $anscount = count($aSubquestions) * 2;
    $fn = 1;
    $answer_main = '';
    if ($anscount == 0) {
        $inputnames = array();
        $answer_main .= '    <li>' . gT('Error: This question has no answers.') . "</li>\n";
    } else {
        foreach ($aSubquestions as $ansrow) {
            $myfname = $ia[1] . $ansrow['title'];
            if ($ansrow['question'] == "") {
                $ansrow['question'] = "&nbsp;";
            }
            if ($slider_layout === false || $slider_separator == '') {
                $theanswer = $ansrow['question'];
                $sliderleft = '';
                $sliderright = '';
            } else {
                $aAnswer = explode($slider_separator, $ansrow['question']);
                $theanswer = isset($aAnswer[0]) ? $aAnswer[0] : "";
                $sliderleft = isset($aAnswer[1]) ? $aAnswer[1] : "";
                $sliderright = isset($aAnswer[2]) ? $aAnswer[2] : "";
                $sliderleft = "<div class=\"slider_lefttext\">{$sliderleft}</div>";
                $sliderright = "<div class=\"slider_righttext\">{$sliderright}</div>";
            }
            // color code missing mandatory questions red
            if ($ia[6] == 'Y' && $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname] === '') {
                $theanswer = "<span class='errormandatory'>{$theanswer}</span>";
            }
            list($htmltbody2, $hiddenfield) = return_array_filter_strings($ia, $aQuestionAttributes, $thissurvey, $ansrow, $myfname, '', $myfname, "li", "question-item answer-item text-item numeric-item" . $extraclass);
            $answer_main .= "\t{$htmltbody2}\n";
            $answer_main .= "<label for=\"answer{$myfname}\" class=\"{$prefixclass}-label\">{$theanswer}</label>\n";
            $sSeparator = getRadixPointData($thissurvey['surveyls_numberformat']);
            $sSeparator = $sSeparator['separator'];
            $answer_main .= "{$sliderleft}<span class=\"input\">\n\t" . $prefix . "\n\t<input class=\"text {$kpclass}\" type=\"text\" size=\"" . $tiwidth . "\" name=\"" . $myfname . "\" id=\"answer" . $myfname . "\" title=\"" . gT('Only numbers may be entered in this field.') . "\" value=\"";
            if (isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname])) {
                $dispVal = $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname];
                if (strpos($dispVal, ".")) {
                    $dispVal = rtrim(rtrim($dispVal, "0"), ".");
                }
                $dispVal = str_replace('.', $sSeparator, $dispVal);
                $answer_main .= $dispVal;
            }
            $answer_main .= '" onkeyup="' . $checkconditionFunction . '(this.value, this.name, this.type);" ' . " {$maxlength} />\n\t" . $suffix . "\n</span>{$sliderright}\n\t</li>\n";
            $fn++;
            $inputnames[] = $myfname;
        }
        if (trim($aQuestionAttributes['equals_num_value']) != '' || trim($aQuestionAttributes['min_num_value']) != '' || trim($aQuestionAttributes['max_num_value']) != '') {
            $qinfo = LimeExpressionManager::GetQuestionStatus($ia[0]);
            if (trim($aQuestionAttributes['equals_num_value']) != '') {
                $answer_main .= "\t<li class='multiplenumerichelp help-item'>\n" . "<span class=\"label\">" . gT('Remaining: ') . "</span>\n" . "<span id=\"remainingvalue_{$ia[0]}\" class=\"dynamic_remaining\">{$prefix}\n" . "{" . $qinfo['sumRemainingEqn'] . "}\n" . "{$suffix}</span>\n" . "\t</li>\n";
            }
            $answer_main .= "\t<li class='multiplenumerichelp  help-item'>\n" . "<span class=\"label\">" . gT('Total: ') . "</span>\n" . "<span id=\"totalvalue_{$ia[0]}\" class=\"dynamic_sum\">{$prefix}\n" . "{" . $qinfo['sumEqn'] . "}\n" . "{$suffix}</span>\n" . "\t</li>\n";
        }
        $answer .= "<ul class=\"subquestions-list questions-list text-list {$prefixclass}-list\">\n" . $answer_main . "</ul>\n";
    }
    if ($aQuestionAttributes['slider_layout'] == 1) {
        Yii::app()->getClientScript()->registerScriptFile(Yii::app()->getConfig('generalscripts') . "numeric-slider.js");
        Yii::app()->getClientScript()->registerCssFile(Yii::app()->getConfig('publicstyleurl') . "numeric-slider.css");
        if ($slider_default != "") {
            $slider_startvalue = $slider_default;
            $slider_displaycallout = 1;
        } elseif ($slider_middlestart != '') {
            $slider_startvalue = $slider_middlestart;
            $slider_displaycallout = 0;
        } else {
            $slider_startvalue = 'NULL';
            $slider_displaycallout = 0;
        }
        $slider_showminmax = $aQuestionAttributes['slider_showminmax'] == 1 ? 1 : 0;
        //some var for slider
        $aJsLang = array('reset' => gT('Reset'), 'tip' => gT('Please click and drag the slider handles to enter your answer.'));
        $aJsVar = array('slider_showminmax' => $slider_showminmax, 'slider_min' => $slider_min, 'slider_mintext' => $slider_mintext, 'slider_max' => $slider_max, 'slider_maxtext' => $slider_maxtext, 'slider_step' => $slider_step, 'slider_startvalue' => $slider_startvalue, 'slider_displaycallout' => $slider_displaycallout, 'slider_prefix' => $prefix, 'slider_suffix' => $suffix, 'slider_reset' => $slider_reset, 'lang' => $aJsLang);
        $answer .= "<script type='text/javascript'><!--\n" . " doNumericSlider({$ia[0]}," . ls_json_encode($aJsVar) . ");\n" . " //--></script>";
    }
    $sSeparator = getRadixPointData($thissurvey['surveyls_numberformat']);
    $sSeparator = $sSeparator['separator'];
    return array($answer, $inputnames);
}
Exemplo n.º 19
0
    /**
     * 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
    }
Exemplo n.º 20
0
 /**
  * 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 .= "&nbsp;<font color='#000080'>{$i}:&nbsp;<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);
     }
 }
Exemplo n.º 21
0
         }
         if (!$grel || !$stepInfo['show']) {
             continue;
         }
         $q = $_SESSION['fieldarray'][$n];
     } else {
         ++$gseq;
         if (!$stepInfo['show']) {
             continue;
         }
         $g = $_SESSION['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['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['maxstep'] == $_SESSION['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>';