/**
* Shows the welcome page, used in group by group and question by question mode
*/
function display_first_page()
{
    global $token, $surveyid, $thissurvey, $navigator;
    $totalquestions = $_SESSION['survey_' . $surveyid]['totalquestions'];
    $clang = Yii::app()->lang;
    // Fill some necessary var for template
    $navigator = surveymover();
    $sitename = Yii::app()->getConfig('sitename');
    $languagechanger = makeLanguageChangerSurvey($clang->langcode);
    sendCacheHeaders();
    doHeader();
    LimeExpressionManager::StartProcessingPage();
    LimeExpressionManager::StartProcessingGroup(-1, false, $surveyid);
    // start on welcome page
    $redata = compact(array_keys(get_defined_vars()));
    $sTemplatePath = $_SESSION['survey_' . $surveyid]['templatepath'];
    echo templatereplace(file_get_contents($sTemplatePath . "startpage.pstpl"), array(), $redata, 'frontend_helper[2757]');
    echo CHtml::form(array("/survey/index"), 'post', array('id' => 'limesurvey', 'name' => 'limesurvey', 'autocomplete' => 'off'));
    echo "\n\n<!-- START THE SURVEY -->\n";
    echo templatereplace(file_get_contents($sTemplatePath . "welcome.pstpl"), array(), $redata, 'frontend_helper[2762]') . "\n";
    if ($thissurvey['anonymized'] == "Y") {
        echo templatereplace(file_get_contents($sTemplatePath . "/privacy.pstpl"), array(), $redata, 'frontend_helper[2765]') . "\n";
    }
    echo templatereplace(file_get_contents($sTemplatePath . "navigator.pstpl"), array(), $redata, 'frontend_helper[2767]');
    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";
    }
    echo "\n<input type='hidden' name='sid' value='{$surveyid}' id='sid' />\n";
    if (isset($token) && !empty($token)) {
        echo "\n<input type='hidden' name='token' value='{$token}' id='token' />\n";
    }
    echo "\n<input type='hidden' name='lastgroupname' value='_WELCOME_SCREEN_' id='lastgroupname' />\n";
    //This is to ensure consistency with mandatory checks, and new group test
    $loadsecurity = returnGlobal('loadsecurity', true);
    if (isset($loadsecurity)) {
        echo "\n<input type='hidden' name='loadsecurity' value='{$loadsecurity}' id='loadsecurity' />\n";
    }
    $_SESSION['survey_' . $surveyid]['LEMpostKey'] = mt_rand();
    echo "<input type='hidden' name='LEMpostKey' value='{$_SESSION['survey_' . $surveyid]['LEMpostKey']}' id='LEMpostKey' />\n";
    echo "<input type='hidden' name='thisstep' id='thisstep' value='0' />\n";
    echo "\n</form>\n";
    echo templatereplace(file_get_contents($sTemplatePath . "endpage.pstpl"), array(), $redata, 'frontend_helper[2782]');
    echo LimeExpressionManager::GetRelevanceAndTailoringJavaScript();
    LimeExpressionManager::FinishProcessingPage();
    doFooter();
}
Exemplo n.º 2
0
    $clang = new limesurvey_lang("en");
    $surveyInfo = explode('|', $_POST['sid']);
    $surveyid = $surveyInfo[0];
    $assessments = $surveyInfo[1] == 'Y';
    $surveyMode = $_POST['surveyMode'];
    $LEMdebugLevel = (isset($_POST['LEM_DEBUG_TIMING']) && $_POST['LEM_DEBUG_TIMING'] == 'Y' ? LEM_DEBUG_TIMING : 0) + (isset($_POST['LEM_DEBUG_VALIDATION_SUMMARY']) && $_POST['LEM_DEBUG_VALIDATION_SUMMARY'] == 'Y' ? LEM_DEBUG_VALIDATION_SUMMARY : 0) + (isset($_POST['LEM_DEBUG_VALIDATION_DETAIL']) && $_POST['LEM_DEBUG_VALIDATION_DETAIL'] == 'Y' ? LEM_DEBUG_VALIDATION_DETAIL : 0) + (isset($_POST['LEM_DEBUG_LOG_SYNTAX_ERRORS_TO_DB']) && $_POST['LEM_DEBUG_LOG_SYNTAX_ERRORS_TO_DB'] == 'Y' ? LEM_DEBUG_LOG_SYNTAX_ERRORS_TO_DB : 0) + (isset($_POST['LEM_PRETTY_PRINT_ALL_SYNTAX']) && $_POST['LEM_PRETTY_PRINT_ALL_SYNTAX'] == 'Y' ? LEM_PRETTY_PRINT_ALL_SYNTAX : 0);
    $surveyOptions = array('active' => false, 'allowsave' => true, 'anonymized' => false, 'assessments' => $assessments, 'datestamp' => true, 'hyperlinkSyntaxHighlighting' => true, 'ipaddr' => true, 'rooturl' => '../../..');
    print '<h3>Starting survey ' . $surveyid . " using Survey Mode '" . $surveyMode . ($assessments ? "' [Uses Assessments]" : "'") . "</h3>";
    $now = microtime(true);
    LimeExpressionManager::StartSurvey($surveyid, $surveyMode, $surveyOptions, true, $LEMdebugLevel);
    print '<b>[StartSurvey() took ' . (microtime(true) - $now) . ' seconds]</b><br/>';
    while (true) {
        $now = microtime(true);
        $result = LimeExpressionManager::NavigateForwards(true);
        print $result['message'] . "<br/>";
        LimeExpressionManager::FinishProcessingPage();
        //                    print LimeExpressionManager::GetRelevanceAndTailoringJavaScript();
        if (($LEMdebugLevel & LEM_DEBUG_TIMING) == LEM_DEBUG_TIMING) {
            print LimeExpressionManager::GetDebugTimingMessage();
        }
        print '<b>[NavigateForwards() took ' . (microtime(true) - $now) . ' seconds]</b><br/>';
        if (is_null($result) || $result['finished'] == true) {
            break;
        }
    }
    print "<h3>Finished survey " . $surveyid . "</h3>";
}
?>
    </body>
</html>
/**
* Shows the welcome page, used in group by group and question by question mode
*/
function display_first_page()
{
    global $token, $surveyid, $thissurvey, $navigator;
    $totalquestions = $_SESSION['survey_' . $surveyid]['totalquestions'];
    // Fill some necessary var for template
    $aNavigator = surveymover();
    $moveprevbutton = $aNavigator['sMovePrevButton'];
    $movenextbutton = $aNavigator['sMoveNextButton'];
    $navigator = $moveprevbutton . ' ' . $movenextbutton;
    $sitename = Yii::app()->getConfig('sitename');
    $languagechanger = makeLanguageChangerSurvey(App()->language);
    sendCacheHeaders();
    doHeader();
    LimeExpressionManager::StartProcessingPage();
    LimeExpressionManager::StartProcessingGroup(-1, false, $surveyid);
    // start on welcome page
    $redata = compact(array_keys(get_defined_vars()));
    $oTemplate = Template::model()->getInstance('', $surveyid);
    $sTemplatePath = $oTemplate->path;
    $sTemplateViewPath = $oTemplate->viewPath;
    echo templatereplace(file_get_contents($sTemplateViewPath . "startpage.pstpl"), array(), $redata, 'frontend_helper[2757]');
    echo CHtml::form(array("/survey/index", "sid" => $surveyid), 'post', array('id' => 'limesurvey', 'name' => 'limesurvey', 'autocomplete' => 'off', 'class' => 'frontend_helper'));
    echo templatereplace(file_get_contents($sTemplateViewPath . "welcome.pstpl"), array(), $redata, 'frontend_helper[2762]') . "\n";
    if ($thissurvey['anonymized'] == "Y") {
        echo templatereplace(file_get_contents($sTemplateViewPath . "/privacy.pstpl"), array(), $redata, 'frontend_helper[2765]') . "\n";
    }
    echo templatereplace(file_get_contents($sTemplateViewPath . "navigator.pstpl"), array(), $redata, 'frontend_helper[2767]');
    echo "\n<input type='hidden' name='sid' value='{$surveyid}' id='sid' />\n";
    if (isset($token) && !empty($token)) {
        echo "\n<input type='hidden' name='token' value='{$token}' id='token' />\n";
    }
    echo "\n<input type='hidden' name='lastgroupname' value='_WELCOME_SCREEN_' id='lastgroupname' />\n";
    //This is to ensure consistency with mandatory checks, and new group test
    $loadsecurity = returnGlobal('loadsecurity', true);
    if (isset($loadsecurity)) {
        echo "\n<input type='hidden' name='loadsecurity' value='{$loadsecurity}' id='loadsecurity' />\n";
    }
    $_SESSION['survey_' . $surveyid]['LEMpostKey'] = mt_rand();
    echo "<input type='hidden' name='LEMpostKey' value='{$_SESSION['survey_' . $surveyid]['LEMpostKey']}' id='LEMpostKey' />\n";
    echo "<input type='hidden' name='thisstep' id='thisstep' value='0' />\n";
    echo "<!--frontendhelper --></form>";
    echo templatereplace(file_get_contents($sTemplateViewPath . "endpage.pstpl"), array(), $redata, 'frontend_helper[2782]');
    echo LimeExpressionManager::GetRelevanceAndTailoringJavaScript();
    LimeExpressionManager::FinishProcessingPage();
    doFooter();
    echo "<!-- end of frontend_helper /  display_first_page -->";
}
Exemplo n.º 4
0
    /**
     * Load preview of a question screen.
     *
     * @access public
     * @param int $surveyid
     * @param int $qid
     * @param string $lang
     * @return void
     */
    public function preview($surveyid, $qid, $lang = null)
    {
        $surveyid = sanitize_int($surveyid);
        $qid = sanitize_int($qid);
        $LEMdebugLevel = 0;
        Yii::app()->loadHelper("qanda");
        Yii::app()->loadHelper("surveytranslator");
        if (empty($surveyid)) {
            $this->getController()->error('No Survey ID provided');
        }
        if (empty($qid)) {
            $this->getController()->error('No Question ID provided');
        }
        if (empty($lang)) {
            $language = Survey::model()->findByPk($surveyid)->language;
        } else {
            $language = $lang;
        }
        if (!isset(Yii::app()->session['step'])) {
            Yii::app()->session['step'] = 0;
        }
        if (!isset(Yii::app()->session['prevstep'])) {
            Yii::app()->session['prevstep'] = 0;
        }
        if (!isset(Yii::app()->session['maxstep'])) {
            Yii::app()->session['maxstep'] = 0;
        }
        // Use $_SESSION instead of $this->session for frontend features.
        $_SESSION['survey_' . $surveyid]['s_lang'] = $language;
        $_SESSION['survey_' . $surveyid]['fieldmap'] = createFieldMap($surveyid, 'full', true, $qid, $language);
        // Prefill question/answer from defaultvalues
        foreach ($_SESSION['survey_' . $surveyid]['fieldmap'] as $field) {
            if (isset($field['defaultvalue'])) {
                $_SESSION['survey_' . $surveyid][$field['fieldname']] = $field['defaultvalue'];
            }
        }
        $clang = new limesurvey_lang($language);
        $thissurvey = getSurveyInfo($surveyid);
        setNoAnswerMode($thissurvey);
        Yii::app()->session['dateformats'] = getDateFormatData($thissurvey['surveyls_dateformat']);
        $qrows = Questions::model()->findByAttributes(array('sid' => $surveyid, 'qid' => $qid, 'language' => $language))->getAttributes();
        $ia = array(0 => $qid, 1 => $surveyid . 'X' . $qrows['gid'] . 'X' . $qid, 2 => $qrows['title'], 3 => $qrows['question'], 4 => $qrows['type'], 5 => $qrows['gid'], 6 => $qrows['mandatory'], 7 => 'N', 8 => 'N');
        $radix = getRadixPointData($thissurvey['surveyls_numberformat']);
        $radix = $radix['seperator'];
        $surveyOptions = array('radix' => $radix, 'tempdir' => Yii::app()->getConfig('tempdir'));
        LimeExpressionManager::StartSurvey($surveyid, 'question', $surveyOptions, false, $LEMdebugLevel);
        $qseq = LimeExpressionManager::GetQuestionSeq($qid);
        $moveResult = LimeExpressionManager::JumpTo($qseq + 1, true, false, true);
        $answers = retrieveAnswers($ia, $surveyid);
        if (!$thissurvey['template']) {
            $thistpl = getTemplatePath(Yii::app()->getConfig('defaulttemplate'));
        } else {
            $thistpl = getTemplatePath(validateTemplateDir($thissurvey['template']));
        }
        doHeader();
        $showQuestion = "\$('#question{$qid}').show();";
        $dummy_js = <<<EOD
            <script type='text/javascript'>
            <!--
            LEMradix='{$radix}';
            var numRegex = new RegExp('[^-' + LEMradix + '0-9]','g');
            var intRegex = new RegExp('[^-0-9]','g');
            function fixnum_checkconditions(value, name, type, evt_type, intonly)
            {
                newval = new String(value);
                if (typeof intonly !=='undefined' && intonly==1) {
                    newval = newval.replace(intRegex,'');
                }
                else {
                    newval = newval.replace(numRegex,'');
                }
                if (LEMradix === ',') {
                    newval = newval.split(',').join('.');
                }
                if (newval != '-' && newval != '.' && newval != '-.' && newval != parseFloat(newval)) {
                    newval = '';
                }
                displayVal = newval;
                if (LEMradix === ',') {
                    displayVal = displayVal.split('.').join(',');
                }
                if (name.match(/other\$/)) {
                    \$('#answer'+name+'text').val(displayVal);
                }
                \$('#answer'+name).val(displayVal);

                if (typeof evt_type === 'undefined')
                {
                    evt_type = 'onchange';
                }
                checkconditions(newval, name, type, evt_type);
            }

            function checkconditions(value, name, type, evt_type)
            {
                if (typeof evt_type === 'undefined')
                {
                    evt_type = 'onchange';
                }
                if (type == 'radio' || type == 'select-one')
                {
                    var hiddenformname='java'+name;
                    document.getElementById(hiddenformname).value=value;
                }
                else if (type == 'checkbox')
                {
                    if (document.getElementById('answer'+name).checked)
                    {
                        \$('#java'+name).val('Y');
                    } else
                    {
                        \$('#java'+name).val('');
                    }
                }
                else if (type == 'text' && name.match(/other\$/) && typeof document.getElementById('java'+name) !== 'undefined' && document.getElementById('java'+name) != null)
                {
                    \$('#java'+name).val(value);
                }
                ExprMgr_process_relevance_and_tailoring(evt_type,name,type);
                {$showQuestion}
            }
            \$(document).ready(function() {
                {$showQuestion}
            });
            \$(document).change(function() {
                {$showQuestion}
            });
            \$(document).bind('keydown',function(e) {
                        if (e.keyCode == 9) {
                            {$showQuestion}
                            return true;
                        }
                        return true;
                    });
        // -->
        </script>
EOD;
        $answer = $answers[0][1];
        //        $help = $answers[0][2];
        $qinfo = LimeExpressionManager::GetQuestionStatus($qid);
        $help = $qinfo['info']['help'];
        $question = $answers[0][0];
        $question['code'] = $answers[0][5];
        $question['class'] = getQuestionClass($qrows['type']);
        $question['essentials'] = 'id="question' . $qrows['qid'] . '"';
        $question['sgq'] = $ia[1];
        $question['aid'] = 'unknown';
        $question['sqid'] = 'unknown';
        if ($qrows['mandatory'] == 'Y') {
            $question['man_class'] = ' mandatory';
        } else {
            $question['man_class'] = '';
        }
        $redata = compact(array_keys(get_defined_vars()));
        $content = templatereplace(file_get_contents("{$thistpl}/startpage.pstpl"), array(), $redata);
        $content .= CHtml::form('index.php', 'post', array('id' => "limesurvey", 'name' => "limesurvey", 'autocomplete' => 'off'));
        $content .= templatereplace(file_get_contents("{$thistpl}/startgroup.pstpl"), array(), $redata);
        $question_template = file_get_contents("{$thistpl}/question.pstpl");
        // the following has been added for backwards compatiblity.
        if (substr_count($question_template, '{QUESTION_ESSENTIALS}') > 0) {
            // LS 1.87 and newer templates
            $content .= "\n" . templatereplace($question_template, array(), $redata, 'Unspecified', false, $qid) . "\n";
        } else {
            // LS 1.86 and older templates
            $content .= '<div ' . $question['essentials'] . ' class="' . $question['class'] . $question['man_class'] . '">';
            $content .= "\n" . templatereplace($question_template, array(), $redata, 'Unspecified', false, $qid) . "\n";
            $content .= "\n\t</div>\n";
        }
        $content .= templatereplace(file_get_contents("{$thistpl}/endgroup.pstpl"), array(), $redata) . $dummy_js;
        LimeExpressionManager::FinishProcessingGroup();
        $content .= LimeExpressionManager::GetRelevanceAndTailoringJavaScript();
        $content .= '<p>&nbsp;</form>';
        $content .= templatereplace(file_get_contents("{$thistpl}/endpage.pstpl"), array(), $redata);
        LimeExpressionManager::FinishProcessingPage();
        echo $content;
        if ($LEMdebugLevel >= 1) {
            echo LimeExpressionManager::GetDebugTimingMessage();
        }
        if ($LEMdebugLevel >= 2) {
            echo "<table><tr><td align='left'><b>Group/Question Validation Results:</b>" . $moveResult['message'] . "</td></tr></table>\n";
        }
        echo "</html>\n";
        exit;
    }
