コード例 #1
0
ファイル: Save.php プロジェクト: josetorerobueno/test_repo
 function showsaveform()
 {
     //Show 'SAVE FORM' only when click the 'Save so far' button the first time, or when duplicate is found on SAVE FORM.
     global $errormsg, $thissurvey, $surveyid, $clang, $clienttoken, $thisstep;
     $redata = compact(array_keys(get_defined_vars()));
     $sTemplatePath = $_SESSION['survey_' . $surveyid]['templatepath'];
     sendCacheHeaders();
     doHeader();
     echo templatereplace(file_get_contents($sTemplatePath . "startpage.pstpl"), array(), $redata);
     echo "\n\n<!-- JAVASCRIPT FOR CONDITIONAL QUESTIONS -->\n" . "\t<script type='text/javascript'>\n" . "\t<!--\n" . "function checkconditions(value, name, type, evt_type)\n" . "\t{\n" . "\t}\n" . "\t//-->\n" . "\t</script>\n\n";
     echo CHtml::form(array("/survey/index"), 'post') . "\n";
     //PRESENT OPTIONS SCREEN
     if (isset($errormsg) && $errormsg != "") {
         $errormsg .= "<p>" . $clang->gT("Please try again.") . "</p>";
     }
     echo templatereplace(file_get_contents($sTemplatePath . "save.pstpl"), array(), $redata);
     //END
     echo "<input type='hidden' name='sid' value='{$surveyid}' />\n";
     echo "<input type='hidden' name='thisstep' value='{$thisstep}' />\n";
     echo CHtml::hiddenField('token', $clienttoken) . "\n";
     echo "<input type='hidden' name='saveprompt' value='Y' />\n";
     echo "</form>";
     echo templatereplace(file_get_contents($sTemplatePath . "endpage.pstpl"), array(), $redata);
     echo "</html>\n";
     exit;
 }
コード例 #2
0
ファイル: save.php プロジェクト: ddrmoscow/queXS
function showsaveform()
{
    //Show 'SAVE FORM' only when click the 'Save so far' button the first time, or when duplicate is found on SAVE FORM.
    global $thistpl, $errormsg, $thissurvey, $surveyid, $clang, $clienttoken, $relativeurl, $thisstep;
    sendcacheheaders();
    doHeader();
    foreach (file("{$thistpl}/startpage.pstpl") as $op) {
        echo templatereplace($op);
    }
    echo "\n\n<!-- JAVASCRIPT FOR CONDITIONAL QUESTIONS -->\n" . "\t<script type='text/javascript'>\n" . "\t<!--\n" . "function checkconditions(value, name, type, evt_type)\n" . "\t{\n" . "\t}\n" . "\t//-->\n" . "\t</script>\n\n";
    echo "<form method='post' action='{$relativeurl}/index.php'>\n";
    //PRESENT OPTIONS SCREEN
    if (isset($errormsg) && $errormsg != "") {
        $errormsg .= "<p>" . $clang->gT("Please try again.") . "</p>";
    }
    foreach (file("{$thistpl}/save.pstpl") as $op) {
        echo templatereplace($op);
    }
    //END
    echo "<input type='hidden' name='sid' value='{$surveyid}' />\n";
    echo "<input type='hidden' name='thisstep' value='", $thisstep, "' />\n";
    echo "<input type='hidden' name='token' value='", $clienttoken, "' />\n";
    echo "<input type='hidden' name='saveprompt' value='Y' />\n";
    echo "</form>";
    foreach (file("{$thistpl}/endpage.pstpl") as $op) {
        echo templatereplace($op);
    }
    echo "</html>\n";
    exit;
}
コード例 #3
0
function doreplacement($file, $data)
{
    //Produce sample page from template file
    /**
    $output=array();
    foreach(file($file) as $op) {
    $output[]=templatereplace($op);
    }
    return $output;
    */
    return (array) templatereplace(file_get_contents($file), array(), $data);
}
コード例 #4
0
 function run($args)
 {
     extract($args);
     $redata = compact(array_keys(get_defined_vars()));
     $sTemplatePath = $_SESSION['survey_' . $surveyid]['templatepath'];
     sendCacheHeaders();
     doHeader();
     echo templatereplace(file_get_contents($sTemplatePath . "startpage.pstpl"), array(), $redata);
     echo "\n\n<!-- JAVASCRIPT FOR CONDITIONAL QUESTIONS -->\n" . "\t<script type='text/javascript'>\n" . "function checkconditions(value, name, type, evt_type)\n" . "\t{\n" . "\t}\n" . "\t</script>\n\n";
     echo CHtml::form(array("/survey/index", "sid" => $surveyid), 'post') . "\n";
     echo templatereplace(file_get_contents($sTemplatePath . "load.pstpl"), array(), $redata);
     //PRESENT OPTIONS SCREEN (Replace with Template Later)
     //END
     echo "<input type='hidden' name='loadall' value='reload' />\n";
     if (isset($clienttoken) && $clienttoken != "") {
         echo "<input type='hidden' name='token' value='{$clienttoken}' />\n";
     }
     echo "</form>";
     echo templatereplace(file_get_contents($sTemplatePath . "endpage.pstpl"), array(), $redata);
     doFooter();
     exit;
 }
