Example #1
0
 public function run()
 {
     /*
      * Instead of manually rendering scripts after this function returns we
      * use the callback. This ensures that scripts are always rendered, even
      * if we call exit at some point in the code. (Which we shouldn't, but
      * it happens.)
      */
     // Ensure to set some var, but script are replaced in SurveyRuntimeHelper
     $aLSJavascriptVar = array();
     $aLSJavascriptVar['bFixNumAuto'] = (int) (bool) Yii::app()->getConfig('bFixNumAuto', 1);
     $aLSJavascriptVar['bNumRealValue'] = (int) (bool) Yii::app()->getConfig('bNumRealValue', 0);
     $aLangData = getLanguageData();
     $aRadix = getRadixPointData($aLangData[Yii::app()->getConfig('defaultlang')]['radixpoint']);
     $aLSJavascriptVar['sLEMradix'] = $aRadix['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();
     ob_start(function ($buffer, $phase) {
         App()->getClientScript()->render($buffer);
         App()->getClientScript()->reset();
         return $buffer;
     });
     ob_implicit_flush(false);
     $this->action();
     ob_flush();
 }
Example #2
0
 public function run()
 {
     /*
      * Instead of manually rendering scripts after this function returns we
      * use the callback. This ensures that scripts are always rendered, even
      * if we call exit at some point in the code. (Which we shouldn't, but
      * it happens.)
      */
     // Ensure to set some var, but script are replaced in SurveyRuntimeHelper
     $aLSJavascriptVar = array();
     $aLSJavascriptVar['bFixNumAuto'] = (int) (bool) Yii::app()->getConfig('bFixNumAuto', 1);
     $aLSJavascriptVar['bNumRealValue'] = (int) (bool) Yii::app()->getConfig('bNumRealValue', 0);
     $aLangData = getLanguageData();
     $aRadix = getRadixPointData($aLangData[Yii::app()->getConfig('defaultlang')]['radixpoint']);
     $aLSJavascriptVar['sLEMradix'] = $aRadix['separator'];
     $sLSJavascriptVar = "LSvar=" . json_encode($aLSJavascriptVar) . ';';
     // Template configuration
     $param = $this->_getParameters(func_get_args(), $_POST);
     $surveyid = $param['sid'];
     // Font awesome
     if (!YII_DEBUG) {
         App()->getClientScript()->registerCssFile(App()->getAssetManager()->publish(dirname(Yii::app()->request->scriptFile) . '/styles-public/font-awesome-43.min.css'));
     } else {
         App()->getClientScript()->registerCssFile(Yii::app()->getBaseUrl(true) . '/styles-public/font-awesome-43-debugmode.min.css');
     }
     global $oTemplate;
     $oTemplate = Template::model()->getTemplateConfiguration('', $surveyid);
     $this->oTemplate = $oTemplate;
     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)
     foreach ($oTemplate->packages as $package) {
         App()->getClientScript()->registerPackage($package);
     }
     App()->getClientScript()->registerScriptFile(Yii::app()->getConfig('generalscripts') . "survey_runtime.js");
     if ($oTemplate->cssFramework == 'bootstrap') {
         App()->bootstrap->register();
     }
     useFirebug();
     ob_start(function ($buffer, $phase) {
         App()->getClientScript()->render($buffer);
         App()->getClientScript()->reset();
         return $buffer;
     });
     ob_implicit_flush(false);
     $this->action();
     ob_flush();
 }
Example #3
0
 public function run()
 {
     /*
      * Instead of manually rendering scripts after this function returns we
      * use the callback. This ensures that scripts are always rendered, even
      * if we call exit at some point in the code. (Which we shouldn't, but
      * it happens.)
      */
     // Ensure to set some var, but script are replaced in SurveyRuntimeHelper
     $aLSJavascriptVar = array();
     $aLSJavascriptVar['bFixNumAuto'] = (int) (bool) Yii::app()->getConfig('bFixNumAuto', 1);
     $aLSJavascriptVar['bNumRealValue'] = (int) (bool) Yii::app()->getConfig('bNumRealValue', 0);
     $aLangData = getLanguageData();
     $aRadix = getRadixPointData($aLangData[Yii::app()->getConfig('defaultlang')]['radixpoint']);
     $aLSJavascriptVar['sLEMradix'] = $aRadix['separator'];
     $sLSJavascriptVar = "LSvar=" . json_encode($aLSJavascriptVar) . ';';
     // Template configuration
     $param = $this->_getParameters(func_get_args(), $_POST);
     $surveyid = $param['sid'];
     $oTemplate = Template::model()->getInstance('', $surveyid);
     $this->oTemplate = $oTemplate;
     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)
     foreach ($oTemplate->packages as $package) {
         App()->getClientScript()->registerPackage((string) $package);
     }
     App()->getClientScript()->registerScriptFile(Yii::app()->getConfig('generalscripts') . "survey_runtime.js");
     if ($oTemplate->cssFramework == 'bootstrap') {
         // We now use the bootstrap package isntead of the Yiistrap TbApi::register() method
         // Then instead of using the composer dependency system for templates
         // We can use the package dependency system
         Yii::app()->getClientScript()->registerMetaTag('width=device-width, initial-scale=1.0', 'viewport');
         App()->bootstrap->registerAllScripts();
     }
     useFirebug();
     ob_start(function ($buffer, $phase) {
         App()->getClientScript()->render($buffer);
         App()->getClientScript()->reset();
         return $buffer;
     });
     ob_implicit_flush(false);
     $this->action();
     ob_flush();
 }
    /**
     * 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();
    }
Example #5
0
function do_array_multiflexi($ia)
{
    global $thissurvey;
    $answer = '';
    $aLastMoveResult = LimeExpressionManager::GetLastMoveResult();
    $aMandatoryViolationSubQ = $aLastMoveResult['mandViolation'] && $ia[6] == 'Y' ? explode("|", $aLastMoveResult['unansweredSQs']) : array();
    $repeatheadings = Yii::app()->getConfig("repeatheadings");
    $minrepeatheadings = Yii::app()->getConfig("minrepeatheadings");
    $extraclass = "";
    $answertypeclass = "";
    $caption = gT("A table of subquestions on each cell. The subquestion texts are in the colum header and concern the row header.");
    $checkconditionFunction = "fixnum_checkconditions";
    $defaultvaluescript = '';
    $qquery = "SELECT other FROM {{questions}} WHERE qid=" . $ia[0] . " AND language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "' and parent_qid=0";
    $other = Yii::app()->db->createCommand($qquery)->queryScalar();
    //Checked
    /*
     * Question Attributes
     */
    $aQuestionAttributes = QuestionAttribute::model()->getQuestionAttributes($ia[0]);
    // Define min and max value
    if (trim($aQuestionAttributes['multiflexible_max']) != '' && trim($aQuestionAttributes['multiflexible_min']) == '') {
        $maxvalue = $aQuestionAttributes['multiflexible_max'];
        $minvalue = 1;
        $extraclass .= " maxvalue maxvalue-" . trim($aQuestionAttributes['multiflexible_max']);
    }
    if (trim($aQuestionAttributes['multiflexible_min']) != '' && trim($aQuestionAttributes['multiflexible_max']) == '') {
        $minvalue = $aQuestionAttributes['multiflexible_min'];
        $maxvalue = $aQuestionAttributes['multiflexible_min'] + 10;
        $extraclass .= " minvalue minvalue-" . trim($aQuestionAttributes['multiflexible_max']);
    }
    if (trim($aQuestionAttributes['multiflexible_min']) == '' && trim($aQuestionAttributes['multiflexible_max']) == '') {
        $maxvalue = 10;
        $minvalue = isset($minvalue['value']) && $minvalue['value'] == 0 ? 0 : 1;
    }
    if (trim($aQuestionAttributes['multiflexible_min']) != '' && trim($aQuestionAttributes['multiflexible_max']) != '') {
        if ($aQuestionAttributes['multiflexible_min'] < $aQuestionAttributes['multiflexible_max']) {
            $minvalue = $aQuestionAttributes['multiflexible_min'];
            $maxvalue = $aQuestionAttributes['multiflexible_max'];
        }
    }
    $stepvalue = trim($aQuestionAttributes['multiflexible_step']) != '' && $aQuestionAttributes['multiflexible_step'] > 0 ? $aQuestionAttributes['multiflexible_step'] : 1;
    if ($aQuestionAttributes['reverse'] == 1) {
        $tmp = $minvalue;
        $minvalue = $maxvalue;
        $maxvalue = $tmp;
        $reverse = true;
        $stepvalue = -$stepvalue;
    } else {
        $reverse = false;
    }
    $checkboxlayout = false;
    $inputboxlayout = false;
    $textAlignment = 'right';
    if ($aQuestionAttributes['multiflexible_checkbox'] != 0) {
        $minvalue = 0;
        $maxvalue = 1;
        $checkboxlayout = true;
        $answertypeclass = " checkbox";
        $caption .= gT("Please check the matching combinations.");
        $textAlignment = 'center';
    } elseif ($aQuestionAttributes['input_boxes'] != 0) {
        $inputboxlayout = true;
        $answertypeclass .= " numeric-item text";
        $extraclass .= " numberonly";
        $caption .= gT("Please enter only numbers.");
        $textAlignment = 'right';
    } else {
        $answertypeclass = " dropdown";
        $caption .= gT("Please select an answer for each combination.");
    }
    if (ctype_digit(trim($aQuestionAttributes['repeat_headings'])) && trim($aQuestionAttributes['repeat_headings'] != "")) {
        $repeatheadings = intval($aQuestionAttributes['repeat_headings']);
        $minrepeatheadings = 0;
    }
    if (intval(trim($aQuestionAttributes['maximum_chars'])) > 0) {
        // Only maxlength attribute, use textarea[maxlength] jquery selector for textarea
        $maximum_chars = intval(trim($aQuestionAttributes['maximum_chars']));
        $maxlength = "maxlength='{$maximum_chars}' ";
        $extraclass .= " maxchars maxchars-" . $maximum_chars;
    } else {
        $maxlength = "";
    }
    if ($thissurvey['nokeyboard'] == 'Y') {
        includeKeypad();
        $kpclass = " num-keypad";
        $extraclass .= " inputkeypad";
    } else {
        $kpclass = "";
    }
    if (trim($aQuestionAttributes['answer_width']) != '') {
        $answerwidth = $aQuestionAttributes['answer_width'];
        $useAnswerWidth = true;
    } else {
        $answerwidth = 20;
        // If answerwidth is not given, we want to default to Bootstrap column.
        // Otherwise bug on phone screen.
        $useAnswerWidth = false;
    }
    $columnswidth = 100 - $answerwidth * 2;
    $lquery = "SELECT * FROM {{questions}} WHERE parent_qid={$ia[0]}  AND language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "' and scale_id=1 ORDER BY question_order";
    $lresult = dbExecuteAssoc($lquery);
    $aQuestions = $lresult->readAll();
    $labelans = array();
    $labelcode = array();
    foreach ($aQuestions as $lrow) {
        $labelans[] = $lrow['question'];
        $labelcode[] = $lrow['title'];
    }
    if ($numrows = count($labelans)) {
        if ($ia[6] != 'Y' && SHOW_NO_ANSWER == 1) {
            $numrows++;
        }
        $cellwidth = $columnswidth / $numrows;
        $cellwidth = sprintf('%02d', $cellwidth);
        $sQuery = "SELECT count(question) FROM {{questions}} WHERE parent_qid=" . $ia[0] . " AND scale_id=0 AND question like '%|%'";
        $iCount = Yii::app()->db->createCommand($sQuery)->queryScalar();
        if ($iCount > 0) {
            $right_exists = true;
            $answerwidth = $answerwidth / 2;
            $caption .= gT("The last cell gives some information.");
        } else {
            $right_exists = false;
        }
        // $right_exists is a flag to find out if there are any right hand answer parts. If there arent we can leave out the right td column
        if ($aQuestionAttributes['random_order'] == 1) {
            $ansquery = "SELECT * FROM {{questions}} WHERE parent_qid={$ia['0']} AND scale_id=0 AND language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "' ORDER BY " . dbRandom();
        } else {
            $ansquery = "SELECT * FROM {{questions}} WHERE parent_qid={$ia['0']} AND scale_id=0 AND language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "' ORDER BY question_order";
        }
        $ansresult = dbExecuteAssoc($ansquery)->readAll();
        //Checked
        if (trim($aQuestionAttributes['parent_order'] != '')) {
            $iParentQID = (int) $aQuestionAttributes['parent_order'];
            $aResult = array();
            $sessionao = isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['answer_order']) ? $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['answer_order'] : array();
            if (isset($sessionao[$iParentQID])) {
                foreach ($sessionao[$iParentQID] as $aOrigRow) {
                    $sCode = $aOrigRow['title'];
                    foreach ($ansresult as $aRow) {
                        if ($sCode == $aRow['title']) {
                            $aResult[] = $aRow;
                        }
                    }
                }
                $ansresult = $aResult;
            }
        }
        $anscount = count($ansresult);
        $fn = 1;
        $sAnswerRows = '';
        foreach ($ansresult as $j => $ansrow) {
            if (isset($repeatheadings) && $repeatheadings > 0 && $fn - 1 > 0 && ($fn - 1) % $repeatheadings == 0) {
                if ($anscount - $fn + 1 >= $minrepeatheadings) {
                    $sAnswerRows .= doRender('/survey/questions/arrays/multiflexi/rows/repeat_header', array('labelans' => $labelans, 'right_exists' => $right_exists, 'cellwidth' => $cellwidth, 'answerwidth' => $answerwidth, 'textAlignment' => $textAlignment), true);
                }
            }
            $myfname = $ia[1] . $ansrow['title'];
            $answertext = $ansrow['question'];
            $answertextsave = $answertext;
            /* Check the sub Q mandatory violation */
            $error = false;
            if ($ia[6] == 'Y' && !empty($aMandatoryViolationSubQ)) {
                //Go through each labelcode and check for a missing answer! Default :If any are found, highlight this line, checkbox : if one is not found : don't highlight
                // PS : we really need a better system : event for EM !
                $emptyresult = $aQuestionAttributes['multiflexible_checkbox'] != 0 ? 1 : 0;
                foreach ($labelcode as $ld) {
                    $myfname2 = $myfname . '_' . $ld;
                    if ($aQuestionAttributes['multiflexible_checkbox'] != 0) {
                        if (!in_array($myfname2, $aMandatoryViolationSubQ)) {
                            $emptyresult = 0;
                        }
                    } else {
                        if (in_array($myfname2, $aMandatoryViolationSubQ)) {
                            $emptyresult = 1;
                        }
                    }
                }
                $error = $emptyresult == 1 ? true : false;
            }
            $sSeparator = getRadixPointData($thissurvey['surveyls_numberformat']);
            $sSeparator = $sSeparator['separator'];
            // Get array_filter stuff
            $sDisplayStyle = return_display_style($ia, $aQuestionAttributes, $thissurvey, $myfname);
            if (strpos($answertext, '|')) {
                $answertext = substr($answertext, 0, strpos($answertext, '|'));
            }
            $row_value = isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname]) ? $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname] : '';
            $first_hidden_field = '';
            $thiskey = 0;
            $answer_tds = '';
            foreach ($labelcode as $i => $ld) {
                $myfname2 = $myfname . "_{$ld}";
                $value = isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname2]) ? $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname2] : '';
                // Possibly replace '.' with ','
                $surveyId = Yii::app()->getConfig('surveyID');
                $surveyLabel = 'survey_' . $surveyId;
                $fieldnameIsNumeric = isset($_SESSION[$surveyLabel][$myfname2]) && is_numeric($_SESSION[$surveyLabel][$myfname2]);
                if ($fieldnameIsNumeric) {
                    $value = str_replace('.', $sSeparator, $_SESSION[$surveyLabel][$myfname2]);
                }
                if ($checkboxlayout == false) {
                    $answer_tds .= doRender('/survey/questions/arrays/multiflexi/rows/cells/answer_td', array('dataTitle' => $labelans[$i], 'ld' => $ld, 'answertypeclass' => $answertypeclass, 'answertext' => $answertext, 'stepvalue' => $stepvalue, 'extraclass' => $extraclass, 'myfname2' => $myfname2, 'error' => $error, 'inputboxlayout' => $inputboxlayout, 'checkconditionFunction' => $checkconditionFunction, 'minvalue' => $minvalue, 'maxvalue' => $maxvalue, 'reverse' => $reverse, 'value' => $value, 'sSeparator' => $sSeparator, 'kpclass' => $kpclass, 'maxlength' => $maxlength), true);
                    $inputnames[] = $myfname2;
                    $thiskey++;
                } else {
                    if (isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname2]) && $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname2] == '1') {
                        $myvalue = '1';
                        $setmyvalue = CHECKED;
                    } else {
                        $myvalue = '';
                        $setmyvalue = '';
                    }
                    $answer_tds .= doRender('/survey/questions/arrays/multiflexi/rows/cells/answer_td_checkboxes', array('dataTitle' => $labelans[$i], 'ld' => $ld, 'answertypeclass' => $answertypeclass, 'value' => $myvalue, 'setmyvalue' => $setmyvalue, 'myfname2' => $myfname2, 'checkconditionFunction' => $checkconditionFunction, 'extraclass' => $extraclass), true);
                    $inputnames[] = $myfname2;
                    $thiskey++;
                }
            }
            $rightTd = false;
            $answertextright = '';
            if (strpos($answertextsave, '|')) {
                $answertextright = substr($answertextsave, strpos($answertextsave, '|') + 1);
                $rightTd = true;
            } elseif ($right_exists) {
                $rightTd = true;
            }
            $sAnswerRows .= doRender('/survey/questions/arrays/multiflexi/rows/answer_row', array('sDisplayStyle' => $sDisplayStyle, 'useAnswerWidth' => $useAnswerWidth, 'answerwidth' => $answerwidth, 'myfname' => $myfname, 'error' => $error, 'row_value' => $row_value, 'answertext' => $answertext, 'answertextright' => $answertextright, 'answer_tds' => $answer_tds, 'rightTd' => $rightTd, 'zebra' => 2 - $j % 2), true);
            $fn++;
        }
        $answer = doRender('/survey/questions/arrays/multiflexi/answer', array('answertypeclass' => $answertypeclass, 'extraclass' => $extraclass, 'answerwidth' => $answerwidth, 'labelans' => $labelans, 'cellwidth' => $cellwidth, 'right_exists' => $right_exists, 'sAnswerRows' => $sAnswerRows, 'textAlignment' => $textAlignment), true);
    } else {
        $answer = doRender('/survey/questions/arrays/multiflexi/empty_error', array(), true);
        $inputnames = '';
    }
    return array($answer, $inputnames);
}
/**
 * Marks a tokens as completed and sends a confirmation email to the participiant.
 * If $quotaexit is set to true then the user exited the survey due to a quota
 * restriction and the according token is only marked as 'Q'
 *
 * @param mixed $quotaexit
 */