Exemplo n.º 5
0
 /**
  * Create HTML view of the survey, showing everything that uses EM
  * @param <type> $sid
  * @param <type> $gid
  * @param <type> $qid
  */
 public static function ShowSurveyLogicFile($sid, $gid = NULL, $qid = NULL, $LEMdebugLevel = 0, $assessments = false)
 {
     // Title
     // Welcome
     // G1, name, relevance, text
     // *Q1, name [type], relevance [validation], text, help, default, help_msg
     // SQ1, name [scale], relevance [validation], text
     // A1, code, assessment_value, text
     // End Message
     global $rooturl;
     $LEM =& LimeExpressionManager::singleton();
     $allErrors = array();
     $surveyOptions = array('assessments' => $assessments, 'hyperlinkSyntaxHighlighting' => true, 'rooturl' => $rooturl);
     $varNamesUsed = array();
     // keeps track of whether variables have been declared
     if (!is_null($qid)) {
         $surveyMode = 'question';
         LimeExpressionManager::StartSurvey($sid, 'question', $surveyOptions, false, $LEMdebugLevel);
         $qseq = LimeExpressionManager::GetQuestionSeq($qid);
         $moveResult = LimeExpressionManager::JumpTo($qseq + 1, true, false, true);
     } else {
         if (!is_null($gid)) {
             $surveyMode = 'group';
             LimeExpressionManager::StartSurvey($sid, 'group', $surveyOptions, false, $LEMdebugLevel);
             $gseq = LimeExpressionManager::GetGroupSeq($gid);
             $moveResult = LimeExpressionManager::JumpTo($gseq + 1, true, false, true);
         } else {
             $surveyMode = 'survey';
             LimeExpressionManager::StartSurvey($sid, 'survey', $surveyOptions, false, $LEMdebugLevel);
             $moveResult = LimeExpressionManager::NavigateForwards();
         }
     }
     $qtypes = getqtypelist('', 'array');
     templatereplace('{SITENAME}');
     // to ensure that lime replacement fields loaded
     if (is_null($moveResult) || is_null($LEM->currentQset) || count($LEM->currentQset) == 0) {
         return array('errors' => 1, 'html' => $LEM->gT('Invalid question - probably missing sub-questions or language-specific settings for language ') . $_SESSION['LEMlang']);
     }
     $out = "<table border='1'>" . "<tr><th>#</th><th>" . $LEM->gT('Name [ID]') . "</th><th>" . $LEM->gT('Relevance [Validation] (Default)') . "</th><th>" . $LEM->gT('Text [Help] (Tip)') . "</th></tr>\n";
     $_gseq = -1;
     foreach ($LEM->currentQset as $q) {
         $gseq = $q['info']['gseq'];
         $gid = $q['info']['gid'];
         $qid = $q['info']['qid'];
         $qseq = $q['info']['qseq'];
         $errorCount = 0;
         //////
         // SHOW GROUP-LEVEL INFO
         //////
         if ($gseq != $_gseq) {
             $LEM->ParseResultCache = array();
             // reset for each group so get proper color coding?
             $_gseq = $gseq;
             $ginfo = $LEM->gseq2info[$gseq];
             $grelevance = '{' . ($ginfo['grelevance'] == '' ? 1 : $ginfo['grelevance']) . '}';
             $gtext = trim($ginfo['description']) == '' ? '&nbsp;' : $ginfo['description'];
             $groupRow = "<tr class='LEMgroup'>" . "<td>G-{$gseq}</td>" . "<td><b>" . $ginfo['group_name'] . "</b><br/>[<a target='_blank' href='{$rooturl}/admin/admin.php?action=orderquestions&sid={$sid}&gid={$gid}'>GID " . $gid . "</a>]</td>" . "<td>" . $grelevance . "</td>" . "<td>" . $gtext . "</td>" . "</tr>\n";
             $LEM->ProcessString($groupRow, $qid, NULL, false, 1, 1, false, false);
             $out .= $LEM->GetLastPrettyPrintExpression();
             if ($LEM->em->HasErrors()) {
                 ++$errorCount;
             }
         }
         //////
         // SHOW QUESTION-LEVEL INFO
         //////
         $mandatory = $q['info']['mandatory'] == 'Y' ? "<span style='color:red'>*</span>" : '';
         $type = $q['info']['type'];
         $typedesc = $qtypes[$type]['description'];
         $sgqas = explode('|', $q['sgqa']);
         if (count($sgqas) == 1 && !is_null($q['info']['default'])) {
             $LEM->ProcessString($q['info']['default'], $qid, NULL, false, 1, 1, false, false);
             $_default = $LEM->GetLastPrettyPrintExpression();
             if ($LEM->em->HasErrors()) {
                 ++$errorCount;
             }
             $default = '<br/>(' . $LEM->gT('DEFAULT:') . '  ' . $_default . ')';
         } else {
             $default = '';
         }
         $qtext = $q['info']['qtext'] != '' ? $q['info']['qtext'] : '&nbsp';
         $help = $q['info']['help'] != '' ? '<hr/>[' . $LEM->gT("HELP:") . ' ' . $q['info']['help'] . ']' : '';
         $prettyValidTip = $q['prettyValidTip'] == '' ? '' : '<hr/>(' . $LEM->gT("TIP:") . ' ' . $q['prettyValidTip'] . ')';
         //////
         // SHOW QUESTION ATTRIBUTES THAT ARE PROCESSED BY EM
         //////
         $attrTable = '';
         if (isset($LEM->qattr[$qid]) && count($LEM->qattr[$qid]) > 0) {
             $attrTable = "<hr/><table border='1'><tr><th>" . $LEM->gT("Question Attribute") . "</th><th>" . $LEM->gT("Value") . "</th></tr>\n";
             $count = 0;
             foreach ($LEM->qattr[$qid] as $key => $value) {
                 if (is_null($value) || trim($value) == '') {
                     continue;
                 }
                 switch ($key) {
                     default:
                     case 'exclude_all_others':
                     case 'exclude_all_others_auto':
                     case 'hidden':
                         if ($value == false || $value == '0') {
                             $value = NULL;
                             // so can skip this one - just using continue here doesn't work.
                         }
                         break;
                     case 'relevance':
                         $value = NULL;
                         // means an outdate database structure
                         break;
                     case 'array_filter':
                     case 'array_filter_exclude':
                     case 'code_filter':
                     case 'em_validation_q_tip':
                     case 'em_validation_sq_tip':
                         break;
                     case 'equals_num_value':
                     case 'em_validation_q':
                     case 'em_validation_sq':
                     case 'max_answers':
                     case 'max_num_value':
                     case 'max_num_value_n':
                     case 'min_answers':
                     case 'min_num_value':
                     case 'min_num_value_n':
                     case 'multiflexible_max':
                     case 'multiflexible_min':
                         $value = '{' . $value . '}';
                         break;
                     case 'other_replace_text':
                     case 'show_totals':
                         break;
                 }
                 if (is_null($value)) {
                     continue;
                     // since continuing from within a switch statement doesn't work
                 }
                 ++$count;
                 $attrTable .= "<tr><td>{$key}</td><td>{$value}</td></tr>\n";
             }
             $attrTable .= "</table>\n";
             if ($count == 0) {
                 $attrTable = '';
             }
         }
         $LEM->ProcessString($qtext . $help . $prettyValidTip . $attrTable, $qid, NULL, false, 1, 1, false, false);
         $qdetails = $LEM->GetLastPrettyPrintExpression();
         if ($LEM->em->HasErrors()) {
             ++$errorCount;
         }
         //////
         // SHOW RELEVANCE
         //////
         // Must parse Relevance this way, otherwise if try to first split expressions, regex equations won't work
         $relevanceEqn = $q['info']['relevance'] == '' ? 1 : $q['info']['relevance'];
         if (!isset($LEM->ParseResultCache[$relevanceEqn])) {
             $result = $LEM->em->ProcessBooleanExpression($relevanceEqn, $gseq, $qseq);
             $prettyPrint = $LEM->em->GetPrettyPrintString();
             $hasErrors = $LEM->em->HasErrors();
             $LEM->ParseResultCache[$relevanceEqn] = array('result' => $result, 'prettyPrint' => $prettyPrint, 'hasErrors' => $hasErrors);
         }
         $relevance = $LEM->ParseResultCache[$relevanceEqn]['prettyPrint'];
         if ($LEM->ParseResultCache[$relevanceEqn]['hasErrors']) {
             ++$errorCount;
         }
         //////
         // SHOW VALIDATION EQUATION
         //////
         // Must parse Validation this way so that regex (preg) works
         $prettyValidEqn = '';
         if ($q['prettyValidEqn'] != '') {
             $validationEqn = $q['validEqn'];
             if (!isset($LEM->ParseResultCache[$validationEqn])) {
                 $result = $LEM->em->ProcessBooleanExpression($validationEqn, $gseq, $qseq);
                 $prettyPrint = $LEM->em->GetPrettyPrintString();
                 $hasErrors = $LEM->em->HasErrors();
                 $LEM->ParseResultCache[$validationEqn] = array('result' => $result, 'prettyPrint' => $prettyPrint, 'hasErrors' => $hasErrors);
             }
             $prettyValidEqn = '<hr/>(' . $LEM->gT("VALIDATION:") . ' ' . $LEM->ParseResultCache[$validationEqn]['prettyPrint'] . ')';
             if ($LEM->ParseResultCache[$validationEqn]['hasErrors']) {
                 ++$errorCount;
             }
         }
         //////
         // TEST VALIDITY OF ROOT VARIABLE NAME AND WHETHER HAS BEEN USED
         //////
         $rootVarName = $q['info']['rootVarName'];
         $varNameErrorMsg = '';
         $varNameError = NULL;
         if (isset($varNamesUsed[$rootVarName])) {
             $varNameErrorMsg .= $LEM->gT('This variable name has already been used.');
         } else {
             $varNamesUsed[$rootVarName] = array('gid' => $gid, 'qid' => $qid);
         }
         if (!preg_match('/^[_a-zA-Z][_0-9a-zA-Z]*$/', $rootVarName)) {
             $varNameErrorMsg .= $LEM->gT('Starting in 1.92, variable names should only contain letters, numbers, and underscores; and may not start with a number. This variable name is deprecated.');
         }
         if ($varNameErrorMsg != '') {
             $varNameError = array('message' => $varNameErrorMsg, 'gid' => $varNamesUsed[$rootVarName]['gid'], 'qid' => $varNamesUsed[$rootVarName]['qid']);
             if (!$LEM->sgqaNaming) {
                 ++$errorCount;
             }
         }
         //////
         // SHOW ALL SUB-QUESTIONS
         //////
         $sqRows = '';
         $i = 0;
         $sawThis = array();
         // array of rowdivids already seen so only show them once
         foreach ($sgqas as $sgqa) {
             if ($LEM->knownVars[$sgqa]['qcode'] == $rootVarName) {
                 continue;
                 // so don't show the main question as a sub-question too
             }
             $rowdivid = $sgqa;
             $varName = $LEM->knownVars[$sgqa]['qcode'];
             switch ($q['info']['type']) {
                 case '1':
                     if (preg_match('/#1$/', $sgqa)) {
                         $rowdivid = NULL;
                         // so that doesn't show same message for second scale
                     } else {
                         $rowdivid = substr($sgqa, 0, -2);
                         // strip suffix
                         $varName = substr($LEM->knownVars[$sgqa]['qcode'], 0, -2);
                     }
                     break;
                 case 'P':
                     if (preg_match('/comment$/', $sgqa)) {
                         $rowdivid = NULL;
                     }
                     break;
                 case ':':
                 case ';':
                     $_rowdivid = $LEM->knownVars[$sgqa]['rowdivid'];
                     if (isset($sawThis[$qid . '~' . $_rowdivid])) {
                         $rowdivid = NULL;
                         // so don't show again
                     } else {
                         $sawThis[$qid . '~' . $_rowdivid] = true;
                         $rowdivid = $_rowdivid;
                         $sgqa_len = strlen($sid . 'X' . $gid . 'X' . $qid);
                         $varName = $rootVarName . '_' . substr($_rowdivid, $sgqa_len);
                     }
                 case 'L':
                     // TODO - need to show array filters applied to lists
                     break;
             }
             if (is_null($rowdivid)) {
                 continue;
             }
             ++$i;
             $subQeqn = '&nbsp;';
             if (isset($LEM->subQrelInfo[$qid][$rowdivid])) {
                 $sq = $LEM->subQrelInfo[$qid][$rowdivid];
                 $subQeqn = $sq['prettyPrintEqn'];
                 // {' . $sq['eqn'] . '}';  // $sq['prettyPrintEqn'];
                 if ($sq['hasErrors']) {
                     ++$errorCount;
                 }
             }
             $sgqaInfo = $LEM->knownVars[$sgqa];
             $subqText = $sgqaInfo['subqtext'];
             if (isset($sgqaInfo['default']) && $sgqaInfo['default'] !== '') {
                 $LEM->ProcessString($sgqaInfo['default'], $qid, NULL, false, 1, 1, false, false);
                 $_default = $LEM->GetLastPrettyPrintExpression();
                 if ($LEM->em->HasErrors()) {
                     ++$errorCount;
                 }
                 $subQeqn .= '<br/>(' . $LEM->gT('DEFAULT:') . '  ' . $_default . ')';
             }
             $sqRows .= "<tr class='LEMsubq'>" . "<td>SQ-{$i}</td>" . "<td><b>" . $varName . "</b></td>" . "<td>{$subQeqn}</td>" . "<td>" . $subqText . "</td>" . "</tr>";
         }
         $LEM->ProcessString($sqRows, $qid, NULL, false, 1, 1, false, false);
         $sqRows = $LEM->GetLastPrettyPrintExpression();
         if ($LEM->em->HasErrors()) {
             ++$errorCount;
         }
         //////
         // SHOW ANSWER OPTIONS FOR ENUMERATED LISTS, AND FOR MULTIFLEXI
         //////
         $answerRows = '';
         if (isset($LEM->qans[$qid]) || isset($LEM->multiflexiAnswers[$qid])) {
             $_scale = -1;
             if (isset($LEM->multiflexiAnswers[$qid])) {
                 $ansList = $LEM->multiflexiAnswers[$qid];
             } else {
                 $ansList = $LEM->qans[$qid];
             }
             foreach ($ansList as $ans => $value) {
                 $ansInfo = explode('~', $ans);
                 $valParts = explode('|', $value);
                 $valInfo[0] = array_shift($valParts);
                 $valInfo[1] = implode('|', $valParts);
                 if ($_scale != $ansInfo[0]) {
                     $i = 1;
                     $_scale = $ansInfo[0];
                 }
                 $answerRows .= "<tr class='LEManswer'>" . "<td>A[" . $ansInfo[0] . "]-" . $i++ . "</td>" . "<td><b>" . $ansInfo[1] . "</b></td>" . "<td>[VALUE: " . $valInfo[0] . "]</td>" . "<td>" . $valInfo[1] . "</td>" . "</tr>\n";
             }
             $LEM->ProcessString($answerRows, $qid, NULL, false, 1, 1, false, false);
             $answerRows = $LEM->GetLastPrettyPrintExpression();
             if ($LEM->em->HasErrors()) {
                 ++$errorCount;
             }
         }
         //////
         // FINALLY, SHOW THE QUESTION ROW(S), COLOR-CODING QUESTIONS THAT CONTAIN ERRORS
         //////
         $errclass = $errorCount > 0 ? "class='LEMerror' title='" . sprintf($LEM->gT("This question has at least %s error(s)"), $errorCount) . "'" : '';
         $questionRow = "<tr class='LEMquestion'>" . "<td {$errclass}>Q-" . $q['info']['qseq'] . "</td>" . "<td><b>" . $mandatory;
         if ($varNameErrorMsg == '') {
             $questionRow .= $rootVarName;
         } else {
             $editlink = $LEM->surveyOptions['rooturl'] . '/admin/admin.php?sid=' . $LEM->sid . '&gid=' . $varNameError['gid'] . '&qid=' . $varNameError['qid'];
             $questionRow .= "<span style='border-style: solid; border-width: 2px; border-color: #FF00FF; color: red;' title='" . $varNameError['message'] . "' " . "onclick='window.open(\"{$editlink}\",\"_blank\")'>" . $rootVarName . "</span>";
         }
         $questionRow .= "</b><br/>[<a target='_blank' href='{$rooturl}/admin/admin.php?sid={$sid}&gid={$gid}&qid={$qid}'>QID {$qid}</a>]<br/>{$typedesc} [{$type}]</td>" . "<td>" . $relevance . $prettyValidEqn . $default . "</td>" . "<td>" . $qdetails . "</td>" . "</tr>\n";
         $out .= $questionRow;
         $out .= $sqRows;
         $out .= $answerRows;
         if ($errorCount > 0) {
             $allErrors[$gid . '~' . $qid] = $errorCount;
         }
     }
     $out .= "</table>";
     LimeExpressionManager::FinishProcessingPage();
     if (($LEMdebugLevel & LEM_DEBUG_TIMING) == LEM_DEBUG_TIMING) {
         $out .= LimeExpressionManager::GetDebugTimingMessage();
     }
     if (count($allErrors) > 0) {
         $out = "<p class='LEMerror'>" . sprintf($LEM->gT("%s question(s) contain errors that need to be corrected"), count($allErrors)) . "</p>\n" . $out;
     } else {
         switch ($surveyMode) {
             case 'survey':
                 $message = $LEM->gT('No syntax errors detected in this survey');
                 break;
             case 'group':
                 $message = $LEM->gT('This group, by itself, does not contain any syntax errors');
                 break;
             case 'question':
                 $message = $LEM->gT('This question, by itself, does not contain any syntax errors');
                 break;
         }
         $out = "<p class='LEMerror'>{$message}</p>\n" . $out;
     }
     return array('errors' => $allErrors, 'html' => $out);
 }