コード例 #5
0
/**
* 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();
}
コード例 #6
0
$clang->eT("Question:");
?>
</strong></td><td>
            <?php 
templatereplace($qrrow['question'], array(), $aReplacementData, 'Unspecified', false, $qid);
echo FlattenText(LimeExpressionManager::GetLastPrettyPrintExpression(), true);
?>
</td></tr>
    <tr><td><strong>
            <?php 
$clang->eT("Help:");
?>
</strong></td><td>
            <?php 
if (trim($qrrow['help']) != '') {
    templatereplace($qrrow['help'], array(), $aReplacementData, 'Unspecified', false, $qid);
    echo FlattenText(LimeExpressionManager::GetLastPrettyPrintExpression(), true);
}
?>
        </td></tr>
    <?php 
if ($qrrow['preg']) {
    ?>
        <tr ><td><strong>
                <?php 
    $clang->eT("Validation:");
    ?>
</strong></td><td><?php 
    echo htmlspecialchars($qrrow['preg']);
    ?>
            </td></tr>
コード例 #7
0
ファイル: question.php プロジェクト: ryu1inaba/LimeSurvey
    /**
     * 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;
    }
コード例 #8
0
            <?php 
templatereplace(flattenText($surveyinfo['surveyls_welcometext']));
echo LimeExpressionManager::GetLastPrettyPrintExpression();
?>
        </td>
    </tr>
    <tr>
        <td>
            <strong><?php 
$clang->eT("End message:");
?>
</strong>
        </td>
        <td>
            <?php 
templatereplace(flattenText($surveyinfo['surveyls_endtext']));
echo LimeExpressionManager::GetLastPrettyPrintExpression();
?>
        </td>
    </tr>
    <tr>
        <td>
            <strong><?php 
$clang->eT("Administrator:");
?>
</strong>
        </td>
        <td>
            <?php 
echo flattenText("{$surveyinfo['admin']} ({$surveyinfo['adminemail']})");
?>
コード例 #9
0
 private function _renderHtml($html, $thistpl, $aSurveyInfo)
 {
     sendCacheHeaders();
     doHeader();
     $aSupportData = array('thissurvey' => $aSurveyInfo);
     echo templatereplace(file_get_contents($thistpl . DIRECTORY_SEPARATOR . 'startpage.pstpl'), array(), $aSupportData);
     $aData['html'] = $html;
     $aData['thistpl'] = $thistpl;
     $this->render('/opt_view', $aData);
     echo templatereplace(file_get_contents($thistpl . DIRECTORY_SEPARATOR . 'endpage.pstpl'), array(), $aSupportData);
     doFooter();
 }
コード例 #10
0
    echo $assess['minimum'];
    ?>
</td>
<td><?php 
    echo $assess['maximum'];
    ?>
</td>
<td><?php 
    $aReplacementData = array();
    templatereplace($assess['name'], array(), $aReplacementData, 'Unspecified', false, $assess['sid']);
    echo FlattenText(LimeExpressionManager::GetLastPrettyPrintExpression(), true);
    ?>
</td>
<td><?php 
    $aReplacementData = array();
    templatereplace($assess['message'], array(), $aReplacementData, 'Unspecified', false, $assess['sid']);
    echo FlattenText(LimeExpressionManager::GetLastPrettyPrintExpression(), true);
    ?>
</td>

</tr>
<?php 
}
?>
</tbody></table>

<?php 
if (Permission::model()->hasSurveyPermission($surveyid, 'assessments', 'update') && $actionvalue == "assessmentupdate" || Permission::model()->hasSurveyPermission($surveyid, 'assessments', 'create') && $actionvalue == "assessmentadd") {
    ?>
<br />
<?php 
コード例 #11
0
 /**
  * Function that initialises all data and call other functions to load default view.
  *
  * @access protected
  * @param string $templatename
  * @param string $screenname
  * @param string $editfile
  * @param bool $showsummary
  * @return
  */
 protected function _initialise($templatename, $screenname, $editfile, $showsummary = true)
 {
     App()->getClientScript()->reset();
     $clang = $this->getController()->lang;
     Yii::app()->loadHelper('surveytranslator');
     Yii::app()->loadHelper('admin/template');
     $files = $this->_initfiles($templatename);
     $cssfiles = $this->_initcssfiles();
     // Standard Support Files
     // These files may be edited or saved
     $supportfiles[] = array('name' => 'print_img_radio.png');
     $supportfiles[] = array('name' => 'print_img_checkbox.png');
     // Standard screens
     // Only these may be viewed
     $screens[] = array('name' => $clang->gT('Survey List Page'), 'id' => 'surveylist');
     $screens[] = array('name' => $clang->gT('Welcome Page'), 'id' => 'welcome');
     $screens[] = array('name' => $clang->gT('Question Page'), 'id' => 'question');
     $screens[] = array('name' => $clang->gT('Completed Page'), 'id' => 'completed');
     $screens[] = array('name' => $clang->gT('Clear All Page'), 'id' => 'clearall');
     $screens[] = array('name' => $clang->gT('Register Page'), 'id' => 'register');
     $screens[] = array('name' => $clang->gT('Load Page'), 'id' => 'load');
     $screens[] = array('name' => $clang->gT('Save Page'), 'id' => 'save');
     $screens[] = array('name' => $clang->gT('Print answers page'), 'id' => 'printanswers');
     $screens[] = array('name' => $clang->gT('Printable survey page'), 'id' => 'printablesurvey');
     // Page display blocks
     $SurveyList = array('startpage.pstpl', 'surveylist.pstpl', 'endpage.pstpl');
     $Welcome = array('startpage.pstpl', 'welcome.pstpl', 'privacy.pstpl', 'navigator.pstpl', 'endpage.pstpl');
     $Question = array('startpage.pstpl', 'survey.pstpl', 'startgroup.pstpl', 'groupdescription.pstpl', 'question.pstpl', 'endgroup.pstpl', 'navigator.pstpl', 'endpage.pstpl');
     $CompletedTemplate = array('startpage.pstpl', 'assessment.pstpl', 'completed.pstpl', 'endpage.pstpl');
     $Clearall = array('startpage.pstpl', 'clearall.pstpl', 'endpage.pstpl');
     $Register = array('startpage.pstpl', 'survey.pstpl', 'register.pstpl', 'endpage.pstpl');
     $Save = array('startpage.pstpl', 'save.pstpl', 'endpage.pstpl');
     $Load = array('startpage.pstpl', 'load.pstpl', 'endpage.pstpl');
     $printtemplate = array('startpage.pstpl', 'printanswers.pstpl', 'endpage.pstpl');
     $printablesurveytemplate = array('print_survey.pstpl', 'print_group.pstpl', 'print_question.pstpl');
     $file_version = "LimeSurvey template editor " . Yii::app()->getConfig('versionnumber');
     Yii::app()->session['s_lang'] = Yii::app()->session['adminlang'];
     $templatename = sanitize_dirname($templatename);
     $screenname = autoUnescape($screenname);
     // Checks if screen name is in the list of allowed screen names
     if (multiarray_search($screens, 'id', $screenname) === false) {
         $this->getController()->error('Invalid screen name');
     }
     if (!isset($action)) {
         $action = sanitize_paranoid_string(returnGlobal('action'));
     }
     if (!isset($subaction)) {
         $subaction = sanitize_paranoid_string(returnGlobal('subaction'));
     }
     if (!isset($newname)) {
         $newname = sanitize_dirname(returnGlobal('newname'));
     }
     if (!isset($copydir)) {
         $copydir = sanitize_dirname(returnGlobal('copydir'));
     }
     if (is_file(Yii::app()->getConfig('usertemplaterootdir') . '/' . $templatename . '/question_start.pstpl')) {
         $files[] = array('name' => 'question_start.pstpl');
         $Question[] = 'question_start.pstpl';
     }
     $availableeditorlanguages = array('bg', 'cs', 'de', 'dk', 'en', 'eo', 'es', 'fi', 'fr', 'hr', 'it', 'ja', 'mk', 'nl', 'pl', 'pt', 'ru', 'sk', 'zh');
     $extension = substr(strrchr($editfile, "."), 1);
     if ($extension == 'css' || $extension == 'js') {
         $highlighter = $extension;
     } else {
         $highlighter = 'html';
     }
     if (in_array(Yii::app()->session['adminlang'], $availableeditorlanguages)) {
         $codelanguage = Yii::app()->session['adminlang'];
     } else {
         $codelanguage = 'en';
     }
     $templates = getTemplateList();
     if (!isset($templates[$templatename])) {
         $templatename = Yii::app()->getConfig('defaulttemplate');
     }
     $normalfiles = array("DUMMYENTRY", ".", "..", "preview.png");
     foreach ($files as $fl) {
         $normalfiles[] = $fl["name"];
     }
     foreach ($cssfiles as $fl) {
         $normalfiles[] = $fl["name"];
     }
     // Some global data
     $aData['sitename'] = Yii::app()->getConfig('sitename');
     $siteadminname = Yii::app()->getConfig('siteadminname');
     $siteadminemail = Yii::app()->getConfig('siteadminemail');
     // Set this so common.php doesn't throw notices about undefined variables
     $thissurvey['active'] = 'N';
     // FAKE DATA FOR TEMPLATES
     $thissurvey['name'] = $clang->gT("Template Sample");
     $thissurvey['description'] = "<p>" . $clang->gT('This is a sample survey description. It could be quite long.') . "</p>" . "<p>" . $clang->gT("But this one isn't.") . "<p>";
     $thissurvey['welcome'] = "<p>" . $clang->gT('Welcome to this sample survey') . "<p>" . "<p>" . $clang->gT('You should have a great time doing this') . "<p>";
     $thissurvey['allowsave'] = "Y";
     $thissurvey['active'] = "Y";
     $thissurvey['tokenanswerspersistence'] = "Y";
     $thissurvey['templatedir'] = $templatename;
     $thissurvey['format'] = "G";
     $thissurvey['surveyls_url'] = "http://www.limesurvey.org/";
     $thissurvey['surveyls_urldescription'] = $clang->gT("Some URL description");
     $thissurvey['usecaptcha'] = "A";
     $percentcomplete = makegraph(6, 10);
     $groupname = $clang->gT("Group 1: The first lot of questions");
     $groupdescription = $clang->gT("This group description is fairly vacuous, but quite important.");
     $navigator = $this->getController()->render('/admin/templates/templateeditor_navigator_view', array('screenname' => $screenname, 'clang' => $clang), true);
     $completed = $this->getController()->render('/admin/templates/templateeditor_completed_view', array('clang' => $clang), true);
     $assessments = $this->getController()->render('/admin/templates/templateeditor_assessments_view', array('clang' => $clang), true);
     $printoutput = $this->getController()->render('/admin/templates/templateeditor_printoutput_view', array('clang' => $clang), true);
     $totalquestions = '10';
     $surveyformat = 'Format';
     $notanswered = '5';
     $privacy = '';
     $surveyid = '1295';
     $token = 1234567;
     $templatedir = getTemplatePath($templatename);
     $templateurl = getTemplateURL($templatename);
     // Save these variables in an array
     $aData['thissurvey'] = $thissurvey;
     $aData['percentcomplete'] = $percentcomplete;
     $aData['groupname'] = $groupname;
     $aData['groupdescription'] = $groupdescription;
     $aData['navigator'] = $navigator;
     $aData['help'] = $clang->gT("This is some help text.");
     $aData['surveyformat'] = $surveyformat;
     $aData['totalquestions'] = $totalquestions;
     $aData['completed'] = $completed;
     $aData['notanswered'] = $notanswered;
     $aData['privacy'] = $privacy;
     $aData['surveyid'] = $surveyid;
     $aData['sid'] = $surveyid;
     $aData['token'] = $token;
     $aData['assessments'] = $assessments;
     $aData['printoutput'] = $printoutput;
     $aData['templatedir'] = $templatedir;
     $aData['templateurl'] = $templateurl;
     $aData['templatename'] = $templatename;
     $aData['screenname'] = $screenname;
     $aData['editfile'] = $editfile;
     $myoutput[] = "";
     switch ($screenname) {
         case 'surveylist':
             unset($files);
             $surveylist = array("nosid" => $clang->gT("You have not provided a survey identification number"), "contact" => sprintf($clang->gT("Please contact %s ( %s ) for further assistance."), Yii::app()->getConfig("siteadminname"), Yii::app()->getConfig("siteadminemail")), "listheading" => $clang->gT("The following surveys are available:"), "list" => $this->getController()->render('/admin/templates/templateeditor_surveylist_view', array(), true));
             $aData['surveylist'] = $surveylist;
             $myoutput[] = "";
             foreach ($SurveyList as $qs) {
                 $files[] = array("name" => $qs);
                 $myoutput = array_merge($myoutput, doreplacement(getTemplatePath($templatename) . "/{$qs}", $aData));
             }
             break;
         case 'question':
             unset($files);
             foreach ($Question as $qs) {
                 $files[] = array("name" => $qs);
             }
             $myoutput[] = $this->getController()->render('/admin/templates/templateeditor_question_meta_view', array('clang' => $clang), true);
             $myoutput = array_merge($myoutput, doreplacement(getTemplatePath($templatename) . "/startpage.pstpl", $aData));
             $myoutput = array_merge($myoutput, doreplacement(getTemplatePath($templatename) . "/survey.pstpl", $aData));
             $myoutput = array_merge($myoutput, doreplacement(getTemplatePath($templatename) . "/startgroup.pstpl", $aData));
             $myoutput = array_merge($myoutput, doreplacement(getTemplatePath($templatename) . "/groupdescription.pstpl", $aData));
             $question = array('all' => $clang->gT("How many roads must a man walk down?"), 'text' => $clang->gT("How many roads must a man walk down?"), 'code' => '1a', 'help' => 'helpful text', 'mandatory' => $clang->gT("*"), 'man_class' => ' mandatory', 'man_message' => '', 'valid_message' => '', 'file_valid_message' => '', 'essentials' => 'id="question1"', 'class' => 'list-radio', 'input_error_class' => '', 'number' => '1', 'type' => 'L');
             $aData['question'] = $question;
             $answer = $this->getController()->render('/admin/templates/templateeditor_question_answer_view', array('clang' => $clang), true);
             $aData['answer'] = $answer;
             $myoutput = array_merge($myoutput, doreplacement(getTemplatePath($templatename) . "/question.pstpl", $aData));
             $answer = $this->getController()->render('/admin/templates/templateeditor_question_answer_view', array('alt' => true, 'clang' => $clang), true);
             $aData['answer'] = $answer;
             $question = array('all' => $clang->gT("Please explain something in detail:"), 'text' => $clang->gT('Please explain something in detail:'), 'code' => '2a', 'help' => '', 'mandatory' => '', 'man_message' => '', 'valid_message' => '', 'file_valid_message' => '', 'essentials' => 'id="question2"', 'class' => 'text-long', 'man_class' => 'mandatory', 'input_error_class' => '', 'number' => '2', 'type' => 'T');
             $aData['question'] = $question;
             $myoutput = array_merge($myoutput, doreplacement(getTemplatePath($templatename) . "/question.pstpl", $aData));
             $myoutput = array_merge($myoutput, doreplacement(getTemplatePath($templatename) . "/endgroup.pstpl", $aData));
             $myoutput = array_merge($myoutput, doreplacement(getTemplatePath($templatename) . "/navigator.pstpl", $aData));
             $myoutput = array_merge($myoutput, doreplacement(getTemplatePath($templatename) . "/endpage.pstpl", $aData));
             break;
         case 'welcome':
             unset($files);
             $myoutput[] = "";
             foreach ($Welcome as $qs) {
                 $files[] = array("name" => $qs);
                 $myoutput = array_merge($myoutput, doreplacement(getTemplatePath($templatename) . "/{$qs}", $aData));
             }
             break;
         case 'register':
             unset($files);
             foreach ($Register as $qs) {
                 $files[] = array("name" => $qs);
             }
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/startpage.pstpl"), array(), $aData);
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/survey.pstpl"), array(), $aData);
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/register.pstpl"), array(), $aData);
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/endpage.pstpl"), array(), $aData);
             $myoutput[] = "\n";
             break;
         case 'save':
             unset($files);
             foreach ($Save as $qs) {
                 $files[] = array("name" => $qs);
             }
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/startpage.pstpl"), array(), $aData);
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/save.pstpl"), array(), $aData);
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/endpage.pstpl"), array(), $aData);
             $myoutput[] = "\n";
             break;
         case 'load':
             unset($files);
             foreach ($Load as $qs) {
                 $files[] = array("name" => $qs);
             }
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/startpage.pstpl"), array(), $aData);
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/load.pstpl"), array(), $aData);
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/endpage.pstpl"), array(), $aData);
             $myoutput[] = "\n";
             break;
         case 'clearall':
             unset($files);
             foreach ($Clearall as $qs) {
                 $files[] = array("name" => $qs);
             }
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/startpage.pstpl"), array(), $aData);
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/clearall.pstpl"), array(), $aData);
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/endpage.pstpl"), array(), $aData);
             $myoutput[] = "\n";
             break;
         case 'completed':
             unset($files);
             $myoutput[] = "";
             foreach ($CompletedTemplate as $qs) {
                 $files[] = array("name" => $qs);
                 $myoutput = array_merge($myoutput, doreplacement(getTemplatePath($templatename) . "/{$qs}", $aData));
             }
             break;
         case 'printablesurvey':
             unset($files);
             foreach ($printablesurveytemplate as $qs) {
                 $files[] = array("name" => $qs);
             }
             $questionoutput = array();
             foreach (file("{$templatedir}/print_question.pstpl") as $op) {
                 $questionoutput[] = templatereplace($op, array('QUESTION_NUMBER' => '1', 'QUESTION_CODE' => 'Q1', 'QUESTION_MANDATORY' => $clang->gT('*'), 'QUESTION_SCENARIO' => 'Only answer this if certain conditions are met.', 'QUESTION_CLASS' => ' mandatory list-radio', 'QUESTION_TYPE_HELP' => $clang->gT('Please choose *only one* of the following:'), 'QUESTION_MAN_MESSAGE' => '', 'QUESTION_VALID_MESSAGE' => '', 'QUESTION_FILE_VALID_MESSAGE' => '', 'QUESTION_TEXT' => $clang->gT('This is a sample question text. The user was asked to pick an entry.'), 'QUESTIONHELP' => $clang->gT('This is some help text for this question.'), 'ANSWER' => $this->getController()->render('/admin/templates/templateeditor_printablesurvey_quesanswer_view', array('templateurl' => $templateurl, 'clang' => $clang), true)), $aData);
             }
             $groupoutput = array();
             $groupoutput[] = templatereplace(file_get_contents("{$templatedir}/print_group.pstpl"), array('QUESTIONS' => implode(' ', $questionoutput)), $aData);
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/print_survey.pstpl"), array('GROUPS' => implode(' ', $groupoutput), 'FAX_TO' => $clang->gT("Please fax your completed survey to:") . " 000-000-000", 'SUBMIT_TEXT' => $clang->gT("Submit your survey."), 'HEADELEMENTS' => getPrintableHeader(), 'SUBMIT_BY' => sprintf($clang->gT("Please submit by %s"), date('d.m.y')), 'THANKS' => $clang->gT('Thank you for completing this survey.'), 'END' => $clang->gT('This is the survey end message.')), $aData);
             break;
         case 'printanswers':
             unset($files);
             foreach ($printtemplate as $qs) {
                 $files[] = array("name" => $qs);
             }
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/startpage.pstpl"), array(), $aData);
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/printanswers.pstpl"), array('ANSWERTABLE' => $printoutput), $aData);
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/endpage.pstpl"), array(), $aData);
             $myoutput[] = "\n";
             break;
     }
     $myoutput[] = "</html>";
     if (is_array($files)) {
         $match = 0;
         foreach ($files as $f) {
             if ($editfile == $f["name"]) {
                 $match = 1;
             }
         }
         foreach ($cssfiles as $f) {
             if ($editfile == $f["name"]) {
                 $match = 1;
             }
         }
         if ($match == 0) {
             if (count($files) > 0) {
                 $editfile = $files[0]["name"];
             } else {
                 $editfile = "";
             }
         }
     }
     // Get list of 'otherfiles'
     $otherfiles = array();
     if ($handle = opendir($templatedir)) {
         while (false !== ($file = readdir($handle))) {
             if (!array_search($file, $normalfiles)) {
                 if (!is_dir($templatedir . DIRECTORY_SEPARATOR . $file)) {
                     $otherfiles[] = array("name" => $file);
                 }
             }
         }
         closedir($handle);
     }
     $aData['clang'] = $this->getController()->lang;
     $aData['codelanguage'] = $codelanguage;
     $aData['highlighter'] = $highlighter;
     $aData['screens'] = $screens;
     $aData['templatename'] = $templatename;
     $aData['templates'] = $templates;
     $aData['editfile'] = $editfile;
     $aData['screenname'] = $screenname;
     $aData['tempdir'] = Yii::app()->getConfig('tempdir');
     $aData['usertemplaterootdir'] = Yii::app()->getConfig('usertemplaterootdir');
     $aViewUrls['templateeditorbar_view'][] = $aData;
     if ($showsummary) {
         $aViewUrls = array_merge($aViewUrls, $this->_templatesummary($templatename, $screenname, $editfile, $templates, $files, $cssfiles, $otherfiles, $myoutput));
     }
     App()->getClientScript()->registerScriptFile(Yii::app()->getConfig('adminscripts') . 'admin_core.js');
     return $aViewUrls;
 }