function submittokens($quotaexit = false)
{
    global $thissurvey, $timeadjust, $emailcharset;
    global $dbprefix, $surveyid, $connect;
    global $sitename, $thistpl, $clang, $clienttoken;
    // Shift the date due to global timeadjust setting
    $today = date_shift(date("Y-m-d H:i:s"), "Y-m-d H:i", $timeadjust);
    // check how many uses the token has left
    $usesquery = "SELECT usesleft FROM {$dbprefix}tokens_{$surveyid} WHERE token='" . db_quote($clienttoken) . "'";
    $usesresult = db_execute_assoc($usesquery);
    $usesrow = $usesresult->FetchRow();
    if (isset($usesrow)) {
        $usesleft = $usesrow['usesleft'];
    }
    $utquery = "UPDATE {$dbprefix}tokens_{$surveyid}\n";
    if ($quotaexit == true) {
        $utquery .= "SET completed='Q', usesleft=usesleft-1\n";
    } elseif (bIsTokenCompletedDatestamped($thissurvey)) {
        if (isset($usesleft) && $usesleft <= 1) {
            $utquery .= "SET usesleft=usesleft-1, completed='{$today}'\n";
        } else {
            $utquery .= "SET usesleft=usesleft-1\n";
        }
    } else {
        if (isset($usesleft) && $usesleft <= 1) {
            $utquery .= "SET usesleft=usesleft-1, completed='Y'\n";
        } else {
            $utquery .= "SET usesleft=usesleft-1\n";
        }
    }
    $utquery .= "WHERE token='" . db_quote($clienttoken) . "'";
    $utresult = $connect->Execute($utquery) or safe_die("Couldn't update tokens table!<br />\n{$utquery}<br />\n" . $connect->ErrorMsg());
    //Checked
    if ($quotaexit == false) {
        // TLR change to put date into sent and completed
        $cnfquery = "SELECT * FROM " . db_table_name("tokens_{$surveyid}") . " WHERE token='" . db_quote($clienttoken) . "' AND completed!='N' AND completed!=''";
        $cnfresult = db_execute_assoc($cnfquery);
        //Checked
        $cnfrow = $cnfresult->FetchRow();
        if (isset($cnfrow)) {
            $from = "{$thissurvey['adminname']} <{$thissurvey['adminemail']}>";
            $to = $cnfrow['email'];
            $subject = $thissurvey['email_confirm_subj'];
            $fieldsarray["{ADMINNAME}"] = $thissurvey['adminname'];
            $fieldsarray["{ADMINEMAIL}"] = $thissurvey['adminemail'];
            $fieldsarray["{SURVEYNAME}"] = $thissurvey['name'];
            $fieldsarray["{SURVEYDESCRIPTION}"] = $thissurvey['description'];
            $fieldsarray["{FIRSTNAME}"] = $cnfrow['firstname'];
            $fieldsarray["{LASTNAME}"] = $cnfrow['lastname'];
            $fieldsarray["{TOKEN}"] = $clienttoken;
            $attrfieldnames = GetAttributeFieldnames($surveyid);
            foreach ($attrfieldnames as $attr_name) {
                $fieldsarray["{" . strtoupper($attr_name) . "}"] = $cnfrow[$attr_name];
            }
            $dateformatdatat = getDateFormatData($thissurvey['surveyls_dateformat']);
            $numberformatdatat = getRadixPointData($thissurvey['surveyls_numberformat']);
            $fieldsarray["{EXPIRY}"] = convertDateTimeFormat($thissurvey["expiry"], 'Y-m-d H:i:s', $dateformatdatat['phpdate']);
            $subject = ReplaceFields($subject, $fieldsarray, true);
            if ($thissurvey['anonymized'] == "N") {
                // Survey is not anonymous, we can translate insertAns placeholder
                $subject = dTexts::run($subject);
            }
            $subject = html_entity_decode($subject, ENT_QUOTES, $emailcharset);
            if (getEmailFormat($surveyid) == 'html') {
                $ishtml = true;
            } else {
                $ishtml = false;
            }
            if (trim(strip_tags($thissurvey['email_confirm'])) != "") {
                $message = $thissurvey['email_confirm'];
                $message = ReplaceFields($message, $fieldsarray, true);
                if ($thissurvey['anonymized'] == "N") {
                    // Survey is not anonymous, we can translate insertAns placeholder
                    $message = dTexts::run($message);
                }
                if (!$ishtml) {
                    $message = strip_tags(br2nl(html_entity_decode($message, ENT_QUOTES, $emailcharset)));
                } else {
                    $message = html_entity_decode($message, ENT_QUOTES, $emailcharset);
                }
                //Only send confirmation email if there is a valid email address
                if (validate_email($cnfrow['email'])) {
                    SendEmailMessage(null, $message, $subject, $to, $from, $sitename, $ishtml);
                }
            } else {
                //There is nothing in the message, so don't send a confirmation email
                //This section only here as placeholder to indicate new feature :-)
            }
        }
    }
}
 /**
  * setJavascriptVar
  *
  * @return @void
  * @param integer $iSurveyId : the survey id for the script
  */
 public function setJavascriptVar($iSurveyId)
 {
     $aSurveyinfo = getSurveyInfo($iSurveyId, App()->getLanguage());
     if (isset($aSurveyinfo['surveyls_numberformat'])) {
         $aLSJavascriptVar = array();
         $aLSJavascriptVar['bFixNumAuto'] = (int) (bool) Yii::app()->getConfig('bFixNumAuto', 1);
         $aLSJavascriptVar['bNumRealValue'] = (int) (bool) Yii::app()->getConfig('bNumRealValue', 0);
         $aRadix = getRadixPointData($aSurveyinfo['surveyls_numberformat']);
         $aLSJavascriptVar['sLEMradix'] = $aRadix['separator'];
         $sLSJavascriptVar = "LSvar=" . json_encode($aLSJavascriptVar) . ';';
         App()->clientScript->registerScript('sLSJavascriptVar', $sLSJavascriptVar, CClientScript::POS_HEAD);
     }
     // Maybe remove one from index and allow empty $surveyid here.
 }