Exemplo n.º 6
0
 /**
  * Renders template(s) wrapped in header and footer
  *
  * Addition of parameters should be avoided if they can be added to $aData
  *
  * @param string $sAction Current action, the folder to fetch views from
  * @param string|array $aViewUrls View url(s)
  * @param array $aData Data to be passed on. Optional.
  */
 protected function _renderWrappedTemplate($sAction = '', $aViewUrls = array(), $aData = array())
 {
     // Gather the data
     $aData['clang'] = $clang = Yii::app()->lang;
     $aData['sImageURL'] = Yii::app()->getConfig('adminimageurl');
     $aData = $this->_addPseudoParams($aData);
     $aViewUrls = (array) $aViewUrls;
     $sViewPath = '/admin/';
     if (!empty($sAction)) {
         $sViewPath .= $sAction . '/';
     }
     // Header
     if (!isset($aData['display']['header']) || $aData['display']['header'] !== false) {
         // Send HTTP header
         header("Content-type: text/html; charset=UTF-8");
         // needed for correct UTF-8 encoding
         Yii::app()->getController()->_getAdminHeader();
     }
     // Menu bars
     if (!isset($aData['display']['menu_bars']) || $aData['display']['menu_bars'] !== false && (!is_array($aData['display']['menu_bars']) || !in_array('browse', array_keys($aData['display']['menu_bars'])))) {
         Yii::app()->getController()->_showadminmenu(!empty($aData['surveyid']) ? $aData['surveyid'] : null);
         if (!empty($aData['surveyid'])) {
             LimeExpressionManager::StartProcessingPage(false, Yii::app()->baseUrl, true);
             // so can click on syntax highlighting to edit questions
             $this->_surveybar($aData['surveyid'], !empty($aData['gid']) ? $aData['gid'] : null);
             if (isset($aData['display']['menu_bars']['surveysummary'])) {
                 if ((empty($aData['display']['menu_bars']['surveysummary']) || !is_string($aData['display']['menu_bars']['surveysummary'])) && !empty($aData['gid'])) {
                     $aData['display']['menu_bars']['surveysummary'] = 'viewgroup';
                 }
                 $this->_surveysummary($aData['surveyid'], !empty($aData['display']['menu_bars']['surveysummary']) ? $aData['display']['menu_bars']['surveysummary'] : null, !empty($aData['gid']) ? $aData['gid'] : null);
             }
             if (!empty($aData['gid'])) {
                 if (empty($aData['display']['menu_bars']['gid_action']) && !empty($aData['qid'])) {
                     $aData['display']['menu_bars']['gid_action'] = 'viewquestion';
                 }
                 $this->_questiongroupbar($aData['surveyid'], $aData['gid'], !empty($aData['qid']) ? $aData['qid'] : null, !empty($aData['display']['menu_bars']['gid_action']) ? $aData['display']['menu_bars']['gid_action'] : null);
                 if (!empty($aData['qid'])) {
                     $this->_questionbar($aData['surveyid'], $aData['gid'], $aData['qid'], !empty($aData['display']['menu_bars']['qid_action']) ? $aData['display']['menu_bars']['qid_action'] : null);
                 }
             }
             LimeExpressionManager::FinishProcessingPage();
         }
     }
     if (!empty($aData['display']['menu_bars']['browse']) && !empty($aData['surveyid'])) {
         $this->_browsemenubar($aData['surveyid'], $aData['display']['menu_bars']['browse']);
     }
     if (!empty($aData['display']['menu_bars']['user_group'])) {
         $this->_userGroupBar(!empty($aData['ugid']) ? $aData['ugid'] : 0);
     }
     // Load views
     foreach ($aViewUrls as $sViewKey => $viewUrl) {
         if (empty($sViewKey) || !in_array($sViewKey, array('message', 'output'))) {
             if (is_numeric($sViewKey)) {
                 Yii::app()->getController()->render($sViewPath . $viewUrl, $aData);
             } elseif (is_array($viewUrl)) {
                 foreach ($viewUrl as $aSubData) {
                     $aSubData = array_merge($aData, $aSubData);
                     Yii::app()->getController()->render($sViewPath . $sViewKey, $aSubData);
                 }
             }
         } else {
             switch ($sViewKey) {
                 // Message
                 case 'message':
                     if (empty($viewUrl['class'])) {
                         Yii::app()->getController()->_showMessageBox($viewUrl['title'], $viewUrl['message']);
                     } else {
                         Yii::app()->getController()->_showMessageBox($viewUrl['title'], $viewUrl['message'], $viewUrl['class']);
                     }
                     break;
                     // Output
                 // Output
                 case 'output':
                     echo $viewUrl;
                     break;
             }
         }
     }
     // Footer
     if (!isset($aData['display']['endscripts']) || $aData['display']['endscripts'] !== false) {
         Yii::app()->getController()->_loadEndScripts();
     }
     if (!isset($aData['display']['footer']) || $aData['display']['footer'] !== false) {
         Yii::app()->getController()->_getAdminFooter('http://docs.limesurvey.org', $clang->gT('LimeSurvey online manual'));
     }
 }
 /**
  * Renders template(s) wrapped in header and footer
  *
  * Addition of parameters should be avoided if they can be added to $aData
  *
  * NOTE FROM LOUIS : We want to remove this function, wich doesn't respect MVC pattern.
  * The work it's doing should be handle by layout files, and subviews inside views.
  * Eg : for route "admin/survey/sa/listquestiongroups/surveyid/282267"
  *       the Group controller should use a main layout (with admin menu bar as a widget), then render the list view, in wich the question group bar is called as a subview.
  *
  * So for now, we try to evacuate all the renderWrappedTemplate logic (if statements, etc.) to subfunctions, then it will be easier to remove.
  * Comments starting with //// indicate how it should work in the future
  *
  * @param string $sAction Current action, the folder to fetch views from
  * @param string|array $aViewUrls View url(s)
  * @param array $aData Data to be passed on. Optional.
  */
 protected function _renderWrappedTemplate($sAction = '', $aViewUrls = array(), $aData = array())
 {
     // Gather the data
     $aData = $this->_addPseudoParams($aData);
     //// the check of the surveyid should be done in the Admin controller it self.
     $aData['sImageURL'] = Yii::app()->getBaseUrl(true) . '/images/lime-icons/328637/';
     //// This will be handle by subviews inclusions
     $aViewUrls = (array) $aViewUrls;
     $sViewPath = '/admin/';
     if (!empty($sAction)) {
         $sViewPath .= $sAction . '/';
     }
     ob_start();
     //// That was used before the MVC pattern, in procedural code. Will not be used anymore.
     $this->_showHeaders($aData);
     //// THe headers will be called from the layout
     $this->_showadminmenu();
     //// The admin menu will be called from the layout, probably as a widget for dynamic content.
     $this->_userGroupBar($aData);
     //// Here will start the rendering from the controller of the main view.
     //// For example, the Group controller will use the main.php layout, and then render the view list_group.php
     //// This view will call as a subview the questiongroupbar, and then _listquestiongroup subview.
     //// This check will be useless when it will be handle directly by each specific controller.
     if (!empty($aData['surveyid'])) {
         //// TODO : check what is doing exactly this function. (application/helpers/expressions/em_manager_helper.php)
         //// If it's about initialiazing global variables, should be removed and parsed in right controllers.
         //// But it seems that it's just useless.
         LimeExpressionManager::StartProcessingPage(false, Yii::app()->baseUrl, true);
         // so can click on syntax highlighting to edit questions
         $oSurvey = $aData['oSurvey'] = Survey::model()->findByPk($aData['surveyid']);
         $this->_titlebar($aData);
         //// Each view will call the correct bar as a subview.
         $this->_surveybar($aData);
         $this->_nquestiongroupbar($aData);
         $this->_questionbar($aData);
         $this->_browsemenubar($aData);
         $this->_tokenbar($aData);
         $this->_organizequestionbar($aData);
         //// TODO : check what it's doing exactly, and why it is here (not after or before)
         //// It seems that it is not used at all. It's about timing
         LimeExpressionManager::FinishProcessingPage();
         //// TODO : Move this div inside each correct view ASAP !
         echo '<div class="container-fluid" id="in_survey_common"><div class="row">';
         $this->_updatenotification();
         $this->_notifications();
         //// Here the main content views.
         $this->_surveysidemenu($aData);
         $this->_listquestiongroups($aData);
         $this->_listquestions($aData);
         $this->_nsurveysummary($aData);
     } else {
         ///
         $this->_fullpagebar($aData);
         $this->_updatenotification();
         $this->_notifications();
         //// TODO : Move this div inside each correct view ASAP !
         echo '
                 <!-- Full page, started in Survey_Common_Action::render_wrapped_template() -->
                     <div class="container-fluid full-page-wrapper" id="in_survey_common_action">
                         <div class="row">';
     }
     //// Here the rendering of all the subviews process. Will not be use anymore, because each subview will be directly called from her parent view.
     ////  TODO : while refactoring, we must replace the use of $aViewUrls by $aData[.. conditions ..], and then call to function such as $this->_nsurveysummary($aData);
     // Load views
     foreach ($aViewUrls as $sViewKey => $viewUrl) {
         if (empty($sViewKey) || !in_array($sViewKey, array('message', 'output'))) {
             if (is_numeric($sViewKey)) {
                 Yii::app()->getController()->renderPartial($sViewPath . $viewUrl, $aData);
             } elseif (is_array($viewUrl)) {
                 foreach ($viewUrl as $aSubData) {
                     $aSubData = array_merge($aData, $aSubData);
                     Yii::app()->getController()->renderPartial($sViewPath . $sViewKey, $aSubData);
                 }
             }
         } else {
             switch ($sViewKey) {
                 //// We'll use some Bootstrap alerts, and call them inside each correct view.
                 // Message
                 case 'message':
                     if (empty($viewUrl['class'])) {
                         Yii::app()->getController()->_showMessageBox($viewUrl['title'], $viewUrl['message']);
                     } else {
                         Yii::app()->getController()->_showMessageBox($viewUrl['title'], $viewUrl['message'], $viewUrl['class']);
                     }
                     break;
                     // Output
                 // Output
                 case 'output':
                     //// TODO : http://goo.gl/ABl5t5
                     echo $viewUrl;
                     if (isset($aViewUrls['afteroutput'])) {
                         echo $aViewUrls['afteroutput'];
                     }
                     break;
             }
         }
     }
     //// TODO : Move this div inside each correct view ASAP !
     echo '</div></div>';
     //// THe footer will be called directly from the layout.
     // Footer
     if (!isset($aData['display']['endscripts']) || $aData['display']['endscripts'] !== false) {
         Yii::app()->getController()->_loadEndScripts();
     }
     if (!Yii::app()->user->isGuest) {
         if (!isset($aData['display']['footer']) || $aData['display']['footer'] !== false) {
             Yii::app()->getController()->_getAdminFooter('http://manual.limesurvey.org', gT('LimeSurvey online manual'));
         }
     }
     $out = ob_get_contents();
     ob_clean();
     App()->getClientScript()->render($out);
     echo $out;
 }