コード例 #12
0
 /**
  * Get the complete HTML from a string
  * @param string $sExpression : the string to parse
  * @param array $aReplacement : optionnal array of replacemement
  * @param string $sDebugSource : optionnal debug source (for templatereplace)
  * @uses ExpressionValidate::$iSurveyId
  * @uses ExpressionValidate::$sLang
  *
  * @author Denis Chenu
  * @version 1.0
  */
 private function getHtmlExpression($sExpression, $aReplacement = array(), $sDebugSource = __CLASS__)
 {
     $LEM = LimeExpressionManager::singleton();
     $LEM::SetDirtyFlag();
     // Not sure it's needed
     $LEM::SetPreviewMode('logic');
     $aReData = array();
     if ($this->iSurveyId) {
         $LEM::StartSurvey($this->iSurveyId, 'survey', array('hyperlinkSyntaxHighlighting' => true));
         // replace QCODE
         $aReData['thissurvey'] = getSurveyInfo($this->iSurveyId, $this->sLang);
     }
     // TODO : Find error in class name, style etc ....
     // need: templatereplace without any filter and find if there are error but $bHaveError=$LEM->em->HasErrors() is Private
     $oFilter = new CHtmlPurifier();
     templatereplace($oFilter->purify(viewHelper::filterScript($sExpression)), $aReplacement, $aReData, $sDebugSource, false, null, array(), true);
     return $LEM::GetLastPrettyPrintExpression();
 }