/**
* Marks a tokens as completed and sends a confirmation email to the participiant.
* If $quotaexit is set to true then the user exited the survey due to a quota
* restriction and the according token is only marked as 'Q'
*
* @param mixed $quotaexit
*/
function submittokens($quotaexit = false)
{
    $surveyid = Yii::app()->getConfig('surveyID');
    if (isset($_SESSION['survey_' . $surveyid]['s_lang'])) {
        $thissurvey = getSurveyInfo($surveyid, $_SESSION['survey_' . $surveyid]['s_lang']);
    } else {
        $thissurvey = getSurveyInfo($surveyid);
    }
    $clienttoken = $_SESSION['survey_' . $surveyid]['token'];
    $sitename = Yii::app()->getConfig("sitename");
    $emailcharset = Yii::app()->getConfig("emailcharset");
    // Shift the date due to global timeadjust setting
    $today = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i", Yii::app()->getConfig("timeadjust"));
    // check how many uses the token has left
    $token = Token::model($surveyid)->findByAttributes(array('token' => $clienttoken));
    if ($quotaexit == true) {
        $token->completed = 'Q';
        $token->usesleft--;
    } else {
        if ($token->usesleft <= 1) {
            // Finish the token
            if (isTokenCompletedDatestamped($thissurvey)) {
                $token->completed = $today;
            } else {
                $token->completed = 'Y';
            }
            if (isset($token->participant_id)) {
                $slquery = SurveyLink::model()->find('participant_id = :pid AND survey_id = :sid AND token_id = :tid', array(':pid' => $token->participant_id, ':sid' => $surveyid, ':tid' => $token->tid));
                if ($slquery) {
                    if (isTokenCompletedDatestamped($thissurvey)) {
                        $slquery->date_completed = $today;
                    } else {
                        // Update the survey_links table if necessary, to protect anonymity, use the date_created field date
                        $slquery->date_completed = $slquery->date_created;
                    }
                    $slquery->save();
                }
            }
        }
        $token->usesleft--;
    }
    $token->save();
    if ($quotaexit == false) {
        if ($token && trim(strip_tags($thissurvey['email_confirm'])) != "" && $thissurvey['sendconfirmation'] == "Y") {
            //   if($token->completed == "Y" || $token->completed == $today)
            //            {
            $from = "{$thissurvey['adminname']} <{$thissurvey['adminemail']}>";
            $subject = $thissurvey['email_confirm_subj'];
            $aReplacementVars = array();
            $aReplacementVars["ADMINNAME"] = $thissurvey['admin'];
            $aReplacementVars["ADMINEMAIL"] = $thissurvey['adminemail'];
            $aReplacementVars['ADMINEMAIL'] = $thissurvey['adminemail'];
            //Fill with token info, because user can have his information with anonimity control
            $aReplacementVars["FIRSTNAME"] = $token->firstname;
            $aReplacementVars["LASTNAME"] = $token->lastname;
            $aReplacementVars["TOKEN"] = $token->token;
            // added survey url in replacement vars
            $surveylink = Yii::app()->createAbsoluteUrl("/survey/index/sid/{$surveyid}", array('lang' => $_SESSION['survey_' . $surveyid]['s_lang'], 'token' => $token->token));
            $aReplacementVars['SURVEYURL'] = $surveylink;
            $attrfieldnames = getAttributeFieldNames($surveyid);
            foreach ($attrfieldnames as $attr_name) {
                $aReplacementVars[strtoupper($attr_name)] = $token->{$attr_name};
            }
            $dateformatdatat = getDateFormatData($thissurvey['surveyls_dateformat']);
            $numberformatdatat = getRadixPointData($thissurvey['surveyls_numberformat']);
            $redata = array('thissurvey' => $thissurvey);
            $subject = templatereplace($subject, $aReplacementVars, $redata, '', false, null, array(), true);
            $subject = html_entity_decode($subject, ENT_QUOTES, $emailcharset);
            if (getEmailFormat($surveyid) == 'html') {
                $ishtml = true;
            } else {
                $ishtml = false;
            }
            $message = $thissurvey['email_confirm'];
            //$message=ReplaceFields($message, $fieldsarray, true);
            $message = templatereplace($message, $aReplacementVars, $redata, '', false, null, array(), true);
            if (!$ishtml) {
                $message = strip_tags(breakToNewline(html_entity_decode($message, ENT_QUOTES, $emailcharset)));
            } else {
                $message = html_entity_decode($message, ENT_QUOTES, $emailcharset);
            }
            //Only send confirmation email if there is a valid email address
            $sToAddress = validateEmailAddresses($token->email);
            if ($sToAddress) {
                $aAttachments = unserialize($thissurvey['attachments']);
                $aRelevantAttachments = array();
                /*
                 * Iterate through attachments and check them for relevance.
                 */
                if (isset($aAttachments['confirmation'])) {
                    foreach ($aAttachments['confirmation'] as $aAttachment) {
                        $relevance = $aAttachment['relevance'];
                        // If the attachment is relevant it will be added to the mail.
                        if (LimeExpressionManager::ProcessRelevance($relevance) && file_exists($aAttachment['url'])) {
                            $aRelevantAttachments[] = $aAttachment['url'];
                        }
                    }
                }
                SendEmailMessage($message, $subject, $sToAddress, $from, $sitename, $ishtml, null, $aRelevantAttachments);
            }
            //   } else {
            // Leave it to send optional confirmation at closed token
            //          }
        }
    }
}
Example #9
0
 public function doQuestion($ia)
 {
     global $thissurvey;
     if ($thissurvey['nokeyboard'] == 'Y') {
         includeKeypad();
         $kpclass = "text-keypad";
     } else {
         $kpclass = "";
     }
     $checkconditionFunction = "checkconditions";
     $aQuestionAttributes = getQuestionAttributeValues($ia[0]);
     $query = "SELECT other FROM {{questions}} WHERE qid=" . $ia[0] . " AND language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "' ";
     $result = Yii::app()->db->createCommand($query)->query();
     foreach ($result->readAll() as $row) {
         $other = $row['other'];
     }
     //question attribute random order set?
     if ($aQuestionAttributes['random_order'] == 1) {
         $ansquery = "SELECT * FROM {{answers}} WHERE qid={$ia['0']} AND language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "' and scale_id=0 ORDER BY " . dbRandom();
     } elseif ($aQuestionAttributes['alphasort'] == 1) {
         $ansquery = "SELECT * FROM {{answers}} WHERE qid={$ia['0']} AND language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "' and scale_id=0 ORDER BY answer";
     } else {
         $ansquery = "SELECT * FROM {{answers}} WHERE qid={$ia['0']} AND language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "' and scale_id=0 ORDER BY sortorder, answer";
     }
     $ansresult = dbExecuteAssoc($ansquery)->readAll();
     //Checked
     $anscount = count($ansresult);
     if (trim($aQuestionAttributes['display_columns']) != '') {
         $dcols = $aQuestionAttributes['display_columns'];
     } else {
         $dcols = 1;
     }
     if (trim($aQuestionAttributes['other_replace_text'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']]) != '') {
         $othertext = $aQuestionAttributes['other_replace_text'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']];
     } else {
         $othertext = gT('Other:');
     }
     if (isset($other) && $other == 'Y') {
         $anscount++;
     }
     //Count up for the Other answer
     if ($ia[6] != 'Y' && SHOW_NO_ANSWER == 1) {
         $anscount++;
     }
     //Count up if "No answer" is showing
     $wrapper = setupColumns($dcols, $anscount, "answers-list radio-list", "answer-item radio-item");
     $iBootCols = round(12 / $dcols);
     $ansByCol = round($anscount / $dcols);
     $ansByCol = $ansByCol > 0 ? $ansByCol : 1;
     //$answer = 'IKI: '.$iBootCols.' '.$ansByCol.' '.$wrapper['whole-start'];
     $answer = '<div class="row">';
     $answer .= '    <div class="col-xs-' . $iBootCols . '">AAAAAAAAAAAAAA';
     //Time Limit Code
     if (trim($aQuestionAttributes['time_limit']) != '') {
         $answer .= return_timer_script($aQuestionAttributes, $ia);
     }
     //End Time Limit Code
     // Get array_filter stuff
     $rowcounter = 0;
     $colcounter = 1;
     $trbc = '';
     foreach ($ansresult as $key => $ansrow) {
         $myfname = $ia[1] . $ansrow['code'];
         $check_ans = '';
         if ($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$ia[1]] == $ansrow['code']) {
             $check_ans = CHECKED;
         }
         list($htmltbody2, $hiddenfield) = return_array_filter_strings($ia, $aQuestionAttributes, $thissurvey, $ansrow, $myfname, '', $myfname, "div", "form-group answer-item radio-item");
         /*    if(substr($wrapper['item-start'],0,4) == "\t<li")
                     {
                         $startitem = "\t$htmltbody2\n";
                     } else {
                         $startitem = $wrapper['item-start'];
                     }
         
                     $answer .= $startitem;*/
         $answer .= "\t{$hiddenfield}\n";
         $answer .= '<div  class="form-group">';
         $answer .= '    <label for="answer' . $ia[1] . $ansrow['code'] . '" class="answertext control-label">' . $ansrow['answer'] . '</label>';
         $answer .= '        <input class="radio" type="radio" value="' . $ansrow['code'] . '" name="' . $ia[1] . '" id="answer' . $ia[1] . $ansrow['code'] . '"' . $check_ans . ' onclick="if (document.getElementById(\'answer' . $ia[1] . 'othertext\') != null) document.getElementById(\'answer' . $ia[1] . 'othertext\').value=\'\';' . $checkconditionFunction . '(this.value, this.name, this.type)" />';
         $answer .= $wrapper['item-end'];
         $answer .= '</div>';
         ++$rowcounter;
         //if ($rowcounter == $wrapper['maxrows'] && $colcounter < $wrapper['cols'] || (count($ansresult)-$key)==$wrapper['cols']-$colcounter)
         if ($rowcounter == $ansByCol && $colcounter < $wrapper['cols']) {
             if ($colcounter == $wrapper['cols']) {
                 //$answer .= 'là '.$wrapper['col-devide-last'];
                 $answer .= '    </div><!-- last -->';
             } else {
                 //$answer .= 'et là '.$wrapper['col-devide'];
                 $answer .= '    </div><!-- devide --> ';
                 $answer .= '    <div class="col-xs-' . $iBootCols . '">';
             }
             $rowcounter = 0;
             ++$colcounter;
         }
     }
     if (isset($other) && $other == 'Y') {
         $sSeparator = getRadixPointData($thissurvey['surveyls_numberformat']);
         $sSeparator = $sSeparator['separator'];
         if ($aQuestionAttributes['other_numbers_only'] == 1) {
             $oth_checkconditionFunction = 'fixnum_checkconditions';
         } else {
             $oth_checkconditionFunction = 'checkconditions';
         }
         if ($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$ia[1]] == '-oth-') {
             $check_ans = CHECKED;
         } else {
             $check_ans = '';
         }
         $thisfieldname = $ia[1] . 'other';
         if (isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$thisfieldname])) {
             $dispVal = $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$thisfieldname];
             if ($aQuestionAttributes['other_numbers_only'] == 1) {
                 $dispVal = str_replace('.', $sSeparator, $dispVal);
             }
             $answer_other = ' value="' . htmlspecialchars($dispVal, ENT_QUOTES) . '"';
         } else {
             $answer_other = ' value=""';
         }
         list($htmltbody2, $hiddenfield) = return_array_filter_strings($ia, $aQuestionAttributes, $thissurvey, array("code" => "other"), $thisfieldname, $trbc, $myfname, "div", "form-group answer-item radio-item other-item other");
         $answer .= "\t{$hiddenfield}\n";
         $answer .= '<div  class="form-group">';
         $answer .= '    <label for="SOTH' . $ia[1] . '" class="answertext control-label">' . $othertext . '</label>';
         $answer .= '    <input class="radio" type="radio" value="-oth-" name="' . $ia[1] . '" id="SOTH' . $ia[1] . '"' . $check_ans . ' onclick="' . $checkconditionFunction . '(this.value, this.name, this.type)" />';
         $answer .= '    <input type="text" class="text ' . $kpclass . '" id="answer' . $ia[1] . 'othertext" name="' . $ia[1] . 'other" title="' . gT('Other') . '"' . $answer_other . ' onkeyup="if($.trim($(this).val())!=\'\'){ $(\'#SOTH' . $ia[1] . '\').click(); }; ' . $oth_checkconditionFunction . '(this.value, this.name, this.type);" />';
         $answer .= $wrapper['item-end'];
         $answer .= '</div>';
         $inputnames[] = $thisfieldname;
         ++$rowcounter;
         if ($rowcounter == $ansByCol && $colcounter < $wrapper['cols']) {
             if ($colcounter == $wrapper['cols']) {
                 $answer .= '    </div><!-- last -->';
             } else {
                 $answer .= '    </div><!-- devide -->';
                 $answer .= '    <div class="col-xs-' . $iBootCols . '">';
             }
             $rowcounter = 0;
             ++$colcounter;
         }
     }
     if ($ia[6] != 'Y' && SHOW_NO_ANSWER == 1) {
         if (!isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$ia[1]]) || $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$ia[1]] == '' || $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$ia[1]] == ' ') {
             $check_ans = CHECKED;
             //Check the "no answer" radio button if there is no answer in session.
         } else {
             $check_ans = '';
         }
         $answer .= '<div  class="form-group">';
         $answer .= '    <label for="answer' . $ia[1] . 'NANS" class="answertext control-label">' . gT('No answer') . '</label>';
         $answer .= '        <input class="radio" type="radio" name="' . $ia[1] . '" id="answer' . $ia[1] . 'NANS" value=""' . $check_ans . ' onclick="if (document.getElementById(\'answer' . $ia[1] . 'othertext\') != null) document.getElementById(\'answer' . $ia[1] . 'othertext\').value=\'\';' . $checkconditionFunction . '(this.value, this.name, this.type)" />';
         $answer .= $wrapper['item-end'];
         $answer .= '</div>';
         // --> END NEW FEATURE - SAVE
         ++$rowcounter;
         //if ($rowcounter == $wrapper['maxrows'] && $colcounter < $wrapper['cols'])
         if ($rowcounter == $ansByCol && $colcounter < $wrapper['cols']) {
             if ($colcounter == $wrapper['cols']) {
                 //$answer .= $wrapper['col-devide-last'];
                 $answer .= '    </div><!-- last -->';
             } else {
                 //$answer .= $wrapper['col-devide'];
                 $answer .= '    </div><!-- devide -->';
                 $answer .= '    <div class="col-xs-' . $iBootCols . '">';
             }
             $rowcounter = 0;
             ++$colcounter;
         }
     }
     //END OF ITEMS
     //$answer .= $wrapper['whole-end'].'
     $answer .= '    <input type="hidden" name="java' . $ia[1] . '" id="java' . $ia[1] . "\" value=\"" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$ia[1]] . "\" />\n";
     $answer .= '</div> <!-- wrapper row -->';
     $inputnames[] = $ia[1];
     return array($answer, $inputnames);
 }