Exemplo n.º 8
0
 /**
  * Main function
  *
  * @param mixed $surveyid
  * @param mixed $args
  */
 function run($surveyid, $args)
 {
     global $errormsg;
     extract($args);
     if (!$thissurvey) {
         $thissurvey = getSurveyInfo($surveyid);
     }
     $LEMsessid = 'survey_' . $surveyid;
     $this->setJavascriptVar($surveyid);
     global $oTemplate;
     $sTemplatePath = $oTemplate->path;
     $sTemplateViewPath = $oTemplate->viewPath;
     //$sTemplatePath=getTemplatePath(Yii::app()->getConfig("defaulttemplate")).DIRECTORY_SEPARATOR;
     // TODO : check if necessary :
     /*
     if (isset ($_SESSION['survey_'.$surveyid]['templatepath']))
     {
         $sTemplatePath=$_SESSION['survey_'.$surveyid]['templatepath'];
     }
     */
     // $LEMdebugLevel - customizable debugging for Lime Expression Manager
     $LEMdebugLevel = 0;
     // LEM_DEBUG_TIMING;    // (LEM_DEBUG_TIMING + LEM_DEBUG_VALIDATION_SUMMARY + LEM_DEBUG_VALIDATION_DETAIL);
     $LEMskipReprocessing = false;
     // true if used GetLastMoveResult to avoid generation of unneeded extra JavaScript
     switch ($thissurvey['format']) {
         case "A":
             //All in one
             $surveyMode = 'survey';
             break;
         default:
         case "S":
             //One at a time
             $surveyMode = 'question';
             break;
         case "G":
             //Group at a time
             $surveyMode = 'group';
             break;
     }
     $radix = getRadixPointData($thissurvey['surveyls_numberformat']);
     $radix = $radix['separator'];
     $surveyOptions = array('active' => $thissurvey['active'] == 'Y', 'allowsave' => $thissurvey['allowsave'] == 'Y', 'anonymized' => $thissurvey['anonymized'] != 'N', 'assessments' => $thissurvey['assessments'] == 'Y', 'datestamp' => $thissurvey['datestamp'] == 'Y', 'deletenonvalues' => Yii::app()->getConfig('deletenonvalues'), 'hyperlinkSyntaxHighlighting' => ($LEMdebugLevel & LEM_DEBUG_VALIDATION_SUMMARY) == LEM_DEBUG_VALIDATION_SUMMARY, 'ipaddr' => $thissurvey['ipaddr'] == 'Y', 'radix' => $radix, 'refurl' => $thissurvey['refurl'] == "Y" && isset($_SESSION[$LEMsessid]['refurl']) ? $_SESSION[$LEMsessid]['refurl'] : NULL, 'savetimings' => $thissurvey['savetimings'] == "Y", 'surveyls_dateformat' => isset($thissurvey['surveyls_dateformat']) ? $thissurvey['surveyls_dateformat'] : 1, 'startlanguage' => isset(App()->language) ? App()->language : $thissurvey['language'], 'target' => Yii::app()->getConfig('uploaddir') . DIRECTORY_SEPARATOR . 'surveys' . DIRECTORY_SEPARATOR . $thissurvey['sid'] . DIRECTORY_SEPARATOR . 'files' . DIRECTORY_SEPARATOR, 'tempdir' => Yii::app()->getConfig('tempdir') . DIRECTORY_SEPARATOR, 'timeadjust' => isset($timeadjust) ? $timeadjust : 0, 'token' => isset($clienttoken) ? $clienttoken : NULL);
     //Security Checked: POST, GET, SESSION, REQUEST, returnGlobal, DB
     $previewgrp = false;
     if ($surveyMode == 'group' && isset($param['action']) && $param['action'] == 'previewgroup') {
         $previewgrp = true;
     }
     $previewquestion = false;
     if ($surveyMode == 'question' && isset($param['action']) && $param['action'] == 'previewquestion') {
         $previewquestion = true;
     }
     //        if (isset($param['newtest']) && $param['newtest'] == "Y")
     //            setcookie("limesurvey_timers", "0");   //@todo fix - sometimes results in headers already sent error
     $show_empty_group = false;
     if ($previewgrp || $previewquestion) {
         $_SESSION[$LEMsessid]['prevstep'] = 2;
         $_SESSION[$LEMsessid]['maxstep'] = 0;
     } else {
         //RUN THIS IF THIS IS THE FIRST TIME , OR THE FIRST PAGE ########################################
         if (!isset($_SESSION[$LEMsessid]['step'])) {
             buildsurveysession($surveyid);
             //TODO : check if necessary
             //$sTemplatePath = $_SESSION[$LEMsessid]['templatepath'];
             if ($surveyid != LimeExpressionManager::getLEMsurveyId()) {
                 LimeExpressionManager::SetDirtyFlag();
             }
             LimeExpressionManager::StartSurvey($surveyid, $surveyMode, $surveyOptions, false, $LEMdebugLevel);
             $_SESSION[$LEMsessid]['step'] = 0;
             if ($surveyMode == 'survey') {
                 LimeExpressionManager::JumpTo(1, false, false, true);
             } elseif (isset($thissurvey['showwelcome']) && $thissurvey['showwelcome'] == 'N') {
                 $moveResult = LimeExpressionManager::NavigateForwards();
                 //$_SESSION[$LEMsessid]['step']=1;
             }
         } elseif ($surveyid != LimeExpressionManager::getLEMsurveyId()) {
             $_SESSION[$LEMsessid]['step'] = $_SESSION[$LEMsessid]['step'] < 0 ? 0 : $_SESSION[$LEMsessid]['step'];
             //$_SESSION[$LEMsessid]['step'] can not be less than 0, fix it always #09772
             LimeExpressionManager::StartSurvey($surveyid, $surveyMode, $surveyOptions, false, $LEMdebugLevel);
             LimeExpressionManager::JumpTo($_SESSION[$LEMsessid]['step'], false, false);
         }
         $totalquestions = $_SESSION['survey_' . $surveyid]['totalquestions'];
         if (!isset($_SESSION[$LEMsessid]['totalsteps'])) {
             $_SESSION[$LEMsessid]['totalsteps'] = 0;
         }
         if (!isset($_SESSION[$LEMsessid]['maxstep'])) {
             $_SESSION[$LEMsessid]['maxstep'] = 0;
         }
         if (isset($_SESSION[$LEMsessid]['LEMpostKey']) && isset($_POST['LEMpostKey']) && $_POST['LEMpostKey'] != $_SESSION[$LEMsessid]['LEMpostKey']) {
             // then trying to resubmit (e.g. Next, Previous, Submit) from a cached copy of the page
             // Does not try to save anything from the page to the database
             $moveResult = LimeExpressionManager::GetLastMoveResult(true);
             if (isset($_POST['thisstep']) && isset($moveResult['seq']) && $_POST['thisstep'] == $moveResult['seq']) {
                 // then pressing F5 or otherwise refreshing the current page, which is OK
                 $LEMskipReprocessing = true;
                 $move = "movenext";
                 // so will re-display the survey
             } else {
                 // trying to use browser back buttons, which may be disallowed if no 'previous' button is present
                 $LEMskipReprocessing = true;
                 $move = "movenext";
                 // so will re-display the survey
                 $invalidLastPage = true;
                 $backpopup = gT("Please use the LimeSurvey navigation buttons or index.  It appears you attempted to use the browser back button to re-submit a page.");
             }
         }
         if (isset($move) && $move == "clearcancel") {
             $moveResult = LimeExpressionManager::JumpTo($_SESSION[$LEMsessid]['step'], false, true, false, true);
             //$backpopup=gT("Clear all need confirmation.");
         }
         if (isset($move)) {
             if (!in_array($move, array("clearall", "changelang", "saveall", "reload"))) {
                 $_SESSION[$LEMsessid]['prevstep'] = $_SESSION[$LEMsessid]['step'];
             } else {
                 // Accepted $move without error
                 $_SESSION[$LEMsessid]['prevstep'] = $move;
             }
         } else {
             //$_SESSION[$LEMsessid]['prevstep'] = $_SESSION[$LEMsessid]['step']-1; // Is this needed ?
         }
         if (!isset($_SESSION[$LEMsessid]['prevstep'])) {
             $_SESSION[$LEMsessid]['prevstep'] = $_SESSION[$LEMsessid]['step'] - 1;
             // this only happens on re-load
         }
         if (isset($_SESSION[$LEMsessid]['LEMtokenResume'])) {
             LimeExpressionManager::StartSurvey($thissurvey['sid'], $surveyMode, $surveyOptions, false, $LEMdebugLevel);
             if (isset($_SESSION[$LEMsessid]['maxstep']) && $_SESSION[$LEMsessid]['maxstep'] > $_SESSION[$LEMsessid]['step']) {
                 LimeExpressionManager::JumpTo($_SESSION[$LEMsessid]['maxstep'], false, false);
             }
             $moveResult = LimeExpressionManager::JumpTo($_SESSION[$LEMsessid]['step'], false, false);
             // if late in the survey, will re-validate contents, which may be overkill
             unset($_SESSION[$LEMsessid]['LEMtokenResume']);
         } else {
             if (!$LEMskipReprocessing) {
                 //Move current step ###########################################################################
                 if (isset($move) && $move == 'moveprev' && ($thissurvey['allowprev'] == 'Y' || $thissurvey['questionindex'] > 0)) {
                     $moveResult = LimeExpressionManager::NavigateBackwards();
                     if ($moveResult['at_start']) {
                         $_SESSION[$LEMsessid]['step'] = 0;
                         unset($moveResult);
                         // so display welcome page again
                     }
                 }
                 if (isset($move) && $move == "movenext") {
                     $moveResult = LimeExpressionManager::NavigateForwards();
                 }
                 if (isset($move) && $move == 'movesubmit') {
                     if ($surveyMode == 'survey') {
                         $moveResult = LimeExpressionManager::NavigateForwards();
                     } else {
                         // may be submitting from the navigation bar, in which case need to process all intervening questions
                         // in order to update equations and ensure there are no intervening relevant mandatory or relevant invalid questions
                         if ($thissurvey['questionindex'] == 2) {
                             // Must : save actual page , review whole before set finished to true (see #09906), index==1 seems to don't need it : (don't force move)
                             LimeExpressionManager::StartSurvey($surveyid, $surveyMode, $surveyOptions);
                         }
                         $moveResult = LimeExpressionManager::JumpTo($_SESSION[$LEMsessid]['totalsteps'] + 1, false);
                     }
                 }
                 if (isset($move) && $move == 'changelang') {
                     // jump to current step using new language, processing POST values
                     $moveResult = LimeExpressionManager::JumpTo($_SESSION[$LEMsessid]['step'], false, true, true, true);
                     // do process the POST data
                 }
                 if (isset($move) && isNumericInt($move) && $thissurvey['questionindex'] == 1) {
                     $move = (int) $move;
                     if ($move > 0 && ($move <= $_SESSION[$LEMsessid]['step'] || isset($_SESSION[$LEMsessid]['maxstep']) && $move <= $_SESSION[$LEMsessid]['maxstep'])) {
                         $moveResult = LimeExpressionManager::JumpTo($move, false);
                     }
                 } elseif (isset($move) && isNumericInt($move) && $thissurvey['questionindex'] == 2) {
                     $move = (int) $move;
                     $moveResult = LimeExpressionManager::JumpTo($move, false, true, true);
                 }
                 if (!isset($moveResult) && !($surveyMode != 'survey' && $_SESSION[$LEMsessid]['step'] == 0)) {
                     // Just in case not set via any other means, but don't do this if it is the welcome page
                     $moveResult = LimeExpressionManager::GetLastMoveResult(true);
                     $LEMskipReprocessing = true;
                 }
             }
         }
         if (isset($moveResult) && isset($moveResult['seq'])) {
             // With complete index, we need to revalidate whole group bug #08806. It's actually the only mode where we JumpTo with force
             if ($moveResult['finished'] == true && $move != 'movesubmit' && $thissurvey['questionindex'] == 2) {
                 //LimeExpressionManager::JumpTo(-1, false, false, true);
                 LimeExpressionManager::StartSurvey($surveyid, $surveyMode, $surveyOptions);
                 $moveResult = LimeExpressionManager::JumpTo($_SESSION[$LEMsessid]['totalsteps'] + 1, false, false, false);
                 // no preview, no save data and NO force
                 if (!$moveResult['mandViolation'] && $moveResult['valid'] && empty($moveResult['invalidSQs'])) {
                     $moveResult['finished'] = true;
                 }
             }
             if ($moveResult['finished'] == true) {
                 $move = 'movesubmit';
             } else {
                 $_SESSION[$LEMsessid]['step'] = $moveResult['seq'] + 1;
                 // step is index base 1
                 $stepInfo = LimeExpressionManager::GetStepIndexInfo($moveResult['seq']);
             }
             if ($move == "movesubmit" && $moveResult['finished'] == false) {
                 // then there are errors, so don't finalize the survey
                 $move = "movenext";
                 // so will re-display the survey
                 $invalidLastPage = true;
             }
         }
         // We do not keep the participant session anymore when the same browser is used to answer a second time a survey (let's think of a library PC for instance).
         // Previously we used to keep the session and redirect the user to the
         // submit page.
         if ($surveyMode != 'survey' && $_SESSION[$LEMsessid]['step'] == 0) {
             $_SESSION[$LEMsessid]['test'] = time();
             display_first_page();
             Yii::app()->end();
             // So we can still see debug messages
         }
         // TODO FIXME
         if ($thissurvey['active'] == "Y") {
             Yii::import("application.libraries.Save");
             $cSave = new Save();
         }
         if ($thissurvey['active'] == "Y" && Yii::app()->request->getPost('saveall')) {
             $bTokenAnswerPersitance = $thissurvey['tokenanswerspersistence'] == 'Y' && isset($surveyid) && tableExists('tokens_' . $surveyid);
             // must do this here to process the POSTed values
             $moveResult = LimeExpressionManager::JumpTo($_SESSION[$LEMsessid]['step'], false);
             // by jumping to current step, saves data so far
             if (!isset($_SESSION[$LEMsessid]['scid']) && !$bTokenAnswerPersitance) {
                 $cSave->showsaveform();
                 // generates a form and exits, awaiting input
             } else {
                 // Intentional retest of all conditions to be true, to make sure we do have tokens and surveyid
                 // Now update lastpage to $_SESSION[$LEMsessid]['step'] in SurveyDynamic, otherwise we land on
                 // the previous page when we return.
                 $iResponseID = $_SESSION[$LEMsessid]['srid'];
                 $oResponse = SurveyDynamic::model($surveyid)->findByPk($iResponseID);
                 $oResponse->lastpage = $_SESSION[$LEMsessid]['step'];
                 $oResponse->save();
             }
         }
         if ($thissurvey['active'] == "Y" && Yii::app()->request->getParam('savesubmit')) {
             // The response from the save form
             // CREATE SAVED CONTROL RECORD USING SAVE FORM INFORMATION
             $popup = $cSave->savedcontrol();
             if (isset($errormsg) && $errormsg != "") {
                 $cSave->showsaveform();
                 // reshow the form if there is an error
             }
             $moveResult = LimeExpressionManager::GetLastMoveResult(true);
             $LEMskipReprocessing = true;
             // TODO - does this work automatically for token answer persistence? Used to be savedsilent()
         }
         //Now, we check mandatory questions if necessary
         //CHECK IF ALL CONDITIONAL MANDATORY QUESTIONS THAT APPLY HAVE BEEN ANSWERED
         global $notanswered;
         if (isset($moveResult) && !$moveResult['finished']) {
             $unansweredSQList = $moveResult['unansweredSQs'];
             if (strlen($unansweredSQList) > 0) {
                 $notanswered = explode('|', $unansweredSQList);
             } else {
                 $notanswered = array();
             }
             //CHECK INPUT
             $invalidSQList = $moveResult['invalidSQs'];
             if (strlen($invalidSQList) > 0) {
                 $notvalidated = explode('|', $invalidSQList);
             } else {
                 $notvalidated = array();
             }
         }
         // CHECK UPLOADED FILES
         // TMSW - Move this into LEM::NavigateForwards?
         $filenotvalidated = checkUploadedFileValidity($surveyid, $move);
         //SEE IF THIS GROUP SHOULD DISPLAY
         $show_empty_group = false;
         if ($_SESSION[$LEMsessid]['step'] == 0) {
             $show_empty_group = true;
         }
         $redata = compact(array_keys(get_defined_vars()));
         //SUBMIT ###############################################################################
         if (isset($move) && $move == "movesubmit") {
             //                setcookie("limesurvey_timers", "", time() - 3600); // remove the timers cookies   //@todo fix - sometimes results in headers already sent error
             if ($thissurvey['refurl'] == "Y") {
                 if (!in_array("refurl", $_SESSION[$LEMsessid]['insertarray'])) {
                     $_SESSION[$LEMsessid]['insertarray'][] = "refurl";
                 }
             }
             resetTimers();
             //Before doing the "templatereplace()" function, check the $thissurvey['url']
             //field for limereplace stuff, and do transformations!
             $thissurvey['surveyls_url'] = passthruReplace($thissurvey['surveyls_url'], $thissurvey);
             $thissurvey['surveyls_url'] = templatereplace($thissurvey['surveyls_url'], array(), $redata, 'URLReplace', false, NULL, array(), true);
             // to do INSERTANS substitutions
             //END PAGE - COMMIT CHANGES TO DATABASE
             if ($thissurvey['active'] != "Y") {
                 if ($thissurvey['assessments'] == "Y") {
                     $assessments = doAssessment($surveyid);
                 }
                 sendCacheHeaders();
                 doHeader();
                 echo templatereplace(file_get_contents($sTemplateViewPath . "startpage.pstpl"), array(), $redata, 'SubmitStartpageI', false, NULL, array(), true);
                 //Check for assessments
                 if ($thissurvey['assessments'] == "Y" && $assessments) {
                     echo templatereplace(file_get_contents($sTemplateViewPath . "assessment.pstpl"), array(), $redata, 'SubmitAssessmentI', false, NULL, array(), true);
                 }
                 // fetch all filenames from $_SESSIONS['files'] and delete them all
                 // from the /upload/tmp/ directory
                 /* echo "<pre>";print_r($_SESSION);echo "</pre>";
                    for($i = 1; isset($_SESSION[$LEMsessid]['files'][$i]); $i++)
                    {
                    unlink('upload/tmp/'.$_SESSION[$LEMsessid]['files'][$i]['filename']);
                    }
                    */
                 // can't kill session before end message, otherwise INSERTANS doesn't work.
                 $completed = templatereplace($thissurvey['surveyls_endtext'], array(), $redata, 'SubmitEndtextI', false, NULL, array(), true);
                 $completed .= "<br /><strong><font size='2' color='red'>" . gT("Did Not Save") . "</font></strong><br /><br />\n\n";
                 $completed .= gT("Your survey responses have not been recorded. This survey is not yet active.") . "<br /><br />\n";
                 if ($thissurvey['printanswers'] == 'Y') {
                     // 'Clear all' link is only relevant for survey with printanswers enabled
                     // in other cases the session is cleared at submit time
                     $completed .= "<a href='" . Yii::app()->getController()->createUrl("survey/index/sid/{$surveyid}/move/clearall") . "'>" . gT("Clear Responses") . "</a><br /><br />\n";
                 }
             } else {
                 if ($thissurvey['usecookie'] == "Y" && $tokensexist != 1) {
                     setcookie("LS_" . $surveyid . "_STATUS", "COMPLETE", time() + 31536000);
                     //Cookie will expire in 365 days
                 }
                 $content = '';
                 $content .= templatereplace(file_get_contents($sTemplateViewPath . "startpage.pstpl"), array(), $redata, 'SubmitStartpage', false, NULL, array(), true);
                 //Check for assessments
                 if ($thissurvey['assessments'] == "Y") {
                     $assessments = doAssessment($surveyid);
                     if ($assessments) {
                         $content .= templatereplace(file_get_contents($sTemplateViewPath . "assessment.pstpl"), array(), $redata, 'SubmitAssessment', false, NULL, array(), true);
                     }
                 }
                 //Update the token if needed and send a confirmation email
                 if (isset($_SESSION['survey_' . $surveyid]['token'])) {
                     submittokens();
                 }
                 //Send notifications
                 sendSubmitNotifications($surveyid);
                 $content = '';
                 $content .= templatereplace(file_get_contents($sTemplateViewPath . "startpage.pstpl"), array(), $redata, 'SubmitStartpage', false, NULL, array(), true);
                 //echo $thissurvey['url'];
                 //Check for assessments
                 if ($thissurvey['assessments'] == "Y") {
                     $assessments = doAssessment($surveyid);
                     if ($assessments) {
                         $content .= templatereplace(file_get_contents($sTemplateViewPath . "assessment.pstpl"), array(), $redata, 'SubmitAssessment', false, NULL, array(), true);
                     }
                 }
                 if (trim(str_replace(array('<p>', '</p>'), '', $thissurvey['surveyls_endtext'])) == '') {
                     $completed = "<br /><span class='success'>" . gT("Thank you!") . "</span><br /><br />\n\n" . gT("Your survey responses have been recorded.") . "<br /><br />\n";
                 } else {
                     $completed = templatereplace($thissurvey['surveyls_endtext'], array(), $redata, 'SubmitAssessment', false, NULL, array(), true);
                 }
                 // Link to Print Answer Preview  **********
                 if ($thissurvey['printanswers'] == 'Y') {
                     $url = Yii::app()->getController()->createUrl("/printanswers/view/surveyid/{$surveyid}");
                     $completed .= "<br /><br />" . "<a class='printlink' href='{$url}'  target='_blank'>" . gT("Print your answers.") . "</a><br />\n";
                 }
                 //*****************************************
                 if ($thissurvey['publicstatistics'] == 'Y' && $thissurvey['printanswers'] == 'Y') {
                     $completed .= '<br />' . gT("or");
                 }
                 // Link to Public statistics  **********
                 if ($thissurvey['publicstatistics'] == 'Y') {
                     $url = Yii::app()->getController()->createUrl("/statistics_user/action/surveyid/{$surveyid}/language/" . $_SESSION[$LEMsessid]['s_lang']);
                     $completed .= "<br /><br />" . "<a class='publicstatisticslink' href='{$url}' target='_blank'>" . gT("View the statistics for this survey.") . "</a><br />\n";
                 }
                 //*****************************************
                 $_SESSION[$LEMsessid]['finished'] = true;
                 $_SESSION[$LEMsessid]['sid'] = $surveyid;
                 sendCacheHeaders();
                 if (isset($thissurvey['autoredirect']) && $thissurvey['autoredirect'] == "Y" && $thissurvey['surveyls_url']) {
                     //Automatically redirect the page to the "url" setting for the survey
                     header("Location: {$thissurvey['surveyls_url']}");
                 }
                 doHeader();
                 echo $content;
             }
             $redata['completed'] = $completed;
             // @todo Remove direct session access.
             $event = new PluginEvent('afterSurveyComplete');
             if (isset($_SESSION[$LEMsessid]['srid'])) {
                 $event->set('responseId', $_SESSION[$LEMsessid]['srid']);
             }
             $event->set('surveyId', $surveyid);
             App()->getPluginManager()->dispatchEvent($event);
             $blocks = array();
             foreach ($event->getAllContent() as $blockData) {
                 /* @var $blockData PluginEventContent */
                 $blocks[] = CHtml::tag('div', array('id' => $blockData->getCssId(), 'class' => $blockData->getCssClass()), $blockData->getContent());
             }
             $redata['completed'] = implode("\n", $blocks) . "\n" . $redata['completed'];
             $redata['thissurvey']['surveyls_url'] = $thissurvey['surveyls_url'];
             echo templatereplace(file_get_contents($sTemplateViewPath . "completed.pstpl"), array('completed' => $completed), $redata, 'SubmitCompleted', false, NULL, array(), true);
             echo "\n";
             if (($LEMdebugLevel & LEM_DEBUG_TIMING) == LEM_DEBUG_TIMING) {
                 echo LimeExpressionManager::GetDebugTimingMessage();
             }
             if (($LEMdebugLevel & LEM_DEBUG_VALIDATION_SUMMARY) == LEM_DEBUG_VALIDATION_SUMMARY) {
                 echo "<table><tr><td align='left'><b>Group/Question Validation Results:</b>" . $moveResult['message'] . "</td></tr></table>\n";
             }
             echo templatereplace(file_get_contents($sTemplateViewPath . "endpage.pstpl"), array(), $redata, 'SubmitEndpage', false, NULL, array(), true);
             doFooter();
             // The session cannot be killed until the page is completely rendered
             if ($thissurvey['printanswers'] != 'Y') {
                 killSurveySession($surveyid);
             }
             exit;
         }
     }
     $redata = compact(array_keys(get_defined_vars()));
     // IF GOT THIS FAR, THEN DISPLAY THE ACTIVE GROUP OF QUESTIONSs
     //SEE IF $surveyid EXISTS ####################################################################
     if ($surveyExists < 1) {
         //SURVEY DOES NOT EXIST. POLITELY EXIT.
         echo templatereplace(file_get_contents($sTemplateViewPath . "startpage.pstpl"), array(), $redata);
         echo "\t<center><br />\n";
         echo "\t" . gT("Sorry. There is no matching survey.") . "<br /></center>&nbsp;\n";
         echo templatereplace(file_get_contents($sTemplateViewPath . "endpage.pstpl"), array(), $redata);
         doFooter();
         exit;
     }
     createFieldMap($surveyid, 'full', false, false, $_SESSION[$LEMsessid]['s_lang']);
     //GET GROUP DETAILS
     if ($surveyMode == 'group' && $previewgrp) {
         //            setcookie("limesurvey_timers", "0"); //@todo fix - sometimes results in headers already sent error
         $_gid = sanitize_int($param['gid']);
         LimeExpressionManager::StartSurvey($thissurvey['sid'], 'group', $surveyOptions, false, $LEMdebugLevel);
         $gseq = LimeExpressionManager::GetGroupSeq($_gid);
         if ($gseq == -1) {
             echo gT('Invalid group number for this survey: ') . $_gid;
             exit;
         }
         $moveResult = LimeExpressionManager::JumpTo($gseq + 1, true);
         if (is_null($moveResult)) {
             echo gT('This group contains no questions.  You must add questions to this group before you can preview it');
             exit;
         }
         if (isset($moveResult)) {
             $_SESSION[$LEMsessid]['step'] = $moveResult['seq'] + 1;
             // step is index base 1?
         }
         $stepInfo = LimeExpressionManager::GetStepIndexInfo($moveResult['seq']);
         $gid = $stepInfo['gid'];
         $groupname = $stepInfo['gname'];
         $groupdescription = $stepInfo['gtext'];
     } else {
         if ($show_empty_group || !isset($_SESSION[$LEMsessid]['grouplist'])) {
             $gid = -1;
             // Make sure the gid is unused. This will assure that the foreach (fieldarray as ia) has no effect.
             $groupname = gT("Submit your answers");
             $groupdescription = gT("There are no more questions. Please press the <Submit> button to finish this survey.");
         } else {
             if ($surveyMode != 'survey') {
                 if ($previewquestion) {
                     $_qid = sanitize_int($param['qid']);
                     LimeExpressionManager::StartSurvey($surveyid, 'question', $surveyOptions, false, $LEMdebugLevel);
                     $qSec = LimeExpressionManager::GetQuestionSeq($_qid);
                     $moveResult = LimeExpressionManager::JumpTo($qSec + 1, true, false, true);
                     $stepInfo = LimeExpressionManager::GetStepIndexInfo($moveResult['seq']);
                 } else {
                     $stepInfo = LimeExpressionManager::GetStepIndexInfo($moveResult['seq']);
                 }
                 $gid = $stepInfo['gid'];
                 $groupname = $stepInfo['gname'];
                 $groupdescription = $stepInfo['gtext'];
             }
         }
     }
     if ($previewquestion) {
         $_SESSION[$LEMsessid]['step'] = 0;
         //maybe unset it after the question has been displayed?
     }
     if ($_SESSION[$LEMsessid]['step'] > $_SESSION[$LEMsessid]['maxstep']) {
         $_SESSION[$LEMsessid]['maxstep'] = $_SESSION[$LEMsessid]['step'];
     }
     // If the survey uses answer persistence and a srid is registered in SESSION
     // then loadanswers from this srid
     /* Only survey mode used this - should all?
        if ($thissurvey['tokenanswerspersistence'] == 'Y' &&
        $thissurvey['anonymized'] == "N" &&
        isset($_SESSION[$LEMsessid]['srid']) &&
        $thissurvey['active'] == "Y")
        {
        loadanswers();
        }
        */
     //******************************************************************************************************
     //PRESENT SURVEY
     //******************************************************************************************************
     $okToShowErrors = !$previewgrp && (isset($invalidLastPage) || $_SESSION[$LEMsessid]['prevstep'] == $_SESSION[$LEMsessid]['step']);
     Yii::app()->getController()->loadHelper('qanda');
     setNoAnswerMode($thissurvey);
     //Iterate through the questions about to be displayed:
     $inputnames = array();
     foreach ($_SESSION[$LEMsessid]['grouplist'] as $gl) {
         $gid = $gl['gid'];
         $qnumber = 0;
         if ($surveyMode != 'survey') {
             $onlyThisGID = $stepInfo['gid'];
             if ($onlyThisGID != $gid) {
                 continue;
             }
         }
         // TMSW - could iterate through LEM::currentQset instead
         //// To diplay one question, all the questions are processed ?
         foreach ($_SESSION[$LEMsessid]['fieldarray'] as $key => $ia) {
             ++$qnumber;
             $ia[9] = $qnumber;
             // incremental question count;
             if (isset($ia[10]) && $ia[10] == $gid || !isset($ia[10]) && $ia[5] == $gid) {
                 if ($surveyMode == 'question' && $ia[0] != $stepInfo['qid']) {
                     continue;
                 }
                 $qidattributes = getQuestionAttributeValues($ia[0]);
                 if ($ia[4] != '*' && ($qidattributes === false || !isset($qidattributes['hidden']) || $qidattributes['hidden'] == 1)) {
                     continue;
                 }
                 //Get the answers/inputnames
                 // TMSW - can content of retrieveAnswers() be provided by LEM?  Review scope of what it provides.
                 // TODO - retrieveAnswers is slow - queries database separately for each question. May be fixed in _CI or _YII ports, so ignore for now
                 list($plus_qanda, $plus_inputnames) = retrieveAnswers($ia, $surveyid);
                 if ($plus_qanda) {
                     $plus_qanda[] = $ia[4];
                     $plus_qanda[] = $ia[6];
                     // adds madatory identifyer for adding mandatory class to question wrapping div
                     // Add a finalgroup in qa array , needed for random attribute : TODO: find a way to have it in new quanda_helper in 2.1
                     if (isset($ia[10])) {
                         $plus_qanda['finalgroup'] = $ia[10];
                     } else {
                         $plus_qanda['finalgroup'] = $ia[5];
                     }
                     $qanda[] = $plus_qanda;
                 }
                 if ($plus_inputnames) {
                     $inputnames = addtoarray_single($inputnames, $plus_inputnames);
                 }
                 //Display the "mandatory" popup if necessary
                 // TMSW - get question-level error messages - don't call **_popup() directly
                 if ($okToShowErrors && $stepInfo['mandViolation']) {
                     list($mandatorypopup, $popup) = mandatory_popup($ia, $notanswered);
                 }
                 //Display the "validation" popup if necessary
                 if ($okToShowErrors && !$stepInfo['valid']) {
                     list($validationpopup, $vpopup) = validation_popup($ia, $notvalidated);
                 }
                 // Display the "file validation" popup if necessary
                 if ($okToShowErrors && isset($filenotvalidated)) {
                     list($filevalidationpopup, $fpopup) = file_validation_popup($ia, $filenotvalidated);
                 }
             }
             if ($ia[4] == "|") {
                 $upload_file = TRUE;
             }
         }
         //end iteration
     }
     if ($surveyMode != 'survey' && isset($thissurvey['showprogress']) && $thissurvey['showprogress'] == 'Y') {
         if ($show_empty_group) {
             $percentcomplete = makegraph($_SESSION[$LEMsessid]['totalsteps'] + 1, $_SESSION[$LEMsessid]['totalsteps']);
         } else {
             $percentcomplete = makegraph($_SESSION[$LEMsessid]['step'], $_SESSION[$LEMsessid]['totalsteps']);
         }
     }
     if (!(isset($languagechanger) && strlen($languagechanger) > 0) && function_exists('makeLanguageChangerSurvey')) {
         $languagechanger = makeLanguageChangerSurvey($_SESSION[$LEMsessid]['s_lang']);
     }
     //READ TEMPLATES, INSERT DATA AND PRESENT PAGE
     sendCacheHeaders();
     doHeader();
     /**
      * Question Index
      */
     $aQuestionindexbuttons = null;
     $aQuestionindexbuttonsmenu = null;
     if (!$previewgrp && !$previewquestion) {
         if ($surveyMode != 'survey' && $thissurvey['questionindex'] == 1) {
             //$aQuestionindex = $this->createIncrementalQuestionIndex($LEMsessid, $surveyMode);
             $aQuestionindexmenu = $this->createIncrementalQuestionIndexMenu($LEMsessid, $surveyMode);
         } elseif ($surveyMode != 'survey' && $thissurvey['questionindex'] == 2) {
             //$aQuestionindex = $this->createFullQuestionIndex($LEMsessid, $surveyMode);
             $aQuestionindexmenu = $this->createFullQuestionIndexMenu($LEMsessid, $surveyMode);
         }
         //$questionindex = (isset($aQuestionindex['menulist']))?$aQuestionindex['menulist']:'';
         $questionindexmenu = isset($aQuestionindexmenu['menulist']) ? $aQuestionindexmenu['menulist'] : '';
         //$aQuestionindexbuttons = (isset($aQuestionindex['buttons']))?$aQuestionindex['buttons']:'';
         $aQuestionindexbuttonsmenu = isset($aQuestionindexmenu['buttons']) ? $aQuestionindexmenu['buttons'] : '';
     }
     /////////////////////////////////
     // First call to templatereplace
     echo "<!-- SurveyRunTimeHelper -->";
     $redata = compact(array_keys(get_defined_vars()));
     echo templatereplace(file_get_contents($sTemplateViewPath . "startpage.pstpl"), array(), $redata);
     $aPopup = array();
     // We can move this part where we want now
     if (isset($backpopup)) {
         $aPopup[] = $backpopup;
         // If user click reload: no need other popup
     } else {
         if (isset($popup)) {
             $aPopup[] = $popup;
         }
         if (isset($vpopup)) {
             $aPopup[] = $vpopup;
         }
         if (isset($fpopup)) {
             $aPopup[] = $fpopup;
         }
     }
     Yii::app()->clientScript->registerScript("showpopup", "showpopup=" . (int) Yii::app()->getConfig('showpopups') . ";", CClientScript::POS_HEAD);
     //if(count($aPopup))
     Yii::app()->clientScript->registerScript('startPopup', "startPopups=" . json_encode($aPopup) . ";", CClientScript::POS_HEAD);
     //ALTER PAGE CLASS TO PROVIDE WHOLE-PAGE ALTERNATION
     if ($surveyMode != 'survey' && $_SESSION[$LEMsessid]['step'] != $_SESSION[$LEMsessid]['prevstep'] || isset($_SESSION[$LEMsessid]['stepno']) && $_SESSION[$LEMsessid]['stepno'] % 2) {
         if (!isset($_SESSION[$LEMsessid]['stepno'])) {
             $_SESSION[$LEMsessid]['stepno'] = 0;
         }
         if ($_SESSION[$LEMsessid]['step'] != $_SESSION[$LEMsessid]['prevstep']) {
             ++$_SESSION[$LEMsessid]['stepno'];
         }
         if ($_SESSION[$LEMsessid]['stepno'] % 2) {
             echo "<script type=\"text/javascript\">\n" . "  \$(\"body\").addClass(\"page-odd\");\n" . "</script>\n";
         }
     }
     $hiddenfieldnames = implode("|", $inputnames);
     if (isset($upload_file) && $upload_file) {
         echo CHtml::form(array("/survey/index", "sid" => $surveyid), 'post', array('enctype' => 'multipart/form-data', 'id' => 'limesurvey', 'name' => 'limesurvey', 'autocomplete' => 'off', 'class' => 'survey-form-container surveyRunTimeUploadFile')) . "\n\n            <!-- INPUT NAMES -->\n            <input type='hidden' name='fieldnames' value='{$hiddenfieldnames}' id='fieldnames' />\n";
     } else {
         echo CHtml::form(array("/survey/index", "sid" => $surveyid), 'post', array('id' => 'limesurvey', 'name' => 'limesurvey', 'autocomplete' => 'off', 'class' => 'survey-form-container  surveyRunTime')) . "\n\n            <!-- INPUT NAMES -->\n            <input type='hidden' name='fieldnames' value='{$hiddenfieldnames}' id='fieldnames' />\n";
     }
     // <-- END FEATURE - SAVE
     // The default submit button
     echo CHtml::htmlButton("default", array('type' => 'submit', 'id' => "defaultbtn", 'value' => "default", 'name' => 'move', 'class' => "submit noview", 'style' => 'display:none'));
     if ($surveyMode == 'survey') {
         if (isset($thissurvey['showwelcome']) && $thissurvey['showwelcome'] == 'N') {
             //Hide the welcome screen if explicitly set
         } else {
             echo templatereplace(file_get_contents($sTemplateViewPath . "welcome.pstpl"), array(), $redata) . "\n";
         }
         if ($thissurvey['anonymized'] == "Y") {
             echo templatereplace(file_get_contents($sTemplateViewPath . "privacy.pstpl"), array(), $redata) . "\n";
         }
     }
     // <-- START THE SURVEY -->
     if ($surveyMode != 'survey') {
         echo templatereplace(file_get_contents($sTemplateViewPath . "survey.pstpl"), array(), $redata);
     }
     // runonce element has been changed from a hidden to a text/display:none one. In order to workaround an not-reproduced issue #4453 (lemeur)
     // We don't need runonce actually (140228): the script was updated and replaced by EM see #08783 (grep show no other runonce)
     // echo "<input type='text' id='runonce' value='0' style='display: none;'/>";
     $showpopups = Yii::app()->getConfig('showpopups');
     //Display the "mandatory" message on page if necessary
     if (!$showpopups && $stepInfo['mandViolation'] && $okToShowErrors) {
         echo "<p class='errormandatory alert alert-danger' role='alert'>" . gT("One or more mandatory questions have not been answered. You cannot proceed until these have been completed.") . "</p>";
     }
     //Display the "validation" message on page if necessary
     if (!$showpopups && !$stepInfo['valid'] && $okToShowErrors) {
         echo "<p class='errormandatory alert alert-danger' role='alert'>" . gT("One or more questions have not been answered in a valid manner. You cannot proceed until these answers are valid.") . "</p>";
     }
     //Display the "file validation" message on page if necessary
     if (!$showpopups && isset($filenotvalidated) && $filenotvalidated == true && $okToShowErrors) {
         echo "<p class='errormandatory alert alert-danger' role='alert'>" . gT("One or more uploaded files are not in proper format/size. You cannot proceed until these files are valid.") . "</p>";
     }
     $_gseq = -1;
     foreach ($_SESSION[$LEMsessid]['grouplist'] as $gl) {
         $gid = $gl['gid'];
         ++$_gseq;
         $groupname = $gl['group_name'];
         $groupdescription = $gl['description'];
         if ($surveyMode != 'survey' && $gid != $onlyThisGID) {
             continue;
         }
         $redata = compact(array_keys(get_defined_vars()));
         Yii::app()->setConfig('gid', $gid);
         // To be used in templaterplace in whole group. Attention : it's the actual GID (not the GID of the question)
         echo "\n\n<!-- START THE GROUP (in SurveyRunTime ) -->\n";
         echo "\n\n<div id='group-{$_gseq}'";
         $gnoshow = LimeExpressionManager::GroupIsIrrelevantOrHidden($_gseq);
         if ($gnoshow && !$previewgrp) {
             echo " style='display: none;'";
         }
         echo " class='row'>\n";
         echo templatereplace(file_get_contents($sTemplateViewPath . "startgroup.pstpl"), array(), $redata);
         echo "\n";
         if (!$previewquestion && trim($redata['groupdescription']) == "") {
             echo templatereplace(file_get_contents($sTemplateViewPath . "groupdescription.pstpl"), array(), $redata);
         }
         echo "\n";
         echo "\n\n<!-- PRESENT THE QUESTIONS (in SurveyRunTime )  -->\n";
         foreach ($qanda as $qa) {
             // Test if finalgroup is in this qid (for all in one survey, else we do only qanda for needed question (in one by one or group by goup)
             if ($gid != $qa['finalgroup']) {
                 continue;
             }
             $qid = $qa[4];
             $qinfo = LimeExpressionManager::GetQuestionStatus($qid);
             $lastgrouparray = explode("X", $qa[7]);
             $lastgroup = $lastgrouparray[0] . "X" . $lastgrouparray[1];
             // id of the last group, derived from question id
             $lastanswer = $qa[7];
             $n_q_display = '';
             if ($qinfo['hidden'] && $qinfo['info']['type'] != '*') {
                 continue;
                 // skip this one
             }
             $aReplacement = array();
             $question = $qa[0];
             //===================================================================
             // The following four variables offer the templating system the
             // capacity to fully control the HTML output for questions making the
             // above echo redundant if desired.
             $question['sgq'] = $qa[7];
             $question['aid'] = !empty($qinfo['info']['aid']) ? $qinfo['info']['aid'] : 0;
             $question['sqid'] = !empty($qinfo['info']['sqid']) ? $qinfo['info']['sqid'] : 0;
             //===================================================================
             $question_template = file_get_contents($sTemplateViewPath . 'question.pstpl');
             // Fix old template : can we remove it ? Old template are surely already broken by another issue
             if (preg_match('/\\{QUESTION_ESSENTIALS\\}/', $question_template) === false || preg_match('/\\{QUESTION_CLASS\\}/', $question_template) === false) {
                 // if {QUESTION_ESSENTIALS} is present in the template but not {QUESTION_CLASS} remove it because you don't want id="" and display="" duplicated.
                 $question_template = str_replace('{QUESTION_ESSENTIALS}', '', $question_template);
                 $question_template = str_replace('{QUESTION_CLASS}', '', $question_template);
                 $question_template = "<div {QUESTION_ESSENTIALS} class='{QUESTION_CLASS} {QUESTION_MAN_CLASS} {QUESTION_INPUT_ERROR_CLASS}'" . $question_template . "</div>";
             }
             $redata = compact(array_keys(get_defined_vars()));
             $aQuestionReplacement = $this->getQuestionReplacement($qa);
             echo templatereplace($question_template, $aQuestionReplacement, $redata, false, false, $qa[4]);
         }
         if ($surveyMode == 'group') {
             echo "<input type='hidden' name='lastgroup' value='{$lastgroup}' id='lastgroup' />\n";
             // for counting the time spent on each group
         }
         if ($surveyMode == 'question') {
             echo "<input type='hidden' name='lastanswer' value='{$lastanswer}' id='lastanswer' />\n";
         }
         echo "\n\n<!-- END THE GROUP -->\n";
         echo templatereplace(file_get_contents($sTemplateViewPath . "endgroup.pstpl"), array(), $redata);
         echo "\n\n</div>\n";
         Yii::app()->setConfig('gid', '');
     }
     LimeExpressionManager::FinishProcessingGroup($LEMskipReprocessing);
     echo LimeExpressionManager::GetRelevanceAndTailoringJavaScript();
     LimeExpressionManager::FinishProcessingPage();
     /**
      * Navigator
      */
     if (!$previewgrp && !$previewquestion) {
         $aNavigator = surveymover();
         $moveprevbutton = $aNavigator['sMovePrevButton'];
         $movenextbutton = $aNavigator['sMoveNextButton'];
         $navigator = $moveprevbutton . ' ' . $movenextbutton;
         $redata = compact(array_keys(get_defined_vars()));
         echo "\n\n<!-- PRESENT THE NAVIGATOR -->\n";
         echo templatereplace(file_get_contents($sTemplateViewPath . "navigator.pstpl"), array(), $redata);
         echo "\n";
         if ($thissurvey['active'] != "Y") {
             echo "<p style='text-align:center' class='error'>" . gT("This survey is currently not active. You will not be able to save your responses.") . "</p>\n";
         }
         if ($surveyMode != 'survey' && $thissurvey['questionindex'] == 1) {
             $this->createIncrementalQuestionIndex($LEMsessid, $surveyMode);
             $this->createIncrementalQuestionIndexMenu($LEMsessid, $surveyMode);
         } elseif ($surveyMode != 'survey' && $thissurvey['questionindex'] == 2) {
             $this->createFullQuestionIndex($LEMsessid, $surveyMode);
             $this->createFullQuestionIndexMenu($LEMsessid, $surveyMode);
         }
         echo "<input type='hidden' name='thisstep' value='{$_SESSION[$LEMsessid]['step']}' id='thisstep' />\n";
         echo "<input type='hidden' name='sid' value='{$surveyid}' id='sid' />\n";
         echo "<input type='hidden' name='start_time' value='" . time() . "' id='start_time' />\n";
         $_SESSION[$LEMsessid]['LEMpostKey'] = mt_rand();
         echo "<input type='hidden' name='LEMpostKey' value='{$_SESSION[$LEMsessid]['LEMpostKey']}' id='LEMpostKey' />\n";
         if (isset($token) && !empty($token)) {
             echo "\n<input type='hidden' name='token' value='{$token}' id='token' />\n";
         }
     }
     if (($LEMdebugLevel & LEM_DEBUG_TIMING) == LEM_DEBUG_TIMING) {
         echo LimeExpressionManager::GetDebugTimingMessage();
     }
     if (($LEMdebugLevel & LEM_DEBUG_VALIDATION_SUMMARY) == LEM_DEBUG_VALIDATION_SUMMARY) {
         echo "<table><tr><td align='left'><b>Group/Question Validation Results:</b>" . $moveResult['message'] . "</td></tr></table>\n";
     }
     echo "</form>\n";
     echo templatereplace(file_get_contents($sTemplateViewPath . "endpage.pstpl"), array(), $redata);
     echo "\n";
     doFooter();
 }