コード例 #13
0
<?php 
    doHeader();
    echo templatereplace(file_get_contents(getTemplatePath(validateTemplateDir($sTemplatePath))."/startpage.pstpl"));
?>
<script type='text/javascript'>
    var graphUrl="<?php echo Yii::app()->getController()->createUrl("admin/statistics/graph"); ?>";
</script>
        <div id='statsContainer'>
            <div id='statsHeader'>
                <div class='statsSurveyTitle'><?php echo $thisSurveyTitle; ?></div>
                <div class='statsNumRecords'><?php echo $clang->gT("Total records in survey")." : $totalrecords"; ?></div>
            </div>
            <?php if (isset($statisticsoutput) && $statisticsoutput) { echo $statisticsoutput; } ?><br />
        </div>
<?php 
    echo templatereplace(file_get_contents(getTemplatePath(validateTemplateDir($sTemplatePath))."/endpage.pstpl"));
?>

コード例 #14
0
?>
    </td>
</tr>
<?php 
if (trim($grow['grelevance']) != '') {
    ?>
    <tr>
        <td><strong>
            <?php 
    $clang->eT("Relevance:");
    ?>
</strong>
        </td>
        <td>
            <?php 
    templatereplace('{' . $grow['grelevance'] . '}');
    echo LimeExpressionManager::GetLastPrettyPrintExpression();
    ?>
        </td>
    </tr>
    <?php 
}
if (trim($grow['randomization_group']) != '') {
    ?>
    <tr>
        <td><?php 
    $clang->eT("Randomization group:");
    ?>
</td><td><?php 
    echo $grow['randomization_group'];
    ?>
コード例 #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);
 }
コード例 #16
0
$data['templateurl'] = getTemplateURL(Yii::app()->getConfig("defaulttemplate")) . "/";
$data['templatename'] = Yii::app()->getConfig("defaulttemplate");
$data['sitename'] = Yii::app()->getConfig("sitename");
$data['languagechanger'] = makeLanguageChanger(App()->lang->langcode);
//A nice exit
sendCacheHeaders();
doHeader();
// Javascript Var
$aLSJavascriptVar = array();
$aLSJavascriptVar['bFixNumAuto'] = (int) (bool) Yii::app()->getConfig('bFixNumAuto', 1);
$aLSJavascriptVar['bNumRealValue'] = (int) (bool) Yii::app()->getConfig('bNumRealValue', 0);
if (isset($thissurvey['surveyls_numberformat'])) {
    $radix = getRadixPointData($thissurvey['surveyls_numberformat']);
} else {
    $aLangData = getLanguageData();
    $radix = getRadixPointData($aLangData[Yii::app()->getConfig('defaultlang')]['radixpoint']);
    // or $clang->langcode . defaultlang  ensure it's same for each language ?
}
$aLSJavascriptVar['sLEMradix'] = $radix['separator'];
$sLSJavascriptVar = "LSvar=" . json_encode($aLSJavascriptVar);
App()->clientScript->registerScript('sLSJavascriptVar', $sLSJavascriptVar, CClientScript::POS_HEAD);
App()->clientScript->registerScript('setJsVar', "setJsVar();", CClientScript::POS_BEGIN);
// Ensure all js var is set before rendering the page (User can click before $.ready)
App()->getClientScript()->registerPackage('jqueryui');
App()->getClientScript()->registerPackage('jquery-touch-punch');
App()->getClientScript()->registerScriptFile(Yii::app()->getConfig('generalscripts') . "survey_runtime.js");
useFirebug();
echo templatereplace(file_get_contents(getTemplatePath(Yii::app()->getConfig("defaulttemplate")) . "/startpage.pstpl"), array(), $data, 'survey[' . __LINE__ . ']');
echo templatereplace(file_get_contents(getTemplatePath(Yii::app()->getConfig("defaulttemplate")) . "/surveylist.pstpl"), array(), $data, 'survey[' . __LINE__ . ']');
echo templatereplace(file_get_contents(getTemplatePath(Yii::app()->getConfig("defaulttemplate")) . "/endpage.pstpl"), array(), $data, 'survey[' . __LINE__ . ']');
doFooter();
コード例 #17
0
 private function _renderHtml($html, $thistpl, $aSurveyInfo)
 {
     sendCacheHeaders();
     doHeader();
     $aSupportData = array('thissurvey' => $aSurveyInfo);
     // $oTemplate is a global variable defined in controller/survey/index
     global $oTemplate;
     $sTemplatePath = $oTemplate->path;
     $thistpl = $oTemplate->viewPath;
     echo templatereplace(file_get_contents($thistpl . 'startpage.pstpl'), array(), $aSupportData);
     $aData['html'] = $html;
     $aData['thistpl'] = $thistpl;
     $this->render('/opt_view', $aData);
     echo templatereplace(file_get_contents($thistpl . 'endpage.pstpl'), array(), $aSupportData);
     doFooter();
 }
コード例 #18
0
                                                            </em>
                                                        </span>
                                                    </div>

                                                <!-- Other questions -->
                                                <?php else: ?>
                                                    <a href="<?php echo $this->createUrl("/admin/questions/sa/view/surveyid/$iSurveyId/gid/".$aGroup->gid."/qid/".$question->qid); ?>" class="question-link" >
                                                        <span class="question-collapse-title">
                                                            <span class="glyphicon glyphicon-list"></span>
                                                            <strong>
                                                                <?php echo sanitize_html_string(strip_tags($question->title));?>
                                                            </strong>
                                                            <br/>
                                                            <em>
                                                                <?php
                                                                    templatereplace($question->question, array(),$aReplacementData,'Unspecified', false ,$question->qid);
                                                                    echo viewHelper::stripTagsEM(LimeExpressionManager::GetLastPrettyPrintExpression());
                                                                ?>
                                                            </em>
                                                        </span>
                                                    </a>
                                                <?php endif; ?>
                                            <?php endif; ?>
                                        <?php endforeach;?>
                                    <?php else:?>
                                        <a href="" onclick="event.preventDefault();" style="cursor: default;">
                                            <?php eT('There are no questions in this group.');?>
                                        </a>
                                    <?php endif;?>
                                </div>
                            </div>