Example #10
0
 }
 if (intval(trim($qidattributes['maximum_chars'])) > 0 && intval(trim($qidattributes['maximum_chars'])) < 4000) {
     // Limit to 4000 to maintain compatibility
     $maximum_chars = intval(trim($qidattributes['maximum_chars']));
     $maxlength = "maxlength='{$maximum_chars}' ";
 } else {
     $maxlength = "maxlength='4000' ";
     // Default to 4000 chars if not set within limits
 }
 if (trim($qidattributes['text_input_width']) != '') {
     $tiwidth = $qidattributes['text_input_width'];
 } else {
     $tiwidth = 50;
 }
 if ($qidattributes['numbers_only'] == 1) {
     $sSeparator = getRadixPointData($thissurvey['surveyls_numberformat']);
     $sSeparator = $sSeparator['separator'];
     $numbersonly = 'onkeypress="return goodchars(event,\'-0123456789' . $sSeparator . '\')"';
 } else {
     $numbersonly = '';
 }
 if (trim($qidattributes['display_rows']) != '') {
     //question attribute "display_rows" is set -> we need a textarea to be able to show several rows
     $drows = $qidattributes['display_rows'];
     //if a textarea should be displayed we make it equal width to the long text question
     //this looks nicer and more continuous
     if ($tiwidth == 50) {
         $tiwidth = 40;
     }
     echo $prefix;
     ?>
Example #11
0
/**
 * Marks a tokens as completed and sends a confirmation email to the participiant.
 * If $quotaexit is set to true then the user exited the survey due to a quota
 * restriction and the according token is only marked as 'Q'
 *
 * @param mixed $quotaexit
 */
function submittokens($quotaexit = false)
{
    global $thissurvey;
    global $surveyid;
    global $clienttoken;
    $clang = Yii::app()->lang;
    $sitename = Yii::app()->getConfig("sitename");
    $emailcharset = Yii::app()->getConfig("emailcharset");
    // Shift the date due to global timeadjust setting
    $today = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i", Yii::app()->getConfig("timeadjust"));
    // check how many uses the token has left
    $usesquery = "SELECT usesleft, participant_id, tid FROM {{tokens_{$surveyid}}} WHERE token='" . $clienttoken . "'";
    $usesresult = dbExecuteAssoc($usesquery);
    $usesrow = $usesresult->read();
    if (isset($usesrow)) {
        $usesleft = $usesrow['usesleft'];
        $participant_id = $usesrow['participant_id'];
        $token_id = $usesrow['tid'];
    }
    $utquery = "UPDATE {{tokens_{$surveyid}}}\n";
    if ($quotaexit == true) {
        $utquery .= "SET completed='Q', usesleft=usesleft-1\n";
    } elseif (isTokenCompletedDatestamped($thissurvey)) {
        if (isset($usesleft) && $usesleft <= 1) {
            $utquery .= "SET usesleft=usesleft-1, completed='{$today}'\n";
            if (!empty($participant_id)) {
                //Update the survey_links table if necessary
                $slquery = Survey_links::model()->find('participant_id = "' . $participant_id . '" AND survey_id = ' . $surveyid . ' AND token_id = ' . $token_id);
                $slquery->date_completed = $today;
                $slquery->save();
            }
        } else {
            $utquery .= "SET usesleft=usesleft-1\n";
        }
    } else {
        if (isset($usesleft) && $usesleft <= 1) {
            $utquery .= "SET usesleft=usesleft-1, completed='Y'\n";
            if (!empty($participant_id)) {
                //Update the survey_links table if necessary, to protect anonymity, use the date_created field date
                $slquery = Survey_links::model()->find('participant_id = "' . $participant_id . '" AND survey_id = ' . $surveyid . ' AND token_id = ' . $token_id);
                $slquery->date_completed = $slquery->date_created;
                $slquery->save();
            }
        } else {
            $utquery .= "SET usesleft=usesleft-1\n";
        }
    }
    $utquery .= "WHERE token='" . $clienttoken . "'";
    $utresult = dbExecuteAssoc($utquery) or safeDie("Couldn't update tokens table!<br />\n{$utquery}<br />\n");
    //Checked
    if ($quotaexit == false) {
        // TLR change to put date into sent and completed
        $cnfquery = "SELECT * FROM {{tokens_{$surveyid}}} WHERE token='" . $clienttoken . "' AND completed!='N' AND completed!=''";
        $cnfresult = dbExecuteAssoc($cnfquery);
        //Checked
        $cnfrow = $cnfresult->read();
        if (isset($cnfrow)) {
            $from = "{$thissurvey['adminname']} <{$thissurvey['adminemail']}>";
            $to = $cnfrow['email'];
            $subject = $thissurvey['email_confirm_subj'];
            $fieldsarray["{ADMINNAME}"] = $thissurvey['adminname'];
            $fieldsarray["{ADMINEMAIL}"] = $thissurvey['adminemail'];
            $fieldsarray["{SURVEYNAME}"] = $thissurvey['name'];
            $fieldsarray["{SURVEYDESCRIPTION}"] = $thissurvey['description'];
            $fieldsarray["{FIRSTNAME}"] = $cnfrow['firstname'];
            $fieldsarray["{LASTNAME}"] = $cnfrow['lastname'];
            $fieldsarray["{TOKEN}"] = $clienttoken;
            $attrfieldnames = getAttributeFieldNames($surveyid);
            foreach ($attrfieldnames as $attr_name) {
                $fieldsarray["{" . strtoupper($attr_name) . "}"] = $cnfrow[$attr_name];
            }
            $dateformatdatat = getDateFormatData($thissurvey['surveyls_dateformat']);
            $numberformatdatat = getRadixPointData($thissurvey['surveyls_numberformat']);
            $fieldsarray["{EXPIRY}"] = convertDateTimeFormat($thissurvey["expiry"], 'Y-m-d H:i:s', $dateformatdatat['phpdate']);
            $subject = ReplaceFields($subject, $fieldsarray, true);
            $subject = html_entity_decode($subject, ENT_QUOTES, $emailcharset);
            if (getEmailFormat($surveyid) == 'html') {
                $ishtml = true;
            } else {
                $ishtml = false;
            }
            if (trim(strip_tags($thissurvey['email_confirm'])) != "" && $thissurvey['sendconfirmation'] == "Y") {
                $message = $thissurvey['email_confirm'];
                $message = ReplaceFields($message, $fieldsarray, true);
                if (!$ishtml) {
                    $message = strip_tags(breakToNewline(html_entity_decode($message, ENT_QUOTES, $emailcharset)));
                } else {
                    $message = html_entity_decode($message, ENT_QUOTES, $emailcharset);
                }
                //Only send confirmation email if there is a valid email address
                if (validateEmailAddress($cnfrow['email'])) {
                    SendEmailMessage($message, $subject, $to, $from, $sitename, $ishtml);
                }
            } else {
                //There is nothing in the message or "Send confirmation emails" is set to "No" , so don't send a confirmation email
                //This section only here as placeholder to indicate new feature :-)
            }
        }
    }
}
Example #12
0
 /**
  * setJavascriptVar
  *
  *
  * @return @void
  * @param integer $iSurveyId : the survey id for the script
  * @param string $sLanguage : the actual language for the survey
  */
 public function setJavascriptVar($iSurveyId, $sLanguage)
 {
     $aSurveyinfo = getSurveyInfo($iSurveyId, $sLanguage);
     if (isset($aSurveyinfo['surveyls_numberformat'])) {
         $aLSJavascriptVar = array();
         $aLSJavascriptVar['bFixNumAuto'] = (int) (bool) Yii::app()->getConfig('bFixNumAuto', 1);
         $aLSJavascriptVar['bNumRealValue'] = (int) (bool) Yii::app()->getConfig('bNumRealValue', 0);
         $aRadix = getRadixPointData($aSurveyinfo['surveyls_numberformat']);
         $aLSJavascriptVar['sLEMradix'] = $aRadix['separator'];
         $sLSJavascriptVar = "LSvar=" . json_encode($aLSJavascriptVar) . ';';
         App()->clientScript->registerScript('sLSJavascriptVar', $sLSJavascriptVar, CClientScript::POS_HEAD);
     }
     // Don't update, because already set in index/run
 }
Example #13
0
function do_array_multiflexi($ia)
{
    global $dbprefix, $connect, $thissurvey, $clang;
    global $repeatheadings;
    global $notanswered;
    global $minrepeatheadings;

    if ($ia[8] == 'Y')
    {
        $checkconditionFunction = "checkconditions";
    }
    else
    {
        $checkconditionFunction = "noop_checkconditions";
    }

    //echo '<pre>'; print_r($_POST); echo '</pre>';
    $defaultvaluescript = '';
    $qquery = "SELECT other FROM {$dbprefix}questions WHERE qid=".$ia[0]." AND language='".$_SESSION['s_lang']."' and parent_qid=0";
    $qresult = db_execute_assoc($qquery);
    while($qrow = $qresult->FetchRow()) {$other = $qrow['other'];}

    $qidattributes=getQuestionAttributes($ia[0],$ia[4]);
    if (trim($qidattributes['multiflexible_max'])!='' && trim($qidattributes['multiflexible_min']) ==''){
        $maxvalue=$qidattributes['multiflexible_max'];
        if(isset($minvalue['value']) && $minvalue['value'] == 0) {$minvalue = 0;} else {$minvalue=1;}
    }
    if (trim($qidattributes['multiflexible_min'])!='' && trim($qidattributes['multiflexible_max']) ==''){
        $minvalue=$qidattributes['multiflexible_min'];
        $maxvalue=$qidattributes['multiflexible_min'] + 10;
    }
    if (trim($qidattributes['multiflexible_min'])=='' && trim($qidattributes['multiflexible_max']) ==''){
        if(isset($minvalue['value']) && $minvalue['value'] == 0) {$minvalue = 0;} else {$minvalue=1;}
        $maxvalue=10;
    }
    if (trim($qidattributes['multiflexible_min']) !='' && trim($qidattributes['multiflexible_max']) !=''){
        if($qidattributes['multiflexible_min'] < $qidattributes['multiflexible_max']){
            $minvalue=$qidattributes['multiflexible_min'];
            $maxvalue=$qidattributes['multiflexible_max'];
        }
    }

    if (trim($qidattributes['multiflexible_step'])!='' && $qidattributes['multiflexible_step'] > 0)
    {
        $stepvalue=$qidattributes['multiflexible_step'];
    }
    else
    {
        $stepvalue=1;
    }

    if($qidattributes['reverse']==1)
    {
        $tmp = $minvalue;
        $minvalue = $maxvalue;
        $maxvalue = $tmp;
        $reverse=true;
        $stepvalue=-$stepvalue;
    }
    else
    {
        $reverse=false;
    }

    $checkboxlayout=false;
    if ($qidattributes['multiflexible_checkbox']!=0)
    {
        $minvalue=0;
        $maxvalue=1;
        $checkboxlayout=true;
    }

    $inputboxlayout=false;
    if ($qidattributes['input_boxes']!=0)
    {
        $inputboxlayout=true;
    }

    if (trim($qidattributes['maximum_chars'])!='')
    {
        $maxsize=$qidattributes['maximum_chars'];
    }
    else
    {
        $maxsize=255;
    }

    if ($thissurvey['nokeyboard']=='Y')
    {
        vIncludeKeypad();
        $kpclass = "num-keypad";
    }
    else
    {
        $kpclass = "";
    }

    if (trim($qidattributes['answer_width'])!='')
    {
        $answerwidth=$qidattributes['answer_width'];
    }
    else
    {
        $answerwidth=20;
    }
    $columnswidth=100-($answerwidth*2);

    $lquery = "SELECT * FROM {$dbprefix}questions WHERE parent_qid={$ia[0]}  AND language='".$_SESSION['s_lang']."' and scale_id=1 ORDER BY question_order";
    $lresult = db_execute_assoc($lquery);
    if ($lresult->RecordCount() > 0)
    {
        while ($lrow=$lresult->FetchRow())
        {
            $labelans[]=$lrow['question'];
            $labelcode[]=$lrow['title'];
        }
        $numrows=count($labelans);
        if ($ia[6] != 'Y' && SHOW_NO_ANSWER == 1) {$numrows++;}
        $cellwidth=$columnswidth/$numrows;

        $cellwidth=sprintf('%02d', $cellwidth);

        $ansquery = "SELECT question FROM {$dbprefix}questions WHERE parent_qid=".$ia[0]." AND scale_id=0 AND question like '%|%'";
        $ansresult = db_execute_assoc($ansquery);
        if ($ansresult->RecordCount()>0) {$right_exists=true;$answerwidth=$answerwidth/2;} else {$right_exists=false;}
        // $right_exists is a flag to find out if there are any right hand answer parts. If there arent we can leave out the right td column
        if ($qidattributes['random_order']==1) {
            $ansquery = "SELECT * FROM {$dbprefix}questions WHERE parent_qid=$ia[0] AND scale_id=0 AND language='".$_SESSION['s_lang']."' ORDER BY ".db_random();
        }
        else
        {
            $ansquery = "SELECT * FROM {$dbprefix}questions WHERE parent_qid=$ia[0] AND scale_id=0 AND language='".$_SESSION['s_lang']."' ORDER BY question_order";
        }
        $ansresult = db_execute_assoc($ansquery);
        $anscount = $ansresult->RecordCount();
        $fn=1;

        $mycols = "\t<colgroup class=\"col-responses\">\n"
        . "\n\t<col class=\"answertext\" width=\"$answerwidth%\" />\n";

        $myheader = "\n\t<thead>\n"
        . "<tr>\n"
        . "\t<td >&nbsp;</td>\n";

        $odd_even = '';
        foreach ($labelans as $ld)
        {
            $myheader .= "\t<th>".$ld."</th>\n";
            $odd_even = alternation($odd_even);
            $mycols .= "<col class=\"$odd_even\" width=\"$cellwidth%\" />\n";
        }
        if ($right_exists)
        {
            $myheader .= "\t<td>&nbsp;</td>";
            $odd_even = alternation($odd_even);
            $mycols .= "<col class=\"answertextright $odd_even\" width=\"$answerwidth%\" />\n";
        }
        $myheader .= "</tr>\n"
        . "\t</thead>\n";
        $mycols .= "\t</colgroup>\n";

        $trbc = '';
        $answer = "\n<table class=\"question\" summary=\"".str_replace('"','' ,strip_tags($ia[3]))." - an array type question with dropdown responses\">\n" . $mycols . $myheader . "\n";

        while ($ansrow = $ansresult->FetchRow())
        {
            if (isset($repeatheadings) && $repeatheadings > 0 && ($fn-1) > 0 && ($fn-1) % $repeatheadings == 0)
            {
                if ( ($anscount - $fn + 1) >= $minrepeatheadings )
                {
                    $trbc = alternation($trbc , 'row');
                    $answer .= "<tbody>\n<tr class=\"$trbc repeat\">\n"
                    . "\t<td>&nbsp;</td>\n";
                    foreach ($labelans as $ld)
                    {
                        $answer .= "\t<th>".$ld."</th>\n";
                    }
                    $answer .= "</tr>\n</tbody>\n";
                }
            }
            $myfname = $ia[1].$ansrow['title'];
            $answertext=dTexts::run($ansrow['question']);
            $answertextsave=$answertext;
            /* Check if this item has not been answered: the 'notanswered' variable must be an array,
             containing a list of unanswered questions, the current question must be in the array,
             and there must be no answer available for the item in this session. */
            if ((is_array($notanswered)) && (array_search($ia[1], $notanswered) !== FALSE))
            {
                //Go through each labelcode and check for a missing answer! If any are found, highlight this line
                $emptyresult=0;
                foreach($labelcode as $ld)
                {
                    $myfname2=$myfname.'_'.$ld;
                    if($_SESSION[$myfname2] == "")
                    {
                        $emptyresult=1;
                    }
                }
                if ($emptyresult == 1)
                {
                    $answertext = '<span class="errormandatory">'.$answertext.'</span>';
                }
            }

            // Get array_filter stuff
            list($htmltbody2, $hiddenfield)=return_array_filter_strings($ia, $qidattributes, $thissurvey, $ansrow, $myfname, $trbc, $myfname);

            $answer .= $htmltbody2;

            if (strpos($answertext,'|')) {$answertext=substr($answertext,0, strpos($answertext,'|'));}

            $trbc = alternation($trbc , 'row');

            $answer .= "<tr class=\"$trbc\">\n"
            . "\t<th class=\"answertext\" width=\"$answerwidth%\">\n"
            . "$answertext\n"
            . $hiddenfield
            . "<input type=\"hidden\" name=\"java$myfname\" id=\"java$myfname\" value=\"";
            if (isset($_SESSION[$myfname]))
            {
                $answer .= $_SESSION[$myfname];
            }
            $answer .= "\" />\n\t</th>\n";
            $first_hidden_field = '';
            $thiskey=0;
            foreach ($labelcode as $ld)
            {

                if ($checkboxlayout == false)
                {
                    $myfname2=$myfname."_$ld";
                    if(isset($_SESSION[$myfname2]))
                    {
                        $myfname2_java_value = " value=\"$_SESSION[$myfname2]\" ";
                    }
                    else
                    {
                        $myfname2_java_value = "";
                    }
                    $answer .= "\t<td class=\"answer_cell_00$ld\">\n"
                    . "<label for=\"answer{$myfname2}\">\n"
                    . "\t<input type=\"hidden\" name=\"java{$myfname2}\" id=\"java{$myfname2}\" $myfname2_java_value />\n";

                    if($inputboxlayout == false) {
                        $answer .= "\t<select class=\"multiflexiselect\" name=\"$myfname2\" id=\"answer{$myfname2}\" title=\""
                        . html_escape($labelans[$thiskey]).'"'
                        . " onchange=\"$checkconditionFunction(this.value, this.name, this.type)\">\n"
                        . "<option value=\"\">".$clang->gT('...')."</option>\n";

                        for($ii=$minvalue; ($reverse? $ii>=$maxvalue:$ii<=$maxvalue); $ii+=$stepvalue) {
                            $answer .= "<option value=\"$ii\"";
                            if(isset($_SESSION[$myfname2]) && $_SESSION[$myfname2] == $ii) {
                                $answer .= SELECTED;
                            }
                            $answer .= ">$ii</option>\n";
                        }
                        $answer .= "\t</select>\n";
                    } elseif ($inputboxlayout == true)
                    {
                        $sSeperator = getRadixPointData($thissurvey['surveyls_numberformat']);
                        $sSeperator = $sSeperator['seperator'];
                        $answer .= "\t<input type='text' class=\"multiflexitext $kpclass\" name=\"$myfname2\" id=\"answer{$myfname2}\" maxlength=\"{$maxsize}\" size=5 title=\""
                        . html_escape($labelans[$thiskey]).'"'
                        . " onchange=\"$checkconditionFunction(this.value, this.name, this.type)\" onkeypress=\"return goodchars(event,'0123456789$sSeperator')\""
                        . " value=\"";
                        if(isset($_SESSION[$myfname2]) && $_SESSION[$myfname2]) {
                            $answer .= $_SESSION[$myfname2];
                        }
                        $answer .= "\" />\n";
                    }
                    $answer .= "</label>\n"
                    . "\t</td>\n";

                    $inputnames[]=$myfname2;
                    $thiskey++;
                }
                else
                {
                    $myfname2=$myfname."_$ld";
                    if(isset($_SESSION[$myfname2]) && $_SESSION[$myfname2] == '1')
                    {
                        $myvalue = '1';
                        $setmyvalue = CHECKED;
                    }
                    else
                    {
                        $myvalue = '0';
                        $setmyvalue = '';
                    }
                    $answer .= "\t<td class=\"answer_cell_00$ld\">\n"
                    //					. "<label for=\"answer{$myfname2}\">\n"
                    . "\t<input type=\"hidden\" name=\"java{$myfname2}\" id=\"java{$myfname2}\" value=\"$myvalue\"/>\n"
                    . "\t<input type=\"hidden\" name=\"$myfname2\" id=\"answer{$myfname2}\" value=\"$myvalue\" />\n";
                    $answer .= "\t<input type=\"checkbox\" name=\"cbox_$myfname2\" id=\"cbox_$myfname2\" $setmyvalue "
                    . " onclick=\"cancelBubbleThis(event); "
                    . " aelt=document.getElementById('answer{$myfname2}');"
                    . " jelt=document.getElementById('java{$myfname2}');"
                    . " if(this.checked) {"
                    . "  aelt.value=1;jelt.value=1;$checkconditionFunction(1,'answer{$myfname2}',aelt.type);"
                    . " } else {"
                    . "  aelt.value=0;jelt.value=0;$checkconditionFunction(0,'answer{$myfname2}',aelt.type);"
                    . " }; return true;\" "
                    //					. " onchange=\"checkconditions(this.value, this.name, this.type)\" "
                    . " />\n";
                    $inputnames[]=$myfname2;
                    //					$answer .= "</label>\n"
                    $answer .= ""
                    . "\t</td>\n";
                    $thiskey++;
                }
            }
            if (strpos($answertextsave,'|'))
            {
                $answertext=substr($answertextsave,strpos($answertextsave,'|')+1);
                $answer .= "\t<td class=\"answertextright\" style='text-align:left;' width=\"$answerwidth%\">$answertext</td>\n";
            }
            elseif ($right_exists)
            {
                $answer .= "\t<td class=\"answertextright\" style='text-align:left;' width=\"$answerwidth%\">&nbsp;</td>\n";
            }

            $answer .= "</tr>\n\t</tbody>";
            //IF a MULTIPLE of flexi-redisplay figure, repeat the headings
            $fn++;
        }
        $answer .= "\n</table>\n";
    }
    else
    {
        $answer = "\n<p class=\"error\">".$clang->gT("Error: There are no answer options for this question and/or they don't exist in this language.")."</p>\n";
        $inputnames = '';
    }
    return array($answer, $inputnames);
}
Example #14
0
if (!isset($_GET['lang']) || $_GET['lang'] == "") {
    $language = GetBaseLanguageFromSurveyID($surveyid);
} else {
    $language = sanitize_languagecode($_GET['lang']);
}
$_SESSION['s_lang'] = $language;
$clang = new limesurvey_lang($language);
$thissurvey = getSurveyInfo($surveyid);
$_SESSION['dateformats'] = getDateFormatData($thissurvey['surveyls_dateformat']);
require_once dirname(__FILE__) . '/../qanda.php';
$qquery = 'SELECT * FROM ' . db_table_name('questions') . " WHERE sid='{$surveyid}' AND qid='{$qid}' AND language='{$language}'";
$qresult = db_execute_assoc($qquery);
$qrows = $qresult->FetchRow();
$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');
// ia[8] is usedinconditions
$radix = getRadixPointData($thissurvey['surveyls_numberformat']);
$radix = $radix['seperator'];
$surveyOptions = array('radix' => $radix);
LimeExpressionManager::StartSurvey($thissurvey['sid'], 'question', $surveyOptions, false, $LEMdebugLevel);
$qseq = LimeExpressionManager::GetQuestionSeq($qid);
$moveResult = LimeExpressionManager::JumpTo($qseq + 1, true, false, true);
$answers = retrieveAnswers($ia);
if (!$thissurvey['template']) {
    $thistpl = sGetTemplatePath($defaulttemplate);
} else {
    $thistpl = sGetTemplatePath(validate_templatedir($thissurvey['template']));
}
doHeader();
$showQuestion = "\$('#question{$qid}').show();";
$dummy_js = <<<EOD
    <script type='text/javascript'>
 /**
  * setJavascriptVar
  *
  * @return @void
  * @param integer $iSurveyId : the survey id for the script
  */
 public function setJavascriptVar($iSurveyId)
 {
     $aSurveyinfo = getSurveyInfo($iSurveyId, App()->getLanguage());
     if (isset($aSurveyinfo['surveyls_numberformat'])) {
         $aLSJavascriptVar = array();
         $aLSJavascriptVar['bFixNumAuto'] = (int) (bool) Yii::app()->getConfig('bFixNumAuto', 1);
         $aLSJavascriptVar['bNumRealValue'] = (int) (bool) Yii::app()->getConfig('bNumRealValue', 0);
         $aRadix = getRadixPointData($aSurveyinfo['surveyls_numberformat']);
         $aLSJavascriptVar['sLEMradix'] = $aRadix['separator'];
         /*
         $aCfieldnameWithDependences = Condition::model()->getAllCfieldnameWithDependenciesForOneSurvey($iSurveyId);
         foreach($aCfieldnameWithDependences as $sCfieldname)
         {
             $aLSJavascriptVar['aFieldWithDependencies'][] = $sCfieldname;
         }
         */
         $sLSJavascriptVar = "LSvar=" . json_encode($aLSJavascriptVar) . ';';
         App()->clientScript->registerScript('sLSJavascriptVar', $sLSJavascriptVar, CClientScript::POS_HEAD);
     }
     // Maybe remove one from index and allow empty $surveyid here.
 }
    <li><label for='numberformat_<?php 
echo $esrow['surveyls_language'];
?>
'><?php 
$clang->eT("Decimal mark:");
?>
</label>
        <select size='1' id='numberformat_<?php 
echo $esrow['surveyls_language'];
?>
' name='numberformat_<?php 
echo $esrow['surveyls_language'];
?>
'>
            <?php 
foreach (getRadixPointData() as $index => $radixptdata) {
    ?>
                <option value='<?php 
    echo $index;
    ?>
'
                    <?php 
    if ($esrow['surveyls_numberformat'] == $index) {
        ?>
                        selected='selected'
                        <?php 
    }
    ?>
                    ><?php 
    echo $radixptdata['desc'];
    ?>
Example #17
0
    /**
     * Load preview of a question screen.
     *
     * @access public
     * @param int $surveyid
     * @param int $qid
     * @param string $lang
     * @return void
     */
    public function preview($surveyid, $qid, $lang = null)
    {
        $surveyid = sanitize_int($surveyid);
        $qid = sanitize_int($qid);
        $LEMdebugLevel = 0;
        Yii::app()->loadHelper("qanda");
        Yii::app()->loadHelper("surveytranslator");
        if (empty($surveyid)) {
            $this->getController()->error('No Survey ID provided');
        }
        if (empty($qid)) {
            $this->getController()->error('No Question ID provided');
        }
        if (empty($lang)) {
            $language = Survey::model()->findByPk($surveyid)->language;
        } else {
            $language = $lang;
        }
        if (!isset(Yii::app()->session['step'])) {
            Yii::app()->session['step'] = 0;
        }
        if (!isset(Yii::app()->session['prevstep'])) {
            Yii::app()->session['prevstep'] = 0;
        }
        if (!isset(Yii::app()->session['maxstep'])) {
            Yii::app()->session['maxstep'] = 0;
        }
        // Use $_SESSION instead of $this->session for frontend features.
        $_SESSION['survey_' . $surveyid]['s_lang'] = $language;
        $_SESSION['survey_' . $surveyid]['fieldmap'] = createFieldMap($surveyid, 'full', true, $qid, $language);
        // Prefill question/answer from defaultvalues
        foreach ($_SESSION['survey_' . $surveyid]['fieldmap'] as $field) {
            if (isset($field['defaultvalue'])) {
                $_SESSION['survey_' . $surveyid][$field['fieldname']] = $field['defaultvalue'];
            }
        }
        $clang = new limesurvey_lang($language);
        $thissurvey = getSurveyInfo($surveyid);
        setNoAnswerMode($thissurvey);
        Yii::app()->session['dateformats'] = getDateFormatData($thissurvey['surveyls_dateformat']);
        $qrows = Questions::model()->findByAttributes(array('sid' => $surveyid, 'qid' => $qid, 'language' => $language))->getAttributes();
        $ia = array(0 => $qid, 1 => $surveyid . 'X' . $qrows['gid'] . 'X' . $qid, 2 => $qrows['title'], 3 => $qrows['question'], 4 => $qrows['type'], 5 => $qrows['gid'], 6 => $qrows['mandatory'], 7 => 'N', 8 => 'N');
        $radix = getRadixPointData($thissurvey['surveyls_numberformat']);
        $radix = $radix['seperator'];
        $surveyOptions = array('radix' => $radix, 'tempdir' => Yii::app()->getConfig('tempdir'));
        LimeExpressionManager::StartSurvey($surveyid, 'question', $surveyOptions, false, $LEMdebugLevel);
        $qseq = LimeExpressionManager::GetQuestionSeq($qid);
        $moveResult = LimeExpressionManager::JumpTo($qseq + 1, true, false, true);
        $answers = retrieveAnswers($ia, $surveyid);
        if (!$thissurvey['template']) {
            $thistpl = getTemplatePath(Yii::app()->getConfig('defaulttemplate'));
        } else {
            $thistpl = getTemplatePath(validateTemplateDir($thissurvey['template']));
        }
        doHeader();
        $showQuestion = "\$('#question{$qid}').show();";
        $dummy_js = <<<EOD
            <script type='text/javascript'>
            <!--
            LEMradix='{$radix}';
            var numRegex = new RegExp('[^-' + LEMradix + '0-9]','g');
            var intRegex = new RegExp('[^-0-9]','g');
            function fixnum_checkconditions(value, name, type, evt_type, intonly)
            {
                newval = new String(value);
                if (typeof intonly !=='undefined' && intonly==1) {
                    newval = newval.replace(intRegex,'');
                }
                else {
                    newval = newval.replace(numRegex,'');
                }
                if (LEMradix === ',') {
                    newval = newval.split(',').join('.');
                }
                if (newval != '-' && newval != '.' && newval != '-.' && newval != parseFloat(newval)) {
                    newval = '';
                }
                displayVal = newval;
                if (LEMradix === ',') {
                    displayVal = displayVal.split('.').join(',');
                }
                if (name.match(/other\$/)) {
                    \$('#answer'+name+'text').val(displayVal);
                }
                \$('#answer'+name).val(displayVal);

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

            function checkconditions(value, name, type, evt_type)
            {
                if (typeof evt_type === 'undefined')
                {
                    evt_type = 'onchange';
                }
                if (type == 'radio' || type == 'select-one')
                {
                    var hiddenformname='java'+name;
                    document.getElementById(hiddenformname).value=value;
                }
                else if (type == 'checkbox')
                {
                    if (document.getElementById('answer'+name).checked)
                    {
                        \$('#java'+name).val('Y');
                    } else
                    {
                        \$('#java'+name).val('');
                    }
                }
                else if (type == 'text' && name.match(/other\$/) && typeof document.getElementById('java'+name) !== 'undefined' && document.getElementById('java'+name) != null)
                {
                    \$('#java'+name).val(value);
                }
                ExprMgr_process_relevance_and_tailoring(evt_type,name,type);
                {$showQuestion}
            }
            \$(document).ready(function() {
                {$showQuestion}
            });
            \$(document).change(function() {
                {$showQuestion}
            });
            \$(document).bind('keydown',function(e) {
                        if (e.keyCode == 9) {
                            {$showQuestion}
                            return true;
                        }
                        return true;
                    });
        // -->
        </script>
EOD;
        $answer = $answers[0][1];
        //        $help = $answers[0][2];
        $qinfo = LimeExpressionManager::GetQuestionStatus($qid);
        $help = $qinfo['info']['help'];
        $question = $answers[0][0];
        $question['code'] = $answers[0][5];
        $question['class'] = getQuestionClass($qrows['type']);
        $question['essentials'] = 'id="question' . $qrows['qid'] . '"';
        $question['sgq'] = $ia[1];
        $question['aid'] = 'unknown';
        $question['sqid'] = 'unknown';
        if ($qrows['mandatory'] == 'Y') {
            $question['man_class'] = ' mandatory';
        } else {
            $question['man_class'] = '';
        }
        $redata = compact(array_keys(get_defined_vars()));
        $content = templatereplace(file_get_contents("{$thistpl}/startpage.pstpl"), array(), $redata);
        $content .= CHtml::form('index.php', 'post', array('id' => "limesurvey", 'name' => "limesurvey", 'autocomplete' => 'off'));
        $content .= templatereplace(file_get_contents("{$thistpl}/startgroup.pstpl"), array(), $redata);
        $question_template = file_get_contents("{$thistpl}/question.pstpl");
        // the following has been added for backwards compatiblity.
        if (substr_count($question_template, '{QUESTION_ESSENTIALS}') > 0) {
            // LS 1.87 and newer templates
            $content .= "\n" . templatereplace($question_template, array(), $redata, 'Unspecified', false, $qid) . "\n";
        } else {
            // LS 1.86 and older templates
            $content .= '<div ' . $question['essentials'] . ' class="' . $question['class'] . $question['man_class'] . '">';
            $content .= "\n" . templatereplace($question_template, array(), $redata, 'Unspecified', false, $qid) . "\n";
            $content .= "\n\t</div>\n";
        }
        $content .= templatereplace(file_get_contents("{$thistpl}/endgroup.pstpl"), array(), $redata) . $dummy_js;
        LimeExpressionManager::FinishProcessingGroup();
        $content .= LimeExpressionManager::GetRelevanceAndTailoringJavaScript();
        $content .= '<p>&nbsp;</form>';
        $content .= templatereplace(file_get_contents("{$thistpl}/endpage.pstpl"), array(), $redata);
        LimeExpressionManager::FinishProcessingPage();
        echo $content;
        if ($LEMdebugLevel >= 1) {
            echo LimeExpressionManager::GetDebugTimingMessage();
        }
        if ($LEMdebugLevel >= 2) {
            echo "<table><tr><td align='left'><b>Group/Question Validation Results:</b>" . $moveResult['message'] . "</td></tr></table>\n";
        }
        echo "</html>\n";
        exit;
    }
    //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();
?>
Example #19
0
 /**
  * survey::_generalTabNewSurvey()
  * Load "General" tab of new survey screen.
  * @return
  */
 private function _generalTabNewSurvey()
 {
     //Use the current user details for the default administrator name and email for this survey
     $user = User::model()->findByPk(Yii::app()->session['loginID']);
     $owner = $user->attributes;
     //Degrade gracefully to $siteadmin details if anything is missing.
     if (empty($owner['full_name'])) {
         $owner['full_name'] = getGlobalSetting('siteadminname');
     }
     if (empty($owner['email'])) {
         $owner['email'] = getGlobalSetting('siteadminemail');
     }
     //Bounce setting by default to global if it set globally
     if (getGlobalSetting('bounceaccounttype') != 'off') {
         $owner['bounce_email'] = getGlobalSetting('siteadminbounce');
     } else {
         $owner['bounce_email'] = $owner['email'];
     }
     $aData['action'] = "newsurvey";
     $aData['owner'] = $owner;
     $aLanguageDetails = getLanguageDetails(Yii::app()->session['adminlang']);
     $aData['sRadixDefault'] = $aLanguageDetails['radixpoint'];
     $aData['sDateFormatDefault'] = $aLanguageDetails['dateformat'];
     foreach (getRadixPointData() as $index => $radixptdata) {
         $aRadixPointData[$index] = $radixptdata['desc'];
     }
     $aData['aRadixPointData'] = $aRadixPointData;
     foreach (getDateFormatData(0, Yii::app()->session['adminlang']) as $index => $dateformatdata) {
         $aDateFormatData[$index] = $dateformatdata['dateformat'];
     }
     $aData['aDateFormatData'] = $aDateFormatData;
     return $aData;
 }
$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();
Example #21
0
function do_array_multiflexi($ia)
{
    global $thissurvey;
    $aLastMoveResult = LimeExpressionManager::GetLastMoveResult();
    $aMandatoryViolationSubQ = $aLastMoveResult['mandViolation'] && $ia[6] == 'Y' ? explode("|", $aLastMoveResult['unansweredSQs']) : array();
    $repeatheadings = Yii::app()->getConfig("repeatheadings");
    $minrepeatheadings = Yii::app()->getConfig("minrepeatheadings");
    $extraclass = "";
    $answertypeclass = "";
    $caption = gT("An array of sub-question on each cell. The sub-question text are in the table header and concerns line header. ");
    $checkconditionFunction = "fixnum_checkconditions";
    //echo '<pre>'; print_r($_POST); echo '</pre>';
    $defaultvaluescript = '';
    $qquery = "SELECT other FROM {{questions}} WHERE qid=" . $ia[0] . " AND language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "' and parent_qid=0";
    $other = Yii::app()->db->createCommand($qquery)->queryScalar();
    //Checked
    $aQuestionAttributes = getQuestionAttributeValues($ia[0]);
    if (trim($aQuestionAttributes['multiflexible_max']) != '' && trim($aQuestionAttributes['multiflexible_min']) == '') {
        $maxvalue = $aQuestionAttributes['multiflexible_max'];
        $extraclass .= " maxvalue maxvalue-" . trim($aQuestionAttributes['multiflexible_max']);
        if (isset($minvalue['value']) && $minvalue['value'] == 0) {
            $minvalue = 0;
        } else {
            $minvalue = 1;
        }
    }
    if (trim($aQuestionAttributes['multiflexible_min']) != '' && trim($aQuestionAttributes['multiflexible_max']) == '') {
        $minvalue = $aQuestionAttributes['multiflexible_min'];
        $extraclass .= " minvalue minvalue-" . trim($aQuestionAttributes['multiflexible_max']);
        $maxvalue = $aQuestionAttributes['multiflexible_min'] + 10;
    }
    if (trim($aQuestionAttributes['multiflexible_min']) == '' && trim($aQuestionAttributes['multiflexible_max']) == '') {
        if (isset($minvalue['value']) && $minvalue['value'] == 0) {
            $minvalue = 0;
        } else {
            $minvalue = 1;
        }
        $maxvalue = 10;
    }
    if (trim($aQuestionAttributes['multiflexible_min']) != '' && trim($aQuestionAttributes['multiflexible_max']) != '') {
        if ($aQuestionAttributes['multiflexible_min'] < $aQuestionAttributes['multiflexible_max']) {
            $minvalue = $aQuestionAttributes['multiflexible_min'];
            $maxvalue = $aQuestionAttributes['multiflexible_max'];
        }
    }
    if (trim($aQuestionAttributes['multiflexible_step']) != '' && $aQuestionAttributes['multiflexible_step'] > 0) {
        $stepvalue = $aQuestionAttributes['multiflexible_step'];
    } else {
        $stepvalue = 1;
    }
    if ($aQuestionAttributes['reverse'] == 1) {
        $tmp = $minvalue;
        $minvalue = $maxvalue;
        $maxvalue = $tmp;
        $reverse = true;
        $stepvalue = -$stepvalue;
    } else {
        $reverse = false;
    }
    $checkboxlayout = false;
    $inputboxlayout = false;
    if ($aQuestionAttributes['multiflexible_checkbox'] != 0) {
        $minvalue = 0;
        $maxvalue = 1;
        $checkboxlayout = true;
        $answertypeclass = " checkbox";
        $caption .= gT("Check or uncheck the answer for each subquestion. ");
    } elseif ($aQuestionAttributes['input_boxes'] != 0) {
        $inputboxlayout = true;
        $answertypeclass .= " numeric-item text";
        $extraclass .= " numberonly";
        $caption .= gT("Each answers are a number. ");
    } else {
        $answertypeclass = " dropdown";
        $caption .= gT("Select the answer for each subquestion. ");
    }
    if (ctype_digit(trim($aQuestionAttributes['repeat_headings'])) && trim($aQuestionAttributes['repeat_headings'] != "")) {
        $repeatheadings = intval($aQuestionAttributes['repeat_headings']);
        $minrepeatheadings = 0;
    }
    if (intval(trim($aQuestionAttributes['maximum_chars'])) > 0) {
        // Only maxlength attribute, use textarea[maxlength] jquery selector for textarea
        $maximum_chars = intval(trim($aQuestionAttributes['maximum_chars']));
        $maxlength = "maxlength='{$maximum_chars}' ";
        $extraclass .= " maxchars maxchars-" . $maximum_chars;
    } else {
        $maxlength = "";
    }
    if ($thissurvey['nokeyboard'] == 'Y') {
        includeKeypad();
        $kpclass = " num-keypad";
        $extraclass .= " inputkeypad";
    } else {
        $kpclass = "";
    }
    if (trim($aQuestionAttributes['answer_width']) != '') {
        $answerwidth = $aQuestionAttributes['answer_width'];
    } else {
        $answerwidth = 20;
    }
    $columnswidth = 100 - $answerwidth * 2;
    $lquery = "SELECT * FROM {{questions}} WHERE parent_qid={$ia[0]}  AND language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "' and scale_id=1 ORDER BY question_order";
    $lresult = dbExecuteAssoc($lquery);
    $aQuestions = $lresult->readAll();
    $labelans = array();
    $labelcode = array();
    foreach ($aQuestions as $lrow) {
        $labelans[] = $lrow['question'];
        $labelcode[] = $lrow['title'];
    }
    if ($numrows = count($labelans)) {
        if ($ia[6] != 'Y' && SHOW_NO_ANSWER == 1) {
            $numrows++;
        }
        $cellwidth = $columnswidth / $numrows;
        $cellwidth = sprintf('%02d', $cellwidth);
        $sQuery = "SELECT count(question) FROM {{questions}} WHERE parent_qid=" . $ia[0] . " AND scale_id=0 AND question like '%|%'";
        $iCount = Yii::app()->db->createCommand($sQuery)->queryScalar();
        if ($iCount > 0) {
            $right_exists = true;
            $answerwidth = $answerwidth / 2;
            $caption .= gT("The last cell give some information. ");
        } else {
            $right_exists = false;
        }
        // $right_exists is a flag to find out if there are any right hand answer parts. If there arent we can leave out the right td column
        if ($aQuestionAttributes['random_order'] == 1) {
            $ansquery = "SELECT * FROM {{questions}} WHERE parent_qid={$ia['0']} AND scale_id=0 AND language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "' ORDER BY " . dbRandom();
        } else {
            $ansquery = "SELECT * FROM {{questions}} WHERE parent_qid={$ia['0']} AND scale_id=0 AND language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "' ORDER BY question_order";
        }
        $ansresult = dbExecuteAssoc($ansquery)->readAll();
        //Checked
        if (trim($aQuestionAttributes['parent_order'] != '')) {
            $iParentQID = (int) $aQuestionAttributes['parent_order'];
            $aResult = array();
            $sessionao = $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['answer_order'];
            foreach ($sessionao[$iParentQID] as $aOrigRow) {
                $sCode = $aOrigRow['title'];
                foreach ($ansresult as $aRow) {
                    if ($sCode == $aRow['title']) {
                        $aResult[] = $aRow;
                    }
                }
            }
            $ansresult = $aResult;
        }
        $anscount = count($ansresult);
        $fn = 1;
        $mycols = "\t<colgroup class=\"col-responses\">\n" . "\n\t<col class=\"answertext\" width=\"{$answerwidth}%\" />\n";
        $answer_head_line = "\t<td >&nbsp;</td>\n";
        $odd_even = '';
        foreach ($labelans as $ld) {
            $answer_head_line .= "\t<th>" . $ld . "</th>\n";
            $odd_even = alternation($odd_even);
            $mycols .= "<col class=\"{$odd_even}\" width=\"{$cellwidth}%\" />\n";
        }
        if ($right_exists) {
            $answer_head_line .= "\t<td>&nbsp;</td>";
            $odd_even = alternation($odd_even);
            $mycols .= "<col class=\"answertextright {$odd_even}\" width=\"{$answerwidth}%\" />\n";
        }
        $answer_head = "\n\t<thead>\n<tr class=\"dontread\">\n" . $answer_head_line . "</tr>\n\t</thead>\n";
        $mycols .= "\t</colgroup>\n";
        $trbc = '';
        $answer = "\n<table class=\"question subquestions-list questions-list {$answertypeclass}-list {$extraclass}\" summary=\"{$caption}\">\n" . $mycols . $answer_head . "\n";
        $answer .= "<tbody>";
        foreach ($ansresult as $ansrow) {
            if (isset($repeatheadings) && $repeatheadings > 0 && $fn - 1 > 0 && ($fn - 1) % $repeatheadings == 0) {
                if ($anscount - $fn + 1 >= $minrepeatheadings) {
                    $answer .= "</tbody>\n<tbody>";
                    // Close actual body and open another one
                    $answer .= "<tr class=\"repeat headings dontread\">\n" . $answer_head_line . "</tr>\n\n";
                }
            }
            $myfname = $ia[1] . $ansrow['title'];
            $answertext = $ansrow['question'];
            $answertextsave = $answertext;
            /* Check the sub Q mandatory violation */
            if ($ia[6] == 'Y' && !empty($aMandatoryViolationSubQ)) {
                //Go through each labelcode and check for a missing answer! Default :If any are found, highlight this line, checkbox : if one is not found : don't highlight
                // PS : we really need a better system : event for EM !
                $emptyresult = $aQuestionAttributes['multiflexible_checkbox'] != 0 ? 1 : 0;
                foreach ($labelcode as $ld) {
                    $myfname2 = $myfname . '_' . $ld;
                    if ($aQuestionAttributes['multiflexible_checkbox'] != 0) {
                        if (!in_array($myfname2, $aMandatoryViolationSubQ)) {
                            $emptyresult = 0;
                        }
                    } else {
                        if (in_array($myfname2, $aMandatoryViolationSubQ)) {
                            $emptyresult = 1;
                        }
                    }
                }
                if ($emptyresult == 1) {
                    $answertext = '<span class="errormandatory">' . $answertext . '</span>';
                }
            }
            // Get array_filter stuff
            $trbc = alternation($trbc, 'row');
            list($htmltbody2, $hiddenfield) = return_array_filter_strings($ia, $aQuestionAttributes, $thissurvey, $ansrow, $myfname, $trbc, $myfname, "tr", "{$trbc} subquestions-list questions-list {$answertypeclass}-list");
            $answer .= $htmltbody2;
            if (strpos($answertext, '|')) {
                $answertext = substr($answertext, 0, strpos($answertext, '|'));
            }
            $answer .= "\t<th class=\"answertext\" width=\"{$answerwidth}%\">\n" . "{$answertext}\n" . $hiddenfield . "<input type=\"hidden\" name=\"java{$myfname}\" id=\"java{$myfname}\" value=\"";
            if (isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname])) {
                $answer .= $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname];
            }
            $answer .= "\" />\n\t</th>\n";
            $first_hidden_field = '';
            $thiskey = 0;
            foreach ($labelcode as $ld) {
                if ($checkboxlayout == false) {
                    $myfname2 = $myfname . "_{$ld}";
                    if (isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname2])) {
                        $myfname2_java_value = " value=\"{$_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname2]}\" ";
                    } else {
                        $myfname2_java_value = "";
                    }
                    $answer .= "\t<td class=\"answer_cell_00{$ld} question-item answer-item {$answertypeclass}-item {$extraclass}\">\n" . "\t<input type=\"hidden\" name=\"java{$myfname2}\" id=\"java{$myfname2}\" {$myfname2_java_value} />\n" . "<label class=\"hide read\" for=\"answer{$myfname2}\">{$labelans[$thiskey]}</label>\n";
                    $sSeparator = getRadixPointData($thissurvey['surveyls_numberformat']);
                    $sSeparator = $sSeparator['separator'];
                    if ($inputboxlayout == false) {
                        $answer .= "\t<select class=\"multiflexiselect\" name=\"{$myfname2}\" id=\"answer{$myfname2}\"" . " onchange=\"{$checkconditionFunction}(this.value, this.name, this.type)\">\n" . "<option value=\"\">" . gT('...') . "</option>\n";
                        for ($ii = $minvalue; $reverse ? $ii >= $maxvalue : $ii <= $maxvalue; $ii += $stepvalue) {
                            $answer .= '<option value="' . str_replace('.', $sSeparator, $ii) . '"';
                            if (isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname2]) && (string) $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname2] == (string) $ii) {
                                $answer .= SELECTED;
                            }
                            $answer .= ">" . str_replace('.', $sSeparator, $ii) . "</option>\n";
                        }
                        $answer .= "\t</select>\n";
                    } elseif ($inputboxlayout == true) {
                        $answer .= "\t<input type='text' class=\"multiflexitext text {$kpclass}\" name=\"{$myfname2}\" id=\"answer{$myfname2}\" {$maxlength} size=5 " . " onkeyup=\"{$checkconditionFunction}(this.value, this.name, this.type)\"" . " value=\"";
                        if (isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname2]) && is_numeric($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname2])) {
                            $answer .= str_replace('.', $sSeparator, $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname2]);
                        }
                        $answer .= "\" />\n";
                    }
                    $answer .= "\t</td>\n";
                    $inputnames[] = $myfname2;
                    $thiskey++;
                } else {
                    $myfname2 = $myfname . "_{$ld}";
                    if (isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname2]) && $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname2] == '1') {
                        $myvalue = '1';
                        $setmyvalue = CHECKED;
                    } else {
                        $myvalue = '';
                        $setmyvalue = '';
                    }
                    $answer .= "\t<td class=\"answer_cell_00{$ld} question-item answer-item {$answertypeclass}-item\">\n" . "\t<input type=\"hidden\" name=\"java{$myfname2}\" id=\"java{$myfname2}\" value=\"{$myvalue}\"/>\n" . "\t<input type=\"hidden\" name=\"{$myfname2}\" id=\"answer{$myfname2}\" value=\"{$myvalue}\" />\n";
                    $answer .= "\t<input type=\"checkbox\" class=\"checkbox {$extraclass}\" name=\"cbox_{$myfname2}\" id=\"cbox_{$myfname2}\" {$setmyvalue} " . " onclick=\"cancelBubbleThis(event); " . " aelt=document.getElementById('answer{$myfname2}');" . " jelt=document.getElementById('java{$myfname2}');" . " if(this.checked) {" . "  aelt.value=1;jelt.value=1;{$checkconditionFunction}(1,'{$myfname2}',aelt.type);" . " } else {" . "  aelt.value='';jelt.value='';{$checkconditionFunction}('','{$myfname2}',aelt.type);" . " }; return true;\" " . " />\n";
                    $answer .= "<label class=\"hide read\" for=\"cbox_{$myfname2}\">{$labelans[$thiskey]}</label>\n";
                    $inputnames[] = $myfname2;
                    //                    $answer .= "</label>\n"
                    $answer .= "" . "\t</td>\n";
                    $thiskey++;
                }
            }
            if (strpos($answertextsave, '|')) {
                $answertext = substr($answertextsave, strpos($answertextsave, '|') + 1);
                $answer .= "\t<td class=\"answertextright\" style='text-align:left;' width=\"{$answerwidth}%\">{$answertext}</td>\n";
            } elseif ($right_exists) {
                $answer .= "\t<td class=\"answertextright\" style='text-align:left;' width=\"{$answerwidth}%\">&nbsp;</td>\n";
            }
            $answer .= "</tr>\n";
            //IF a MULTIPLE of flexi-redisplay figure, repeat the headings
            $fn++;
        }
        $answer .= "\t</tbody>\n</table>\n";
    } else {
        $answer = "\n<p class=\"error\">" . gT("Error: There are no answer options for this question and/or they don't exist in this language.") . "</p>\n";
        $inputnames = '';
    }
    return array($answer, $inputnames);
}
Example #22
0
 function scriptadvance()
 {
     $this->commonhelper->checkpermission("modify_scripts");
     $go_ErrorPassingemptydatacontactyoursupport = $this->lang->line('go_ErrorPassingemptydatacontactyoursupport');
     // check if $_POST has value
     if (!empty($_POST)) {
         global $dbprefix, $connect, $clang, $databasetype, $databasetabletype, $uploaddir, $limedb, $link;
         $rootdir = $this->config->item('lime_path') . "/limesurvey";
         require $rootdir . '/common_functions_ci.php';
         require $rootdir . '/admin/admin_functions_ci.php';
         require $rootdir . '/classes/core/sanitize.php';
         require $rootdir . '/classes/core/language.php';
         require $rootdir . '/admin/classes/core/sha256.php';
         $clang = new limesurvey_lang('en');
         require $rootdir . '/classes/core/surveytranslator_ci.php';
         include $rootdir . '/admin/activate_functions.php';
         require $rootdir . '/limesurvey_functions_ce.php';
         // get asterisk dbname
         $database = $this->go_script->asteriskDB->database;
         // vicidial_script table
         $data['fields'] = array('fullname' => 'Agent Name', 'vendor_lead_code' => 'vendor_lead_code', 'source_id' => 'source_id', 'list_id' => 'list_id', 'gmt_offset_now' => 'gmt_offset_now', 'called_since_last_reset' => 'called_since_last_reset', 'phone_code' => 'phone_code', 'phone_number' => 'phone_number', 'title' => 'title', 'first_name' => 'first_name', 'middle_initial' => 'middle_initial', 'last_name' => 'last_name', 'address1' => 'address1', 'address2' => 'address2', 'address3' => 'address3', 'city' => 'city', 'state' => 'state', 'province' => 'province', 'postal_code' => 'postal_code', 'country_code' => 'country_code', 'gender' => 'gender', 'date_of_birth' => 'date_of_birth', 'alt_phone' => 'alt_phone', 'email' => 'email', 'security_phrase' => 'security_phrase', 'comments' => 'comments', 'lead_id' => 'lead_id', 'campaign' => 'campaign', 'phone_login' => 'phone_login', 'group' => 'group', 'channel_group' => 'channel_group', 'SQLdate' => 'SQLdate', 'epoch' => 'epoch', 'uniqueid' => 'uniqueid', 'customer_zap_channel' => 'customer_zap_channel', 'server_ip' => 'server_ip', 'SIPexten' => 'SIPexten', 'session_id' => 'session_id', 'dialed_number' => 'dialed_number', 'dialed_label' => 'dialed_label', 'rank' => 'rank', 'owner' => 'owner', 'camp_script' => 'camp_script', 'in_script' => 'in_script', 'script_width' => 'script_width', 'script_height' => 'script_height', 'recording_filename' => 'recording_filename', 'recording_id' => 'recording_id', 'user_custom_one' => 'user_custom_one', 'user_custom_two' => 'user_custom_two', 'user_custom_three' => 'user_custom_three', 'user_custom_four' => 'user_custom_four', 'user_custom_five' => 'user_custom_five', 'preset_number_a' => 'preset_number_a', 'preset_number_b' => 'preset_number_b', 'preset_number_c' => 'preset_number_c', 'preset_number_d' => 'preset_number_d', 'preset_number_e' => 'preset_number_e', 'preset_number_f' => 'preset_number_f', 'preset_dtmf_a' => 'preset_dtmf_a', 'preset_dtmf_b' => 'preset_dtmf_b', 'did_id' => 'did_id', 'did_extension' => 'did_extension', 'did_pattern' => 'did_pattern', 'did_description' => 'did_description', 'closecallid' => 'closecallid', 'xfercallid' => 'xfercallid', 'agent_log_id' => 'agent_log_id', 'entry_list_id' => 'entry_list_id');
         $info = $this->commonhelper->simpleretrievedata('vicidial_scripts', "script_id,script_name,script_comments,script_text,active", null, array(array('script_id' => $_POST['script_id'])));
         $data['vicidial_script'] = $info->result();
         // get the data from limesurvey
         $this->go_script->limesurveyDB->select("surveyls_survey_id,surveyls_title,surveyls_description,ls.active,surveyls_welcometext,\n                                                   surveyls_endtext,surveyls_language,surveyls_url,surveyls_urldescription,surveyls_dateformat,\n                                                   admin,adminemail,format,showwelcome,navigationdelay,allowprev,allowjumps,nokeyboard,showprogress,\n\t                                           printanswers,publicstatistics,publicgraphs,autoredirect,showXquestions,showgroupinfo,showqnumcode,\n\t                                           ls.template,surveyls_numberformat,ls.sid,vs.script_name,vs.script_comments,vs.script_id");
         $this->go_script->limesurveyDB->from("lime_surveys_languagesettings as lsl");
         $this->go_script->limesurveyDB->join("lime_surveys as ls", "lsl.surveyls_survey_id=ls.sid", "left");
         $this->go_script->limesurveyDB->join("{$database}.go_scripts as gs", "ls.sid={$database}.gs.surveyid", "right");
         $this->go_script->limesurveyDB->join("{$database}.vicidial_scripts as vs", "gs.script_id={$database}.vs.script_id", "right");
         $this->go_script->limesurveyDB->where("gs.script_id = '" . $_POST['script_id'] . "'");
         $data['script'] = $this->go_script->limesurveyDB->get()->result();
         //get the questions
         $this->go_script->limesurveyDB->select("qid,title,question,type,mandatory,question_order,language,help,preg");
         $this->go_script->limesurveyDB->where("sid", $data['script'][0]->sid);
         $this->go_script->limesurveyDB->order_by("question_order", "asc");
         $data['questions'] = $this->go_script->limesurveyDB->get("lime_questions")->result();
         $data['script'][0]->surveyls_language = getLanguageNameFromCode($data['script'][0]->surveyls_language, false, $clang);
         foreach (getRadixPointData(-1, $clang) as $index => $val) {
             $data['radixpoint'][$index] = $val['desc'];
         }
         $templaterootDir = $rootdir . "/templates";
         $standardtemplate = $rootdir . "/templates";
         $standardtemplaterootDir = $rootdir . "/templates";
         foreach (gettemplatelist($templaterootDir, $standardtemplate, $standardtemplaterootDir) as $template => $templateval) {
             $data['template'][$template] = $template;
         }
         $data['type'] = getqtypelist($data['questions'][0]->type, 'group');
         $data['preview'] = sGetTemplateURL($data['script'][0]->template);
         $this->load->view('go_script/go_script_advance_ce', $data);
     } else {
         //die ($go_ErrorPassingemptydatacontactyoursupport);
         die("" . $this->lang->line("go_error_passing_empty_data") . "");
     }
 }