Exemplo n.º 9
0
 /**
  * Renders template(s) wrapped in header and footer
  *
  * Addition of parameters should be avoided if they can be added to $aData
  *
  * @param string $sAction Current action, the folder to fetch views from
  * @param string|array $aViewUrls View url(s)
  * @param array $aData Data to be passed on. Optional.
  */
 protected function _renderWrappedTemplate($sAction = '', $aViewUrls = array(), $aData = array())
 {
     // Gather the data
     $aData['clang'] = $clang = Yii::app()->lang;
     $aData['sImageURL'] = Yii::app()->getConfig('adminimageurl');
     $aData = $this->_addPseudoParams($aData);
     $aViewUrls = (array) $aViewUrls;
     $sViewPath = '/pl/';
     if (!empty($sAction)) {
         $sViewPath .= $sAction . '/';
     }
     // Header
     ob_start();
     if (!isset($aData['display']['header']) || $aData['display']['header'] !== false) {
         // Send HTTP header
         header("Content-type: text/html; charset=UTF-8");
         // needed for correct UTF-8 encoding
         Yii::app()->getController()->_getPLHeader();
     }
     // Menu bars
     if (!isset($aData['display']['menu_bars']) || $aData['display']['menu_bars'] !== false && (!is_array($aData['display']['menu_bars']) || !in_array('browse', array_keys($aData['display']['menu_bars'])))) {
         Yii::app()->getController()->_showPLmenu(!empty($aData['plid']) ? $aData['plid'] : null);
         if (!empty($aData['plid'])) {
             LimeExpressionManager::StartProcessingPage(false, Yii::app()->baseUrl, true);
             // so can click on syntax highlighting to edit questions
             $this->_surveybar($aData['plid'], !empty($aData['gid']) ? $aData['gid'] : null);
             LimeExpressionManager::FinishProcessingPage();
         }
     }
     // Load views
     foreach ($aViewUrls as $sViewKey => $viewUrl) {
         if (empty($sViewKey) || !in_array($sViewKey, array('message', 'output'))) {
             if (is_numeric($sViewKey)) {
                 Yii::app()->getController()->renderPartial($sViewPath . $viewUrl, $aData);
             } elseif (is_array($viewUrl)) {
                 foreach ($viewUrl as $aSubData) {
                     $aSubData = array_merge($aData, $aSubData);
                     Yii::app()->getController()->renderPartial($sViewPath . $sViewKey, $aSubData);
                 }
             }
         } else {
             switch ($sViewKey) {
                 // Message
                 case 'message':
                     if (empty($viewUrl['class'])) {
                         Yii::app()->getController()->_showMessageBox($viewUrl['title'], $viewUrl['message']);
                     } else {
                         Yii::app()->getController()->_showMessageBox($viewUrl['title'], $viewUrl['message'], $viewUrl['class']);
                     }
                     break;
                     // Output
                 // Output
                 case 'output':
                     echo $viewUrl;
                     break;
             }
         }
     }
     // Footer
     /*
     if (!isset($aData['display']['endscripts']) || $aData['display']['endscripts'] !== false)
         Yii::app()->getController()->_loadEndScripts();
     */
     if (!isset($aData['display']['footer']) || $aData['display']['footer'] !== false) {
         Yii::app()->getController()->_getPLFooter('http://docs.gowebsurvey.com', $clang->gT('GoWebSurvey Online Manual'));
     }
     $out = ob_get_contents();
     ob_clean();
     App()->getClientScript()->render($out);
     echo $out;
 }