コード例 #19
0
ファイル: display.php プロジェクト: BertHankes/LimeSurvey
<?php

global $oTemplate;
echo templatereplace(file_get_contents($oTemplate->viewPath . "startpage.pstpl"), array(), $aData);
echo templatereplace(file_get_contents($oTemplate->viewPath . "survey.pstpl"), array(), $aData);
echo $content;
echo templatereplace(file_get_contents($oTemplate->viewPath . "endpage.pstpl"), array(), $aData);
コード例 #20
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();
    }
コード例 #21
0
ファイル: pdf.php プロジェクト: rouben/LimeSurvey
 /**
  *
  * Add answer to PDF
  *
  * @param $sQuestion - Question field text array
  * @param $sResponse - Answer field text array
  * @param $bReplaceExpressions - Try to replace LimeSurvey Expressions. This is false when exporting answers PDF from admin GUI
  *                               because we can not interpret expressions so just purify.
  *                               TODO: Find a universal valid method to interpret expressions
  * @param $bAllowBreakPage - Allow break cell in two pages
  * @return unknown_type
  */
 function addAnswer($sQuestion, $sResponse, $bReplaceExpressions = true, $bAllowBreakPage = false)
 {
     $oPurifier = new CHtmlPurifier();
     $sQuestionHTML = str_replace('-oth-', '', $sQuestion);
     // Copied from Writer::stripTagsFull. Really necessary?
     $sQuestionHTML = html_entity_decode(stripJavaScript($oPurifier->purify($sQuestionHTML)), ENT_COMPAT);
     if ($bReplaceExpressions) {
         $sData['thissurvey'] = $this->_aSurveyInfo;
         $sQuestionHTML = templatereplace($sQuestionHTML, array(), $sData, '', $this->_aSurveyInfo['anonymized'] == "Y", NULL, array(), true);
     }
     $sResponse = flattenText($sResponse, false, true, 'UTF-8', false);
     $startPage = $this->getPage();
     $this->startTransaction();
     $this->SetFontSize($this->_ibaseAnswerFontSize);
     $this->WriteHTMLCell(0, $this->_iCellHeight, $this->getX(), $this->getY(), $sQuestionHTML, 1, 1, true, true, 'L');
     $this->MultiCell(0, $this->_iCellHeight, $sResponse, 1, 'L', 0, 1, '', '', true);
     $this->ln(2);
     if ($this->getPage() != $startPage && !$bAllowBreakPage) {
         $this->rollbackTransaction(true);
         $this->AddPage();
         $this->addAnswer($sQuestion, $sResponse, $bReplaceExpressions, true);
         // "Last param = true" prevents an endless loop if a cell is longer than a page
     } else {
         $this->commitTransaction();
     }
 }
コード例 #22
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)
 {
     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();
 }
コード例 #23
0
 function actionAction($surveyid, $language = null)
 {
     $sLanguage = $language;
     ob_start(function ($buffer, $phase) {
         App()->getClientScript()->render($buffer);
         App()->getClientScript()->reset();
         return $buffer;
     });
     ob_implicit_flush(false);
     $iSurveyID = (int) $surveyid;
     //$postlang = returnglobal('lang');
     Yii::import('application.libraries.admin.progressbar', true);
     Yii::app()->loadHelper("admin/statistics");
     Yii::app()->loadHelper('database');
     Yii::app()->loadHelper('surveytranslator');
     App()->getClientScript()->registerPackage('jqueryui');
     App()->getClientScript()->registerPackage('jquery-touch-punch');
     App()->getClientScript()->registerScriptFile(Yii::app()->getConfig('generalscripts') . "survey_runtime.js");
     $data = array();
     if (!isset($iSurveyID)) {
         $iSurveyID = returnGlobal('sid');
     } else {
         $iSurveyID = (int) $iSurveyID;
     }
     if (!$iSurveyID) {
         //This next line ensures that the $iSurveyID value is never anything but a number.
         safeDie('You have to provide a valid survey ID.');
     }
     if ($iSurveyID) {
         $actresult = Survey::model()->findAll('sid = :sid AND active = :active', array(':sid' => $iSurveyID, ':active' => 'Y'));
         //Checked
         if (count($actresult) == 0) {
             safeDie('You have to provide a valid survey ID.');
         } else {
             $surveyinfo = getSurveyInfo($iSurveyID);
             // CHANGE JSW_NZ - let's get the survey title for display
             $thisSurveyTitle = $surveyinfo["name"];
             // CHANGE JSW_NZ - let's get css from individual template.css - so define path
             $thisSurveyCssPath = getTemplateURL($surveyinfo["template"]);
             if ($surveyinfo['publicstatistics'] != 'Y') {
                 safeDie('The public statistics for this survey are deactivated.');
             }
             //check if graphs should be shown for this survey
             if ($surveyinfo['publicgraphs'] == 'Y') {
                 $publicgraphs = 1;
             } else {
                 $publicgraphs = 0;
             }
         }
     }
     //we collect all the output within this variable
     $statisticsoutput = '';
     //for creating graphs we need some more scripts which are included here
     //True -> include
     //False -> forget about charts
     if (isset($publicgraphs) && $publicgraphs == 1) {
         require_once APPPATH . 'third_party/pchart/pchart/pChart.class';
         require_once APPPATH . 'third_party/pchart/pchart/pData.class';
         require_once APPPATH . 'third_party/pchart/pchart/pCache.class';
         $MyCache = new pCache(Yii::app()->getConfig("tempdir") . DIRECTORY_SEPARATOR);
         //$currentuser is created as prefix for pchart files
         if (isset($_SERVER['REDIRECT_REMOTE_USER'])) {
             $currentuser = $_SERVER['REDIRECT_REMOTE_USER'];
         } else {
             if (session_id()) {
                 $currentuser = substr(session_id(), 0, 15);
             } else {
                 $currentuser = "******";
             }
         }
     }
     // Set language for questions and labels to base language of this survey
     if ($sLanguage == null || !in_array($sLanguage, Survey::model()->findByPk($iSurveyID)->getAllLanguages())) {
         $sLanguage = Survey::model()->findByPk($iSurveyID)->language;
     } else {
         $sLanguage = sanitize_languagecode($sLanguage);
     }
     //set survey language for translations
     SetSurveyLanguage($iSurveyID, $sLanguage);
     //Create header
     sendCacheHeaders();
     $condition = false;
     $sitename = Yii::app()->getConfig("sitename");
     $data['surveylanguage'] = $sLanguage;
     $data['sitename'] = $sitename;
     $data['condition'] = $condition;
     $data['thisSurveyCssPath'] = $thisSurveyCssPath;
     /*
      * only show questions where question attribute "public_statistics" is set to "1"
      */
     $query = "SELECT q.* , group_name, group_order FROM {{questions}} q, {{groups}} g, {{question_attributes}} qa\n                    WHERE g.gid = q.gid AND g.language = :lang1 AND q.language = :lang2 AND q.sid = :surveyid AND q.qid = qa.qid AND q.parent_qid = 0 AND qa.attribute = 'public_statistics'";
     $databasetype = Yii::app()->db->getDriverName();
     if ($databasetype == 'mssql' || $databasetype == "sqlsrv" || $databasetype == "dblib") {
         $query .= " AND CAST(CAST(qa.value as varchar) as int)='1'\n";
     } else {
         $query .= " AND qa.value='1'\n";
     }
     //execute query
     $result = Yii::app()->db->createCommand($query)->bindParam(":lang1", $sLanguage, PDO::PARAM_STR)->bindParam(":lang2", $sLanguage, PDO::PARAM_STR)->bindParam(":surveyid", $iSurveyID, PDO::PARAM_INT)->queryAll();
     //store all the data in $rows
     $rows = $result;
     //SORT IN NATURAL ORDER!
     usort($rows, 'groupOrderThenQuestionOrder');
     //put the question information into the filter array
     foreach ($rows as $row) {
         //store some column names in $filters array
         $filters[] = array($row['qid'], $row['gid'], $row['type'], $row['title'], $row['group_name'], flattenText($row['question']));
     }
     //number of records for this survey
     $totalrecords = 0;
     //count number of answers
     $query = "SELECT count(*) FROM {{survey_" . intval($iSurveyID) . "}}";
     //if incompleted answers should be filtert submitdate has to be not null
     //this setting is taken from config-defaults.php
     if (Yii::app()->getConfig("filterout_incomplete_answers") == true) {
         $query .= " WHERE {{survey_" . intval($iSurveyID) . "}}.submitdate is not null";
     }
     $result = Yii::app()->db->createCommand($query)->queryAll();
     //$totalrecords = total number of answers
     foreach ($result as $row) {
         $totalrecords = reset($row);
     }
     //this is the array which we need later...
     $summary = array();
     //...while this is the array from copy/paste which we don't want to replace because this is a nasty source of error
     $allfields = array();
     //---------- CREATE SGQA OF ALL QUESTIONS WHICH USE "PUBLIC_STATISTICS" ----------
     /*
              * let's go through the filter array which contains
              *     ['qid'],
              ['gid'],
              ['type'],
              ['title'],
              ['group_name'],
              ['question'];
     */
     $currentgroup = '';
     // use to check if there are any question with public statistics
     if (isset($filters)) {
         foreach ($filters as $flt) {
             //SGQ identifier
             $myfield = "{$iSurveyID}X{$flt[1]}X{$flt[0]}";
             //let's switch through the question type for each question
             switch ($flt[2]) {
                 case "K":
                     // Multiple Numerical
                 // Multiple Numerical
                 case "Q":
                     // Multiple Short Text
                     //get answers
                     $query = "SELECT title as code, question as answer FROM {{questions}} WHERE parent_qid=:flt_0 AND language = :lang ORDER BY question_order";
                     $result = Yii::app()->db->createCommand($query)->bindParam(":flt_0", $flt[0], PDO::PARAM_INT)->bindParam(":lang", $sLanguage, PDO::PARAM_STR)->queryAll();
                     //go through all the (multiple) answers
                     foreach ($result as $row) {
                         $myfield2 = $flt[2] . $myfield . reset($row);
                         $allfields[] = $myfield2;
                     }
                     break;
                 case "A":
                     // ARRAY OF 5 POINT CHOICE QUESTIONS
                 // ARRAY OF 5 POINT CHOICE QUESTIONS
                 case "B":
                     // ARRAY OF 10 POINT CHOICE QUESTIONS
                 // ARRAY OF 10 POINT CHOICE QUESTIONS
                 case "C":
                     // ARRAY OF YES\No\gT("Uncertain") QUESTIONS
                 // ARRAY OF YES\No\gT("Uncertain") QUESTIONS
                 case "E":
                     // ARRAY OF Increase/Same/Decrease QUESTIONS
                 // ARRAY OF Increase/Same/Decrease QUESTIONS
                 case "F":
                     // FlEXIBLE ARRAY
                 // FlEXIBLE ARRAY
                 case "H":
                     // ARRAY (By Column)
                     //get answers
                     $query = "SELECT title as code, question as answer FROM {{questions}} WHERE parent_qid=:flt_0 AND language = :lang ORDER BY question_order";
                     $result = Yii::app()->db->createCommand($query)->bindParam(":flt_0", $flt[0], PDO::PARAM_INT)->bindParam(":lang", $sLanguage, PDO::PARAM_STR)->queryAll();
                     //go through all the (multiple) answers
                     foreach ($result as $row) {
                         $myfield2 = $myfield . reset($row);
                         $allfields[] = $myfield2;
                     }
                     break;
                     // all "free text" types (T, U, S)  get the same prefix ("T")
                 // all "free text" types (T, U, S)  get the same prefix ("T")
                 case "T":
                     // Long free text
                 // Long free text
                 case "U":
                     // Huge free text
                 // Huge free text
                 case "S":
                     // Short free text
                     $myfield = "T{$myfield}";
                     $allfields[] = $myfield;
                     break;
                 case ";":
                     //ARRAY (Multi Flex) (Text)
                 //ARRAY (Multi Flex) (Text)
                 case ":":
                     //ARRAY (Multi Flex) (Numbers)
                     $query = "SELECT title, question FROM {{questions}} WHERE parent_qid=:flt_0 AND language=:lang AND scale_id = 0 ORDER BY question_order";
                     $result = Yii::app()->db->createCommand($query)->bindParam(":flt_0", $flt[0], PDO::PARAM_INT)->bindParam(":lang", $sLanguage, PDO::PARAM_STR)->queryAll();
                     foreach ($result as $row) {
                         $fquery = "SELECT * FROM {{questions}} WHERE parent_qid = :flt_0 AND language = :lang AND scale_id = 1 ORDER BY question_order, title";
                         $fresult = Yii::app()->db->createCommand($query)->bindParam(":flt_0", $flt[0], PDO::PARAM_INT)->bindParam(":lang", $sLanguage, PDO::PARAM_STR)->queryAll();
                         foreach ($fresult as $frow) {
                             $myfield2 = $myfield . reset($row) . "_" . $frow['title'];
                             $allfields[] = $myfield2;
                         }
                     }
                     break;
                 case "R":
                     //RANKING
                     //get some answers
                     $query = "SELECT code, answer FROM {{answers}} WHERE qid = :flt_0 AND language = :lang ORDER BY sortorder, answer";
                     $result = Yii::app()->db->createCommand($query)->bindParam(":flt_0", $flt[0], PDO::PARAM_INT)->bindParam(":lang", $sLanguage, PDO::PARAM_STR)->queryAll();
                     //get number of answers
                     $count = count($result);
                     //loop through all answers. if there are 3 items to rate there will be 3 statistics
                     for ($i = 1; $i <= $count; $i++) {
                         $myfield2 = "R" . $myfield . $i . "-" . strlen($i);
                         $allfields[] = $myfield2;
                     }
                     break;
                     //Boilerplate questions are only used to put some text between other questions -> no analysis needed
                 //Boilerplate questions are only used to put some text between other questions -> no analysis needed
                 case "X":
                     //This is a boilerplate question and it has no business in this script
                     break;
                 case "1":
                     // MULTI SCALE
                     //get answers
                     $query = "SELECT title, question FROM {{questions}} WHERE parent_qid = :flt_0 AND language = :lang ORDER BY question_order";
                     $result = Yii::app()->db->createCommand($query)->bindParam(":flt_0", $flt[0], PDO::PARAM_INT)->bindParam(":lang", $sLanguage, PDO::PARAM_STR)->queryAll();
                     //loop through answers
                     foreach ($result as $row) {
                         //----------------- LABEL 1 ---------------------
                         $myfield2 = $myfield . $row['title'] . "#0";
                         $allfields[] = $myfield2;
                         //----------------- LABEL 2 ---------------------
                         $myfield2 = $myfield . $row['title'] . "#1";
                         $allfields[] = $myfield2;
                     }
                     //end WHILE -> loop through all answers
                     break;
                 case "P":
                     //P - Multiple choice with comments
                 //P - Multiple choice with comments
                 case "M":
                     //M - Multiple choice
                 //M - Multiple choice
                 case "N":
                     //N - Numerical input
                 //N - Numerical input
                 case "D":
                     //D - Date
                     $myfield2 = $flt[2] . $myfield;
                     $allfields[] = $myfield2;
                     break;
                 default:
                     //Default settings
                     $allfields[] = $myfield;
                     break;
             }
             //end switch -> check question types and create filter forms
         }
         //end foreach -> loop through all questions with "public_statistics" enabled
     }
     // end if -> for removing the error message in case there are no filters
     $summary = $allfields;
     // Get the survey inforamtion
     $thissurvey = getSurveyInfo($surveyid, $sLanguage);
     //SET THE TEMPLATE DIRECTORY
     $data['sTemplatePath'] = $surveyinfo['template'];
     // surveyinfo=getSurveyInfo and if survey don't exist : stop before.
     //---------- CREATE STATISTICS ----------
     $redata = compact(array_keys(get_defined_vars()));
     doHeader();
     echo templatereplace(file_get_contents(getTemplatePath($data['sTemplatePath']) . DIRECTORY_SEPARATOR . "startpage.pstpl"), array(), $redata);
     //some progress bar stuff
     // Create progress bar which is shown while creating the results
     $prb = new ProgressBar();
     $prb->pedding = 2;
     // Bar Pedding
     $prb->brd_color = "#404040 #dfdfdf #dfdfdf #404040";
     // Bar Border Color
     $prb->setFrame();
     // set ProgressBar Frame
     $prb->frame['left'] = 50;
     // Frame position from left
     $prb->frame['top'] = 80;
     // Frame position from top
     $prb->addLabel('text', 'txt1', gT("Please wait ..."));
     // add Text as Label 'txt1' and value 'Please wait'
     $prb->addLabel('percent', 'pct1');
     // add Percent as Label 'pct1'
     $prb->addButton('btn1', gT('Go back'), '?action=statistics&amp;sid=' . $iSurveyID);
     // add Button as Label 'btn1' and action '?restart=1'
     //progress bar starts with 35%
     $process_status = 35;
     $prb->show();
     // show the ProgressBar
     // 1: Get list of questions with answers chosen
     //"Getting Questions and Answer ..." is shown above the bar
     $prb->setLabelValue('txt1', gT('Getting questions and answers ...'));
     $prb->moveStep(5);
     // creates array of post variable names
     for (reset($_POST); $key = key($_POST); next($_POST)) {
         $postvars[] = $key;
     }
     $data['thisSurveyTitle'] = $thisSurveyTitle;
     $data['totalrecords'] = $totalrecords;
     $data['summary'] = $summary;
     //show some main data at the beginnung
     // CHANGE JSW_NZ - let's allow html formatted questions to show
     //push progress bar from 35 to 40
     $process_status = 40;
     //Show Summary results
     if (isset($summary) && $summary) {
         //"Generating Summaries ..." is shown above the progress bar
         $prb->setLabelValue('txt1', gT('Generating summaries ...'));
         $prb->moveStep($process_status);
         //let's run through the survey // Fixed bug 3053 with array_unique
         $runthrough = array_unique($summary);
         //loop through all selected questions
         foreach ($runthrough as $rt) {
             //update progress bar
             if ($process_status < 100) {
                 $process_status++;
             }
             $prb->moveStep($process_status);
         }
         // end foreach -> loop through all questions
         $helper = new statistics_helper();
         $statisticsoutput .= $helper->generate_statistics($iSurveyID, $summary, $summary, $publicgraphs, 'html', null, $sLanguage, false);
     }
     //end if -> show summary results
     $data['statisticsoutput'] = $statisticsoutput;
     //done! set progress bar to 100%
     if (isset($prb)) {
         $prb->setLabelValue('txt1', gT('Completed'));
         $prb->moveStep(100);
         $prb->hide();
     }
     $redata = compact(array_keys(get_defined_vars()));
     $data['redata'] = $redata;
     Yii::app()->getClientScript()->registerScriptFile(Yii::app()->getConfig('generalscripts') . 'statistics_user.js');
     $this->renderPartial('/statistics_user_view', $data);
     //output footer
     echo getFooter();
     //Delete all Session Data
     Yii::app()->session['finished'] = true;
 }