Exemplo n.º 10
0
 /**
  * printanswers::view()
  * View answers at the end of a survey in one place. To export as pdf, set 'usepdfexport' = 1 in lsconfig.php and $printableexport='pdf'.
  * @param mixed $surveyid
  * @param bool $printableexport
  * @return
  */
 function actionView($surveyid, $printableexport = FALSE)
 {
     global $siteadminname, $siteadminemail;
     Yii::app()->loadHelper("frontend");
     Yii::import('application.libraries.admin.pdf');
     $surveyid = (int) $surveyid;
     Yii::app()->loadHelper('database');
     if (isset($_SESSION['survey_' . $surveyid]['sid'])) {
         $surveyid = $_SESSION['survey_' . $surveyid]['sid'];
     } else {
         die('Invalid survey/session');
     }
     //Debut session time out
     if (!isset($_SESSION['survey_' . $surveyid]['finished']) || !isset($_SESSION['survey_' . $surveyid]['srid'])) {
         //require_once($rootdir.'/classes/core/language.php');
         $baselang = Survey::model()->findByPk($surveyid)->language;
         Yii::import('application.libraries.Limesurvey_lang', true);
         $clang = new Limesurvey_lang($baselang);
         //A nice exit
         sendCacheHeaders();
         doHeader();
         echo templatereplace(file_get_contents(getTemplatePath(validateTemplateDir("default")) . "/startpage.pstpl"), array(), array());
         echo "<center><br />\n" . "\t<font color='RED'><strong>" . $clang->gT("Error") . "</strong></font><br />\n" . "\t" . $clang->gT("We are sorry but your session has expired.") . "<br />" . $clang->gT("Either you have been inactive for too long, you have cookies disabled for your browser, or there were problems with your connection.") . "<br />\n" . "\t" . sprintf($clang->gT("Please contact %s ( %s ) for further assistance."), $siteadminname, $siteadminemail) . "\n" . "</center><br />\n";
         echo templatereplace(file_get_contents(getTemplatePath(validateTemplateDir("default")) . "/endpage.pstpl"), array(), array());
         doFooter();
         exit;
     }
     //Fin session time out
     $id = $_SESSION['survey_' . $surveyid]['srid'];
     //I want to see the answers with this id
     $clang = $_SESSION['survey_' . $surveyid]['s_lang'];
     //Ensure script is not run directly, avoid path disclosure
     //if (!isset($rootdir) || isset($_REQUEST['$rootdir'])) {die( "browse - Cannot run this script directly");}
     // Set the language for dispay
     //require_once($rootdir.'/classes/core/language.php');  // has been secured
     if (isset($_SESSION['survey_' . $surveyid]['s_lang'])) {
         $clang = SetSurveyLanguage($surveyid, $_SESSION['survey_' . $surveyid]['s_lang']);
         $language = $_SESSION['survey_' . $surveyid]['s_lang'];
     } else {
         $language = Survey::model()->findByPk($surveyid)->language;
         $clang = SetSurveyLanguage($surveyid, $language);
     }
     // Get the survey inforamtion
     $thissurvey = getSurveyInfo($surveyid, $language);
     //SET THE TEMPLATE DIRECTORY
     if (!isset($thissurvey['templatedir']) || !$thissurvey['templatedir']) {
         $thistpl = validateTemplateDir("default");
     } else {
         $thistpl = validateTemplateDir($thissurvey['templatedir']);
     }
     if ($thissurvey['printanswers'] == 'N') {
         die;
         //Die quietly if print answers is not permitted
     }
     //CHECK IF SURVEY IS ACTIVATED AND EXISTS
     $surveytable = "{{survey_{$surveyid}}}";
     $surveyname = $thissurvey['surveyls_title'];
     $anonymized = $thissurvey['anonymized'];
     //OK. IF WE GOT THIS FAR, THEN THE SURVEY EXISTS AND IT IS ACTIVE, SO LETS GET TO WORK.
     //SHOW HEADER
     $printoutput = '';
     $printoutput .= "<form action='" . Yii::app()->getController()->createUrl('printanswers/view/surveyid/' . $surveyid . '/printableexport/pdf') . "' method='post'>\n<center><input type='submit' value='" . $clang->gT("PDF export") . "'id=\"exportbutton\"/><input type='hidden' name='printableexport' /></center></form>";
     if ($printableexport == 'pdf') {
         require Yii::app()->getConfig('rootdir') . '/application/config/tcpdf.php';
         Yii::import('application.libraries.admin.pdf', true);
         $pdf = new pdf();
         $pdf->setConfig($tcpdf);
         //$pdf->SetFont($pdfdefaultfont,'',$pdffontsize);
         $pdf->AddPage();
         //$pdf->titleintopdf($clang->gT("Survey name (ID)",'unescaped').": {$surveyname} ({$surveyid})");
         $pdf->SetTitle($clang->gT("Survey name (ID)", 'unescaped') . ": {$surveyname} ({$surveyid})");
     }
     $printoutput .= "\t<div class='printouttitle'><strong>" . $clang->gT("Survey name (ID):") . "</strong> {$surveyname} ({$surveyid})</div><p>&nbsp;\n";
     LimeExpressionManager::StartProcessingPage(true);
     // means that all variables are on the same page
     // Since all data are loaded, and don't need JavaScript, pretend all from Group 1
     LimeExpressionManager::StartProcessingGroup(1, $thissurvey['anonymized'] != "N", $surveyid);
     $aFullResponseTable = getFullResponseTable($surveyid, $id, $language, true);
     //Get the fieldmap @TODO: do we need to filter out some fields?
     unset($aFullResponseTable['id']);
     unset($aFullResponseTable['token']);
     unset($aFullResponseTable['lastpage']);
     unset($aFullResponseTable['startlanguage']);
     unset($aFullResponseTable['datestamp']);
     unset($aFullResponseTable['startdate']);
     $printoutput .= "<table class='printouttable' >\n";
     if ($printableexport == 'pdf') {
         $pdf->intopdf($clang->gT("Question", 'unescaped') . ": " . $clang->gT("Your answer", 'unescaped'));
     }
     $oldgid = 0;
     $oldqid = 0;
     foreach ($aFullResponseTable as $sFieldname => $fname) {
         if (substr($sFieldname, 0, 4) == 'gid_') {
             if ($printableexport) {
                 $pdf->intopdf(flattenText($fname[0], false, true));
                 $pdf->ln(2);
             } else {
                 $printoutput .= "\t<tr class='printanswersgroup'><td colspan='2'>{$fname[0]}</td></tr>\n";
             }
         } elseif (substr($sFieldname, 0, 4) == 'qid_') {
             if ($printableexport == 'pdf') {
                 $pdf->intopdf(flattenText($fname[0] . $fname[1], false, true) . ": " . $fname[2]);
                 $pdf->ln(2);
             } else {
                 $printoutput .= "\t<tr class='printanswersquestionhead'><td  colspan='2'>{$fname[0]}</td></tr>\n";
             }
         } elseif ($sFieldname == 'submitdate') {
             if ($anonymized != 'Y') {
                 if ($printableexport == 'pdf') {
                     $pdf->intopdf(flattenText($fname[0] . $fname[1], false, true) . ": " . $fname[2]);
                     $pdf->ln(2);
                 } else {
                     $printoutput .= "\t<tr class='printanswersquestion'><td>{$fname[0]} {$fname[1]} {$sFieldname}</td><td class='printanswersanswertext'>{$fname[2]}</td></tr>";
                 }
             }
         } else {
             if ($printableexport == 'pdf') {
                 $pdf->intopdf(flattenText($fname[0] . $fname[1], false, true) . ": " . $fname[2]);
                 $pdf->ln(2);
             } else {
                 $printoutput .= "\t<tr class='printanswersquestion'><td>{$fname[0]} {$fname[1]}</td><td class='printanswersanswertext'>{$fname[2]}</td></tr>";
             }
         }
     }
     $printoutput .= "</table>\n";
     if ($printableexport == 'pdf') {
         header("Pragma: public");
         header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
         $sExportFileName = sanitize_filename($surveyname);
         $pdf->Output($sExportFileName . "-" . $surveyid . ".pdf", "D");
     }
     //Display the page with user answers
     if (!$printableexport) {
         sendCacheHeaders();
         doHeader();
         echo templatereplace(file_get_contents(getTemplatePath($thistpl) . '/startpage.pstpl'));
         echo templatereplace(file_get_contents(getTemplatePath($thistpl) . '/printanswers.pstpl'), array('ANSWERTABLE' => $printoutput));
         echo templatereplace(file_get_contents(getTemplatePath($thistpl) . '/endpage.pstpl'));
         echo "</body></html>";
     }
     LimeExpressionManager::FinishProcessingGroup();
     LimeExpressionManager::FinishProcessingPage();
 }
 /**
  * printanswers::view()
  * View answers at the end of a survey in one place. To export as pdf, set 'usepdfexport' = 1 in lsconfig.php and $printableexport='pdf'.
  * @param mixed $surveyid
  * @param bool $printableexport
  * @return
  */
 function actionView($surveyid, $printableexport = FALSE)
 {
     Yii::app()->loadHelper("frontend");
     Yii::import('application.libraries.admin.pdf');
     $iSurveyID = (int) $surveyid;
     $sExportType = $printableexport;
     Yii::app()->loadHelper('database');
     if (isset($_SESSION['survey_' . $iSurveyID]['sid'])) {
         $iSurveyID = $_SESSION['survey_' . $iSurveyID]['sid'];
     } else {
         //die('Invalid survey/session');
     }
     // Get the survey inforamtion
     // Set the language for dispay
     if (isset($_SESSION['survey_' . $iSurveyID]['s_lang'])) {
         $sLanguage = $_SESSION['survey_' . $iSurveyID]['s_lang'];
     } elseif (Survey::model()->findByPk($iSurveyID)) {
         $sLanguage = Survey::model()->findByPk($iSurveyID)->language;
     } else {
         $iSurveyID = 0;
         $sLanguage = Yii::app()->getConfig("defaultlang");
     }
     SetSurveyLanguage($iSurveyID, $sLanguage);
     $aSurveyInfo = getSurveyInfo($iSurveyID, $sLanguage);
     $oTemplate = Template::model()->getInstance(null, $iSurveyID);
     //Survey is not finished or don't exist
     if (!isset($_SESSION['survey_' . $iSurveyID]['finished']) || !isset($_SESSION['survey_' . $iSurveyID]['srid'])) {
         sendCacheHeaders();
         doHeader();
         /// $oTemplate is a global variable defined in controller/survey/index
         echo templatereplace(file_get_contents($oTemplate->viewPath . '/startpage.pstpl'), array());
         echo "<center><br />\n" . "\t<font color='RED'><strong>" . gT("Error") . "</strong></font><br />\n" . "\t" . gT("We are sorry but your session has expired.") . "<br />" . gT("Either you have been inactive for too long, you have cookies disabled for your browser, or there were problems with your connection.") . "<br />\n" . "\t" . sprintf(gT("Please contact %s ( %s ) for further assistance."), Yii::app()->getConfig("siteadminname"), Yii::app()->getConfig("siteadminemail")) . "\n" . "</center><br />\n";
         echo templatereplace(file_get_contents($oTemplate->viewPath . '/endpage.pstpl'), array());
         doFooter();
         exit;
     }
     //Fin session time out
     $sSRID = $_SESSION['survey_' . $iSurveyID]['srid'];
     //I want to see the answers with this id
     //Ensure script is not run directly, avoid path disclosure
     //if (!isset($rootdir) || isset($_REQUEST['$rootdir'])) {die( "browse - Cannot run this script directly");}
     //Ensure Participants printAnswer setting is set to true or that the logged user have read permissions over the responses.
     if ($aSurveyInfo['printanswers'] == 'N' && !Permission::model()->hasSurveyPermission($iSurveyID, 'responses', 'read')) {
         throw new CHttpException(401, 'You are not allowed to print answers.');
     }
     //CHECK IF SURVEY IS ACTIVATED AND EXISTS
     $sSurveyName = $aSurveyInfo['surveyls_title'];
     $sAnonymized = $aSurveyInfo['anonymized'];
     //OK. IF WE GOT THIS FAR, THEN THE SURVEY EXISTS AND IT IS ACTIVE, SO LETS GET TO WORK.
     //SHOW HEADER
     if ($sExportType != 'pdf') {
         $sOutput = CHtml::form(array("printanswers/view/surveyid/{$iSurveyID}/printableexport/pdf"), 'post') . "<center><input class='btn btn-default' type='submit' value='" . gT("PDF export") . "'id=\"exportbutton\"/><input type='hidden' name='printableexport' /></center></form>";
         $sOutput .= "\t<div class='printouttitle'><strong>" . gT("Survey name (ID):") . "</strong> {$sSurveyName} ({$iSurveyID})</div><p>&nbsp;\n";
         LimeExpressionManager::StartProcessingPage(true);
         // means that all variables are on the same page
         // Since all data are loaded, and don't need JavaScript, pretend all from Group 1
         LimeExpressionManager::StartProcessingGroup(1, $aSurveyInfo['anonymized'] != "N", $iSurveyID);
         $printanswershonorsconditions = Yii::app()->getConfig('printanswershonorsconditions');
         $aFullResponseTable = getFullResponseTable($iSurveyID, $sSRID, $sLanguage, $printanswershonorsconditions);
         //Get the fieldmap @TODO: do we need to filter out some fields?
         if ($aSurveyInfo['datestamp'] != "Y" || $sAnonymized == 'Y') {
             unset($aFullResponseTable['submitdate']);
         } else {
             unset($aFullResponseTable['id']);
         }
         unset($aFullResponseTable['token']);
         unset($aFullResponseTable['lastpage']);
         unset($aFullResponseTable['startlanguage']);
         unset($aFullResponseTable['datestamp']);
         unset($aFullResponseTable['startdate']);
         $sOutput .= "<table class='printouttable' >\n";
         foreach ($aFullResponseTable as $sFieldname => $fname) {
             if (substr($sFieldname, 0, 4) == 'gid_') {
                 $sOutput .= "\t<tr class='printanswersgroup'><td colspan='2'>{$fname[0]}</td></tr>\n";
                 $sOutput .= "\t<tr class='printanswersgroupdesc'><td colspan='2'>{$fname[1]}</td></tr>\n";
             } elseif ($sFieldname == 'submitdate') {
                 if ($sAnonymized != 'Y') {
                     $sOutput .= "\t<tr class='printanswersquestion'><td>{$fname[0]} {$fname[1]} {$sFieldname}</td><td class='printanswersanswertext'>{$fname[2]}</td></tr>";
                 }
             } elseif (substr($sFieldname, 0, 4) != 'qid_') {
                 $sOutput .= "\t<tr class='printanswersquestion'><td>{$fname[0]} {$fname[1]}</td><td class='printanswersanswertext'>" . flattenText($fname[2]) . "</td></tr>";
             }
         }
         $sOutput .= "</table>\n";
         $sData['thissurvey'] = $aSurveyInfo;
         $sOutput = templatereplace($sOutput, array(), $sData, '', $aSurveyInfo['anonymized'] == "Y", NULL, array(), true);
         // Do a static replacement
         ob_start(function ($buffer, $phase) {
             App()->getClientScript()->render($buffer);
             App()->getClientScript()->reset();
             return $buffer;
         });
         ob_implicit_flush(false);
         sendCacheHeaders();
         doHeader();
         echo templatereplace(file_get_contents($oTemplate->viewPath . '/startpage.pstpl'), array(), $sData);
         echo templatereplace(file_get_contents($oTemplate->viewPath . '/printanswers.pstpl'), array('ANSWERTABLE' => $sOutput), $sData);
         echo templatereplace(file_get_contents($oTemplate->viewPath . '/endpage.pstpl'), array(), $sData);
         echo "</body></html>";
         ob_flush();
     }
     if ($sExportType == 'pdf') {
         // Get images for TCPDF from template directory
         define('K_PATH_IMAGES', getTemplatePath($aSurveyInfo['template']) . DIRECTORY_SEPARATOR);
         Yii::import('application.libraries.admin.pdf', true);
         Yii::import('application.helpers.pdfHelper');
         $aPdfLanguageSettings = pdfHelper::getPdfLanguageSettings(App()->language);
         $oPDF = new pdf();
         $sDefaultHeaderString = $sSurveyName . " (" . gT("ID", 'unescaped') . ":" . $iSurveyID . ")";
         $oPDF->initAnswerPDF($aSurveyInfo, $aPdfLanguageSettings, Yii::app()->getConfig('sitename'), $sSurveyName, $sDefaultHeaderString);
         LimeExpressionManager::StartProcessingPage(true);
         // means that all variables are on the same page
         // Since all data are loaded, and don't need JavaScript, pretend all from Group 1
         LimeExpressionManager::StartProcessingGroup(1, $aSurveyInfo['anonymized'] != "N", $iSurveyID);
         $printanswershonorsconditions = Yii::app()->getConfig('printanswershonorsconditions');
         $aFullResponseTable = getFullResponseTable($iSurveyID, $sSRID, $sLanguage, $printanswershonorsconditions);
         //Get the fieldmap @TODO: do we need to filter out some fields?
         if ($aSurveyInfo['datestamp'] != "Y" || $sAnonymized == 'Y') {
             unset($aFullResponseTable['submitdate']);
         } else {
             unset($aFullResponseTable['id']);
         }
         unset($aFullResponseTable['token']);
         unset($aFullResponseTable['lastpage']);
         unset($aFullResponseTable['startlanguage']);
         unset($aFullResponseTable['datestamp']);
         unset($aFullResponseTable['startdate']);
         foreach ($aFullResponseTable as $sFieldname => $fname) {
             if (substr($sFieldname, 0, 4) == 'gid_') {
                 $oPDF->addGidAnswer($fname[0], $fname[1]);
             } elseif ($sFieldname == 'submitdate') {
                 if ($sAnonymized != 'Y') {
                     $oPDF->addAnswer($fname[0] . " " . $fname[1], $fname[2]);
                 }
             } elseif (substr($sFieldname, 0, 4) != 'qid_') {
                 $oPDF->addAnswer($fname[0] . " " . $fname[1], $fname[2]);
             }
         }
         header("Pragma: public");
         header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
         $sExportFileName = sanitize_filename($sSurveyName);
         $oPDF->Output($sExportFileName . "-" . $iSurveyID . ".pdf", "D");
     }
     LimeExpressionManager::FinishProcessingGroup();
     LimeExpressionManager::FinishProcessingPage();
 }