コード例 #24
0
ファイル: register.php プロジェクト: nmklong/limesurvey-cdio3
//PRINT COMPLETED PAGE
if (!$thissurvey['template'])
{
    $thistpl=sGetTemplatePath(validate_templatedir('default'));
} 
else 
{
    $thistpl=sGetTemplatePath(validate_templatedir($thissurvey['template']));
}

sendcacheheaders();
doHeader();

foreach(file("$thistpl/startpage.pstpl") as $op)
{
    echo templatereplace($op);
}
foreach(file("$thistpl/survey.pstpl") as $op)
{
    echo "\t".templatereplace($op);
}
echo $html;
foreach(file("$thistpl/endpage.pstpl") as $op)
{
    echo templatereplace($op);
}
doFooter();

// Closing PHP tag is intentially left out (yes, it's fine!)
コード例 #25
0
 /**
  * function will parse the templates data
  * @return displays the requested template
  */
 function _printTemplateContent($sTemplateFile, &$redata, $iDebugLine = -1)
 {
     echo templatereplace(file_get_contents($sTemplateFile), array(), $redata, 'survey[' . $iDebugLine . ']');
 }
コード例 #26
0
/**
* 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 -->";
}
コード例 #27
0
ファイル: surveyadmin.php プロジェクト: nicbon/LimeSurvey
 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);
 }
コード例 #28
0
$data['templateurl'] = Template::getTemplateURL(Yii::app()->getConfig("defaulttemplate")) . "/";
$data['templatename'] = $oTemplate->name;
$data['sitename'] = Yii::app()->getConfig("sitename");
$data['languagechanger'] = makeLanguageChanger(App()->language);
//A nice exit
sendCacheHeaders();
doHeader();
// Javascript Var
$aLSJavascriptVar = array();
$aLSJavascriptVar['bFixNumAuto'] = (int) (bool) Yii::app()->getConfig('bFixNumAuto', 1);
$aLSJavascriptVar['bNumRealValue'] = (int) (bool) Yii::app()->getConfig('bNumRealValue', 0);
if (isset($thissurvey['surveyls_numberformat'])) {
    $radix = getRadixPointData($thissurvey['surveyls_numberformat']);
} else {
    $aLangData = getLanguageData();
    $radix = getRadixPointData($aLangData[Yii::app()->getConfig('defaultlang')]['radixpoint']);
    // or App()->language . defaultlang  ensure it's same for each language ?
}
$aLSJavascriptVar['sLEMradix'] = $radix['separator'];
$sLSJavascriptVar = "LSvar=" . json_encode($aLSJavascriptVar);
App()->clientScript->registerScript('sLSJavascriptVar', $sLSJavascriptVar, CClientScript::POS_HEAD);
App()->clientScript->registerScript('setJsVar', "setJsVar();", CClientScript::POS_BEGIN);
// Ensure all js var is set before rendering the page (User can click before $.ready)
App()->getClientScript()->registerPackage('jqueryui');
App()->getClientScript()->registerPackage('jquery-touch-punch');
App()->getClientScript()->registerScriptFile(Yii::app()->getConfig('generalscripts') . "survey_runtime.js");
useFirebug();
echo templatereplace(file_get_contents($oTemplate->viewPath . "/startpage.pstpl"), array(), $data, 'survey[' . __LINE__ . ']');
echo templatereplace(file_get_contents($oTemplate->viewPath . "/surveylist.pstpl"), array(), $data, 'survey[' . __LINE__ . ']');
echo templatereplace(file_get_contents($oTemplate->viewPath . "/endpage.pstpl"), array(), $data, 'survey[' . __LINE__ . ']');
doFooter();
コード例 #29
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();
 }
コード例 #30
0
function createinsertquery()
{
    global $thissurvey, $timeadjust, $move, $thisstep;
    global $deletenonvalues, $thistpl;
    global $surveyid, $connect, $clang, $postedfieldnames, $bFinalizeThisAnswer;
    require_once "classes/inputfilter/class.inputfilter_clean.php";
    $myFilter = new InputFilter('', '', 1, 1, 1);
    $fieldmap = createFieldMap($surveyid);
    //Creates a list of the legitimate questions for this survey
    if (isset($_SESSION['insertarray']) && is_array($_SESSION['insertarray'])) {
        $inserts = array_unique($_SESSION['insertarray']);
        $colnames_hidden = array();
        foreach ($inserts as $value) {
            //Work out if the field actually exists in this survey
            $fieldexists = '';
            if (isset($fieldmap[$value])) {
                $fieldexists = $fieldmap[$value];
            }
            //Iterate through possible responses
            if (isset($_SESSION[$value]) && !empty($fieldexists)) {
                //Only create column name and data entry if there is actually data!
                $colnames[] = $value;
                //If deletenonvalues is ON, delete any values that shouldn't exist
                if ($deletenonvalues == 1 && !checkconfield($value)) {
                    $values[] = 'NULL';
                    $colnames_hidden[] = $value;
                } elseif ($_SESSION[$value] == '' && $fieldexists['type'] == 'D' || $_SESSION[$value] == '' && $fieldexists['type'] == 'K' || $_SESSION[$value] == '' && $fieldexists['type'] == 'N') {
                    // most databases do not allow to insert an empty value into a datefield,
                    // therefore if no date was chosen in a date question the insert value has to be NULL
                    $values[] = 'NULL';
                } else {
                    // Empty the 'Other' field if a value other than '-oth-' was set for the main field (prevent invalid other values being saved - for example if Javascript fails to hide the 'Other' input field)
                    if ($fieldexists['type'] == '!' && $fieldmap[$value]['aid'] == 'other' && isset($_POST[substr($value, 0, strlen($value) - 5)]) && $_POST[substr($value, 0, strlen($value) - 5)] != '-oth-') {
                        $_SESSION[$value] = '';
                    } elseif ($fieldexists['type'] == 'N') {
                        $_SESSION[$value] = sanitize_float($_SESSION[$value]);
                    } elseif ($fieldexists['type'] == 'D' && is_array($postedfieldnames) && in_array($value, $postedfieldnames)) {
                        // convert the date to the right DB Format but only if it was posted
                        $dateformatdatat = getDateFormatData($thissurvey['surveyls_dateformat']);
                        $datetimeobj = new Date_Time_Converter($_SESSION[$value], $dateformatdatat['phpdate']);
                        $_SESSION[$value] = $datetimeobj->convert("Y-m-d");
                        $_SESSION[$value] = $connect->BindDate($_SESSION[$value]);
                    }
                    $values[] = $connect->qstr($_SESSION[$value], get_magic_quotes_gpc());
                }
            }
        }
        if ($thissurvey['datestamp'] == "Y") {
            $_SESSION['datestamp'] = date_shift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust);
        }
        // First compute the submitdate
        if ($thissurvey['private'] == "Y" && $thissurvey['datestamp'] == "N") {
            // In case of anonymous answers survey with no datestamp
            // then the the answer submutdate gets a conventional timestamp
            // 1st Jan 1980
            $mysubmitdate = date("Y-m-d H:i:s", mktime(0, 0, 0, 1, 1, 1980));
        } else {
            $mysubmitdate = date_shift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust);
        }
        // CHECK TO SEE IF ROW ALREADY EXISTS
        // srid (=Survey Record ID ) is set when the there were already answers saved for that survey
        if (!isset($_SESSION['srid'])) {
            //Prepare row insertion
            if (!isset($colnames) || !is_array($colnames)) {
                echo submitfailed();
                exit;
            }
            // INSERT NEW ROW
            $query = "INSERT INTO " . db_quote_id($thissurvey['tablename']) . "\n" . "(" . implode(', ', array_map('db_quote_id', $colnames));
            $query .= "," . db_quote_id('lastpage');
            if ($thissurvey['datestamp'] == "Y") {
                $query .= "," . db_quote_id('datestamp');
                $query .= "," . db_quote_id('startdate');
            }
            if ($thissurvey['ipaddr'] == "Y") {
                $query .= "," . db_quote_id('ipaddr');
            }
            $query .= "," . db_quote_id('startlanguage');
            if ($thissurvey['refurl'] == "Y") {
                $query .= "," . db_quote_id('refurl');
            }
            if ($bFinalizeThisAnswer === true && $thissurvey['format'] != "A") {
                $query .= "," . db_quote_id('submitdate');
            }
            $query .= ") ";
            $query .= "VALUES (" . implode(", ", $values);
            $query .= "," . ($thisstep + 1);
            if ($thissurvey['datestamp'] == "Y") {
                $query .= ", '" . $_SESSION['datestamp'] . "'";
                $query .= ", '" . $_SESSION['datestamp'] . "'";
            }
            if ($thissurvey['ipaddr'] == "Y") {
                $query .= ", '" . $_SERVER['REMOTE_ADDR'] . "'";
            }
            $query .= ", '" . $_SESSION['s_lang'] . "'";
            if ($thissurvey['refurl'] == "Y") {
                $query .= ", '" . $_SESSION['refurl'] . "'";
            }
            if ($bFinalizeThisAnswer === true && $thissurvey['format'] != "A") {
                // is if a ALL-IN-ONE survey, we don't set the submit date before the data is validated
                $query .= ", " . $connect->DBDate($mysubmitdate);
            }
            $query .= ")";
        } else {
            // UPDATE EXISTING ROW
            // Updates only the MODIFIED fields posted on current page.
            if (isset($postedfieldnames) && $postedfieldnames) {
                $query = "UPDATE {$thissurvey['tablename']} SET ";
                $query .= " lastpage = '" . $thisstep . "',";
                if ($thissurvey['datestamp'] == "Y") {
                    $query .= " datestamp = '" . $_SESSION['datestamp'] . "',";
                }
                if ($thissurvey['ipaddr'] == "Y") {
                    $query .= " ipaddr = '" . $_SERVER['REMOTE_ADDR'] . "',";
                }
                // is if a ALL-IN-ONE survey, we don't set the submit date before the data is validated
                if ($bFinalizeThisAnswer === true && $thissurvey['format'] != "A") {
                    $query .= " submitdate = " . $connect->DBDate($mysubmitdate) . ", ";
                }
                // Resets fields hidden due to conditions
                if ($deletenonvalues == 1) {
                    $hiddenfields = array_unique(array_values($colnames_hidden));
                    foreach ($hiddenfields as $hiddenfield) {
                        //$fieldinfo = arraySearchByKey($hiddenfield, $fieldmap, "fieldname", 1);
                        //if ($fieldinfo['type']=='D' || $fieldinfo['type']=='N' || $fieldinfo['type']=='K')
                        //{
                        $query .= db_quote_id($hiddenfield) . " = NULL,";
                        //}
                        //else
                        //{
                        //	$query .= db_quote_id($hiddenfield)." = '',";
                        //}
                    }
                } else {
                    $hiddenfields = array();
                }
                $fields = $postedfieldnames;
                $fields = array_unique($fields);
                $fields = array_diff($fields, $hiddenfields);
                // Do not take fields that are hidden
                foreach ($fields as $field) {
                    if (!empty($field)) {
                        $fieldinfo = $fieldmap[$field];
                        if (!isset($_POST[$field])) {
                            $_POST[$field] = '';
                        }
                        //fixed numerical question fields. They have to be NULL instead of '' to avoid database errors
                        if ($_POST[$field] == '' && $fieldinfo['type'] == 'D' || $_POST[$field] == '' && $fieldinfo['type'] == 'N' || $_POST[$field] == '' && $fieldinfo['type'] == 'K') {
                            $query .= db_quote_id($field) . " = NULL,";
                        } else {
                            // Empty the 'Other' field if a value other than '-oth-' was set for the main field (prevent invalid other values being saved - for example if Javascript fails to hide the 'Other' input field)
                            if ($fieldinfo['type'] == '!' && $fieldmap[$field]['aid'] == 'other' && $_POST[substr($field, 0, strlen($field) - 5)] != '-oth-') {
                                $qfield = "''";
                            } elseif ($fieldinfo['type'] == 'N') {
                                $qfield = db_quoteall(sanitize_float($_POST[$field]));
                            } elseif ($fieldinfo['type'] == 'D') {
                                $dateformatdatat = getDateFormatData($thissurvey['surveyls_dateformat']);
                                $datetimeobj = new Date_Time_Converter($_POST[$field], $dateformatdatat['phpdate']);
                                $qfield = db_quoteall($connect->BindDate($datetimeobj->convert("Y-m-d")));
                            } else {
                                $qfield = db_quoteall($_POST[$field], true);
                            }
                            $query .= db_quote_id($field) . " = " . $qfield . ",";
                        }
                    }
                }
                $query .= "WHERE id=" . $_SESSION['srid'];
                $query = str_replace(",WHERE", " WHERE", $query);
                // remove comma before WHERE clause
            } else {
                $query = "";
                if ($bFinalizeThisAnswer === true) {
                    $query = "UPDATE {$thissurvey['tablename']} SET ";
                    $query .= " submitdate = " . $connect->DBDate($mysubmitdate);
                    $query .= " WHERE id=" . $_SESSION['srid'];
                }
            }
        }
        //DEBUG START
        //echo $query;
        //DEBUG END
        return $query;
    } else {
        sendcacheheaders();
        doHeader();
        foreach (file("{$thistpl}/startpage.pstpl") as $op) {
            echo templatereplace($op);
        }
        echo "<br /><center><font face='verdana' size='2'><font color='red'><strong>" . $clang->gT("Error") . "</strong></font><br /><br />\n";
        echo $clang->gT("Cannot submit results - there are none to submit.") . "<br /><br />\n";
        echo "<font size='1'>" . $clang->gT("This error can occur if you have already submitted your responses and pressed 'refresh' on your browser. In this case, your responses have already been saved.") . "<br /><br />" . $clang->gT("If you receive this message in the middle of completing a survey, you should choose '<- BACK' on your browser and then refresh/reload the previous page. While you will lose answers from the last page all your others will still exist. This problem can occur if the webserver is suffering from overload or excessive use. We apologise for this problem.") . "<br />\n";
        echo "</font></center><br /><br />";
        exit;
    }
}