Exemplo n.º 12
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.º 13
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.º 14
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.º 15
0
 /**
  * Create HTML view of the survey, showing everything that uses EM
  * @param <type> $sid
  * @param <type> $gid
  * @param <type> $qid
  */
 public static function ShowSurveyLogicFile($sid, $gid = NULL, $qid = NULL, $LEMdebugLevel = 0, $assessments = false)
 {
     // Title
     // Welcome
     // G1, name, relevance, text
     // *Q1, name [type], relevance [validation], text, help, default, help_msg
     // SQ1, name [scale], relevance [validation], text
     // A1, code, assessment_value, text
     // End Message
     $LEM =& LimeExpressionManager::singleton();
     $LEM->sPreviewMode = 'logic';
     $aSurveyInfo = getSurveyInfo($sid, $_SESSION['LEMlang']);
     $allErrors = array();
     $warnings = 0;
     $surveyOptions = array('assessments' => $aSurveyInfo['assessments'] == 'Y', 'hyperlinkSyntaxHighlighting' => true);
     $varNamesUsed = array();
     // keeps track of whether variables have been declared
     if (!is_null($qid)) {
         $surveyMode = 'question';
         LimeExpressionManager::StartSurvey($sid, 'question', $surveyOptions, false, $LEMdebugLevel);
         $qseq = LimeExpressionManager::GetQuestionSeq($qid);
         $moveResult = LimeExpressionManager::JumpTo($qseq + 1, true, false, true);
     } else {
         if (!is_null($gid)) {
             $surveyMode = 'group';
             LimeExpressionManager::StartSurvey($sid, 'group', $surveyOptions, false, $LEMdebugLevel);
             $gseq = LimeExpressionManager::GetGroupSeq($gid);
             $moveResult = LimeExpressionManager::JumpTo($gseq + 1, true, false, true);
         } else {
             $surveyMode = 'survey';
             LimeExpressionManager::StartSurvey($sid, 'survey', $surveyOptions, false, $LEMdebugLevel);
             $moveResult = LimeExpressionManager::NavigateForwards();
         }
     }
     $qtypes = getQuestionTypeList('', 'array');
     if (is_null($moveResult) || is_null($LEM->currentQset) || count($LEM->currentQset) == 0) {
         return array('errors' => 1, 'html' => sprintf($LEM->gT('Invalid question - probably missing sub-questions or language-specific settings for language %s'), $_SESSION['LEMlang']));
     }
     $surveyname = templatereplace('{SURVEYNAME}', array('SURVEYNAME' => $aSurveyInfo['surveyls_title']));
     $out = '<div id="showlogicfilediv" ><H3>' . $LEM->gT('Logic File for Survey # ') . '[' . $LEM->sid . "]: {$surveyname}</H3>\n";
     $out .= "<table class='table' id='logicfiletable'>";
     if (is_null($gid) && is_null($qid)) {
         if ($aSurveyInfo['surveyls_description'] != '') {
             $LEM->ProcessString($aSurveyInfo['surveyls_description'], 0);
             $sPrint = $LEM->GetLastPrettyPrintExpression();
             $errClass = $LEM->em->HasErrors() ? 'LEMerror' : '';
             $out .= "<tr class='LEMgroup {$errClass}'><td colspan=2>" . $LEM->gT("Description:") . "</td><td colspan=2>" . $sPrint . "</td></tr>";
         }
         if ($aSurveyInfo['surveyls_welcometext'] != '') {
             $LEM->ProcessString($aSurveyInfo['surveyls_welcometext'], 0);
             $sPrint = $LEM->GetLastPrettyPrintExpression();
             $errClass = $LEM->em->HasErrors() ? 'LEMerror' : '';
             $out .= "<tr class='LEMgroup {$errClass}'><td colspan=2>" . $LEM->gT("Welcome:") . "</td><td colspan=2>" . $sPrint . "</td></tr>";
         }
         if ($aSurveyInfo['surveyls_endtext'] != '') {
             $LEM->ProcessString($aSurveyInfo['surveyls_endtext']);
             $sPrint = $LEM->GetLastPrettyPrintExpression();
             $errClass = $LEM->em->HasErrors() ? 'LEMerror' : '';
             $out .= "<tr class='LEMgroup {$errClass}'><td colspan=2>" . $LEM->gT("End message:") . "</td><td colspan=2>" . $sPrint . "</td></tr>";
         }
         if ($aSurveyInfo['surveyls_url'] != '') {
             $LEM->ProcessString($aSurveyInfo['surveyls_urldescription'] . " - " . $aSurveyInfo['surveyls_url']);
             $sPrint = $LEM->GetLastPrettyPrintExpression();
             $errClass = $LEM->em->HasErrors() ? 'LEMerror' : '';
             $out .= "<tr class='LEMgroup {$errClass}'><td colspan=2>" . $LEM->gT("End URL:") . "</td><td colspan=2>" . $sPrint . "</td></tr>";
         }
     }
     $out .= "<tr><th>#</th><th>" . $LEM->gT('Name [ID]') . "</th><th>" . $LEM->gT('Relevance [Validation] (Default value)') . "</th><th>" . $LEM->gT('Text [Help] (Tip)') . "</th></tr>\n";
     $_gseq = -1;
     foreach ($LEM->currentQset as $q) {
         $gseq = $q['info']['gseq'];
         $gid = $q['info']['gid'];
         $qid = $q['info']['qid'];
         $qseq = $q['info']['qseq'];
         $errorCount = 0;
         //////
         // SHOW GROUP-LEVEL INFO
         //////
         if ($gseq != $_gseq) {
             $LEM->ParseResultCache = array();
             // reset for each group so get proper color coding?
             $_gseq = $gseq;
             $ginfo = $LEM->gseq2info[$gseq];
             $grelevance = '{' . ($ginfo['grelevance'] == '' ? 1 : $ginfo['grelevance']) . '}';
             $gtext = trim($ginfo['description']) == '' ? '&nbsp;' : $ginfo['description'];
             $editlink = Yii::app()->getController()->createUrl('admin/questiongroups/sa/view/surveyid/' . $LEM->sid . '/gid/' . $gid);
             $groupRow = "<tr class='LEMgroup'>" . "<td>G-{$gseq}</td>" . "<td><b>" . $ginfo['group_name'] . "</b><br />[<a target='_blank' href='{$editlink}'>GID " . $gid . "</a>]</td>" . "<td>" . $grelevance . "</td>" . "<td>" . $gtext . "</td>" . "</tr>\n";
             $LEM->ProcessString($groupRow, $qid, NULL, false, 1, 1, false, false);
             $out .= $LEM->GetLastPrettyPrintExpression();
             if ($LEM->em->HasErrors()) {
                 ++$errorCount;
             }
         }
         //////
         // SHOW QUESTION-LEVEL INFO
         //////
         $mandatory = $q['info']['mandatory'] == 'Y' ? "<span class='mandatory'>*</span>" : '';
         $type = $q['info']['type'];
         $typedesc = $qtypes[$type]['description'];
         $sgqas = explode('|', $q['sgqa']);
         if (count($sgqas) == 1 && !is_null($q['info']['default'])) {
             $LEM->ProcessString($q['info']['default'], $qid, NULL, false, 1, 1, false, false);
             // Default value is Y or answer code or go to input/textarea, then we can filter it
             $_default = $LEM->GetLastPrettyPrintExpression();
             if ($LEM->em->HasErrors()) {
                 ++$errorCount;
             }
             $default = '<br />(' . $LEM->gT('Default:') . '  ' . viewHelper::filterScript($_default) . ')';
         } else {
             $default = '';
         }
         $qtext = $q['info']['qtext'] != '' ? $q['info']['qtext'] : '&nbsp';
         $help = $q['info']['help'] != '' ? '<hr/>[' . $LEM->gT("Help:") . ' ' . $q['info']['help'] . ']' : '';
         $prettyValidTip = $q['prettyValidTip'] == '' ? '' : '<hr/>(' . $LEM->gT("Tip:") . ' ' . $q['prettyValidTip'] . ')';
         //////
         // SHOW QUESTION ATTRIBUTES THAT ARE PROCESSED BY EM
         //////
         $attrTable = '';
         $attrs = isset($LEM->qattr[$qid]) ? $LEM->qattr[$qid] : array();
         if (isset($LEM->q2subqInfo[$qid]['preg'])) {
             $attrs['regex_validation'] = $LEM->q2subqInfo[$qid]['preg'];
         }
         if (isset($LEM->questionSeq2relevance[$qseq]['other'])) {
             $attrs['other'] = $LEM->questionSeq2relevance[$qseq]['other'];
         }
         if (count($attrs) > 0) {
             $attrTable = "<table class='table' id='logicfileattributetable'><tr><th>" . $LEM->gT("Question attribute") . "</th><th>" . $LEM->gT("Value") . "</th></tr>\n";
             $count = 0;
             foreach ($attrs as $key => $value) {
                 if (is_null($value) || trim($value) == '') {
                     continue;
                 }
                 switch ($key) {
                     // @todo: Rather compares the current attribute value to the defaults in the question attributes array to decide which ones should show (only the ones that are non-standard)
                     default:
                     case 'exclude_all_others':
                     case 'exclude_all_others_auto':
                     case 'hidden':
                         if ($value == false || $value == '0') {
                             $value = NULL;
                             // so can skip this one - just using continue here doesn't work.
                         }
                         break;
                     case 'time_limit_action':
                         if ($value == '1') {
                             $value = NULL;
                             // so can skip this one - just using continue here doesn't work.
                         }
                     case 'relevance':
                         $value = NULL;
                         // means an outdate database structure
                         break;
                     case 'array_filter':
                     case 'array_filter_exclude':
                     case 'code_filter':
                     case 'date_max':
                     case 'date_min':
                     case 'em_validation_q_tip':
                     case 'em_validation_sq_tip':
                         break;
                     case 'equals_num_value':
                     case 'em_validation_q':
                     case 'em_validation_sq':
                     case 'max_answers':
                     case 'max_num_value':
                     case 'max_num_value_n':
                     case 'min_answers':
                     case 'min_num_value':
                     case 'min_num_value_n':
                     case 'min_num_of_files':
                     case 'max_num_of_files':
                     case 'multiflexible_max':
                     case 'multiflexible_min':
                     case 'slider_accuracy':
                     case 'slider_min':
                     case 'slider_max':
                     case 'slider_default':
                         $value = '{' . $value . '}';
                         break;
                     case 'other_replace_text':
                     case 'show_totals':
                     case 'regex_validation':
                         break;
                     case 'other':
                         if ($value == 'N') {
                             $value = NULL;
                             // so can skip this one
                         }
                         break;
                 }
                 if (is_null($value)) {
                     continue;
                     // since continuing from within a switch statement doesn't work
                 }
                 ++$count;
                 $attrTable .= "<tr><td>{$key}</td><td>{$value}</td></tr>\n";
             }
             $attrTable .= "</table>\n";
             if ($count == 0) {
                 $attrTable = '';
             }
         }
         $LEM->ProcessString($qtext . $help . $prettyValidTip . $attrTable, $qid, NULL, false, 1, 1, false, false);
         $qdetails = viewHelper::filterScript($LEM->GetLastPrettyPrintExpression());
         if ($LEM->em->HasErrors()) {
             ++$errorCount;
         }
         //////
         // SHOW RELEVANCE
         //////
         // Must parse Relevance this way, otherwise if try to first split expressions, regex equations won't work
         $relevanceEqn = $q['info']['relevance'] == '' ? 1 : $q['info']['relevance'];
         if (!isset($LEM->ParseResultCache[$relevanceEqn])) {
             $result = $LEM->em->ProcessBooleanExpression($relevanceEqn, $gseq, $qseq);
             $prettyPrint = $LEM->em->GetPrettyPrintString();
             $hasErrors = $LEM->em->HasErrors();
             $LEM->ParseResultCache[$relevanceEqn] = array('result' => $result, 'prettyprint' => $prettyPrint, 'hasErrors' => $hasErrors);
         }
         $relevance = $LEM->ParseResultCache[$relevanceEqn]['prettyprint'];
         if ($LEM->ParseResultCache[$relevanceEqn]['hasErrors']) {
             ++$errorCount;
         }
         //////
         // SHOW VALIDATION EQUATION
         //////
         // Must parse Validation this way so that regex (preg) works
         $prettyValidEqn = '';
         if ($q['prettyValidEqn'] != '') {
             $validationEqn = $q['validEqn'];
             if (!isset($LEM->ParseResultCache[$validationEqn])) {
                 $result = $LEM->em->ProcessBooleanExpression($validationEqn, $gseq, $qseq);
                 $prettyPrint = $LEM->em->GetPrettyPrintString();
                 $hasErrors = $LEM->em->HasErrors();
                 $LEM->ParseResultCache[$validationEqn] = array('result' => $result, 'prettyprint' => $prettyPrint, 'hasErrors' => $hasErrors);
             }
             $prettyValidEqn = '<hr/>(VALIDATION: ' . $LEM->ParseResultCache[$validationEqn]['prettyprint'] . ')';
             if ($LEM->ParseResultCache[$validationEqn]['hasErrors']) {
                 ++$errorCount;
             }
         }
         //////
         // TEST VALIDITY OF ROOT VARIABLE NAME AND WHETHER HAS BEEN USED
         //////
         $rootVarName = $q['info']['rootVarName'];
         $varNameErrorMsg = '';
         $varNameError = NULL;
         if (isset($varNamesUsed[$rootVarName])) {
             $varNameErrorMsg .= $LEM->gT('This variable name has already been used.');
         } else {
             $varNamesUsed[$rootVarName] = array('gseq' => $gseq, 'qid' => $qid);
         }
         if (!preg_match('/^[a-zA-Z][0-9a-zA-Z]*$/', $rootVarName)) {
             $varNameErrorMsg .= $LEM->gT('Starting in 2.05, variable names should only contain letters and numbers; and may not start with a number. This variable name is deprecated.');
         }
         if ($varNameErrorMsg != '') {
             $varNameError = array('message' => $varNameErrorMsg, 'gseq' => $varNamesUsed[$rootVarName]['gseq'], 'qid' => $varNamesUsed[$rootVarName]['qid'], 'gid' => $gid);
             if (!$LEM->sgqaNaming) {
                 ++$errorCount;
             } else {
                 ++$warnings;
             }
         }
         //////
         // SHOW ALL SUB-QUESTIONS
         //////
         $sqRows = '';
         $i = 0;
         $sawThis = array();
         // array of rowdivids already seen so only show them once
         foreach ($sgqas as $sgqa) {
             if ($LEM->knownVars[$sgqa]['qcode'] == $rootVarName) {
                 continue;
                 // so don't show the main question as a sub-question too
             }
             $rowdivid = $sgqa;
             $varName = $LEM->knownVars[$sgqa]['qcode'];
             switch ($q['info']['type']) {
                 case '1':
                     if (preg_match('/#1$/', $sgqa)) {
                         $rowdivid = NULL;
                         // so that doesn't show same message for second scale
                     } else {
                         $rowdivid = substr($sgqa, 0, -2);
                         // strip suffix
                         $varName = substr($LEM->knownVars[$sgqa]['qcode'], 0, -2);
                     }
                     break;
                 case 'P':
                     if (preg_match('/comment$/', $sgqa)) {
                         $rowdivid = NULL;
                     }
                     break;
                 case ':':
                 case ';':
                     $_rowdivid = $LEM->knownVars[$sgqa]['rowdivid'];
                     if (isset($sawThis[$qid . '~' . $_rowdivid])) {
                         $rowdivid = NULL;
                         // so don't show again
                     } else {
                         $sawThis[$qid . '~' . $_rowdivid] = true;
                         $rowdivid = $_rowdivid;
                         $sgqa_len = strlen($sid . 'X' . $gid . 'X' . $qid);
                         $varName = $rootVarName . '_' . substr($_rowdivid, $sgqa_len);
                     }
             }
             if (is_null($rowdivid)) {
                 continue;
             }
             ++$i;
             $subQeqn = '&nbsp;';
             if (isset($LEM->subQrelInfo[$qid][$rowdivid])) {
                 $sq = $LEM->subQrelInfo[$qid][$rowdivid];
                 $subQeqn = $sq['prettyPrintEqn'];
                 // {' . $sq['eqn'] . '}';  // $sq['prettyPrintEqn'];
                 if ($sq['hasErrors']) {
                     ++$errorCount;
                 }
             }
             $sgqaInfo = $LEM->knownVars[$sgqa];
             $subqText = $sgqaInfo['subqtext'];
             if (isset($sgqaInfo['default']) && $sgqaInfo['default'] !== '') {
                 $LEM->ProcessString(htmlspecialchars($sgqaInfo['default']), $qid, NULL, false, 1, 1, false, false);
                 $_default = viewHelper::filterScript($LEM->GetLastPrettyPrintExpression());
                 if ($LEM->em->HasErrors()) {
                     ++$errorCount;
                 }
                 $subQeqn .= '<br />(' . $LEM->gT('Default:') . '  ' . $_default . ')';
             }
             $sqRows .= "<tr class='LEMsubq'>" . "<td>SQ-{$i}</td>" . "<td><b>" . $varName . "</b></td>" . "<td>{$subQeqn}</td>" . "<td>" . $subqText . "</td>" . "</tr>";
         }
         $LEM->ProcessString($sqRows, $qid, NULL, false, 1, 1, false, false);
         $sqRows = viewHelper::filterScript($LEM->GetLastPrettyPrintExpression());
         if ($LEM->em->HasErrors()) {
             ++$errorCount;
         }
         //////
         // SHOW ANSWER OPTIONS FOR ENUMERATED LISTS, AND FOR MULTIFLEXI
         //////
         $answerRows = '';
         if (isset($LEM->qans[$qid]) || isset($LEM->multiflexiAnswers[$qid])) {
             $_scale = -1;
             if (isset($LEM->multiflexiAnswers[$qid])) {
                 $ansList = $LEM->multiflexiAnswers[$qid];
             } else {
                 $ansList = $LEM->qans[$qid];
             }
             foreach ($ansList as $ans => $value) {
                 $ansInfo = explode('~', $ans);
                 $valParts = explode('|', $value);
                 $valInfo[0] = array_shift($valParts);
                 $valInfo[1] = implode('|', $valParts);
                 if ($_scale != $ansInfo[0]) {
                     $i = 1;
                     $_scale = $ansInfo[0];
                 }
                 $subQeqn = '';
                 $rowdivid = $sgqas[0] . $ansInfo[1];
                 if ($q['info']['type'] == 'R') {
                     $rowdivid = $LEM->sid . 'X' . $gid . 'X' . $qid . $ansInfo[1];
                 }
                 if (isset($LEM->subQrelInfo[$qid][$rowdivid])) {
                     $sq = $LEM->subQrelInfo[$qid][$rowdivid];
                     $subQeqn = ' ' . $sq['prettyPrintEqn'];
                     if ($sq['hasErrors']) {
                         ++$errorCount;
                     }
                 }
                 $answerRows .= "<tr class='LEManswer'>" . "<td>A[" . $ansInfo[0] . "]-" . $i++ . "</td>" . "<td><b>" . $ansInfo[1] . "</b></td>" . "<td>[VALUE: " . $valInfo[0] . "]" . $subQeqn . "</td>" . "<td>" . $valInfo[1] . "</td>" . "</tr>\n";
             }
             $LEM->ProcessString($answerRows, $qid, NULL, false, 1, 1, false, false);
             $answerRows = viewHelper::filterScript($LEM->GetLastPrettyPrintExpression());
             if ($LEM->em->HasErrors()) {
                 ++$errorCount;
             }
         }
         //////
         // FINALLY, SHOW THE QUESTION ROW(S), COLOR-CODING QUESTIONS THAT CONTAIN ERRORS
         //////
         $errclass = $errorCount > 0 ? "class='LEMerror' title='" . $LEM->ngT("This question has at least {n} error.|This question has at least {n} errors.", $errorCount) . "'" : '';
         $questionRow = "<tr class='LEMquestion'>" . "<td {$errclass}>Q-" . $q['info']['qseq'] . "</td>" . "<td><b>" . $mandatory;
         if ($varNameErrorMsg == '') {
             $questionRow .= $rootVarName;
         } else {
             $editlink = Yii::app()->getController()->createUrl('admin/questions/sa/view/surveyid/' . $LEM->sid . '/gid/' . $varNameError['gid'] . '/qid/' . $varNameError['qid']);
             $questionRow .= "<span class='highlighterror' title='" . $varNameError['message'] . "' " . "onclick='window.open(\"{$editlink}\",\"_blank\")'>" . $rootVarName . "</span>";
         }
         $editlink = Yii::app()->getController()->createUrl('admin/questions/sa/view/surveyid/' . $sid . '/gid/' . $gid . '/qid/' . $qid);
         $questionRow .= "</b><br />[<a target='_blank' href='{$editlink}'>QID {$qid}</a>]<br/>{$typedesc} [{$type}]</td>" . "<td>" . $relevance . $prettyValidEqn . $default . "</td>" . "<td>" . $qdetails . "</td>" . "</tr>\n";
         $out .= $questionRow;
         $out .= $sqRows;
         $out .= $answerRows;
         if ($errorCount > 0) {
             $allErrors[$gid . '~' . $qid] = $errorCount;
         }
     }
     $out .= "</table>";
     LimeExpressionManager::FinishProcessingPage();
     if (($LEMdebugLevel & LEM_DEBUG_TIMING) == LEM_DEBUG_TIMING) {
         $out .= LimeExpressionManager::GetDebugTimingMessage();
     }
     if (count($allErrors) > 0) {
         $out = "<p class='LEMerror'>" . $LEM->ngT("{n} question contains errors that need to be corrected.|{n} questions contain errors that need to be corrected.", count($allErrors)) . "</p>\n" . $out;
     } else {
         switch ($surveyMode) {
             case 'survey':
                 $message = $LEM->gT('No syntax errors detected in this survey.');
                 break;
             case 'group':
                 $message = $LEM->gT('This group, by itself, does not contain any syntax errors.');
                 break;
             case 'question':
                 $message = $LEM->gT('This question, by itself, does not contain any syntax errors.');
                 break;
         }
         $out = "<p class='LEMheading'>{$message}</p>\n" . $out . "</div>";
     }
     return array('errors' => $allErrors, 'html' => $out);
 }
 /**
  * printanswers::view()
  * View answers at the end of a survey in one place. To export as pdf, set 'usepdfexport' = 1 in lsconfig.php and $printableexport='pdf'.
  * @param mixed $surveyid
  * @param bool $printableexport
  * @return
  */
 function actionView($surveyid, $printableexport = FALSE)
 {
     Yii::app()->loadHelper("frontend");
     Yii::import('application.libraries.admin.pdf');
     $iSurveyID = (int) $surveyid;
     $sExportType = $printableexport;
     Yii::app()->loadHelper('database');
     if (isset($_SESSION['survey_' . $iSurveyID]['sid'])) {
         $iSurveyID = $_SESSION['survey_' . $iSurveyID]['sid'];
     } else {
         //die('Invalid survey/session');
     }
     // Get the survey inforamtion
     // Set the language for dispay
     if (isset($_SESSION['survey_' . $iSurveyID]['s_lang'])) {
         $sLanguage = $_SESSION['survey_' . $iSurveyID]['s_lang'];
     } elseif (Survey::model()->findByPk($iSurveyID)) {
         $sLanguage = Survey::model()->findByPk($iSurveyID)->language;
     } else {
         $iSurveyID = 0;
         $sLanguage = Yii::app()->getConfig("defaultlang");
     }
     $clang = SetSurveyLanguage($iSurveyID, $sLanguage);
     $aSurveyInfo = getSurveyInfo($iSurveyID, $sLanguage);
     //SET THE TEMPLATE DIRECTORY
     if (!isset($aSurveyInfo['templatedir']) || !$aSurveyInfo['templatedir']) {
         $aSurveyInfo['templatedir'] = Yii::app()->getConfig('defaulttemplate');
     }
     $sTemplate = validateTemplateDir($aSurveyInfo['templatedir']);
     //Survey is not finished or don't exist
     if (!isset($_SESSION['survey_' . $iSurveyID]['finished']) || !isset($_SESSION['survey_' . $iSurveyID]['srid'])) {
         sendCacheHeaders();
         doHeader();
         echo templatereplace(file_get_contents(getTemplatePath($sTemplate) . '/startpage.pstpl'), array());
         echo "<center><br />\n" . "\t<font color='RED'><strong>" . $clang->gT("Error") . "</strong></font><br />\n" . "\t" . $clang->gT("We are sorry but your session has expired.") . "<br />" . $clang->gT("Either you have been inactive for too long, you have cookies disabled for your browser, or there were problems with your connection.") . "<br />\n" . "\t" . sprintf($clang->gT("Please contact %s ( %s ) for further assistance."), Yii::app()->getConfig("siteadminname"), Yii::app()->getConfig("siteadminemail")) . "\n" . "</center><br />\n";
         echo templatereplace(file_get_contents(getTemplatePath($sTemplate) . '/endpage.pstpl'), array());
         doFooter();
         exit;
     }
     //Fin session time out
     $sSRID = $_SESSION['survey_' . $iSurveyID]['srid'];
     //I want to see the answers with this id
     //Ensure script is not run directly, avoid path disclosure
     //if (!isset($rootdir) || isset($_REQUEST['$rootdir'])) {die( "browse - Cannot run this script directly");}
     if ($aSurveyInfo['printanswers'] == 'N') {
         die;
         //Die quietly if print answers is not permitted
     }
     //CHECK IF SURVEY IS ACTIVATED AND EXISTS
     $sSurveyName = $aSurveyInfo['surveyls_title'];
     $sAnonymized = $aSurveyInfo['anonymized'];
     //OK. IF WE GOT THIS FAR, THEN THE SURVEY EXISTS AND IT IS ACTIVE, SO LETS GET TO WORK.
     //SHOW HEADER
     $sOutput = CHtml::form(array("printanswers/view/surveyid/{$iSurveyID}/printableexport/pdf"), 'post') . "<center><input type='submit' value='" . $clang->gT("PDF export") . "'id=\"exportbutton\"/><input type='hidden' name='printableexport' /></center></form>";
     if ($sExportType == 'pdf') {
         //require (Yii::app()->getConfig('rootdir').'/application/config/tcpdf.php');
         Yii::import('application.libraries.admin.pdf', true);
         Yii::import('application.helpers.pdfHelper');
         $aPdfLanguageSettings = pdfHelper::getPdfLanguageSettings($clang->langcode);
         $oPDF = new pdf();
         $oPDF->SetTitle($clang->gT("Survey name (ID)", 'unescaped') . ": {$sSurveyName} ({$iSurveyID})");
         $oPDF->SetSubject($sSurveyName);
         $oPDF->SetDisplayMode('fullpage', 'two');
         $oPDF->setLanguageArray($aPdfLanguageSettings['lg']);
         $oPDF->setHeaderFont(array($aPdfLanguageSettings['pdffont'], '', PDF_FONT_SIZE_MAIN));
         $oPDF->setFooterFont(array($aPdfLanguageSettings['pdffont'], '', PDF_FONT_SIZE_DATA));
         $oPDF->SetFont($aPdfLanguageSettings['pdffont'], '', $aPdfLanguageSettings['pdffontsize']);
         $oPDF->AddPage();
         $oPDF->titleintopdf($clang->gT("Survey name (ID)", 'unescaped') . ": {$sSurveyName} ({$iSurveyID})");
     }
     $sOutput .= "\t<div class='printouttitle'><strong>" . $clang->gT("Survey name (ID):") . "</strong> {$sSurveyName} ({$iSurveyID})</div><p>&nbsp;\n";
     LimeExpressionManager::StartProcessingPage(true);
     // means that all variables are on the same page
     // Since all data are loaded, and don't need JavaScript, pretend all from Group 1
     LimeExpressionManager::StartProcessingGroup(1, $aSurveyInfo['anonymized'] != "N", $iSurveyID);
     $printanswershonorsconditions = Yii::app()->getConfig('printanswershonorsconditions');
     $aFullResponseTable = getFullResponseTable($iSurveyID, $sSRID, $sLanguage, $printanswershonorsconditions);
     //Get the fieldmap @TODO: do we need to filter out some fields?
     if ($aSurveyInfo['datestamp'] != "Y" || $sAnonymized == 'Y') {
         unset($aFullResponseTable['submitdate']);
     } else {
         unset($aFullResponseTable['id']);
     }
     unset($aFullResponseTable['token']);
     unset($aFullResponseTable['lastpage']);
     unset($aFullResponseTable['startlanguage']);
     unset($aFullResponseTable['datestamp']);
     unset($aFullResponseTable['startdate']);
     $sOutput .= "<table class='printouttable' >\n";
     foreach ($aFullResponseTable as $sFieldname => $fname) {
         if (substr($sFieldname, 0, 4) == 'gid_') {
             $sOutput .= "\t<tr class='printanswersgroup'><td colspan='2'>{$fname[0]}</td></tr>\n";
         } elseif (substr($sFieldname, 0, 4) == 'qid_') {
             $sOutput .= "\t<tr class='printanswersquestionhead'><td colspan='2'>{$fname[0]}</td></tr>\n";
         } elseif ($sFieldname == 'submitdate') {
             if ($sAnonymized != 'Y') {
                 $sOutput .= "\t<tr class='printanswersquestion'><td>{$fname[0]} {$fname[1]} {$sFieldname}</td><td class='printanswersanswertext'>{$fname[2]}</td></tr>";
             }
         } else {
             $sOutput .= "\t<tr class='printanswersquestion'><td>{$fname[0]} {$fname[1]}</td><td class='printanswersanswertext'>" . flattenText($fname[2]) . "</td></tr>";
         }
     }
     $sOutput .= "</table>\n";
     $sData['thissurvey'] = $aSurveyInfo;
     $sOutput = templatereplace($sOutput, array(), $sData, '', $aSurveyInfo['anonymized'] == "Y", NULL, array(), true);
     // Do a static replacement
     if ($sExportType == 'pdf') {
         $oPDF->writeHTML($sOutput);
         header("Pragma: public");
         header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
         $sExportFileName = sanitize_filename($sSurveyName);
         $oPDF->Output($sExportFileName . "-" . $iSurveyID . ".pdf", "D");
     } else {
         ob_start(function ($buffer, $phase) {
             App()->getClientScript()->render($buffer);
             App()->getClientScript()->reset();
             return $buffer;
         });
         ob_implicit_flush(false);
         sendCacheHeaders();
         doHeader();
         echo templatereplace(file_get_contents(getTemplatePath($sTemplate) . '/startpage.pstpl'), array(), $sData);
         echo templatereplace(file_get_contents(getTemplatePath($sTemplate) . '/printanswers.pstpl'), array('ANSWERTABLE' => $sOutput), $sData);
         echo templatereplace(file_get_contents(getTemplatePath($sTemplate) . '/endpage.pstpl'), array(), $sData);
         echo "</body></html>";
         ob_flush();
     }
     LimeExpressionManager::FinishProcessingGroup();
     LimeExpressionManager::FinishProcessingPage();
 }
Exemplo n.º 17
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();
    }
Exemplo n.º 18
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.º 19
0
/**
* Shows the welcome page, used in group by group and question by question mode
*/
function display_first_page()
{
    global $clang, $thistpl, $token, $surveyid, $thissurvey, $navigator, $publicurl;
    sendcacheheaders();
    doHeader();
    LimeExpressionManager::StartProcessingPage();
    LimeExpressionManager::StartProcessingGroup(-1, false, $surveyid);
    // start on welcome page
    echo templatereplace(file_get_contents("{$thistpl}/startpage.pstpl"));
    echo "\n<form method='post' action='{$publicurl}/index.php' id='limesurvey' name='limesurvey' autocomplete='off'>\n";
    echo "\n\n<!-- START THE SURVEY -->\n";
    echo templatereplace(file_get_contents("{$thistpl}/welcome.pstpl")) . "\n";
    if ($thissurvey['anonymized'] == "Y") {
        echo templatereplace(file_get_contents("{$thistpl}/privacy.pstpl")) . "\n";
    }
    $navigator = surveymover();
    echo templatereplace(file_get_contents("{$thistpl}/navigator.pstpl"));
    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";
    }
    echo "\n<input type='hidden' name='sid' value='{$surveyid}' id='sid' />\n";
    if (isset($token) && !empty($token)) {
        echo "\n<input type='hidden' name='token' value='{$token}' id='token' />\n";
    }
    echo "\n<input type='hidden' name='lastgroupname' value='_WELCOME_SCREEN_' id='lastgroupname' />\n";
    //This is to ensure consistency with mandatory checks, and new group test
    $loadsecurity = returnglobal('loadsecurity');
    if (isset($loadsecurity)) {
        echo "\n<input type='hidden' name='loadsecurity' value='{$loadsecurity}' id='loadsecurity' />\n";
    }
    $_SESSION['LEMpostKey'] = mt_rand();
    echo "<input type='hidden' name='LEMpostKey' value='{$_SESSION['LEMpostKey']}' id='LEMpostKey' />\n";
    echo "<input type='hidden' name='thisstep' id='thisstep' value='0' />\n";
    echo "\n</form>\n";
    echo templatereplace(file_get_contents("{$thistpl}/endpage.pstpl"));
    echo LimeExpressionManager::GetRelevanceAndTailoringJavaScript();
    LimeExpressionManager::FinishProcessingPage();
    doFooter();
}