Ejemplo n.º 1
0
/**
* This function replaces keywords in a text and is mainly intended for templates
* If you use this functions put your replacement strings into the $replacements variable
* instead of using global variables
* NOTE - Don't do any embedded replacements in this function.  Create the array of replacement values and
* they will be done in batch at the end
*
* @param mixed $line Text to search in
* @param mixed $replacements Array of replacements:  Array( <stringtosearch>=><stringtoreplacewith>
* @param boolean $anonymized Determines if token data is being used or just replaced with blanks
* @param questionNum - needed to support dynamic JavaScript-based tailoring within questions
* @return string  Text with replaced strings
*/
function templatereplace($line, $replacements = array(), &$redata = array(), $debugSrc = 'Unspecified', $anonymized = false, $questionNum = NULL, $registerdata = array())
{
    /*
    global $clienttoken,$token,$sitename,$move,$showxquestions,$showqnumcode,$questioncode,$register_errormsg;
    global $s_lang,$errormsg,$saved_id, $relativeurl, $languagechanger,$captchapath,$loadname;
    */
    /*
    $allowedvars = array('surveylist', 'sitename', 'clienttoken', 'rooturl', 'thissurvey', 'imageurl', 'defaulttemplate',
    'percentcomplete', 'move', 'groupname', 'groupdescription', 'question', 'showxquestions',
    'showgroupinfo', 'showqnumcode', 'questioncode', 'answer', 'navigator', 'help', 'totalquestions',
    'surveyformat', 'completed', 'register_errormsg', 'notanswered', 'privacy', 'surveyid', 'publicurl',
    'templatedir', 'token', 'assessments', 's_lang', 'errormsg', 'clang', 'saved_id', 'usertemplaterootdir',
    'relativeurl', 'languagechanger', 'printoutput', 'captchapath', 'loadname');
    */
    $allowedvars = array('answer', 'assessments', 'captchapath', 'clienttoken', 'completed', 'errormsg', 'groupdescription', 'groupname', 'help', 'imageurl', 'languagechanger', 'loadname', 'move', 'navigator', 'percentcomplete', 'privacy', 'question', 'register_errormsg', 'relativeurl', 's_lang', 'saved_id', 'showgroupinfo', 'showqnumcode', 'showxquestions', 'sitename', 'surveylist', 'templatedir', 'thissurvey', 'token', 'totalBoilerplatequestions', 'totalquestions');
    $varsPassed = array();
    foreach ($allowedvars as $var) {
        if (isset($redata[$var])) {
            ${$var} = $redata[$var];
            $varsPassed[] = $var;
        }
    }
    //    if (count($varsPassed) > 0) {
    //        log_message('debug', 'templatereplace() called from ' . $debugSrc . ' contains: ' . implode(', ', $varsPassed));
    //    }
    //    if (isset($redata['question'])) {
    //        LimeExpressionManager::ShowStackTrace('has QID and/or SGA',$allowedvars);
    //    }
    //    extract($redata);   // creates variables for each of the keys in the array
    // Local over-rides in case not set above
    if (!isset($showgroupinfo)) {
        $showgroupinfo = Yii::app()->getConfig('showgroupinfo');
    }
    if (!isset($showqnumcode)) {
        $showqnumcode = Yii::app()->getConfig('showqnumcode');
    }
    $_surveyid = Yii::app()->getConfig('surveyID');
    if (!isset($showxquestions)) {
        $showxquestions = Yii::app()->getConfig('showxquestions');
    }
    if (!isset($s_lang)) {
        $s_lang = isset(Yii::app()->session['survey_' . $_surveyid]['s_lang']) ? Yii::app()->session['survey_' . $_surveyid]['s_lang'] : 'en';
    }
    if (!isset($captchapath)) {
        $captchapath = '';
    }
    $clang = Yii::app()->lang;
    Yii::app()->loadHelper('surveytranslator');
    $questiondetails = array('sid' => 0, 'gid' => 0, 'qid' => 0, 'aid' => 0);
    if (isset($question) && isset($question['sgq'])) {
        $questiondetails = getSIDGIDQIDAIDType($question['sgq']);
    }
    //Gets an array containing SID, GID, QID, AID and Question Type)
    if (isset($thissurvey['sid'])) {
        $surveyid = $thissurvey['sid'];
    }
    // lets sanitize the survey template
    if (isset($thissurvey['templatedir'])) {
        $templatename = $thissurvey['templatedir'];
    } else {
        $templatename = Yii::app()->getConfig('defaulttemplate');
    }
    if (!isset($templatedir)) {
        $templatedir = getTemplatePath($templatename);
    }
    if (!isset($templateurl)) {
        $templateurl = getTemplateURL($templatename) . "/";
    }
    // TEMPLATECSS and TEMPLATEJS
    $_templatecss = "";
    $_templatejs = "";
    if (stripos($line, "{TEMPLATECSS}")) {
        $css_header_includes = Yii::app()->getConfig("css_header_includes");
        if (file_exists($templatedir . DIRECTORY_SEPARATOR . 'jquery-ui-custom.css')) {
            $template_jqueryui_css = "<link rel='stylesheet' type='text/css' media='all' href='{$templateurl}jquery-ui-custom.css' />\n";
        } elseif (file_exists($templatedir . DIRECTORY_SEPARATOR . 'jquery-ui.css')) {
            $template_jqueryui_css = "<link rel='stylesheet' type='text/css' media='all' href='{$templateurl}jquery-ui.css' />\n";
        } else {
            $_templatecss .= "<link rel='stylesheet' type='text/css' media='all' href='" . Yii::app()->getConfig('publicstyleurl') . "jquery-ui.css' />\n";
            // Remove it after corrected slider
            $template_jqueryui_css = "";
        }
        if ($css_header_includes) {
            foreach ($css_header_includes as $cssinclude) {
                if (substr($cssinclude, 0, 4) == 'http' || substr($cssinclude, 0, strlen(Yii::app()->getConfig('publicurl'))) == Yii::app()->getConfig('publicurl')) {
                    $_templatecss .= "<link rel='stylesheet' type='text/css' media='all' href='" . $cssinclude . "' />\n";
                } else {
                    if (file_exists($templatedir . DIRECTORY_SEPARATOR . $cssinclude)) {
                        $_templatecss .= "<link rel='stylesheet' type='text/css' media='all' href='{$templateurl}{$cssinclude}' />\n";
                    } else {
                        $_templatecss .= "<link rel='stylesheet' type='text/css' media='all' href='" . Yii::app()->getConfig('publicstyleurl') . $cssinclude . "' />\n";
                    }
                }
            }
        }
        $_templatecss .= $template_jqueryui_css;
        // Template jquery ui after default css
        $_templatecss .= "<link rel='stylesheet' type='text/css' media='all' href='{$templateurl}template.css' />\n";
        if (getLanguageRTL($clang->langcode)) {
            $_templatecss .= "<link rel='stylesheet' type='text/css' media='all' href='{$templateurl}template-rtl.css' />\n";
        }
    }
    if (stripos($line, "{TEMPLATEJS}")) {
        $js_header_includes = header_includes(false, 'js');
        $_jqueryuijsurl = Yii::app()->getConfig('generalscripts') . "jquery/jquery-ui.js";
        $_templatejs .= "<script type='text/javascript' src='" . Yii::app()->getConfig('generalscripts') . "jquery/jquery.js'></script>\n";
        $_templatejs .= "<script type='text/javascript' src='{$_jqueryuijsurl}'></script>\n";
        $_templatejs .= "<script type='text/javascript' src='" . Yii::app()->getConfig('generalscripts') . "jquery/jquery.ui.touch-punch.min.js'></script>\n";
        if ($js_header_includes) {
            foreach ($js_header_includes as $jsinclude) {
                if (substr($jsinclude, 0, 4) == 'http' || substr($jsinclude, 0, strlen(Yii::app()->getConfig('publicurl'))) == Yii::app()->getConfig('publicurl')) {
                    $_templatejs .= "<script type='text/javascript' src='{$jsinclude}'></script>\n";
                } else {
                    $_templatejs .= "<script type='text/javascript' src='" . Yii::app()->getConfig('generalscripts') . $jsinclude . "'></script>\n";
                }
            }
        }
        $_templatejs .= "<script type='text/javascript' src='" . Yii::app()->getConfig('generalscripts') . "survey_runtime.js'></script>\n";
        $_templatejs .= "<script type='text/javascript' src='{$templateurl}template.js'></script>\n";
        $_templatejs .= useFirebug();
    }
    // surveyformat
    if (isset($thissurvey['format'])) {
        $surveyformat = str_replace(array("A", "S", "G"), array("allinone", "questionbyquestion", "groupbygroup"), $thissurvey['format']);
    } else {
        $surveyformat = "";
    }
    if (isset(Yii::app()->session['step']) && Yii::app()->session['step'] % 2 && $surveyformat != "allinone") {
        $surveyformat .= " page-odd";
    }
    if (isset($thissurvey['allowjumps']) && $thissurvey['allowjumps'] == "Y" && $surveyformat != "allinone" && (isset(Yii::app()->session['step']) && Yii::app()->session['step'] > 0)) {
        $surveyformat .= " withindex";
    }
    if (isset($thissurvey['showprogress']) && $thissurvey['showprogress'] == "Y") {
        $surveyformat .= " showprogress";
    }
    if (isset($thissurvey['showqnumcode'])) {
        $surveyformat .= " showqnumcode-" . $thissurvey['showqnumcode'];
    }
    // real survey contact
    if (isset($surveylist) && isset($surveylist['contact'])) {
        $surveycontact = $surveylist['contact'];
    } elseif (isset($surveylist) && isset($thissurvey['admin']) && $thissurvey['admin'] != "") {
        $surveycontact = sprintf($clang->gT("Please contact %s ( %s ) for further assistance."), $thissurvey['admin'], $thissurvey['adminemail']);
    } else {
        $surveycontact = "";
    }
    // If there are non-bracketed replacements to be made do so above this line.
    // Only continue in this routine if there are bracketed items to replace {}
    if (strpos($line, "{") === false) {
        // process string anyway so that it can be pretty-printed
        return LimeExpressionManager::ProcessString($line, $questionNum, NULL, false, 1, 1, true);
    }
    if ($showgroupinfo == 'both' || $showgroupinfo == 'name' || $showgroupinfo == 'choose' && !isset($thissurvey['showgroupinfo']) || $showgroupinfo == 'choose' && $thissurvey['showgroupinfo'] == 'B' || $showgroupinfo == 'choose' && $thissurvey['showgroupinfo'] == 'N') {
        $_groupname = isset($groupname) ? $groupname : '';
    } else {
        $_groupname = '';
    }
    if ($showgroupinfo == 'both' || $showgroupinfo == 'description' || $showgroupinfo == 'choose' && !isset($thissurvey['showgroupinfo']) || $showgroupinfo == 'choose' && $thissurvey['showgroupinfo'] == 'B' || $showgroupinfo == 'choose' && $thissurvey['showgroupinfo'] == 'D') {
        $_groupdescription = isset($groupdescription) ? $groupdescription : '';
    } else {
        $_groupdescription = '';
    }
    if (isset($question) && is_array($question)) {
        $_question = $question['all'];
        $_question_text = $question['text'];
        $_question_help = $question['help'];
        $_question_mandatory = $question['mandatory'];
        $_question_man_message = $question['man_message'];
        $_question_valid_message = $question['valid_message'];
        $_question_file_valid_message = $question['file_valid_message'];
        $_question_sgq = isset($question['sgq']) ? $question['sgq'] : '';
        $_question_essentials = $question['essentials'];
        $_getQuestionClass = $question['class'];
        $_question_man_class = $question['man_class'];
        $_question_input_error_class = $question['input_error_class'];
        $_question_number = $question['number'];
        $_question_code = $question['code'];
        $_question_type = $question['type'];
    } else {
        $_question = isset($question) ? $question : '';
        $_question_text = '';
        $_question_help = '';
        $_question_mandatory = '';
        $_question_man_message = '';
        $_question_valid_message = '';
        $_question_file_valid_message = '';
        $_question_sgq = '';
        $_question_essentials = '';
        $_getQuestionClass = '';
        $_question_man_class = '';
        $_question_input_error_class = '';
        $_question_number = '';
        $_question_code = '';
        $_question_type = '';
    }
    if ($_question_type == '*') {
        $_question_text = '<div class="em_equation">' . $_question_text . '</div>';
    }
    if (!($showqnumcode == 'both' || $showqnumcode == 'number' || $showqnumcode == 'choose' && !isset($thissurvey['showqnumcode']) || $showqnumcode == 'choose' && $thissurvey['showqnumcode'] == 'B' || $showqnumcode == 'choose' && $thissurvey['showqnumcode'] == 'N')) {
        $_question_number = '';
    }
    if (!($showqnumcode == 'both' || $showqnumcode == 'code' || $showqnumcode == 'choose' && !isset($thissurvey['showqnumcode']) || $showqnumcode == 'choose' && $thissurvey['showqnumcode'] == 'B' || $showqnumcode == 'choose' && $thissurvey['showqnumcode'] == 'C')) {
        $_question_code = '';
    }
    if (!isset($totalquestions)) {
        $totalquestions = 0;
    }
    $_totalquestionsAsked = $totalquestions;
    if ($showxquestions == 'show' || $showxquestions == 'choose' && !isset($thissurvey['showxquestions']) || $showxquestions == 'choose' && $thissurvey['showxquestions'] == 'Y') {
        if ($_totalquestionsAsked < 1) {
            $_therearexquestions = $clang->gT("There are no questions in this survey");
            // Singular
        } elseif ($_totalquestionsAsked == 1) {
            $_therearexquestions = $clang->gT("There is 1 question in this survey");
            //Singular
        } else {
            $_therearexquestions = $clang->gT("There are {NUMBEROFQUESTIONS} questions in this survey.");
            //Note this line MUST be before {NUMBEROFQUESTIONS}
        }
    } else {
        $_therearexquestions = '';
    }
    if (isset($token)) {
        $_token = $token;
    } elseif (isset($clienttoken)) {
        $_token = htmlentities($clienttoken, ENT_QUOTES, 'UTF-8');
        // or should it be URL-encoded?
    } else {
        $_token = '';
    }
    // Expiry
    if (isset($thissurvey['expiry'])) {
        $dateformatdetails = getDateFormatData($thissurvey['surveyls_dateformat']);
        Yii::import('application.libraries.Date_Time_Converter', true);
        $datetimeobj = new Date_Time_Converter($thissurvey['expiry'], "Y-m-d");
        $_dateoutput = $datetimeobj->convert($dateformatdetails['phpdate']);
    } else {
        $_dateoutput = '-';
    }
    $_submitbutton = "<input class='submit' type='submit' value=' " . $clang->gT("Submit") . " ' name='move2' onclick=\"javascript:document.limesurvey.move.value = 'movesubmit';\" />";
    if (isset($thissurvey['surveyls_url']) and $thissurvey['surveyls_url'] != "") {
        if (trim($thissurvey['surveyls_urldescription']) != '') {
            $_linkreplace = "<a href='{$thissurvey['surveyls_url']}'>{$thissurvey['surveyls_urldescription']}</a>";
        } else {
            $_linkreplace = "<a href='{$thissurvey['surveyls_url']}'>{$thissurvey['surveyls_url']}</a>";
        }
    } else {
        $_linkreplace = '';
    }
    if (isset($thissurvey['sid']) && isset($_SESSION['survey_' . $thissurvey['sid']]['srid']) && $thissurvey['active'] == 'Y') {
        $iscompleted = Survey_dynamic::model($surveyid)->isCompleted($_SESSION['survey_' . $thissurvey['sid']]['srid']);
    } else {
        $iscompleted = false;
    }
    if (isset($surveyid) && !$iscompleted) {
        $_clearall = "<input type='button' name='clearallbtn' value='" . $clang->gT("Exit and clear survey") . "' class='clearall' " . "onclick=\"if (confirm('" . $clang->gT("Are you sure you want to clear all your responses?", 'js') . "')) {\nwindow.open('" . Yii::app()->getController()->createUrl("survey/index/sid/{$surveyid}", array('move' => 'clearall', 'lang' => $s_lang), '&amp;');
        if (returnGlobal('token')) {
            $_clearall .= "&amp;token=" . urlencode(trim(sanitize_token(strip_tags(returnGlobal('token')))));
        }
        $_clearall .= "', '_self')}\" />";
    } else {
        $_clearall = "";
    }
    if (isset(Yii::app()->session['datestamp'])) {
        $_datestamp = Yii::app()->session['datestamp'];
    } else {
        $_datestamp = '-';
    }
    if (isset($thissurvey['allowsave']) and $thissurvey['allowsave'] == "Y") {
        // Find out if the user has any saved data
        if ($thissurvey['format'] == 'A') {
            if ($thissurvey['tokenanswerspersistence'] != 'Y' || !isset($surveyid) || !tableExists('tokens_' . $surveyid)) {
                $_saveall = "\t\t\t<input type='button' name='loadall' value='" . $clang->gT("Load unfinished survey") . "' class='saveall' onclick=\"javascript:addHiddenField(document.getElementById('limesurvey'),'loadall',this.value);document.getElementById('limesurvey').submit();\" " . ($thissurvey['active'] != "Y" ? "disabled='disabled'" : "") . "/>" . "\n\t\t\t<input type='button' name='saveallbtn' value='" . $clang->gT("Resume later") . "' class='saveall' onclick=\"javascript:document.limesurvey.move.value = this.value;addHiddenField(document.getElementById('limesurvey'),'saveall',this.value);document.getElementById('limesurvey').submit();\" " . ($thissurvey['active'] != "Y" ? "disabled='disabled'" : "") . "/>";
                // Show Save So Far button
            } else {
                $_saveall = "\t\t\t<input type='button' name='saveallbtn' value='" . $clang->gT("Resume later") . "' class='saveall' onclick=\"javascript:document.limesurvey.move.value = this.value;addHiddenField(document.getElementById('limesurvey'),'saveall',this.value);document.getElementById('limesurvey').submit();\" " . ($thissurvey['active'] != "Y" ? "disabled='disabled'" : "") . "/>";
                // Show Save So Far button
            }
        } elseif (isset($surveyid) && (!isset($_SESSION['survey_' . $surveyid]['step']) || !$_SESSION['survey_' . $surveyid]['step'])) {
            //First page, show LOAD
            if ($thissurvey['tokenanswerspersistence'] != 'Y' || !isset($surveyid) || !tableExists('tokens_' . $surveyid)) {
                $_saveall = "\t\t\t<input type='button' name='loadall' value='" . $clang->gT("Load unfinished survey") . "' class='saveall' onclick=\"javascript:addHiddenField(document.getElementById('limesurvey'),'loadall',this.value);document.getElementById('limesurvey').submit();\" " . ($thissurvey['active'] != "Y" ? "disabled='disabled'" : "") . "/>";
            } else {
                $_saveall = '';
            }
        } elseif (isset(Yii::app()->session['scid']) && (isset($move) && $move == "movelast")) {
            //Already saved and on Submit Page, dont show Save So Far button
            $_saveall = '';
        } else {
            $_saveall = "<input type='button' name='saveallbtn' value='" . $clang->gT("Resume later") . "' class='saveall' onclick=\"javascript:document.limesurvey.move.value = this.value;addHiddenField(document.getElementById('limesurvey'),'saveall',this.value);document.getElementById('limesurvey').submit();\" " . ($thissurvey['active'] != "Y" ? "disabled='disabled'" : "") . "/>";
            // Show Save So Far button
        }
    } else {
        $_saveall = "";
    }
    if (!isset($help)) {
        $help = "";
    }
    if (flattenText($help, true, true) != '') {
        if (!isset($helpicon)) {
            if (file_exists($templatedir . '/help.gif')) {
                $helpicon = $templateurl . 'help.gif';
            } elseif (file_exists($templatedir . '/help.png')) {
                $helpicon = $templateurl . 'help.png';
            } else {
                $helpicon = Yii::app()->getConfig('imageurl') . "/help.gif";
            }
        }
        $_questionhelp = "<img src='{$helpicon}' alt='Help' align='left' />" . $help;
    } else {
        $_questionhelp = $help;
    }
    if (isset($thissurvey['allowprev']) && $thissurvey['allowprev'] == "N") {
        $_strreview = "";
    } else {
        $_strreview = $clang->gT("If you want to check any of the answers you have made, and/or change them, you can do that now by clicking on the [<< prev] button and browsing through your responses.");
    }
    if (isset($thissurvey['active']) and $thissurvey['active'] == "N") {
        $_restart = "<a href='" . Yii::app()->getController()->createUrl("survey/index/sid/{$surveyid}/newtest/Y");
        if (isset($s_lang) && $s_lang != '') {
            $_restart .= "/lang/" . $s_lang;
        }
        $_restart .= "'>" . $clang->gT("Restart this survey") . "</a>";
    } else {
        if (isset($surveyid)) {
            $restart_extra = "";
            $restart_token = returnGlobal('token');
            if (!empty($restart_token)) {
                $restart_extra .= "/token/" . urlencode($restart_token);
            } else {
                $restart_extra = "/newtest/Y";
            }
            if (!empty($_GET['lang'])) {
                $restart_extra .= "/lang/" . returnGlobal('lang');
            }
            $_restart = "<a href='" . Yii::app()->getController()->createUrl("survey/index/sid/{$surveyid}{$restart_extra}") . "'>" . $clang->gT("Restart this Survey") . "</a>";
        } else {
            $_restart = "";
        }
    }
    if (isset($thissurvey['anonymized']) && $thissurvey['anonymized'] == 'Y') {
        $_savealert = $clang->gT("To remain anonymous please use a pseudonym as your username, also an email address is not required.");
    } else {
        $_savealert = "";
    }
    if (isset($surveyid)) {
        $_return_to_survey = "<a href=" . Yii::app()->getController()->createUrl("survey/index/sid/{$surveyid}");
        if (returnGlobal('token')) {
            $_return_to_survey .= "?amp;token=" . urlencode(trim(sanitize_xss_string(strip_tags(returnGlobal('token')))));
        }
        $_return_to_survey .= "'>" . $clang->gT("Return to survey") . "</a>";
    } else {
        $_return_to_survey = "";
    }
    // Save Form
    $_saveform = "<table><tr><td align='right'>" . $clang->gT("Name") . ":</td><td><input type='text' name='savename' value='";
    if (isset($_POST['savename'])) {
        $_saveform .= HTMLEscape(autoUnescape($_POST['savename']));
    }
    $_saveform .= "' /></td></tr>\n" . "<tr><td align='right'>" . $clang->gT("Password") . ":</td><td><input type='password' name='savepass' value='";
    if (isset($_POST['savepass'])) {
        $_saveform .= HTMLEscape(autoUnescape($_POST['savepass']));
    }
    $_saveform .= "' /></td></tr>\n" . "<tr><td align='right'>" . $clang->gT("Repeat password") . ":</td><td><input type='password' name='savepass2' value='";
    if (isset($_POST['savepass2'])) {
        $_saveform .= HTMLEscape(autoUnescape($_POST['savepass2']));
    }
    $_saveform .= "' /></td></tr>\n" . "<tr><td align='right'>" . $clang->gT("Your email address") . ":</td><td><input type='text' name='saveemail' value='";
    if (isset($_POST['saveemail'])) {
        $_saveform .= HTMLEscape(autoUnescape($_POST['saveemail']));
    }
    $_saveform .= "' /></td></tr>\n";
    if (isset($thissurvey['usecaptcha']) && function_exists("ImageCreate") && isCaptchaEnabled('saveandloadscreen', $thissurvey['usecaptcha'])) {
        $_saveform .= "<tr><td align='right'>" . $clang->gT("Security question") . ":</td><td><table><tr><td valign='middle'><img src='" . Yii::app()->getController()->createUrl('/verification/image/sid/' . (isset($surveyid) ? $surveyid : '')) . "' alt6='' /></td><td valign='middle' style='text-align:left'><input type='text' size='5' maxlength='3' name='loadsecurity' value='' /></td></tr></table></td></tr>\n";
    }
    $_saveform .= "<tr><td align='right'></td><td></td></tr>\n" . "<tr><td></td><td><input type='submit'  id='savebutton' name='savesubmit' value='" . $clang->gT("Save Now") . "' /></td></tr>\n" . "</table>";
    // Load Form
    $_loadform = "<table><tr><td align='right'>" . $clang->gT("Saved name") . ":</td><td><input type='text' name='loadname' value='";
    if (isset($loadname)) {
        $_loadform .= HTMLEscape(autoUnescape($loadname));
    }
    $_loadform .= "' /></td></tr>\n" . "<tr><td align='right'>" . $clang->gT("Password") . ":</td><td><input type='password' name='loadpass' value='";
    if (isset($loadpass)) {
        $_loadform .= HTMLEscape(autoUnescape($loadpass));
    }
    $_loadform .= "' /></td></tr>\n";
    if (isset($thissurvey['usecaptcha']) && function_exists("ImageCreate") && isCaptchaEnabled('saveandloadscreen', $thissurvey['usecaptcha'])) {
        $_loadform .= "<tr><td align='right'>" . $clang->gT("Security question") . ":</td><td><table><tr><td valign='middle'><img src='" . Yii::app()->getController()->createUrl('/verification/image/sid/' . $surveyid) . "' alt='' /></td><td valign='middle'><input type='text' size='5' maxlength='3' name='loadsecurity' value='' alt=''/></td></tr></table></td></tr>\n";
    }
    $_loadform .= "<tr><td align='right'></td><td></td></tr>\n" . "<tr><td></td><td><input type='submit' id='loadbutton' value='" . $clang->gT("Load now") . "' /></td></tr></table>\n";
    // Registration Form
    if (isset($surveyid) || isset($registerdata) && $debugSrc == 'register.php') {
        if (isset($surveyid)) {
            $tokensid = $surveyid;
        } else {
            $tokensid = $registerdata['sid'];
        }
        $_registerform = "<form method='post' action='" . Yii::app()->getController()->createUrl('/register/index/surveyid/' . $tokensid) . "'>\n";
        if (!isset($_REQUEST['lang'])) {
            $_reglang = Survey::model()->findByPk($tokensid)->language;
        } else {
            $_reglang = returnGlobal('lang');
        }
        $_registerform .= "<input type='hidden' name='lang' value='" . $_reglang . "' />\n";
        $_registerform .= "<input type='hidden' name='sid' value='{$tokensid}' id='sid' />\n";
        $_registerform .= "<table class='register' summary='Registrationform'>\n" . "<tr><td align='right'>" . $clang->gT("First name") . ":</td>" . "<td align='left'><input class='text' type='text' name='register_firstname'";
        if (isset($_POST['register_firstname'])) {
            $_registerform .= " value='" . htmlentities(returnGlobal('register_firstname'), ENT_QUOTES, 'UTF-8') . "'";
        }
        $_registerform .= " /></td></tr>" . "<tr><td align='right'>" . $clang->gT("Last name") . ":</td>\n" . "<td align='left'><input class='text' type='text' name='register_lastname'";
        if (isset($_POST['register_lastname'])) {
            $_registerform .= " value='" . htmlentities(returnGlobal('register_lastname'), ENT_QUOTES, 'UTF-8') . "'";
        }
        $_registerform .= " /></td></tr>\n" . "<tr><td align='right'>" . $clang->gT("Email address") . ":</td>\n" . "<td align='left'><input class='text' type='text' name='register_email'";
        if (isset($_POST['register_email'])) {
            $_registerform .= " value='" . htmlentities(returnGlobal('register_email'), ENT_QUOTES, 'UTF-8') . "'";
        }
        $_registerform .= " /></td></tr>\n";
        foreach ($thissurvey['attributedescriptions'] as $field => $attribute) {
            if (empty($attribute['show_register']) || $attribute['show_register'] != 'Y') {
                continue;
            }
            $_registerform .= '
            <tr>
            <td align="right">' . $thissurvey['attributecaptions'][$field] . ($attribute['mandatory'] == 'Y' ? '*' : '') . ':</td>
            <td align="left"><input class="text" type="text" name="register_' . $field . '" /></td>
            </tr>';
        }
        if ((count($registerdata) > 1 || isset($thissurvey['usecaptcha'])) && function_exists("ImageCreate") && isCaptchaEnabled('registrationscreen', $thissurvey['usecaptcha'])) {
            $_registerform .= "<tr><td align='right'>" . $clang->gT("Security Question") . ":</td><td><table><tr><td valign='middle'><img src='" . Yii::app()->getController()->createUrl('/verification/image/sid/' . $surveyid) . "' alt='' /></td><td valign='middle'><input type='text' size='5' maxlength='3' name='loadsecurity' value='' /></td></tr></table></td></tr>\n";
        }
        $_registerform .= "<tr><td></td><td><input id='registercontinue' class='submit' type='submit' value='" . $clang->gT("Continue") . "' />" . "</td></tr>\n" . "</table>\n";
        if (count($registerdata) > 1 && $registerdata['sid'] != NULL && $debugSrc == 'register.php') {
            $_registerform .= "<input name='startdate' type ='hidden' value='" . $registerdata['startdate'] . "' />";
            $_registerform .= "<input name='enddate' type ='hidden' value='" . $registerdata['enddate'] . "' />";
        }
        $_registerform .= "</form>\n";
    } else {
        $_registerform = "";
    }
    // Assessments
    $assessmenthtml = "";
    if (isset($surveyid) && !is_null($surveyid) && function_exists('doAssessment')) {
        $assessmentdata = doAssessment($surveyid, true);
        $_assessment_current_total = $assessmentdata['total'];
        if (stripos($line, "{ASSESSMENTS}")) {
            $assessmenthtml = doAssessment($surveyid, false);
        }
    } else {
        $_assessment_current_total = '';
    }
    if (isset($thissurvey['googleanalyticsapikey']) && trim($thissurvey['googleanalyticsapikey']) != '') {
        $_googleAnalyticsAPIKey = trim($thissurvey['googleanalyticsapikey']);
    } else {
        $_googleAnalyticsAPIKey = trim(getGlobalSetting('googleanalyticsapikey'));
    }
    $_googleAnalyticsStyle = isset($thissurvey['googleanalyticsstyle']) ? $thissurvey['googleanalyticsstyle'] : '0';
    $_googleAnalyticsJavaScript = '';
    if ($_googleAnalyticsStyle != '' && $_googleAnalyticsStyle != 0 && $_googleAnalyticsAPIKey != '') {
        switch ($_googleAnalyticsStyle) {
            case '1':
                // Default Google Tracking
                $_googleAnalyticsJavaScript = <<<EOD
<script type="text/javascript">
  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', '{$_googleAnalyticsAPIKey}']);
  _gaq.push(['_trackPageview']);

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

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();
</script>
EOD;
                break;
        }
    }
    $_endtext = '';
    if (isset($thissurvey['surveyls_endtext']) && trim($thissurvey['surveyls_endtext']) != '') {
        $_endtext = $thissurvey['surveyls_endtext'];
    }
    // Set the array of replacement variables here - don't include curly braces
    $coreReplacements = array();
    $coreReplacements['ACTIVE'] = isset($thissurvey['active']) && !($thissurvey['active'] != "Y");
    $coreReplacements['AID'] = isset($questiondetails['aid']) ? $questiondetails['aid'] : '';
    $coreReplacements['ANSWER'] = isset($answer) ? $answer : '';
    // global
    $coreReplacements['ANSWERSCLEARED'] = $clang->gT("Answers cleared");
    $coreReplacements['ASSESSMENTS'] = $assessmenthtml;
    $coreReplacements['ASSESSMENT_CURRENT_TOTAL'] = $_assessment_current_total;
    $coreReplacements['ASSESSMENT_HEADING'] = $clang->gT("Your assessment");
    $coreReplacements['CHECKJAVASCRIPT'] = "<noscript><span class='warningjs'>" . $clang->gT("Caution: JavaScript execution is disabled in your browser. You may not be able to answer all questions in this survey. Please, verify your browser parameters.") . "</span></noscript>";
    $coreReplacements['CLEARALL'] = $_clearall;
    $coreReplacements['CLOSEWINDOW'] = "<a href='javascript:%20self.close()'>" . $clang->gT("Close this window") . "</a>";
    $coreReplacements['COMPLETED'] = isset($redata['completed']) ? $redata['completed'] : '';
    // global
    $coreReplacements['DATESTAMP'] = $_datestamp;
    $coreReplacements['ENDTEXT'] = $_endtext;
    $coreReplacements['EXPIRY'] = $_dateoutput;
    $coreReplacements['GID'] = isset($questiondetails['gid']) ? $questiondetails['gid'] : '';
    $coreReplacements['GOOGLE_ANALYTICS_API_KEY'] = $_googleAnalyticsAPIKey;
    $coreReplacements['GOOGLE_ANALYTICS_JAVASCRIPT'] = $_googleAnalyticsJavaScript;
    $coreReplacements['GROUPDESCRIPTION'] = $_groupdescription;
    $coreReplacements['GROUPNAME'] = $_groupname;
    $coreReplacements['LANG'] = $clang->getlangcode();
    $coreReplacements['LANGUAGECHANGER'] = isset($languagechanger) ? $languagechanger : '';
    // global
    $coreReplacements['LOADERROR'] = isset($errormsg) ? $errormsg : '';
    // global
    $coreReplacements['LOADFORM'] = $_loadform;
    $coreReplacements['LOADHEADING'] = $clang->gT("Load a previously saved survey");
    $coreReplacements['LOADMESSAGE'] = $clang->gT("You can load a survey that you have previously saved from this screen.") . "<br />" . $clang->gT("Type in the 'name' you used to save the survey, and the password.") . "<br />";
    $coreReplacements['NAVIGATOR'] = isset($navigator) ? $navigator : '';
    // global
    $coreReplacements['NOSURVEYID'] = isset($surveylist) ? $surveylist['nosid'] : '';
    $coreReplacements['NUMBEROFQUESTIONS'] = $_totalquestionsAsked;
    $coreReplacements['PERCENTCOMPLETE'] = isset($percentcomplete) ? $percentcomplete : '';
    // global
    $coreReplacements['PRIVACY'] = isset($privacy) ? $privacy : '';
    // global
    $coreReplacements['PRIVACYMESSAGE'] = "<span style='font-weight:bold; font-style: italic;'>" . $clang->gT("A Note On Privacy") . "</span><br />" . $clang->gT("This survey is anonymous.") . "<br />" . $clang->gT("The record kept of your survey responses does not contain any identifying information about you unless a specific question in the survey has asked for this. If you have responded to a survey that used an identifying token to allow you to access the survey, you can rest assured that the identifying token is not kept with your responses. It is managed in a separate database, and will only be updated to indicate that you have (or haven't) completed this survey. There is no way of matching identification tokens with survey responses in this survey.");
    $coreReplacements['QID'] = isset($questiondetails['qid']) ? $questiondetails['qid'] : '';
    $coreReplacements['QUESTION'] = $_question;
    $coreReplacements['QUESTIONHELP'] = $_questionhelp;
    $coreReplacements['QUESTIONHELPPLAINTEXT'] = strip_tags(addslashes($help));
    // global
    $coreReplacements['QUESTION_CLASS'] = $_getQuestionClass;
    $coreReplacements['QUESTION_CODE'] = $_question_code;
    $coreReplacements['QUESTION_ESSENTIALS'] = $_question_essentials;
    $coreReplacements['QUESTION_FILE_VALID_MESSAGE'] = $_question_file_valid_message;
    $coreReplacements['QUESTION_HELP'] = $_question_help;
    $coreReplacements['QUESTION_INPUT_ERROR_CLASS'] = $_question_input_error_class;
    $coreReplacements['QUESTION_MANDATORY'] = $_question_mandatory;
    $coreReplacements['QUESTION_MAN_CLASS'] = $_question_man_class;
    $coreReplacements['QUESTION_MAN_MESSAGE'] = $_question_man_message;
    $coreReplacements['QUESTION_NUMBER'] = $_question_number;
    $coreReplacements['QUESTION_TEXT'] = $_question_text;
    $coreReplacements['QUESTION_VALID_MESSAGE'] = $_question_valid_message;
    $coreReplacements['REGISTERERROR'] = isset($register_errormsg) ? $register_errormsg : '';
    // global
    $coreReplacements['REGISTERFORM'] = $_registerform;
    $coreReplacements['REGISTERMESSAGE1'] = $clang->gT("You must be registered to complete this survey");
    $coreReplacements['REGISTERMESSAGE2'] = $clang->gT("You may register for this survey if you wish to take part.") . "<br />\n" . $clang->gT("Enter your details below, and an email containing the link to participate in this survey will be sent immediately.");
    $coreReplacements['RESTART'] = $_restart;
    $coreReplacements['RETURNTOSURVEY'] = $_return_to_survey;
    $coreReplacements['SAVE'] = $_saveall;
    $coreReplacements['SAVEALERT'] = $_savealert;
    $coreReplacements['SAVEDID'] = isset($saved_id) ? $saved_id : '';
    // global
    $coreReplacements['SAVEERROR'] = isset($errormsg) ? $errormsg : '';
    // global - same as LOADERROR
    $coreReplacements['SAVEFORM'] = $_saveform;
    $coreReplacements['SAVEHEADING'] = $clang->gT("Save your unfinished survey");
    $coreReplacements['SAVEMESSAGE'] = $clang->gT("Enter a name and password for this survey and click save below.") . "<br />\n" . $clang->gT("Your survey will be saved using that name and password, and can be completed later by logging in with the same name and password.") . "<br /><br />\n" . $clang->gT("If you give an email address, an email containing the details will be sent to you.") . "<br /><br />\n" . $clang->gT("After having clicked the save button you can either close this browser window or continue filling out the survey.");
    $coreReplacements['SGQ'] = $_question_sgq;
    $coreReplacements['SID'] = isset($surveyid) ? $surveyid : (isset($questiondetails['sid']) ? $questiondetails['sid'] : '');
    $coreReplacements['SITENAME'] = isset($sitename) ? $sitename : '';
    // global
    $coreReplacements['SUBMITBUTTON'] = $_submitbutton;
    $coreReplacements['SUBMITCOMPLETE'] = "<strong>" . $clang->gT("Thank you!") . "<br /><br />" . $clang->gT("You have completed answering the questions in this survey.") . "</strong><br /><br />" . $clang->gT("Click on 'Submit' now to complete the process and save your answers.");
    $coreReplacements['SUBMITREVIEW'] = $_strreview;
    $coreReplacements['SURVEYCONTACT'] = $surveycontact;
    $coreReplacements['SURVEYDESCRIPTION'] = isset($thissurvey['description']) ? $thissurvey['description'] : '';
    $coreReplacements['SURVEYFORMAT'] = isset($surveyformat) ? $surveyformat : '';
    // global
    $coreReplacements['SURVEYLANGAGE'] = $clang->langcode;
    $coreReplacements['SURVEYLANGUAGE'] = $clang->langcode;
    $coreReplacements['SURVEYLIST'] = isset($surveylist) ? $surveylist['list'] : '';
    $coreReplacements['SURVEYLISTHEADING'] = isset($surveylist) ? $surveylist['listheading'] : '';
    $coreReplacements['SURVEYNAME'] = isset($thissurvey['name']) ? $thissurvey['name'] : '';
    $coreReplacements['TEMPLATECSS'] = $_templatecss;
    $coreReplacements['TEMPLATEJS'] = $_templatejs;
    $coreReplacements['TEMPLATEURL'] = $templateurl;
    $coreReplacements['THEREAREXQUESTIONS'] = $_therearexquestions;
    if (!$anonymized) {
        $coreReplacements['TOKEN'] = $_token;
    }
    $coreReplacements['URL'] = $_linkreplace;
    $coreReplacements['WELCOME'] = isset($thissurvey['welcome']) ? $thissurvey['welcome'] : '';
    if (!is_null($replacements) && is_array($replacements)) {
        $doTheseReplacements = array_merge($coreReplacements, $replacements);
        // so $replacements overrides core values
    } else {
        $doTheseReplacements = $coreReplacements;
    }
    // Now do all of the replacements - In rare cases, need to do 3 deep recursion, that that is default
    $line = LimeExpressionManager::ProcessString($line, $questionNum, $doTheseReplacements, false, 3, 1);
    return $line;
}
Ejemplo n.º 2
0
 /**
  * Function that initialises all data and call other functions to load default view.
  *
  * @access protected
  * @param string $templatename
  * @param string $screenname
  * @param string $editfile
  * @param bool $showsummary
  * @return
  */
 protected function _initialise($templatename, $screenname, $editfile, $showsummary = true)
 {
     App()->getClientScript()->reset();
     $clang = $this->getController()->lang;
     Yii::app()->loadHelper('surveytranslator');
     Yii::app()->loadHelper('admin/template');
     $files = $this->_initfiles($templatename);
     $cssfiles = $this->_initcssfiles();
     // Standard Support Files
     // These files may be edited or saved
     $supportfiles[] = array('name' => 'print_img_radio.png');
     $supportfiles[] = array('name' => 'print_img_checkbox.png');
     // Standard screens
     // Only these may be viewed
     $screens[] = array('name' => $clang->gT('Survey List Page'), 'id' => 'surveylist');
     $screens[] = array('name' => $clang->gT('Welcome Page'), 'id' => 'welcome');
     $screens[] = array('name' => $clang->gT('Question Page'), 'id' => 'question');
     $screens[] = array('name' => $clang->gT('Completed Page'), 'id' => 'completed');
     $screens[] = array('name' => $clang->gT('Clear All Page'), 'id' => 'clearall');
     $screens[] = array('name' => $clang->gT('Register Page'), 'id' => 'register');
     $screens[] = array('name' => $clang->gT('Load Page'), 'id' => 'load');
     $screens[] = array('name' => $clang->gT('Save Page'), 'id' => 'save');
     $screens[] = array('name' => $clang->gT('Print answers page'), 'id' => 'printanswers');
     $screens[] = array('name' => $clang->gT('Printable survey page'), 'id' => 'printablesurvey');
     // Page display blocks
     $SurveyList = array('startpage.pstpl', 'surveylist.pstpl', 'endpage.pstpl');
     $Welcome = array('startpage.pstpl', 'welcome.pstpl', 'privacy.pstpl', 'navigator.pstpl', 'endpage.pstpl');
     $Question = array('startpage.pstpl', 'survey.pstpl', 'startgroup.pstpl', 'groupdescription.pstpl', 'question.pstpl', 'endgroup.pstpl', 'navigator.pstpl', 'endpage.pstpl');
     $CompletedTemplate = array('startpage.pstpl', 'assessment.pstpl', 'completed.pstpl', 'endpage.pstpl');
     $Clearall = array('startpage.pstpl', 'clearall.pstpl', 'endpage.pstpl');
     $Register = array('startpage.pstpl', 'survey.pstpl', 'register.pstpl', 'endpage.pstpl');
     $Save = array('startpage.pstpl', 'save.pstpl', 'endpage.pstpl');
     $Load = array('startpage.pstpl', 'load.pstpl', 'endpage.pstpl');
     $printtemplate = array('startpage.pstpl', 'printanswers.pstpl', 'endpage.pstpl');
     $printablesurveytemplate = array('print_survey.pstpl', 'print_group.pstpl', 'print_question.pstpl');
     $file_version = "LimeSurvey template editor " . Yii::app()->getConfig('versionnumber');
     Yii::app()->session['s_lang'] = Yii::app()->session['adminlang'];
     $templatename = sanitize_dirname($templatename);
     $screenname = autoUnescape($screenname);
     // Checks if screen name is in the list of allowed screen names
     if (multiarray_search($screens, 'id', $screenname) === false) {
         $this->getController()->error('Invalid screen name');
     }
     if (!isset($action)) {
         $action = sanitize_paranoid_string(returnGlobal('action'));
     }
     if (!isset($subaction)) {
         $subaction = sanitize_paranoid_string(returnGlobal('subaction'));
     }
     if (!isset($newname)) {
         $newname = sanitize_dirname(returnGlobal('newname'));
     }
     if (!isset($copydir)) {
         $copydir = sanitize_dirname(returnGlobal('copydir'));
     }
     if (is_file(Yii::app()->getConfig('usertemplaterootdir') . '/' . $templatename . '/question_start.pstpl')) {
         $files[] = array('name' => 'question_start.pstpl');
         $Question[] = 'question_start.pstpl';
     }
     $availableeditorlanguages = array('bg', 'cs', 'de', 'dk', 'en', 'eo', 'es', 'fi', 'fr', 'hr', 'it', 'ja', 'mk', 'nl', 'pl', 'pt', 'ru', 'sk', 'zh');
     $extension = substr(strrchr($editfile, "."), 1);
     if ($extension == 'css' || $extension == 'js') {
         $highlighter = $extension;
     } else {
         $highlighter = 'html';
     }
     if (in_array(Yii::app()->session['adminlang'], $availableeditorlanguages)) {
         $codelanguage = Yii::app()->session['adminlang'];
     } else {
         $codelanguage = 'en';
     }
     $templates = getTemplateList();
     if (!isset($templates[$templatename])) {
         $templatename = Yii::app()->getConfig('defaulttemplate');
     }
     $normalfiles = array("DUMMYENTRY", ".", "..", "preview.png");
     foreach ($files as $fl) {
         $normalfiles[] = $fl["name"];
     }
     foreach ($cssfiles as $fl) {
         $normalfiles[] = $fl["name"];
     }
     // Some global data
     $aData['sitename'] = Yii::app()->getConfig('sitename');
     $siteadminname = Yii::app()->getConfig('siteadminname');
     $siteadminemail = Yii::app()->getConfig('siteadminemail');
     // Set this so common.php doesn't throw notices about undefined variables
     $thissurvey['active'] = 'N';
     // FAKE DATA FOR TEMPLATES
     $thissurvey['name'] = $clang->gT("Template Sample");
     $thissurvey['description'] = "<p>" . $clang->gT('This is a sample survey description. It could be quite long.') . "</p>" . "<p>" . $clang->gT("But this one isn't.") . "<p>";
     $thissurvey['welcome'] = "<p>" . $clang->gT('Welcome to this sample survey') . "<p>" . "<p>" . $clang->gT('You should have a great time doing this') . "<p>";
     $thissurvey['allowsave'] = "Y";
     $thissurvey['active'] = "Y";
     $thissurvey['tokenanswerspersistence'] = "Y";
     $thissurvey['templatedir'] = $templatename;
     $thissurvey['format'] = "G";
     $thissurvey['surveyls_url'] = "http://www.limesurvey.org/";
     $thissurvey['surveyls_urldescription'] = $clang->gT("Some URL description");
     $thissurvey['usecaptcha'] = "A";
     $percentcomplete = makegraph(6, 10);
     $groupname = $clang->gT("Group 1: The first lot of questions");
     $groupdescription = $clang->gT("This group description is fairly vacuous, but quite important.");
     $navigator = $this->getController()->render('/admin/templates/templateeditor_navigator_view', array('screenname' => $screenname, 'clang' => $clang), true);
     $completed = $this->getController()->render('/admin/templates/templateeditor_completed_view', array('clang' => $clang), true);
     $assessments = $this->getController()->render('/admin/templates/templateeditor_assessments_view', array('clang' => $clang), true);
     $printoutput = $this->getController()->render('/admin/templates/templateeditor_printoutput_view', array('clang' => $clang), true);
     $totalquestions = '10';
     $surveyformat = 'Format';
     $notanswered = '5';
     $privacy = '';
     $surveyid = '1295';
     $token = 1234567;
     $templatedir = getTemplatePath($templatename);
     $templateurl = getTemplateURL($templatename);
     // Save these variables in an array
     $aData['thissurvey'] = $thissurvey;
     $aData['percentcomplete'] = $percentcomplete;
     $aData['groupname'] = $groupname;
     $aData['groupdescription'] = $groupdescription;
     $aData['navigator'] = $navigator;
     $aData['help'] = $clang->gT("This is some help text.");
     $aData['surveyformat'] = $surveyformat;
     $aData['totalquestions'] = $totalquestions;
     $aData['completed'] = $completed;
     $aData['notanswered'] = $notanswered;
     $aData['privacy'] = $privacy;
     $aData['surveyid'] = $surveyid;
     $aData['sid'] = $surveyid;
     $aData['token'] = $token;
     $aData['assessments'] = $assessments;
     $aData['printoutput'] = $printoutput;
     $aData['templatedir'] = $templatedir;
     $aData['templateurl'] = $templateurl;
     $aData['templatename'] = $templatename;
     $aData['screenname'] = $screenname;
     $aData['editfile'] = $editfile;
     $myoutput[] = "";
     switch ($screenname) {
         case 'surveylist':
             unset($files);
             $surveylist = array("nosid" => $clang->gT("You have not provided a survey identification number"), "contact" => sprintf($clang->gT("Please contact %s ( %s ) for further assistance."), Yii::app()->getConfig("siteadminname"), Yii::app()->getConfig("siteadminemail")), "listheading" => $clang->gT("The following surveys are available:"), "list" => $this->getController()->render('/admin/templates/templateeditor_surveylist_view', array(), true));
             $aData['surveylist'] = $surveylist;
             $myoutput[] = "";
             foreach ($SurveyList as $qs) {
                 $files[] = array("name" => $qs);
                 $myoutput = array_merge($myoutput, doreplacement(getTemplatePath($templatename) . "/{$qs}", $aData));
             }
             break;
         case 'question':
             unset($files);
             foreach ($Question as $qs) {
                 $files[] = array("name" => $qs);
             }
             $myoutput[] = $this->getController()->render('/admin/templates/templateeditor_question_meta_view', array('clang' => $clang), true);
             $myoutput = array_merge($myoutput, doreplacement(getTemplatePath($templatename) . "/startpage.pstpl", $aData));
             $myoutput = array_merge($myoutput, doreplacement(getTemplatePath($templatename) . "/survey.pstpl", $aData));
             $myoutput = array_merge($myoutput, doreplacement(getTemplatePath($templatename) . "/startgroup.pstpl", $aData));
             $myoutput = array_merge($myoutput, doreplacement(getTemplatePath($templatename) . "/groupdescription.pstpl", $aData));
             $question = array('all' => $clang->gT("How many roads must a man walk down?"), 'text' => $clang->gT("How many roads must a man walk down?"), 'code' => '1a', 'help' => 'helpful text', 'mandatory' => $clang->gT("*"), 'man_class' => ' mandatory', 'man_message' => '', 'valid_message' => '', 'file_valid_message' => '', 'essentials' => 'id="question1"', 'class' => 'list-radio', 'input_error_class' => '', 'number' => '1', 'type' => 'L');
             $aData['question'] = $question;
             $answer = $this->getController()->render('/admin/templates/templateeditor_question_answer_view', array('clang' => $clang), true);
             $aData['answer'] = $answer;
             $myoutput = array_merge($myoutput, doreplacement(getTemplatePath($templatename) . "/question.pstpl", $aData));
             $answer = $this->getController()->render('/admin/templates/templateeditor_question_answer_view', array('alt' => true, 'clang' => $clang), true);
             $aData['answer'] = $answer;
             $question = array('all' => $clang->gT("Please explain something in detail:"), 'text' => $clang->gT('Please explain something in detail:'), 'code' => '2a', 'help' => '', 'mandatory' => '', 'man_message' => '', 'valid_message' => '', 'file_valid_message' => '', 'essentials' => 'id="question2"', 'class' => 'text-long', 'man_class' => 'mandatory', 'input_error_class' => '', 'number' => '2', 'type' => 'T');
             $aData['question'] = $question;
             $myoutput = array_merge($myoutput, doreplacement(getTemplatePath($templatename) . "/question.pstpl", $aData));
             $myoutput = array_merge($myoutput, doreplacement(getTemplatePath($templatename) . "/endgroup.pstpl", $aData));
             $myoutput = array_merge($myoutput, doreplacement(getTemplatePath($templatename) . "/navigator.pstpl", $aData));
             $myoutput = array_merge($myoutput, doreplacement(getTemplatePath($templatename) . "/endpage.pstpl", $aData));
             break;
         case 'welcome':
             unset($files);
             $myoutput[] = "";
             foreach ($Welcome as $qs) {
                 $files[] = array("name" => $qs);
                 $myoutput = array_merge($myoutput, doreplacement(getTemplatePath($templatename) . "/{$qs}", $aData));
             }
             break;
         case 'register':
             unset($files);
             foreach ($Register as $qs) {
                 $files[] = array("name" => $qs);
             }
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/startpage.pstpl"), array(), $aData);
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/survey.pstpl"), array(), $aData);
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/register.pstpl"), array(), $aData);
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/endpage.pstpl"), array(), $aData);
             $myoutput[] = "\n";
             break;
         case 'save':
             unset($files);
             foreach ($Save as $qs) {
                 $files[] = array("name" => $qs);
             }
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/startpage.pstpl"), array(), $aData);
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/save.pstpl"), array(), $aData);
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/endpage.pstpl"), array(), $aData);
             $myoutput[] = "\n";
             break;
         case 'load':
             unset($files);
             foreach ($Load as $qs) {
                 $files[] = array("name" => $qs);
             }
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/startpage.pstpl"), array(), $aData);
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/load.pstpl"), array(), $aData);
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/endpage.pstpl"), array(), $aData);
             $myoutput[] = "\n";
             break;
         case 'clearall':
             unset($files);
             foreach ($Clearall as $qs) {
                 $files[] = array("name" => $qs);
             }
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/startpage.pstpl"), array(), $aData);
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/clearall.pstpl"), array(), $aData);
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/endpage.pstpl"), array(), $aData);
             $myoutput[] = "\n";
             break;
         case 'completed':
             unset($files);
             $myoutput[] = "";
             foreach ($CompletedTemplate as $qs) {
                 $files[] = array("name" => $qs);
                 $myoutput = array_merge($myoutput, doreplacement(getTemplatePath($templatename) . "/{$qs}", $aData));
             }
             break;
         case 'printablesurvey':
             unset($files);
             foreach ($printablesurveytemplate as $qs) {
                 $files[] = array("name" => $qs);
             }
             $questionoutput = array();
             foreach (file("{$templatedir}/print_question.pstpl") as $op) {
                 $questionoutput[] = templatereplace($op, array('QUESTION_NUMBER' => '1', 'QUESTION_CODE' => 'Q1', 'QUESTION_MANDATORY' => $clang->gT('*'), 'QUESTION_SCENARIO' => 'Only answer this if certain conditions are met.', 'QUESTION_CLASS' => ' mandatory list-radio', 'QUESTION_TYPE_HELP' => $clang->gT('Please choose *only one* of the following:'), 'QUESTION_MAN_MESSAGE' => '', 'QUESTION_VALID_MESSAGE' => '', 'QUESTION_FILE_VALID_MESSAGE' => '', 'QUESTION_TEXT' => $clang->gT('This is a sample question text. The user was asked to pick an entry.'), 'QUESTIONHELP' => $clang->gT('This is some help text for this question.'), 'ANSWER' => $this->getController()->render('/admin/templates/templateeditor_printablesurvey_quesanswer_view', array('templateurl' => $templateurl, 'clang' => $clang), true)), $aData);
             }
             $groupoutput = array();
             $groupoutput[] = templatereplace(file_get_contents("{$templatedir}/print_group.pstpl"), array('QUESTIONS' => implode(' ', $questionoutput)), $aData);
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/print_survey.pstpl"), array('GROUPS' => implode(' ', $groupoutput), 'FAX_TO' => $clang->gT("Please fax your completed survey to:") . " 000-000-000", 'SUBMIT_TEXT' => $clang->gT("Submit your survey."), 'HEADELEMENTS' => getPrintableHeader(), 'SUBMIT_BY' => sprintf($clang->gT("Please submit by %s"), date('d.m.y')), 'THANKS' => $clang->gT('Thank you for completing this survey.'), 'END' => $clang->gT('This is the survey end message.')), $aData);
             break;
         case 'printanswers':
             unset($files);
             foreach ($printtemplate as $qs) {
                 $files[] = array("name" => $qs);
             }
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/startpage.pstpl"), array(), $aData);
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/printanswers.pstpl"), array('ANSWERTABLE' => $printoutput), $aData);
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/endpage.pstpl"), array(), $aData);
             $myoutput[] = "\n";
             break;
     }
     $myoutput[] = "</html>";
     if (is_array($files)) {
         $match = 0;
         foreach ($files as $f) {
             if ($editfile == $f["name"]) {
                 $match = 1;
             }
         }
         foreach ($cssfiles as $f) {
             if ($editfile == $f["name"]) {
                 $match = 1;
             }
         }
         if ($match == 0) {
             if (count($files) > 0) {
                 $editfile = $files[0]["name"];
             } else {
                 $editfile = "";
             }
         }
     }
     // Get list of 'otherfiles'
     $otherfiles = array();
     if ($handle = opendir($templatedir)) {
         while (false !== ($file = readdir($handle))) {
             if (!array_search($file, $normalfiles)) {
                 if (!is_dir($templatedir . DIRECTORY_SEPARATOR . $file)) {
                     $otherfiles[] = array("name" => $file);
                 }
             }
         }
         closedir($handle);
     }
     $aData['clang'] = $this->getController()->lang;
     $aData['codelanguage'] = $codelanguage;
     $aData['highlighter'] = $highlighter;
     $aData['screens'] = $screens;
     $aData['templatename'] = $templatename;
     $aData['templates'] = $templates;
     $aData['editfile'] = $editfile;
     $aData['screenname'] = $screenname;
     $aData['tempdir'] = Yii::app()->getConfig('tempdir');
     $aData['usertemplaterootdir'] = Yii::app()->getConfig('usertemplaterootdir');
     $aViewUrls['templateeditorbar_view'][] = $aData;
     if ($showsummary) {
         $aViewUrls = array_merge($aViewUrls, $this->_templatesummary($templatename, $screenname, $editfile, $templates, $files, $cssfiles, $otherfiles, $myoutput));
     }
     App()->getClientScript()->registerScriptFile(Yii::app()->getConfig('adminscripts') . 'admin_core.js');
     return $aViewUrls;
 }
/**
* This function replaces keywords in a text and is mainly intended for templates
* If you use this functions put your replacement strings into the $replacements variable
* instead of using global variables
* NOTE - Don't do any embedded replacements in this function.  Create the array of replacement values and
* they will be done in batch at the end
*
* @param mixed $line Text to search in
* @param mixed $replacements Array of replacements:  Array( <stringtosearch>=><stringtoreplacewith>
* @param boolean $anonymized Determines if token data is being used or just replaced with blanks
* @param questionNum - needed to support dynamic JavaScript-based tailoring within questions
* @param bStaticReplacement - Default off, forces non-dynamic replacements without <SPAN> tags (e.g. for the Completed page)
* @return string  Text with replaced strings
*/
function templatereplace($line, $replacements = array(), &$redata = array(), $debugSrc = 'Unspecified', $anonymized = false, $questionNum = NULL, $registerdata = array(), $bStaticReplacement = false, $oTemplate = '')
{
    /*
    global $clienttoken,$token,$sitename,$move,$showxquestions,$showqnumcode,$questioncode;
    global $s_lang,$errormsg,$saved_id, $languagechanger,$captchapath,$loadname;
    */
    /*
    $allowedvars = array('surveylist', 'sitename', 'clienttoken', 'rooturl', 'thissurvey', 'imageurl', 'defaulttemplate',
    'percentcomplete', 'move', 'groupname', 'groupdescription', 'question', 'showxquestions',
    'showgroupinfo', 'showqnumcode', 'questioncode', 'answer', 'navigator', 'help', 'totalquestions',
    'surveyformat', 'completed', 'notanswered', 'privacy', 'surveyid', 'publicurl',
    'templatedir', 'token', 'assessments', 's_lang', 'errormsg', 'saved_id', 'usertemplaterootdir',
    'languagechanger', 'printoutput', 'captchapath', 'loadname');
    */
    $allowedvars = array('assessments', 'captchapath', 'clienttoken', 'completed', 'errormsg', 'groupdescription', 'groupname', 'imageurl', 'languagechanger', 'loadname', 'move', 'navigator', 'moveprevbutton', 'movenextbutton', 'percentcomplete', 'privacy', 's_lang', 'saved_id', 'showgroupinfo', 'showqnumcode', 'showxquestions', 'sitename', 'sitelogo', 'surveylist', 'templatedir', 'thissurvey', 'token', 'totalBoilerplatequestions', 'totalquestions', 'questionindex', 'questionindexmenu');
    $varsPassed = array();
    foreach ($allowedvars as $var) {
        if (isset($redata[$var])) {
            ${$var} = $redata[$var];
            $varsPassed[] = $var;
        }
    }
    //    if (count($varsPassed) > 0) {
    //        log_message('debug', 'templatereplace() called from ' . $debugSrc . ' contains: ' . implode(', ', $varsPassed));
    //    }
    //    if (isset($redata['question'])) {
    //        LimeExpressionManager::ShowStackTrace('has QID and/or SGA',$allowedvars);
    //    }
    //    extract($redata);   // creates variables for each of the keys in the array
    // Local over-rides in case not set above
    if (!isset($showgroupinfo)) {
        $showgroupinfo = Yii::app()->getConfig('showgroupinfo');
    }
    if (!isset($showqnumcode)) {
        $showqnumcode = Yii::app()->getConfig('showqnumcode');
    }
    $_surveyid = Yii::app()->getConfig('surveyID');
    if (!isset($showxquestions)) {
        $showxquestions = Yii::app()->getConfig('showxquestions');
    }
    if (!isset($s_lang)) {
        $s_lang = isset(Yii::app()->session['survey_' . $_surveyid]['s_lang']) ? Yii::app()->session['survey_' . $_surveyid]['s_lang'] : 'en';
    }
    if ($_surveyid && !isset($thissurvey)) {
        $thissurvey = getSurveyInfo($_surveyid, $s_lang);
    }
    if (!isset($captchapath)) {
        $captchapath = '';
    }
    if (!isset($sitename)) {
        $sitename = Yii::app()->getConfig('sitename');
    }
    if (!isset($saved_id) && isset(Yii::app()->session['survey_' . $_surveyid]['srid'])) {
        $saved_id = Yii::app()->session['survey_' . $_surveyid]['srid'];
    }
    Yii::app()->loadHelper('surveytranslator');
    if (isset($thissurvey['sid'])) {
        $surveyid = $thissurvey['sid'];
    }
    // lets sanitize the survey template
    if (isset($thissurvey['templatedir'])) {
        $templatename = $thissurvey['templatedir'];
    } else {
        $templatename = Yii::app()->getConfig('defaulttemplate');
    }
    if (!isset($templatedir)) {
        $templatedir = getTemplatePath($templatename);
    }
    if (!isset($templateurl)) {
        $templateurl = getTemplateURL($templatename) . "/";
    }
    if (!$anonymized && isset($thissurvey['anonymized'])) {
        $anonymized = $thissurvey['anonymized'] == "Y";
    }
    // TEMPLATECSS
    $_templatecss = "";
    $_templatejs = "";
    /**
     * Template css/js files from the template config files are loaded.
     * It use the asset manager (so user never need to empty the cache, even if template is updated)
     * If debug mode is on, no asset manager is used.
     *
     * oTemplate is defined in controller/survey/index
     *
     * If templatereplace is called from the template editor, a $oTemplate is provided.
     */
    $oTemplate = Template::model()->getInstance($templatename);
    $aCssFiles = $oTemplate->config->files->css->filename;
    $aJsFiles = $oTemplate->config->files->js->filename;
    $aOtherFiles = $oTemplate->otherFiles;
    //var_dump($aOtherFiles); die();
    if (stripos($line, "{TEMPLATECSS}")) {
        // If the template has files for css, we can't publish the files one by one, but we must publish them as a whole directory
        // TODO : extend asset manager so it check for file modification even in directory mode
        if (!YII_DEBUG || count($aOtherFiles) < 0) {
            foreach ($aCssFiles as $sCssFile) {
                if (file_exists($oTemplate->path . DIRECTORY_SEPARATOR . $sCssFile)) {
                    Yii::app()->getClientScript()->registerCssFile(App()->getAssetManager()->publish($oTemplate->path . DIRECTORY_SEPARATOR . $sCssFile), $sCssFile['media']);
                }
            }
        } else {
            foreach ($aCssFiles as $sCssFile) {
                if (file_exists($oTemplate->path . DIRECTORY_SEPARATOR . $sCssFile)) {
                    Yii::app()->getClientScript()->registerCssFile("{$templateurl}{$sCssFile}", $sCssFile['media']);
                }
            }
        }
        /* RTL CSS */
        if (getLanguageRTL(App()->language)) {
            $aCssFiles = (array) $oTemplate->config->files->rtl->css->filename;
            if (!YII_DEBUG) {
                foreach ($aCssFiles as $sCssFile) {
                    if (file_exists($oTemplate->path . DIRECTORY_SEPARATOR . $sCssFile)) {
                        Yii::app()->getClientScript()->registerCssFile(App()->getAssetManager()->publish($oTemplate->path . DIRECTORY_SEPARATOR . $sCssFile), $sCssFile['media']);
                    }
                }
            } else {
                foreach ($aCssFiles as $sCssFile) {
                    if (file_exists($oTemplate->path . DIRECTORY_SEPARATOR . $sCssFile)) {
                        Yii::app()->getClientScript()->registerCssFile("{$templateurl}{$sCssFile}", $sCssFile['media']);
                    }
                }
            }
        }
    }
    if (stripos($line, "{TEMPLATEJS}")) {
        if (!YII_DEBUG) {
            foreach ($aJsFiles as $sJsFile) {
                if (file_exists($oTemplate->path . DIRECTORY_SEPARATOR . $sJsFile)) {
                    App()->getClientScript()->registerScriptFile(App()->getAssetManager()->publish($oTemplate->path . DIRECTORY_SEPARATOR . $sJsFile));
                }
            }
        } else {
            foreach ($aJsFiles as $sJsFile) {
                if (file_exists($oTemplate->path . DIRECTORY_SEPARATOR . $sJsFile)) {
                    Yii::app()->getClientScript()->registerScriptFile("{$templateurl}{$sJsFile}");
                }
            }
        }
        /* RTL JS */
        if (getLanguageRTL(App()->language)) {
            $aJsFiles = (array) $oTemplate->config->files->rtl->js->filename;
            if (!YII_DEBUG) {
                foreach ($aJsFiles as $aJsFile) {
                    if (file_exists($oTemplate->path . DIRECTORY_SEPARATOR . $aJsFile)) {
                        App()->getClientScript()->registerScriptFile(App()->getAssetManager()->publish($oTemplate->path . DIRECTORY_SEPARATOR . $aJsFile));
                    }
                }
            } else {
                foreach ($aJsFiles as $sJsFile) {
                    if (file_exists($oTemplate->path . DIRECTORY_SEPARATOR . $sJsFile)) {
                        Yii::app()->getClientScript()->registerScriptFile("{$templateurl}{$sJsFile}");
                    }
                }
            }
        }
    }
    // surveyformat
    if (isset($thissurvey['format'])) {
        $surveyformat = str_replace(array("A", "S", "G"), array("allinone", "questionbyquestion", "groupbygroup"), $thissurvey['format']);
    } else {
        $surveyformat = "";
    }
    if ($oTemplate->config->engine->cssframework) {
        $surveyformat .= " " . $oTemplate->config->engine->cssframework . "-engine ";
    }
    if (isset(Yii::app()->session['step']) && Yii::app()->session['step'] % 2 && $surveyformat != "allinone") {
        $surveyformat .= " page-odd";
    }
    if (isset($thissurvey['questionindex']) && $thissurvey['questionindex'] > 0 && $surveyformat != "allinone" && (isset(Yii::app()->session['step']) && Yii::app()->session['step'] > 0)) {
        $surveyformat .= " withindex";
    }
    if (isset($thissurvey['showprogress']) && $thissurvey['showprogress'] == "Y") {
        $surveyformat .= " showprogress";
    }
    if (isset($thissurvey['showqnumcode'])) {
        $surveyformat .= " showqnumcode-" . $thissurvey['showqnumcode'];
    }
    // real survey contact
    if (isset($surveylist) && isset($surveylist['contact'])) {
        $surveycontact = $surveylist['contact'];
    } elseif (isset($surveylist) && isset($thissurvey['admin']) && $thissurvey['admin'] != "") {
        $surveycontact = sprintf(gT("Please contact %s ( %s ) for further assistance."), $thissurvey['admin'], $thissurvey['adminemail']);
    } else {
        $surveycontact = "";
    }
    // If there are non-bracketed replacements to be made do so above this line.
    // Only continue in this routine if there are bracketed items to replace {}
    if (strpos($line, "{") === false) {
        // process string anyway so that it can be pretty-printed
        return LimeExpressionManager::ProcessString($line, $questionNum, NULL, false, 1, 1, true);
    }
    if ($showgroupinfo == 'both' || $showgroupinfo == 'name' || $showgroupinfo == 'choose' && !isset($thissurvey['showgroupinfo']) || $showgroupinfo == 'choose' && $thissurvey['showgroupinfo'] == 'B' || $showgroupinfo == 'choose' && $thissurvey['showgroupinfo'] == 'N') {
        $_groupname = isset($groupname) ? $groupname : '';
    } else {
        $_groupname = '';
    }
    if ($showgroupinfo == 'both' || $showgroupinfo == 'description' || $showgroupinfo == 'choose' && !isset($thissurvey['showgroupinfo']) || $showgroupinfo == 'choose' && $thissurvey['showgroupinfo'] == 'B' || $showgroupinfo == 'choose' && $thissurvey['showgroupinfo'] == 'D') {
        $_groupdescription = isset($groupdescription) ? $groupdescription : '';
    } else {
        $_groupdescription = '';
    }
    if (!isset($totalquestions)) {
        $totalquestions = 0;
    }
    $_totalquestionsAsked = $totalquestions;
    if ($showxquestions == 'show' || $showxquestions == 'choose' && !isset($thissurvey['showxquestions']) || $showxquestions == 'choose' && $thissurvey['showxquestions'] == 'Y') {
        if ($_totalquestionsAsked < 1) {
            $_therearexquestions = gT("There are no questions in this survey");
            // Singular
        } elseif ($_totalquestionsAsked == 1) {
            $_therearexquestions = gT("There is 1 question in this survey");
            //Singular
        } else {
            $_therearexquestions = gT("There are {NUMBEROFQUESTIONS} questions in this survey.");
            //Note this line MUST be before {NUMBEROFQUESTIONS}
        }
    } else {
        $_therearexquestions = '';
    }
    if (isset($token)) {
        $_token = $token;
    } elseif (isset($clienttoken)) {
        $_token = htmlentities($clienttoken, ENT_QUOTES, 'UTF-8');
        // or should it be URL-encoded?
    } else {
        $_token = '';
    }
    // Expiry
    if (isset($thissurvey['expiry'])) {
        $dateformatdetails = getDateFormatData($thissurvey['surveyls_dateformat']);
        Yii::import('application.libraries.Date_Time_Converter', true);
        $datetimeobj = new Date_Time_Converter($thissurvey['expiry'], "Y-m-d");
        $_dateoutput = $datetimeobj->convert($dateformatdetails['phpdate']);
    } else {
        $_dateoutput = '-';
    }
    $_submitbutton = "<input class='submit btn btn-default' type='submit' value=' " . gT("Submit") . " ' name='move2' onclick=\"javascript:document.limesurvey.move.value = 'movesubmit';\" />";
    if (isset($thissurvey['surveyls_url']) and $thissurvey['surveyls_url'] != "") {
        if (trim($thissurvey['surveyls_urldescription']) != '') {
            $_linkreplace = "<a href='{$thissurvey['surveyls_url']}'>{$thissurvey['surveyls_urldescription']}</a>";
        } else {
            $_linkreplace = "<a href='{$thissurvey['surveyls_url']}'>{$thissurvey['surveyls_url']}</a>";
        }
    } else {
        $_linkreplace = '';
    }
    if (isset($thissurvey['sid']) && isset($_SESSION['survey_' . $thissurvey['sid']]['srid']) && $thissurvey['active'] == 'Y') {
        $iscompleted = SurveyDynamic::model($surveyid)->isCompleted($_SESSION['survey_' . $thissurvey['sid']]['srid']);
    } else {
        $iscompleted = false;
    }
    if (isset($surveyid) && !$iscompleted) {
        $_clearall = CHtml::htmlButton(gT("Exit and clear survey"), array('type' => 'submit', 'id' => "clearall", 'value' => 'clearall', 'name' => 'clearall', 'class' => 'clearall button  btn btn-default btn-lg  col-xs-4 hidden', 'data-confirmedby' => 'confirm-clearall', 'title' => gT("This action need confirmation.")));
        $_clearall .= CHtml::checkBox("confirm-clearall", false, array('id' => 'confirm-clearall', 'value' => 'confirm', 'class' => 'hide jshide  btn btn-default btn-lg  col-xs-4'));
        $_clearall .= CHtml::label(gT("Are you sure you want to clear all your responses?"), 'confirm-clearall', array('class' => 'hide jshide  btn btn-default btn-lg  col-xs-4'));
        $_clearalllinks = '<li><a href="#" id="clearallbtnlink">' . gT("Exit and clear survey") . '</a></li>';
    } else {
        $_clearall = "";
        $_clearalllinks = '';
    }
    if (isset(Yii::app()->session['datestamp'])) {
        $_datestamp = Yii::app()->session['datestamp'];
    } else {
        $_datestamp = '-';
    }
    if (isset($thissurvey['allowsave']) and $thissurvey['allowsave'] == "Y") {
        $_saveall = doHtmlSaveAll(isset($move) ? $move : NULL);
        $_savelinks = doHtmlSaveLinks(isset($move) ? $move : NULL);
    } else {
        $_saveall = "";
        $_savelinks = "";
    }
    if (isset($thissurvey['allowprev']) && $thissurvey['allowprev'] == "N") {
        $_strreview = "";
    } else {
        $_strreview = gT("If you want to check any of the answers you have made, and/or change them, you can do that now by clicking on the [<< prev] button and browsing through your responses.");
    }
    if (isset($surveyid)) {
        $restartparam = array();
        if ($_token) {
            $restartparam['token'] = sanitize_token($_token);
        }
        // urlencode with needed with sanitize_token
        if (Yii::app()->request->getQuery('lang')) {
            $restartparam['lang'] = sanitize_languagecode(Yii::app()->request->getQuery('lang'));
        } elseif ($s_lang) {
            $restartparam['lang'] = $s_lang;
        }
        $restartparam['newtest'] = "Y";
        $restarturl = Yii::app()->getController()->createUrl("survey/index/sid/{$surveyid}", $restartparam);
        $_restart = "<a href='{$restarturl}'>" . gT("Restart this Survey") . "</a>";
    } else {
        $_restart = "";
    }
    if (isset($thissurvey['anonymized']) && $thissurvey['anonymized'] == 'Y') {
        $_savealert = gT("To remain anonymous please use a pseudonym as your username, also an email address is not required.");
    } else {
        $_savealert = "";
    }
    if (isset($surveyid)) {
        if ($_token) {
            $returnlink = Yii::app()->getController()->createUrl("survey/index/sid/{$surveyid}", array('token' => Token::sanitizeToken($_token)));
        } else {
            $returnlink = Yii::app()->getController()->createUrl("survey/index/sid/{$surveyid}");
        }
        $_return_to_survey = "<a href='{$returnlink}'>" . gT("Return to survey") . "</a>";
    } else {
        $_return_to_survey = "";
    }
    // Save Form
    $_saveform = "<table class='save-survey-form'><tr class='save-survey-row save-survey-name'><td class='save-survey-label label-cell' align='right'><label for='savename'>" . gT("Name") . "</label>:</td><td class='save-survey-input input-cell'><input type='text' name='savename' id='savename' value='";
    if (isset($_POST['savename'])) {
        $_saveform .= HTMLEscape(autoUnescape($_POST['savename']));
    }
    $_saveform .= "' /></td></tr>\n" . "<tr class='save-survey-row save-survey-password-1'><td class='save-survey-label label-cell' align='right'><label for='savepass'>" . gT("Password") . "</label>:</td><td class='save-survey-input input-cell'><input type='password' id='savepass' name='savepass' value='";
    if (isset($_POST['savepass'])) {
        $_saveform .= HTMLEscape(autoUnescape($_POST['savepass']));
    }
    $_saveform .= "' /></td></tr>\n" . "<tr class='save-survey-row save-survey-password-2'><td class='save-survey-label label-cell' align='right'><label for='savepass2'>" . gT("Repeat password") . "</label>:</td><td class='save-survey-input input-cell'><input type='password' id='savepass2' name='savepass2' value='";
    if (isset($_POST['savepass2'])) {
        $_saveform .= HTMLEscape(autoUnescape($_POST['savepass2']));
    }
    $_saveform .= "' /></td></tr>\n" . "<tr class='save-survey-row save-survey-email'><td class='save-survey-label label-cell' align='right'><label for='saveemail'>" . gT("Your email address") . "</label>:</td><td class='save-survey-input input-cell'><input type='text' id='saveemail' name='saveemail' value='";
    if (isset($_POST['saveemail'])) {
        $_saveform .= HTMLEscape(autoUnescape($_POST['saveemail']));
    }
    $_saveform .= "' /></td></tr>\n";
    if (isset($thissurvey['usecaptcha']) && function_exists("ImageCreate") && isCaptchaEnabled('saveandloadscreen', $thissurvey['usecaptcha'])) {
        $_saveform .= "<tr class='save-survey-row save-survey-captcha'><td class='save-survey-label label-cell' align='right'><label for='loadsecurity'>" . gT("Security question") . "</label>:</td><td class='save-survey-input input-cell'><table class='captcha-table'><tr><td class='captcha-image' valign='middle'><img alt='' src='" . Yii::app()->getController()->createUrl('/verification/image/sid/' . (isset($surveyid) ? $surveyid : '')) . "' /></td><td class='captcha-input' valign='middle' style='text-align:left'><input type='text' size='5' maxlength='3' id='loadsecurity' name='loadsecurity' value='' /></td></tr></table></td></tr>\n";
    }
    $_saveform .= "<tr><td align='right'></td><td></td></tr>\n" . "<tr class='save-survey-row save-survey-submit'><td class='save-survey-label label-cell'><label class='hide jshide' for='savebutton'>" . gT("Save Now") . "</label></td><td class='save-survey-input input-cell'><input type='submit' id='savebutton' name='savesubmit' class='button' value='" . gT("Save Now") . "' /></td></tr>\n" . "</table>";
    // Load Form
    $_loadform = "<table class='load-survey-form'><tr class='load-survey-row load-survey-name'><td class='load-survey-label label-cell' align='right'><label for='loadname'>" . gT("Saved name") . "</label>:</td><td class='load-survey-input input-cell'><input type='text' id='loadname' name='loadname' value='";
    if (isset($loadname)) {
        $_loadform .= HTMLEscape(autoUnescape($loadname));
    }
    $_loadform .= "' /></td></tr>\n" . "<tr class='load-survey-row load-survey-password'><td class='load-survey-label label-cell' align='right'><label for='loadpass'>" . gT("Password") . "</label>:</td><td class='load-survey-input input-cell'><input type='password' id='loadpass' name='loadpass' value='";
    if (isset($loadpass)) {
        $_loadform .= HTMLEscape(autoUnescape($loadpass));
    }
    $_loadform .= "' /></td></tr>\n";
    if (isset($thissurvey['usecaptcha']) && function_exists("ImageCreate") && isCaptchaEnabled('saveandloadscreen', $thissurvey['usecaptcha'])) {
        $_loadform .= "<tr class='load-survey-row load-survey-captcha'><td class='load-survey-label label-cell' align='right'><label for='loadsecurity'>" . gT("Security question") . "</label>:</td><td class='load-survey-input input-cell'><table class='captcha-table'><tr><td class='captcha-image' valign='middle'><img src='" . Yii::app()->getController()->createUrl('/verification/image/sid/' . (isset($surveyid) ? $surveyid : '')) . "' alt='' /></td><td class='captcha-input' valign='middle'><input type='text' size='5' maxlength='3' id='loadsecurity' name='loadsecurity' value='' alt=''/></td></tr></table></td></tr>\n";
    }
    $_loadform .= "<tr class='load-survey-row load-survey-submit'><td class='load-survey-label label-cell'><label class='hide jshide' for='loadbutton'>" . gT("Load now") . "</label></td><td class='load-survey-input input-cell'><input type='submit' id='loadbutton' class='button' value='" . gT("Load now") . "' /></td></tr></table>\n";
    // Assessments
    $assessmenthtml = "";
    if (isset($surveyid) && !is_null($surveyid) && function_exists('doAssessment')) {
        $assessmentdata = doAssessment($surveyid, true);
        $_assessment_current_total = $assessmentdata['total'];
        if (stripos($line, "{ASSESSMENTS}")) {
            $assessmenthtml = doAssessment($surveyid, false);
        }
    } else {
        $_assessment_current_total = '';
    }
    if (isset($thissurvey['googleanalyticsapikey']) && trim($thissurvey['googleanalyticsapikey']) != '') {
        $_googleAnalyticsAPIKey = trim($thissurvey['googleanalyticsapikey']);
    } else {
        $_googleAnalyticsAPIKey = trim(getGlobalSetting('googleanalyticsapikey'));
    }
    $_googleAnalyticsStyle = isset($thissurvey['googleanalyticsstyle']) ? $thissurvey['googleanalyticsstyle'] : '0';
    $_googleAnalyticsJavaScript = '';
    if ($_googleAnalyticsStyle != '' && $_googleAnalyticsStyle != 0 && $_googleAnalyticsAPIKey != '') {
        switch ($_googleAnalyticsStyle) {
            case '1':
                // Default Google Tracking
                $_googleAnalyticsJavaScript = <<<EOD
<script>
(function(i,s,o,g,r,a,m){ i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments) },i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');

ga('create', '{$_googleAnalyticsAPIKey}', 'auto');  // Replace with your property ID.
ga('send', 'pageview');

</script>

EOD;
                break;
            case '2':
                // SurveyName-[SID]/[GSEQ]-GroupName - create custom GSEQ based upon page step
                $moveInfo = LimeExpressionManager::GetLastMoveResult();
                if (is_null($moveInfo)) {
                    $gseq = 'welcome';
                } else {
                    if ($moveInfo['finished']) {
                        $gseq = 'finished';
                    } else {
                        if (isset($moveInfo['at_start']) && $moveInfo['at_start']) {
                            $gseq = 'welcome';
                        } else {
                            if (is_null($_groupname)) {
                                $gseq = 'printanswers';
                            } else {
                                $gseq = $moveInfo['gseq'] + 1;
                            }
                        }
                    }
                }
                $_trackURL = htmlspecialchars($thissurvey['name'] . '-[' . $surveyid . ']/[' . $gseq . ']-' . $_groupname);
                $_googleAnalyticsJavaScript = <<<EOD
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');

ga('create', '{$_googleAnalyticsAPIKey}', 'auto');  // Replace with your property ID.
ga('send', 'pageview');
ga('send', 'pageview', '{$_trackURL}');

</script>
EOD;
                break;
        }
    }
    $_endtext = '';
    if (isset($thissurvey['surveyls_endtext']) && trim($thissurvey['surveyls_endtext']) != '') {
        $_endtext = $thissurvey['surveyls_endtext'];
    }
    $sitelogo = !empty($oTemplate->siteLogo) ? '<img src="' . App()->getAssetManager()->publish($oTemplate->path . '/' . $oTemplate->siteLogo) . '"/>' : '';
    // Set the array of replacement variables here - don't include curly braces
    $coreReplacements = array();
    $coreReplacements['ACTIVE'] = isset($thissurvey['active']) && !($thissurvey['active'] != "Y");
    $coreReplacements['ANSWERSCLEARED'] = gT("Answers cleared");
    $coreReplacements['ASSESSMENTS'] = $assessmenthtml;
    $coreReplacements['ASSESSMENT_CURRENT_TOTAL'] = $_assessment_current_total;
    $coreReplacements['ASSESSMENT_HEADING'] = gT("Your assessment");
    $coreReplacements['CHECKJAVASCRIPT'] = "<noscript><span class='warningjs'>" . gT("Caution: JavaScript execution is disabled in your browser. You may not be able to answer all questions in this survey. Please, verify your browser parameters.") . "</span></noscript>";
    $coreReplacements['CLEARALL'] = $_clearall;
    $coreReplacements['CLEARALL_LINKS'] = $_clearalllinks;
    $coreReplacements['CLOSEWINDOW'] = '';
    // Obsolete tag - keep this line for compatibility reaons
    $coreReplacements['COMPLETED'] = isset($redata['completed']) ? $redata['completed'] : '';
    // global
    $coreReplacements['DATESTAMP'] = $_datestamp;
    $coreReplacements['ENDTEXT'] = $_endtext;
    $coreReplacements['EXPIRY'] = $_dateoutput;
    $coreReplacements['ADMINNAME'] = isset($thissurvey['admin']) ? $thissurvey['admin'] : '';
    $coreReplacements['ADMINEMAIL'] = isset($thissurvey['adminemail']) ? $thissurvey['adminemail'] : '';
    $coreReplacements['GID'] = Yii::app()->getConfig('gid', '');
    // Use the gid of the question, except if we are not in question (Randomization group name)
    $coreReplacements['GOOGLE_ANALYTICS_API_KEY'] = $_googleAnalyticsAPIKey;
    $coreReplacements['GOOGLE_ANALYTICS_JAVASCRIPT'] = $_googleAnalyticsJavaScript;
    $coreReplacements['GROUPDESCRIPTION'] = $_groupdescription;
    $coreReplacements['GROUPNAME'] = $_groupname;
    $coreReplacements['LANG'] = App()->language;
    $coreReplacements['LANGUAGECHANGER'] = isset($languagechanger) ? $languagechanger : '';
    // global
    $coreReplacements['LOADERROR'] = isset($errormsg) ? $errormsg : '';
    // global
    $coreReplacements['LOADFORM'] = $_loadform;
    $coreReplacements['LOADHEADING'] = gT("Load a previously saved survey");
    $coreReplacements['LOADMESSAGE'] = gT("You can load a survey that you have previously saved from this screen.") . "<br />" . gT("Type in the 'name' you used to save the survey, and the password.") . "<br />";
    $coreReplacements['NAVIGATOR'] = isset($navigator) ? $navigator : '';
    // global
    $coreReplacements['MOVEPREVBUTTON'] = isset($moveprevbutton) ? $moveprevbutton : '';
    // global
    $coreReplacements['MOVENEXTBUTTON'] = isset($movenextbutton) ? $movenextbutton : '';
    // global
    $coreReplacements['NOSURVEYID'] = isset($surveylist) ? $surveylist['nosid'] : '';
    $coreReplacements['NUMBEROFQUESTIONS'] = $_totalquestionsAsked;
    $coreReplacements['PERCENTCOMPLETE'] = isset($percentcomplete) ? $percentcomplete : '';
    // global
    $coreReplacements['PRIVACY'] = isset($privacy) ? $privacy : '';
    // global
    $coreReplacements['PRIVACYMESSAGE'] = "<span style='font-weight:bold; font-style: italic;'>" . gT("A Note On Privacy") . "</span><br />" . gT("This survey is anonymous.") . "<br />" . gT("The record of your survey responses does not contain any identifying information about you, unless a specific survey question explicitly asked for it.") . ' ' . gT("If you used an identifying token to access this survey, please rest assured that this token will not be stored together with your responses. It is managed in a separate database and will only be updated to indicate whether you did (or did not) complete this survey. There is no way of matching identification tokens with survey responses.");
    $coreReplacements['QUESTION_INDEX'] = isset($questionindex) ? $questionindex : '';
    $coreReplacements['QUESTION_INDEX_MENU'] = isset($questionindexmenu) ? $questionindexmenu : '';
    $coreReplacements['RESTART'] = $_restart;
    $coreReplacements['RETURNTOSURVEY'] = $_return_to_survey;
    $coreReplacements['SAVE_LINKS'] = $_savelinks;
    $coreReplacements['SAVE'] = $_saveall;
    $coreReplacements['SAVEALERT'] = $_savealert;
    $coreReplacements['SAVEDID'] = isset($saved_id) ? $saved_id : '';
    // global
    $coreReplacements['SAVEERROR'] = isset($errormsg) ? $errormsg : '';
    // global - same as LOADERROR
    $coreReplacements['SAVEFORM'] = $_saveform;
    $coreReplacements['SAVEHEADING'] = gT("Save your unfinished survey");
    $coreReplacements['SAVEMESSAGE'] = gT("Enter a name and password for this survey and click save below.") . "<br />\n" . gT("Your survey will be saved using that name and password, and can be completed later by logging in with the same name and password.") . "<br /><br />\n<span class='emailoptional'>" . gT("If you give an email address, an email containing the details will be sent to you.") . "</span><br /><br />\n" . gT("After having clicked the save button you can either close this browser window or continue filling out the survey.");
    $coreReplacements['SID'] = Yii::app()->getConfig('surveyID', '');
    // Allways use surveyID from config
    $coreReplacements['SITENAME'] = isset($sitename) ? $sitename : '';
    // global
    $coreReplacements['SITELOGO'] = $sitelogo;
    $coreReplacements['SUBMITBUTTON'] = $_submitbutton;
    $coreReplacements['SUBMITCOMPLETE'] = "<strong>" . gT("Thank you!") . "<br /><br />" . gT("You have completed answering the questions in this survey.") . "</strong><br /><br />" . gT("Click on 'Submit' now to complete the process and save your answers.");
    $coreReplacements['SUBMITREVIEW'] = $_strreview;
    $coreReplacements['SURVEYCONTACT'] = $surveycontact;
    $coreReplacements['SURVEYDESCRIPTION'] = isset($thissurvey['description']) ? $thissurvey['description'] : '';
    $coreReplacements['SURVEYFORMAT'] = isset($surveyformat) ? $surveyformat : '';
    // global
    $coreReplacements['SURVEYLANGUAGE'] = App()->language;
    $coreReplacements['SURVEYLIST'] = isset($surveylist) ? $surveylist['list'] : '';
    $coreReplacements['SURVEYLISTHEADING'] = isset($surveylist) ? $surveylist['listheading'] : '';
    $coreReplacements['SURVEYNAME'] = isset($thissurvey['name']) ? $thissurvey['name'] : '';
    $coreReplacements['SURVEYRESOURCESURL'] = isset($thissurvey['sid']) ? Yii::app()->getConfig("uploadurl") . '/surveys/' . $thissurvey['sid'] . '/' : '';
    $coreReplacements['TEMPLATECSS'] = $_templatecss;
    $coreReplacements['TEMPLATEJS'] = $_templatejs;
    $coreReplacements['TEMPLATEURL'] = $templateurl;
    $coreReplacements['THEREAREXQUESTIONS'] = $_therearexquestions;
    $coreReplacements['TOKEN'] = !$anonymized ? $_token : '';
    // Silently replace TOKEN by empty string
    $coreReplacements['URL'] = $_linkreplace;
    $coreReplacements['WELCOME'] = isset($thissurvey['welcome']) ? $thissurvey['welcome'] : '';
    if (!isset($replacements['QID'])) {
        Yii::import('application.helpers.SurveyRuntimeHelper');
        $coreReplacements = array_merge($coreReplacements, SurveyRuntimeHelper::getQuestionReplacement(null));
        // so $replacements overrides core values
    }
    if (!is_null($replacements) && is_array($replacements)) {
        $doTheseReplacements = array_merge($coreReplacements, $replacements);
        // so $replacements overrides core values
    } else {
        $doTheseReplacements = $coreReplacements;
    }
    // Now do all of the replacements - In rare cases, need to do 3 deep recursion, that that is default
    $line = LimeExpressionManager::ProcessString($line, $questionNum, $doTheseReplacements, false, 3, 1, false, true, $bStaticReplacement);
    return $line;
}
                        if (Permission::model()->hasGlobalPermission('superadmin','read') || Permission::model()->hasGlobalPermission('templates','read') || hasTemplateManageRights(Yii::app()->session["loginID"], $tname) == 1 || $esrow['template']==htmlspecialchars($tname) ) { ?>
                        <option value='<?php echo $tname; ?>'
                            <?php if ($esrow['template'] && htmlspecialchars($tname) == $esrow['template']) { ?>
                                selected='selected'
                                <?php   } elseif (!$esrow['template'] && $tname == Yii::app()->getConfig('defaulttemplate')) { ?>
                                selected='selected'
                                <?php } ?>
                            ><?php echo $tname; ?></option>
                        <?php }
                } ?>
            </select>
        </li>

        <li><label for='preview'><?php  eT("Template Preview:"); ?></label>
            <img alt='<?php  eT("Template preview image"); ?>' name='preview' id='preview' src='<?php echo getTemplateURL($esrow['template']); ?>/preview.png' />
        </li>


        <li><label for='showwelcome'><?php  eT("Show welcome screen?") ; ?></label>
            <select id='showwelcome' name='showwelcome'>
                <option value='Y'
                    <?php if (!$esrow['showwelcome'] || $esrow['showwelcome'] == "Y") { ?>
                        selected='selected'
                        <?php } ?>
                    ><?php  eT("Yes") ; ?>
                </option>
                <option value='N'
                    <?php if ($esrow['showwelcome'] == "N") { ?>
                        selected='selected'
                        <?php } ?>
 function actionAction($surveyid, $language = null)
 {
     $sLanguage = $language;
     ob_start(function ($buffer, $phase) {
         App()->getClientScript()->render($buffer);
         App()->getClientScript()->reset();
         return $buffer;
     });
     ob_implicit_flush(false);
     $iSurveyID = (int) $surveyid;
     //$postlang = returnglobal('lang');
     Yii::import('application.libraries.admin.progressbar', true);
     Yii::app()->loadHelper("admin/statistics");
     Yii::app()->loadHelper('database');
     Yii::app()->loadHelper('surveytranslator');
     App()->getClientScript()->registerPackage('jqueryui');
     App()->getClientScript()->registerPackage('jquery-touch-punch');
     App()->getClientScript()->registerScriptFile(Yii::app()->getConfig('generalscripts') . "survey_runtime.js");
     $data = array();
     if (!isset($iSurveyID)) {
         $iSurveyID = returnGlobal('sid');
     } else {
         $iSurveyID = (int) $iSurveyID;
     }
     if (!$iSurveyID) {
         //This next line ensures that the $iSurveyID value is never anything but a number.
         safeDie('You have to provide a valid survey ID.');
     }
     if ($iSurveyID) {
         $actresult = Survey::model()->findAll('sid = :sid AND active = :active', array(':sid' => $iSurveyID, ':active' => 'Y'));
         //Checked
         if (count($actresult) == 0) {
             safeDie('You have to provide a valid survey ID.');
         } else {
             $surveyinfo = getSurveyInfo($iSurveyID);
             // CHANGE JSW_NZ - let's get the survey title for display
             $thisSurveyTitle = $surveyinfo["name"];
             // CHANGE JSW_NZ - let's get css from individual template.css - so define path
             $thisSurveyCssPath = getTemplateURL($surveyinfo["template"]);
             if ($surveyinfo['publicstatistics'] != 'Y') {
                 safeDie('The public statistics for this survey are deactivated.');
             }
             //check if graphs should be shown for this survey
             if ($surveyinfo['publicgraphs'] == 'Y') {
                 $publicgraphs = 1;
             } else {
                 $publicgraphs = 0;
             }
         }
     }
     //we collect all the output within this variable
     $statisticsoutput = '';
     //for creating graphs we need some more scripts which are included here
     //True -> include
     //False -> forget about charts
     if (isset($publicgraphs) && $publicgraphs == 1) {
         require_once APPPATH . 'third_party/pchart/pchart/pChart.class';
         require_once APPPATH . 'third_party/pchart/pchart/pData.class';
         require_once APPPATH . 'third_party/pchart/pchart/pCache.class';
         $MyCache = new pCache(Yii::app()->getConfig("tempdir") . DIRECTORY_SEPARATOR);
         //$currentuser is created as prefix for pchart files
         if (isset($_SERVER['REDIRECT_REMOTE_USER'])) {
             $currentuser = $_SERVER['REDIRECT_REMOTE_USER'];
         } else {
             if (session_id()) {
                 $currentuser = substr(session_id(), 0, 15);
             } else {
                 $currentuser = "******";
             }
         }
     }
     // Set language for questions and labels to base language of this survey
     if ($sLanguage == null || !in_array($sLanguage, Survey::model()->findByPk($iSurveyID)->getAllLanguages())) {
         $sLanguage = Survey::model()->findByPk($iSurveyID)->language;
     } else {
         $sLanguage = sanitize_languagecode($sLanguage);
     }
     //set survey language for translations
     SetSurveyLanguage($iSurveyID, $sLanguage);
     //Create header
     sendCacheHeaders();
     $condition = false;
     $sitename = Yii::app()->getConfig("sitename");
     $data['surveylanguage'] = $sLanguage;
     $data['sitename'] = $sitename;
     $data['condition'] = $condition;
     $data['thisSurveyCssPath'] = $thisSurveyCssPath;
     /*
      * only show questions where question attribute "public_statistics" is set to "1"
      */
     $query = "SELECT q.* , group_name, group_order FROM {{questions}} q, {{groups}} g, {{question_attributes}} qa\n                    WHERE g.gid = q.gid AND g.language = :lang1 AND q.language = :lang2 AND q.sid = :surveyid AND q.qid = qa.qid AND q.parent_qid = 0 AND qa.attribute = 'public_statistics'";
     $databasetype = Yii::app()->db->getDriverName();
     if ($databasetype == 'mssql' || $databasetype == "sqlsrv" || $databasetype == "dblib") {
         $query .= " AND CAST(CAST(qa.value as varchar) as int)='1'\n";
     } else {
         $query .= " AND qa.value='1'\n";
     }
     //execute query
     $result = Yii::app()->db->createCommand($query)->bindParam(":lang1", $sLanguage, PDO::PARAM_STR)->bindParam(":lang2", $sLanguage, PDO::PARAM_STR)->bindParam(":surveyid", $iSurveyID, PDO::PARAM_INT)->queryAll();
     //store all the data in $rows
     $rows = $result;
     //SORT IN NATURAL ORDER!
     usort($rows, 'groupOrderThenQuestionOrder');
     //put the question information into the filter array
     foreach ($rows as $row) {
         //store some column names in $filters array
         $filters[] = array($row['qid'], $row['gid'], $row['type'], $row['title'], $row['group_name'], flattenText($row['question']));
     }
     //number of records for this survey
     $totalrecords = 0;
     //count number of answers
     $query = "SELECT count(*) FROM {{survey_" . intval($iSurveyID) . "}}";
     //if incompleted answers should be filtert submitdate has to be not null
     //this setting is taken from config-defaults.php
     if (Yii::app()->getConfig("filterout_incomplete_answers") == true) {
         $query .= " WHERE {{survey_" . intval($iSurveyID) . "}}.submitdate is not null";
     }
     $result = Yii::app()->db->createCommand($query)->queryAll();
     //$totalrecords = total number of answers
     foreach ($result as $row) {
         $totalrecords = reset($row);
     }
     //this is the array which we need later...
     $summary = array();
     //...while this is the array from copy/paste which we don't want to replace because this is a nasty source of error
     $allfields = array();
     //---------- CREATE SGQA OF ALL QUESTIONS WHICH USE "PUBLIC_STATISTICS" ----------
     /*
              * let's go through the filter array which contains
              *     ['qid'],
              ['gid'],
              ['type'],
              ['title'],
              ['group_name'],
              ['question'];
     */
     $currentgroup = '';
     // use to check if there are any question with public statistics
     if (isset($filters)) {
         foreach ($filters as $flt) {
             //SGQ identifier
             $myfield = "{$iSurveyID}X{$flt[1]}X{$flt[0]}";
             //let's switch through the question type for each question
             switch ($flt[2]) {
                 case "K":
                     // Multiple Numerical
                 // Multiple Numerical
                 case "Q":
                     // Multiple Short Text
                     //get answers
                     $query = "SELECT title as code, question as answer FROM {{questions}} WHERE parent_qid=:flt_0 AND language = :lang ORDER BY question_order";
                     $result = Yii::app()->db->createCommand($query)->bindParam(":flt_0", $flt[0], PDO::PARAM_INT)->bindParam(":lang", $sLanguage, PDO::PARAM_STR)->queryAll();
                     //go through all the (multiple) answers
                     foreach ($result as $row) {
                         $myfield2 = $flt[2] . $myfield . reset($row);
                         $allfields[] = $myfield2;
                     }
                     break;
                 case "A":
                     // ARRAY OF 5 POINT CHOICE QUESTIONS
                 // ARRAY OF 5 POINT CHOICE QUESTIONS
                 case "B":
                     // ARRAY OF 10 POINT CHOICE QUESTIONS
                 // ARRAY OF 10 POINT CHOICE QUESTIONS
                 case "C":
                     // ARRAY OF YES\No\gT("Uncertain") QUESTIONS
                 // ARRAY OF YES\No\gT("Uncertain") QUESTIONS
                 case "E":
                     // ARRAY OF Increase/Same/Decrease QUESTIONS
                 // ARRAY OF Increase/Same/Decrease QUESTIONS
                 case "F":
                     // FlEXIBLE ARRAY
                 // FlEXIBLE ARRAY
                 case "H":
                     // ARRAY (By Column)
                     //get answers
                     $query = "SELECT title as code, question as answer FROM {{questions}} WHERE parent_qid=:flt_0 AND language = :lang ORDER BY question_order";
                     $result = Yii::app()->db->createCommand($query)->bindParam(":flt_0", $flt[0], PDO::PARAM_INT)->bindParam(":lang", $sLanguage, PDO::PARAM_STR)->queryAll();
                     //go through all the (multiple) answers
                     foreach ($result as $row) {
                         $myfield2 = $myfield . reset($row);
                         $allfields[] = $myfield2;
                     }
                     break;
                     // all "free text" types (T, U, S)  get the same prefix ("T")
                 // all "free text" types (T, U, S)  get the same prefix ("T")
                 case "T":
                     // Long free text
                 // Long free text
                 case "U":
                     // Huge free text
                 // Huge free text
                 case "S":
                     // Short free text
                     $myfield = "T{$myfield}";
                     $allfields[] = $myfield;
                     break;
                 case ";":
                     //ARRAY (Multi Flex) (Text)
                 //ARRAY (Multi Flex) (Text)
                 case ":":
                     //ARRAY (Multi Flex) (Numbers)
                     $query = "SELECT title, question FROM {{questions}} WHERE parent_qid=:flt_0 AND language=:lang AND scale_id = 0 ORDER BY question_order";
                     $result = Yii::app()->db->createCommand($query)->bindParam(":flt_0", $flt[0], PDO::PARAM_INT)->bindParam(":lang", $sLanguage, PDO::PARAM_STR)->queryAll();
                     foreach ($result as $row) {
                         $fquery = "SELECT * FROM {{questions}} WHERE parent_qid = :flt_0 AND language = :lang AND scale_id = 1 ORDER BY question_order, title";
                         $fresult = Yii::app()->db->createCommand($query)->bindParam(":flt_0", $flt[0], PDO::PARAM_INT)->bindParam(":lang", $sLanguage, PDO::PARAM_STR)->queryAll();
                         foreach ($fresult as $frow) {
                             $myfield2 = $myfield . reset($row) . "_" . $frow['title'];
                             $allfields[] = $myfield2;
                         }
                     }
                     break;
                 case "R":
                     //RANKING
                     //get some answers
                     $query = "SELECT code, answer FROM {{answers}} WHERE qid = :flt_0 AND language = :lang ORDER BY sortorder, answer";
                     $result = Yii::app()->db->createCommand($query)->bindParam(":flt_0", $flt[0], PDO::PARAM_INT)->bindParam(":lang", $sLanguage, PDO::PARAM_STR)->queryAll();
                     //get number of answers
                     $count = count($result);
                     //loop through all answers. if there are 3 items to rate there will be 3 statistics
                     for ($i = 1; $i <= $count; $i++) {
                         $myfield2 = "R" . $myfield . $i . "-" . strlen($i);
                         $allfields[] = $myfield2;
                     }
                     break;
                     //Boilerplate questions are only used to put some text between other questions -> no analysis needed
                 //Boilerplate questions are only used to put some text between other questions -> no analysis needed
                 case "X":
                     //This is a boilerplate question and it has no business in this script
                     break;
                 case "1":
                     // MULTI SCALE
                     //get answers
                     $query = "SELECT title, question FROM {{questions}} WHERE parent_qid = :flt_0 AND language = :lang ORDER BY question_order";
                     $result = Yii::app()->db->createCommand($query)->bindParam(":flt_0", $flt[0], PDO::PARAM_INT)->bindParam(":lang", $sLanguage, PDO::PARAM_STR)->queryAll();
                     //loop through answers
                     foreach ($result as $row) {
                         //----------------- LABEL 1 ---------------------
                         $myfield2 = $myfield . $row['title'] . "#0";
                         $allfields[] = $myfield2;
                         //----------------- LABEL 2 ---------------------
                         $myfield2 = $myfield . $row['title'] . "#1";
                         $allfields[] = $myfield2;
                     }
                     //end WHILE -> loop through all answers
                     break;
                 case "P":
                     //P - Multiple choice with comments
                 //P - Multiple choice with comments
                 case "M":
                     //M - Multiple choice
                 //M - Multiple choice
                 case "N":
                     //N - Numerical input
                 //N - Numerical input
                 case "D":
                     //D - Date
                     $myfield2 = $flt[2] . $myfield;
                     $allfields[] = $myfield2;
                     break;
                 default:
                     //Default settings
                     $allfields[] = $myfield;
                     break;
             }
             //end switch -> check question types and create filter forms
         }
         //end foreach -> loop through all questions with "public_statistics" enabled
     }
     // end if -> for removing the error message in case there are no filters
     $summary = $allfields;
     // Get the survey inforamtion
     $thissurvey = getSurveyInfo($surveyid, $sLanguage);
     //SET THE TEMPLATE DIRECTORY
     $data['sTemplatePath'] = $surveyinfo['template'];
     // surveyinfo=getSurveyInfo and if survey don't exist : stop before.
     //---------- CREATE STATISTICS ----------
     $redata = compact(array_keys(get_defined_vars()));
     doHeader();
     echo templatereplace(file_get_contents(getTemplatePath($data['sTemplatePath']) . DIRECTORY_SEPARATOR . "startpage.pstpl"), array(), $redata);
     //some progress bar stuff
     // Create progress bar which is shown while creating the results
     $prb = new ProgressBar();
     $prb->pedding = 2;
     // Bar Pedding
     $prb->brd_color = "#404040 #dfdfdf #dfdfdf #404040";
     // Bar Border Color
     $prb->setFrame();
     // set ProgressBar Frame
     $prb->frame['left'] = 50;
     // Frame position from left
     $prb->frame['top'] = 80;
     // Frame position from top
     $prb->addLabel('text', 'txt1', gT("Please wait ..."));
     // add Text as Label 'txt1' and value 'Please wait'
     $prb->addLabel('percent', 'pct1');
     // add Percent as Label 'pct1'
     $prb->addButton('btn1', gT('Go back'), '?action=statistics&amp;sid=' . $iSurveyID);
     // add Button as Label 'btn1' and action '?restart=1'
     //progress bar starts with 35%
     $process_status = 35;
     $prb->show();
     // show the ProgressBar
     // 1: Get list of questions with answers chosen
     //"Getting Questions and Answer ..." is shown above the bar
     $prb->setLabelValue('txt1', gT('Getting questions and answers ...'));
     $prb->moveStep(5);
     // creates array of post variable names
     for (reset($_POST); $key = key($_POST); next($_POST)) {
         $postvars[] = $key;
     }
     $data['thisSurveyTitle'] = $thisSurveyTitle;
     $data['totalrecords'] = $totalrecords;
     $data['summary'] = $summary;
     //show some main data at the beginnung
     // CHANGE JSW_NZ - let's allow html formatted questions to show
     //push progress bar from 35 to 40
     $process_status = 40;
     //Show Summary results
     if (isset($summary) && $summary) {
         //"Generating Summaries ..." is shown above the progress bar
         $prb->setLabelValue('txt1', gT('Generating summaries ...'));
         $prb->moveStep($process_status);
         //let's run through the survey // Fixed bug 3053 with array_unique
         $runthrough = array_unique($summary);
         //loop through all selected questions
         foreach ($runthrough as $rt) {
             //update progress bar
             if ($process_status < 100) {
                 $process_status++;
             }
             $prb->moveStep($process_status);
         }
         // end foreach -> loop through all questions
         $helper = new statistics_helper();
         $statisticsoutput .= $helper->generate_statistics($iSurveyID, $summary, $summary, $publicgraphs, 'html', null, $sLanguage, false);
     }
     //end if -> show summary results
     $data['statisticsoutput'] = $statisticsoutput;
     //done! set progress bar to 100%
     if (isset($prb)) {
         $prb->setLabelValue('txt1', gT('Completed'));
         $prb->moveStep(100);
         $prb->hide();
     }
     $redata = compact(array_keys(get_defined_vars()));
     $data['redata'] = $redata;
     Yii::app()->getClientScript()->registerScriptFile(Yii::app()->getConfig('generalscripts') . 'statistics_user.js');
     $this->renderPartial('/statistics_user_view', $data);
     //output footer
     echo getFooter();
     //Delete all Session Data
     Yii::app()->session['finished'] = true;
 }
Ejemplo n.º 6
0
 /**
  * Show printable survey
  */
 function index($surveyid, $lang = null)
 {
     $surveyid = sanitize_int($surveyid);
     if (!Permission::model()->hasSurveyPermission($surveyid, 'surveycontent', 'read')) {
         $aData['surveyid'] = $surveyid;
         App()->getClientScript()->registerPackage('jquery-superfish');
         $message['title'] = gT('Access denied!');
         $message['message'] = gT('You do not have sufficient rights to access this page.');
         $message['class'] = "error";
         $this->_renderWrappedTemplate('survey', array("message" => $message), $aData);
     } else {
         $aSurveyInfo = getSurveyInfo($surveyid, $lang);
         if (!$aSurveyInfo) {
             $this->getController()->error('Invalid survey ID');
         }
         SetSurveyLanguage($surveyid, $lang);
         $sLanguageCode = App()->language;
         $templatename = $aSurveyInfo['template'];
         $welcome = $aSurveyInfo['surveyls_welcometext'];
         $end = $aSurveyInfo['surveyls_endtext'];
         $surveyname = $aSurveyInfo['surveyls_title'];
         $surveydesc = $aSurveyInfo['surveyls_description'];
         $surveyactive = $aSurveyInfo['active'];
         $surveytable = "{{survey_" . $aSurveyInfo['sid'] . "}}";
         $surveyexpirydate = $aSurveyInfo['expires'];
         $surveyfaxto = $aSurveyInfo['faxto'];
         $dateformattype = $aSurveyInfo['surveyls_dateformat'];
         Yii::app()->loadHelper('surveytranslator');
         if (!is_null($surveyexpirydate)) {
             $dformat = getDateFormatData($dateformattype);
             $dformat = $dformat['phpdate'];
             $expirytimestamp = strtotime($surveyexpirydate);
             $expirytimeofday_h = date('H', $expirytimestamp);
             $expirytimeofday_m = date('i', $expirytimestamp);
             $surveyexpirydate = date($dformat, $expirytimestamp);
             if (!empty($expirytimeofday_h) || !empty($expirytimeofday_m)) {
                 $surveyexpirydate .= ' &ndash; ' . $expirytimeofday_h . ':' . $expirytimeofday_m;
             }
             sprintf(gT("Please submit by %s"), $surveyexpirydate);
         } else {
             $surveyexpirydate = '';
         }
         //Fix $templatename : control if print_survey.pstpl exist
         if (is_file(getTemplatePath($templatename) . DIRECTORY_SEPARATOR . 'print_survey.pstpl')) {
             $templatename = $templatename;
             // Change nothing
         } elseif (is_file(getTemplatePath(Yii::app()->getConfig("defaulttemplate")) . DIRECTORY_SEPARATOR . 'print_survey.pstpl')) {
             $templatename = Yii::app()->getConfig("defaulttemplate");
         } else {
             $templatename = "default";
         }
         $sFullTemplatePath = getTemplatePath($templatename) . DIRECTORY_SEPARATOR;
         $sFullTemplateUrl = getTemplateURL($templatename) . "/";
         define('PRINT_TEMPLATE_DIR', $sFullTemplatePath, true);
         define('PRINT_TEMPLATE_URL', $sFullTemplateUrl, true);
         LimeExpressionManager::StartSurvey($surveyid, 'survey', NULL, false, LEM_PRETTY_PRINT_ALL_SYNTAX);
         $moveResult = LimeExpressionManager::NavigateForwards();
         $condition = "sid = '{$surveyid}' AND language = '{$sLanguageCode}'";
         $degresult = QuestionGroup::model()->getAllGroups($condition, array('group_order'));
         //xiao,
         if (!isset($surveyfaxto) || !$surveyfaxto and isset($surveyfaxnumber)) {
             $surveyfaxto = $surveyfaxnumber;
             //Use system fax number if none is set in survey.
         }
         $headelements = getPrintableHeader();
         //if $showsgqacode is enabled at config.php show table name for reference
         $showsgqacode = Yii::app()->getConfig("showsgqacode");
         if (isset($showsgqacode) && $showsgqacode == true) {
             $surveyname = $surveyname . "<br />[" . gT('Database') . " " . gT('table') . ": {$surveytable}]";
         } else {
             $surveyname = $surveyname;
         }
         $survey_output = array('SITENAME' => Yii::app()->getConfig("sitename"), 'SURVEYNAME' => $surveyname, 'SURVEYDESCRIPTION' => $surveydesc, 'WELCOME' => $welcome, 'END' => $end, 'THEREAREXQUESTIONS' => 0, 'SUBMIT_TEXT' => gT("Submit Your Survey."), 'SUBMIT_BY' => $surveyexpirydate, 'THANKS' => gT("Thank you for completing this survey."), 'HEADELEMENTS' => $headelements, 'TEMPLATEURL' => PRINT_TEMPLATE_URL, 'FAXTO' => $surveyfaxto, 'PRIVACY' => '', 'GROUPS' => '');
         $survey_output['FAX_TO'] = '';
         if (!empty($surveyfaxto) && $surveyfaxto != '000-00000000') {
             $survey_output['FAX_TO'] = gT("Please fax your completed survey to:") . " {$surveyfaxto}";
         }
         $total_questions = 0;
         $mapquestionsNumbers = array();
         $answertext = '';
         // otherwise can throw an error on line 1617
         $fieldmap = createFieldMap($surveyid, 'full', false, false, $sLanguageCode);
         // =========================================================
         // START doin the business:
         foreach ($degresult->readAll() as $degrow) {
             // ---------------------------------------------------
             // START doing groups
             $deqresult = Question::model()->getQuestions($surveyid, $degrow['gid'], $sLanguageCode, 0, '"I"');
             $deqrows = array();
             //Create an empty array in case FetchRow does not return any rows
             foreach ($deqresult->readAll() as $deqrow) {
                 $deqrows[] = $deqrow;
             }
             // Get table output into array
             // Perform a case insensitive natural sort on group name then question title of a multidimensional array
             usort($deqrows, 'groupOrderThenQuestionOrder');
             if ($degrow['description']) {
                 $group_desc = $degrow['description'];
             } else {
                 $group_desc = '';
             }
             $group = array('GROUPNAME' => $degrow['group_name'], 'GROUPDESCRIPTION' => $group_desc, 'QUESTIONS' => '');
             // A group can have only hidden questions. In that case you don't want to see the group's header/description either.
             $bGroupHasVisibleQuestions = false;
             $gid = $degrow['gid'];
             //Alternate bgcolor for different groups
             if (!isset($group['ODD_EVEN']) || $group['ODD_EVEN'] == ' g-row-even') {
                 $group['ODD_EVEN'] = ' g-row-odd';
             } else {
                 $group['ODD_EVEN'] = ' g-row-even';
             }
             //Loop through questions
             foreach ($deqrows as $deqrow) {
                 // - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
                 // START doing questions
                 $qidattributes = getQuestionAttributeValues($deqrow['qid'], $deqrow['type']);
                 if ($qidattributes['hidden'] == 1 && $deqrow['type'] != '*') {
                     continue;
                 }
                 $bGroupHasVisibleQuestions = true;
                 //GET ANY CONDITIONS THAT APPLY TO THIS QUESTION
                 $printablesurveyoutput = '';
                 $sExplanation = '';
                 //reset conditions explanation
                 $s = 0;
                 // TMSW Condition->Relevance:  show relevance instead of this whole section to create $explanation
                 $scenarioresult = Condition::model()->getScenarios($deqrow['qid']);
                 $scenarioresult = $scenarioresult->readAll();
                 //Loop through distinct scenarios, thus grouping them together.
                 foreach ($scenarioresult as $scenariorow) {
                     if ($s == 0 && count($scenarioresult) > 1) {
                         $sExplanation .= '<p class="scenario">' . " -------- Scenario {$scenariorow['scenario']} --------</p>\n\n";
                     }
                     if ($s > 0) {
                         $sExplanation .= '<p class="scenario">' . ' -------- ' . gT("or") . " Scenario {$scenariorow['scenario']} --------</p>\n\n";
                     }
                     $x = 0;
                     $conditions1 = "qid={$deqrow['qid']} AND scenario={$scenariorow['scenario']}";
                     $distinctresult = Condition::model()->getSomeConditions(array('cqid', 'method', 'cfieldname'), $conditions1, array('cqid'), array('cqid', 'method', 'cfieldname'));
                     //Loop through each condition for a particular scenario.
                     foreach ($distinctresult->readAll() as $distinctrow) {
                         $condition = "qid = '{$distinctrow['cqid']}' AND parent_qid = 0 AND language = '{$sLanguageCode}'";
                         $subresult = Question::model()->find($condition);
                         if ($x > 0) {
                             $sExplanation .= ' <em class="scenario-and-separator">' . gT('and') . '</em> ';
                         }
                         if (trim($distinctrow['method']) == '') {
                             $distinctrow['method'] = '==';
                         }
                         if ($distinctrow['cqid']) {
                             // cqid != 0  ==> previous answer match
                             if ($distinctrow['method'] == '==') {
                                 $sExplanation .= gT("Answer was") . " ";
                             } elseif ($distinctrow['method'] == '!=') {
                                 $sExplanation .= gT("Answer was NOT") . " ";
                             } elseif ($distinctrow['method'] == '<') {
                                 $sExplanation .= gT("Answer was less than") . " ";
                             } elseif ($distinctrow['method'] == '<=') {
                                 $sExplanation .= gT("Answer was less than or equal to") . " ";
                             } elseif ($distinctrow['method'] == '>=') {
                                 $sExplanation .= gT("Answer was greater than or equal to") . " ";
                             } elseif ($distinctrow['method'] == '>') {
                                 $sExplanation .= gT("Answer was greater than") . " ";
                             } elseif ($distinctrow['method'] == 'RX') {
                                 $sExplanation .= gT("Answer matched (regexp)") . " ";
                             } else {
                                 $sExplanation .= gT("Answer was") . " ";
                             }
                         }
                         if (!$distinctrow['cqid']) {
                             // cqid == 0  ==> token attribute match
                             $tokenData = getTokenFieldsAndNames($surveyid);
                             preg_match('/^{TOKEN:([^}]*)}$/', $distinctrow['cfieldname'], $extractedTokenAttr);
                             $sExplanation .= "Your " . $tokenData[strtolower($extractedTokenAttr[1])]['description'] . " ";
                             if ($distinctrow['method'] == '==') {
                                 $sExplanation .= gT("is") . " ";
                             } elseif ($distinctrow['method'] == '!=') {
                                 $sExplanation .= gT("is NOT") . " ";
                             } elseif ($distinctrow['method'] == '<') {
                                 $sExplanation .= gT("is less than") . " ";
                             } elseif ($distinctrow['method'] == '<=') {
                                 $sExplanation .= gT("is less than or equal to") . " ";
                             } elseif ($distinctrow['method'] == '>=') {
                                 $sExplanation .= gT("is greater than or equal to") . " ";
                             } elseif ($distinctrow['method'] == '>') {
                                 $sExplanation .= gT("is greater than") . " ";
                             } elseif ($distinctrow['method'] == 'RX') {
                                 $sExplanation .= gT("is matched (regexp)") . " ";
                             } else {
                                 $sExplanation .= gT("is") . " ";
                             }
                             $answer_section = ' ' . $distinctrow['value'] . ' ';
                         }
                         $conresult = Condition::model()->getConditionsQuestions($distinctrow['cqid'], $deqrow['qid'], $scenariorow['scenario'], $sLanguageCode);
                         $conditions = array();
                         foreach ($conresult->readAll() as $conrow) {
                             $postans = "";
                             $value = $conrow['value'];
                             switch ($conrow['type']) {
                                 case "Y":
                                     switch ($conrow['value']) {
                                         case "Y":
                                             $conditions[] = gT("Yes");
                                             break;
                                         case "N":
                                             $conditions[] = gT("No");
                                             break;
                                     }
                                     break;
                                 case "G":
                                     switch ($conrow['value']) {
                                         case "M":
                                             $conditions[] = gT("Male");
                                             break;
                                         case "F":
                                             $conditions[] = gT("Female");
                                             break;
                                     }
                                     // switch
                                     break;
                                 case "A":
                                 case "B":
                                 case ":":
                                 case ";":
                                 case "5":
                                     $conditions[] = $conrow['value'];
                                     break;
                                 case "C":
                                     switch ($conrow['value']) {
                                         case "Y":
                                             $conditions[] = gT("Yes");
                                             break;
                                         case "U":
                                             $conditions[] = gT("Uncertain");
                                             break;
                                         case "N":
                                             $conditions[] = gT("No");
                                             break;
                                     }
                                     // switch
                                     break;
                                 case "E":
                                     switch ($conrow['value']) {
                                         case "I":
                                             $conditions[] = gT("Increase");
                                             break;
                                         case "D":
                                             $conditions[] = gT("Decrease");
                                             break;
                                         case "S":
                                             $conditions[] = gT("Same");
                                             break;
                                     }
                                 case "1":
                                     $labelIndex = preg_match("/^[^#]+#([01]{1})\$/", $conrow['cfieldname']);
                                     if ($labelIndex == 0) {
                                         // TIBO
                                         $condition = "qid='{$conrow['cqid']}' AND code='{$conrow['value']}' AND scale_id=0 AND language='{$sLanguageCode}'";
                                         $fresult = Answer::model()->getAllRecords($condition);
                                         foreach ($fresult->readAll() as $frow) {
                                             $postans = $frow['answer'];
                                             $conditions[] = $frow['answer'];
                                         }
                                         // while
                                     } elseif ($labelIndex == 1) {
                                         $condition = "qid='{$conrow['cqid']}' AND code='{$conrow['value']}' AND scale_id=1 AND language='{$sLanguageCode}'";
                                         $fresult = Answer::model()->getAllRecords($condition);
                                         foreach ($fresult->readAll() as $frow) {
                                             $postans = $frow['answer'];
                                             $conditions[] = $frow['answer'];
                                         }
                                         // while
                                     }
                                     break;
                                 case "L":
                                 case "!":
                                 case "O":
                                 case "R":
                                     $condition = "qid='{$conrow['cqid']}' AND code='{$conrow['value']}' AND language='{$sLanguageCode}'";
                                     $ansresult = Answer::model()->findAll($condition);
                                     foreach ($ansresult as $ansrow) {
                                         $conditions[] = $ansrow['answer'];
                                     }
                                     if ($conrow['value'] == "-oth-") {
                                         $conditions[] = gT("Other");
                                     }
                                     $conditions = array_unique($conditions);
                                     break;
                                 case "M":
                                 case "P":
                                     $condition = " parent_qid='{$conrow['cqid']}' AND title='{$conrow['value']}' AND language='{$sLanguageCode}'";
                                     $ansresult = Question::model()->findAll($condition);
                                     foreach ($ansresult as $ansrow) {
                                         $conditions[] = $ansrow['question'];
                                     }
                                     $conditions = array_unique($conditions);
                                     break;
                                 case "N":
                                 case "K":
                                     $conditions[] = $value;
                                     break;
                                 case "F":
                                 case "H":
                                 default:
                                     $value = substr($conrow['cfieldname'], strpos($conrow['cfieldname'], "X" . $conrow['cqid']) + strlen("X" . $conrow['cqid']), strlen($conrow['cfieldname']));
                                     $condition = " qid='{$conrow['cqid']}' AND code='{$conrow['value']}' AND language='{$sLanguageCode}'";
                                     $fresult = Answer::model()->getAllRecords($condition);
                                     foreach ($fresult->readAll() as $frow) {
                                         $postans = $frow['answer'];
                                         $conditions[] = $frow['answer'];
                                     }
                                     // while
                                     break;
                             }
                             // switch
                             // Now let's complete the answer text with the answer_section
                             $answer_section = "";
                             switch ($conrow['type']) {
                                 case "A":
                                 case "B":
                                 case "C":
                                 case "E":
                                 case "F":
                                 case "H":
                                 case "K":
                                     $thiscquestion = $fieldmap[$conrow['cfieldname']];
                                     $condition = "parent_qid='{$conrow['cqid']}' AND title='{$thiscquestion['aid']}' AND language='{$sLanguageCode}'";
                                     $ansresult = Question::model()->findAll($condition);
                                     foreach ($ansresult as $ansrow) {
                                         $answer_section = " (" . $ansrow['question'] . ")";
                                     }
                                     break;
                                 case "1":
                                     // dual: (Label 1), (Label 2)
                                     $labelIndex = substr($conrow['cfieldname'], -1);
                                     $thiscquestion = $fieldmap[$conrow['cfieldname']];
                                     $condition = "parent_qid='{$conrow['cqid']}' AND title='{$thiscquestion['aid']}' AND language='{$sLanguageCode}'";
                                     $ansresult = Question::model()->findAll($condition);
                                     $cqidattributes = getQuestionAttributeValues($conrow['cqid']);
                                     if ($labelIndex == 0) {
                                         if (trim($cqidattributes['dualscale_headerA'][$sLanguageCode]) != '') {
                                             $header = gT($cqidattributes['dualscale_headerA'][$sLanguageCode]);
                                         } else {
                                             $header = '1';
                                         }
                                     } elseif ($labelIndex == 1) {
                                         if (trim($cqidattributes['dualscale_headerB'][$sLanguageCode]) != '') {
                                             $header = gT($cqidattributes['dualscale_headerB'][$sLanguageCode]);
                                         } else {
                                             $header = '2';
                                         }
                                     }
                                     foreach ($ansresult as $ansrow) {
                                         $answer_section = " (" . $ansrow->question . " " . sprintf(gT("Label %s"), $header) . ")";
                                     }
                                     break;
                                 case ":":
                                 case ";":
                                     //multi flexi: ( answer [label] )
                                     $thiscquestion = $fieldmap[$conrow['cfieldname']];
                                     $condition = "parent_qid='{$conrow['cqid']}' AND title='{$thiscquestion['aid']}' AND language='{$sLanguageCode}'";
                                     $ansresult = Question::model()->findAll($condition);
                                     foreach ($ansresult as $ansrow) {
                                         $condition = "qid = '{$conrow['cqid']}' AND code = '{$conrow['value']}' AND language= '{$sLanguageCode}'";
                                         $fresult = Answer::model()->findAll($condition);
                                         foreach ($fresult as $frow) {
                                             //$conditions[]=$frow['title'];
                                             $answer_section = " (" . $ansrow->question . "[" . $frow['answer'] . "])";
                                         }
                                         // while
                                     }
                                     break;
                                 case "R":
                                     // (Rank 1), (Rank 2)... TIBO
                                     $thiscquestion = $fieldmap[$conrow['cfieldname']];
                                     $rankid = $thiscquestion['aid'];
                                     $answer_section = " (" . gT("RANK") . " {$rankid})";
                                     break;
                                 default:
                                     // nothing to add
                                     break;
                             }
                         }
                         if (count($conditions) > 1) {
                             $sExplanation .= "'" . implode("' <em class='scenario-or-separator'>" . gT("or") . "</em> '", $conditions) . "'";
                         } elseif (count($conditions) == 1) {
                             $sExplanation .= "'" . $conditions[0] . "'";
                         }
                         unset($conditions);
                         // Following line commented out because answer_section  was lost, but is required for some question types
                         //$explanation .= " ".gT("to question")." '".$mapquestionsNumbers[$distinctrow['cqid']]."' $answer_section ";
                         if ($distinctrow['cqid']) {
                             $sExplanation .= " <span class='scenario-at-separator'>" . gT("at question") . "</span> '" . $mapquestionsNumbers[$distinctrow['cqid']] . " [" . $subresult['title'] . "]' (" . strip_tags($subresult['question']) . "{$answer_section})";
                         } else {
                             $sExplanation .= " " . $distinctrow['value'];
                         }
                         //$distinctrow
                         $x++;
                     }
                     $s++;
                 }
                 $qinfo = LimeExpressionManager::GetQuestionStatus($deqrow['qid']);
                 $relevance = trim($qinfo['info']['relevance']);
                 $sEquation = $qinfo['relEqn'];
                 if (trim($relevance) != '' && trim($relevance) != '1') {
                     if (isset($qidattributes['printable_help'][$sLanguageCode]) && $qidattributes['printable_help'][$sLanguageCode] != '') {
                         $sExplanation = $qidattributes['printable_help'][$sLanguageCode];
                     } elseif ($sExplanation == '') {
                         $sExplanation = $sEquation;
                         $sEquation = '&nbsp;';
                         // No need to show it twice
                     }
                     $sExplanation = "<b>" . gT('Only answer this question if the following conditions are met:') . "</b><br/> " . $sExplanation;
                     if (Yii::app()->getConfig('showrelevance')) {
                         $sExplanation .= "<span class='printable_equation'><br>" . $sEquation . "</span>";
                     }
                 } else {
                     $sExplanation = '';
                 }
                 ++$total_questions;
                 //TIBO map question qid to their q number
                 $mapquestionsNumbers[$deqrow['qid']] = $total_questions;
                 //END OF GETTING CONDITIONS
                 $qid = $deqrow['qid'];
                 $fieldname = "{$surveyid}" . "X" . "{$gid}" . "X" . "{$qid}";
                 if (isset($showsgqacode) && $showsgqacode == true) {
                     $deqrow['question'] = $deqrow['question'] . "<br />" . gT("ID:") . " {$fieldname} <br />" . gT("Question code:") . " " . $deqrow['title'];
                 }
                 $question = array('QUESTION_NUMBER' => $total_questions, 'QUESTION_CODE' => $deqrow['title'], 'QUESTION_TEXT' => preg_replace('/(?:<br ?\\/?>|<\\/(?:p|h[1-6])>)$/is', '', $deqrow['question']), 'QUESTION_SCENARIO' => $sExplanation, 'QUESTION_MANDATORY' => '', 'QUESTION_ID' => $deqrow['qid'], 'QUESTION_CLASS' => getQuestionClass($deqrow['type']), 'QUESTION_TYPE_HELP' => $qinfo['validTip'], 'QUESTION_MAN_MESSAGE' => '', 'QUESTION_VALID_MESSAGE' => '', 'QUESTION_FILE_VALID_MESSAGE' => '', 'QUESTIONHELP' => '', 'ANSWER' => '');
                 $showqnumcode = Yii::app()->getConfig('showqnumcode');
                 if ($showqnumcode == 'choose' && ($aSurveyInfo['showqnumcode'] == 'N' || $aSurveyInfo['showqnumcode'] == 'X') || $showqnumcode == 'number' || $showqnumcode == 'none') {
                     $question['QUESTION_CODE'] = '';
                 }
                 if ($showqnumcode == 'choose' && ($aSurveyInfo['showqnumcode'] == 'C' || $aSurveyInfo['showqnumcode'] == 'X') || $showqnumcode == 'code' || $showqnumcode == 'none') {
                     $question['QUESTION_NUMBER'] = '';
                 }
                 if ($question['QUESTION_TYPE_HELP'] != "") {
                     $question['QUESTION_TYPE_HELP'] .= "<br />\n";
                 }
                 if ($deqrow['mandatory'] == 'Y') {
                     $question['QUESTION_MANDATORY'] = gT('*');
                     $question['QUESTION_CLASS'] .= ' mandatory';
                 }
                 //DIFFERENT TYPES OF DATA FIELD HERE
                 if ($deqrow['help']) {
                     $question['QUESTIONHELP'] = $deqrow['help'];
                 }
                 if (!empty($qidattributes['page_break'])) {
                     $question['QUESTION_CLASS'] .= ' breakbefore ';
                 }
                 if (isset($qidattributes['maximum_chars']) && $qidattributes['maximum_chars'] != '') {
                     $question['QUESTION_CLASS'] = "max-chars-{$qidattributes['maximum_chars']} " . $question['QUESTION_CLASS'];
                 }
                 switch ($deqrow['type']) {
                     // ==================================================================
                     case "5":
                         //5 POINT CHOICE
                         $question['QUESTION_TYPE_HELP'] .= gT('Please choose *only one* of the following:');
                         $question['ANSWER'] .= "\n\t<ul>\n";
                         for ($i = 1; $i <= 5; $i++) {
                             $question['ANSWER'] .= "\t\t<li>\n\t\t\t" . self::_input_type_image('radio', $i) . "\n\t\t\t{$i} " . self::_addsgqacode("({$i})") . "\n\t\t</li>\n";
                         }
                         $question['ANSWER'] .= "\t</ul>\n";
                         break;
                         // ==================================================================
                     // ==================================================================
                     case "D":
                         //DATE
                         $question['QUESTION_TYPE_HELP'] .= gT('Please enter a date:');
                         $question['ANSWER'] .= "\t" . self::_input_type_image('text', $question['QUESTION_TYPE_HELP'], 30, 1);
                         break;
                         // ==================================================================
                     // ==================================================================
                     case "G":
                         //GENDER
                         $question['QUESTION_TYPE_HELP'] .= gT("Please choose *only one* of the following:");
                         $question['ANSWER'] .= "\n\t<ul>\n";
                         $question['ANSWER'] .= "\t\t<li>\n\t\t\t" . self::_input_type_image('radio', gT("Female")) . "\n\t\t\t" . gT("Female") . " " . self::_addsgqacode("(F)") . "\n\t\t</li>\n";
                         $question['ANSWER'] .= "\t\t<li>\n\t\t\t" . self::_input_type_image('radio', gT("Male")) . "\n\t\t\t" . gT("Male") . " " . self::_addsgqacode("(M)") . "\n\t\t</li>\n";
                         $question['ANSWER'] .= "\t</ul>\n";
                         break;
                         // ==================================================================
                     // ==================================================================
                     case "L":
                         //LIST drop-down/radio-button list
                         // ==================================================================
                     //LIST drop-down/radio-button list
                     // ==================================================================
                     case "!":
                         //List - dropdown
                         if (isset($qidattributes['display_columns']) && trim($qidattributes['display_columns']) != '') {
                             $dcols = $qidattributes['display_columns'];
                         } else {
                             $dcols = 0;
                         }
                         if (isset($qidattributes['category_separator']) && trim($qidattributes['category_separator']) != '') {
                             $optCategorySeparator = $qidattributes['category_separator'];
                         } else {
                             unset($optCategorySeparator);
                         }
                         $question['QUESTION_TYPE_HELP'] .= gT("Please choose *only one* of the following:");
                         $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $sLanguageCode, $surveyid);
                         $dearesult = Answer::model()->getAllRecords(" qid='{$deqrow['qid']}' AND language='{$sLanguageCode}' ", array('sortorder', 'answer'));
                         $dearesult = $dearesult->readAll();
                         $deacount = count($dearesult);
                         if ($deqrow['other'] == "Y") {
                             $deacount++;
                         }
                         $wrapper = setupColumns(0, $deacount);
                         $question['ANSWER'] = $wrapper['whole-start'];
                         $rowcounter = 0;
                         $colcounter = 1;
                         foreach ($dearesult as $dearow) {
                             if (isset($optCategorySeparator)) {
                                 list($category, $answer) = explode($optCategorySeparator, $dearow['answer']);
                                 if ($category != '') {
                                     $dearow['answer'] = "({$category}) {$answer} " . self::_addsgqacode("(" . $dearow['code'] . ")");
                                 } else {
                                     $dearow['answer'] = $answer . self::_addsgqacode(" (" . $dearow['code'] . ")");
                                 }
                                 $question['ANSWER'] .= "\t" . $wrapper['item-start'] . "\t\t" . self::_input_type_image('radio', $dearow['answer']) . "\n\t\t\t" . $dearow['answer'] . "\n" . $wrapper['item-end'];
                             } else {
                                 $question['ANSWER'] .= "\t" . $wrapper['item-start'] . "\t\t" . self::_input_type_image('radio', $dearow['answer']) . "\n\t\t\t" . $dearow['answer'] . self::_addsgqacode(" (" . $dearow['code'] . ")") . "\n" . $wrapper['item-end'];
                             }
                             ++$rowcounter;
                             if ($rowcounter == $wrapper['maxrows'] && $colcounter < $wrapper['cols']) {
                                 if ($colcounter == $wrapper['cols'] - 1) {
                                     $question['ANSWER'] .= $wrapper['col-devide-last'];
                                 } else {
                                     $question['ANSWER'] .= $wrapper['col-devide'];
                                 }
                                 $rowcounter = 0;
                                 ++$colcounter;
                             }
                         }
                         if ($deqrow['other'] == 'Y') {
                             if (trim($qidattributes["other_replace_text"][$sLanguageCode]) == '') {
                                 $qidattributes["other_replace_text"][$sLanguageCode] = gT("Other");
                             }
                             //                    $printablesurveyoutput .="\t".$wrapper['item-start']."\t\t".self::_input_type_image('radio' , gT("Other"))."\n\t\t\t".gT("Other")."\n\t\t\t<input type='text' size='30' readonly='readonly' />\n".$wrapper['item-end'];
                             $question['ANSWER'] .= $wrapper['item-start-other'] . self::_input_type_image('radio', gT($qidattributes["other_replace_text"][$sLanguageCode])) . ' ' . gT($qidattributes["other_replace_text"][$sLanguageCode]) . self::_addsgqacode(" (-oth-)") . "\n\t\t\t" . self::_input_type_image('other') . self::_addsgqacode(" (" . $deqrow['sid'] . "X" . $deqrow['gid'] . "X" . $deqrow['qid'] . "other)") . "\n" . $wrapper['item-end'];
                         }
                         $question['ANSWER'] .= $wrapper['whole-end'];
                         //Let's break the presentation into columns.
                         break;
                         // ==================================================================
                     // ==================================================================
                     case "O":
                         //LIST WITH COMMENT
                         $question['QUESTION_TYPE_HELP'] .= gT("Please choose *only one* of the following:");
                         $dearesult = Answer::model()->getAllRecords(" qid='{$deqrow['qid']}' AND language='{$sLanguageCode}'", array('sortorder', 'answer'));
                         $question['ANSWER'] = "\t<ul>\n";
                         foreach ($dearesult->readAll() as $dearow) {
                             $question['ANSWER'] .= "\t\t<li>\n\t\t\t" . self::_input_type_image('radio', $dearow['answer']) . "\n\t\t\t" . $dearow['answer'] . self::_addsgqacode(" (" . $dearow['code'] . ")") . "\n\t\t</li>\n";
                         }
                         $question['ANSWER'] .= "\t</ul>\n";
                         $question['ANSWER'] .= "\t<p class=\"comment\">\n\t\t" . gT("Make a comment on your choice here:") . "\n";
                         $question['ANSWER'] .= "\t\t" . self::_input_type_image('textarea', gT("Make a comment on your choice here:"), 50, 8) . self::_addsgqacode(" (" . $deqrow['sid'] . "X" . $deqrow['gid'] . "X" . $deqrow['qid'] . "comment)") . "\n\t</p>\n";
                         break;
                         // ==================================================================
                     // ==================================================================
                     case "R":
                         //RANKING Type Question
                         $rearesult = Answer::model()->getAllRecords(" qid='{$deqrow['qid']}' AND language='{$sLanguageCode}'", array('sortorder', 'answer'));
                         $rearesult = $rearesult->readAll();
                         $reacount = count($rearesult);
                         $question['QUESTION_TYPE_HELP'] .= gT("Please number each box in order of preference from 1 to") . " {$reacount}";
                         $question['QUESTION_TYPE_HELP'] .= self::_min_max_answers_help($qidattributes, $sLanguageCode, $surveyid);
                         $question['ANSWER'] = "\n<ul>\n";
                         foreach ($rearesult as $rearow) {
                             $question['ANSWER'] .= "\t<li>\n\t" . self::_input_type_image('rank', '', 4, 1) . "\n\t\t&nbsp;" . $rearow['answer'] . self::_addsgqacode(" (" . $fieldname . $rearow['code'] . ")") . "\n\t</li>\n";
                         }
                         $question['ANSWER'] .= "\n</ul>\n";
                         break;
                         // ==================================================================
                     // ==================================================================
                     case "M":
                         //Multiple choice (Quite tricky really!)
                         if (trim($qidattributes['display_columns']) != '') {
                             $dcols = $qidattributes['display_columns'];
                         } else {
                             $dcols = 0;
                         }
                         $question['QUESTION_TYPE_HELP'] .= gT("Please choose *all* that apply:");
                         $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $sLanguageCode, $surveyid);
                         $mearesult = Question::model()->getAllRecords(" parent_qid='{$deqrow['qid']}' AND language='{$sLanguageCode}' ", array('question_order'));
                         $mearesult = $mearesult->readAll();
                         $meacount = count($mearesult);
                         if ($deqrow['other'] == 'Y') {
                             $meacount++;
                         }
                         $wrapper = setupColumns($dcols, $meacount);
                         $question['ANSWER'] = $wrapper['whole-start'];
                         $rowcounter = 0;
                         $colcounter = 1;
                         foreach ($mearesult as $mearow) {
                             $question['ANSWER'] .= $wrapper['item-start'] . self::_input_type_image('checkbox', $mearow['question']) . "\n\t\t" . $mearow['question'] . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . ") ") . $wrapper['item-end'];
                             ++$rowcounter;
                             if ($rowcounter == $wrapper['maxrows'] && $colcounter < $wrapper['cols']) {
                                 if ($colcounter == $wrapper['cols'] - 1) {
                                     $question['ANSWER'] .= $wrapper['col-devide-last'];
                                 } else {
                                     $question['ANSWER'] .= $wrapper['col-devide'];
                                 }
                                 $rowcounter = 0;
                                 ++$colcounter;
                             }
                         }
                         if ($deqrow['other'] == "Y") {
                             if (trim($qidattributes['other_replace_text'][$sLanguageCode]) == '') {
                                 $qidattributes["other_replace_text"][$sLanguageCode] = "Other";
                             }
                             if (!isset($mearow['answer'])) {
                                 $mearow['answer'] = "";
                             }
                             $question['ANSWER'] .= $wrapper['item-start-other'] . self::_input_type_image('checkbox', $mearow['answer']) . gT($qidattributes["other_replace_text"][$sLanguageCode]) . ":\n\t\t" . self::_input_type_image('other') . self::_addsgqacode(" (" . $fieldname . "other) ") . $wrapper['item-end'];
                         }
                         $question['ANSWER'] .= $wrapper['whole-end'];
                         //                }
                         break;
                         // ==================================================================
                     // ==================================================================
                     case "P":
                         //Multiple choice with comments
                         $question['QUESTION_TYPE_HELP'] .= gT("Please choose all that apply and provide a comment:");
                         $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $sLanguageCode, $surveyid);
                         $mearesult = Question::model()->getAllRecords("parent_qid='{$deqrow['qid']}'  AND language='{$sLanguageCode}'", array('question_order'));
                         //                $printablesurveyoutput .="\t\t\t<u>".gT("Please choose all that apply and provide a comment:")."</u><br />\n";
                         $j = 0;
                         $longest_string = 0;
                         foreach ($mearesult->readAll() as $mearow) {
                             $longest_string = longestString($mearow['question'], $longest_string);
                             $question['ANSWER'] .= "\t<li><span>\n\t\t" . self::_input_type_image('checkbox', $mearow['question']) . $mearow['question'] . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . ") ") . "</span>\n\t\t" . self::_input_type_image('text', 'comment box', 60) . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . "comment) ") . "\n\t</li>\n";
                             $j++;
                         }
                         if ($deqrow['other'] == "Y") {
                             $question['ANSWER'] .= "\t<li class=\"other\">\n\t\t<div class=\"other-replacetext\">" . gT('Other:') . self::_input_type_image('other', '', 1) . "</div>" . self::_input_type_image('othercomment', 'comment box', 50) . self::_addsgqacode(" (" . $fieldname . "other) ") . "\n\t</li>\n";
                             $j++;
                         }
                         $question['ANSWER'] = "\n<ul>\n" . $question['ANSWER'] . "</ul>\n";
                         break;
                         // ==================================================================
                     // ==================================================================
                     case "Q":
                         //MULTIPLE SHORT TEXT
                         $width = 60;
                         // ==================================================================
                     // ==================================================================
                     case "K":
                         //MULTIPLE NUMERICAL
                         $question['QUESTION_TYPE_HELP'] = "";
                         $width = isset($width) ? $width : 16;
                         //                            if (!empty($qidattributes['equals_num_value']))
                         //                            {
                         //                                $question['QUESTION_TYPE_HELP'] .= "* ".sprintf(gT('Total of all entries must equal %d'),$qidattributes['equals_num_value'])."<br />\n";
                         //                            }
                         //                            if (!empty($qidattributes['max_num_value']))
                         //                            {
                         //                                $question['QUESTION_TYPE_HELP'] .= sprintf(gT('Total of all entries must not exceed %d'), $qidattributes['max_num_value'])."<br />\n";
                         //                            }
                         //                            if (!empty($qidattributes['min_num_value']))
                         //                            {
                         //                                $question['QUESTION_TYPE_HELP'] .= sprintf(gT('Total of all entries must be at least %s'),$qidattributes['min_num_value'])."<br />\n";
                         //                            }
                         $question['QUESTION_TYPE_HELP'] .= gT("Please write your answer(s) here:");
                         $longest_string = 0;
                         $mearesult = Question::model()->getAllRecords("parent_qid='{$deqrow['qid']}' AND language='{$sLanguageCode}'", array('question_order'));
                         foreach ($mearesult->readAll() as $mearow) {
                             $longest_string = longestString($mearow['question'], $longest_string);
                             if (isset($qidattributes['slider_layout']) && $qidattributes['slider_layout'] == 1) {
                                 $mearow['question'] = explode(':', $mearow['question']);
                                 $mearow['question'] = $mearow['question'][0];
                             }
                             $question['ANSWER'] .= "\t<li>\n\t\t<span>" . $mearow['question'] . "</span>\n\t\t" . self::_input_type_image('text', $mearow['question'], $width) . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . ") ") . "\n\t</li>\n";
                         }
                         $question['ANSWER'] = "\n<ul>\n" . $question['ANSWER'] . "</ul>\n";
                         break;
                         // ==================================================================
                     // ==================================================================
                     case "S":
                         //SHORT TEXT
                         $question['QUESTION_TYPE_HELP'] .= gT("Please write your answer here:");
                         $question['ANSWER'] = self::_input_type_image('text', $question['QUESTION_TYPE_HELP'], 50);
                         break;
                         // ==================================================================
                     // ==================================================================
                     case "T":
                         //LONG TEXT
                         $question['QUESTION_TYPE_HELP'] .= gT("Please write your answer here:");
                         $question['ANSWER'] = self::_input_type_image('textarea', $question['QUESTION_TYPE_HELP'], '100%', 8);
                         break;
                         // ==================================================================
                     // ==================================================================
                     case "U":
                         //HUGE TEXT
                         $question['QUESTION_TYPE_HELP'] .= gT("Please write your answer here:");
                         $question['ANSWER'] = self::_input_type_image('textarea', $question['QUESTION_TYPE_HELP'], '100%', 30);
                         break;
                         // ==================================================================
                     // ==================================================================
                     case "N":
                         //NUMERICAL
                         $prefix = "";
                         $suffix = "";
                         if ($qidattributes['prefix'][$sLanguageCode] != "") {
                             $prefix = $qidattributes['prefix'][$sLanguageCode];
                         }
                         if ($qidattributes['suffix'][$sLanguageCode] != "") {
                             $suffix = $qidattributes['suffix'][$sLanguageCode];
                         }
                         $question['QUESTION_TYPE_HELP'] .= gT("Please write your answer here:");
                         $question['ANSWER'] = "<ul>\n\t<li>\n\t\t<span>{$prefix}</span>\n\t\t" . self::_input_type_image('text', $question['QUESTION_TYPE_HELP'], 20) . "\n\t\t<span>{$suffix}</span>\n\t\t</li>\n\t</ul>";
                         break;
                         // ==================================================================
                     // ==================================================================
                     case "Y":
                         //YES/NO
                         $question['QUESTION_TYPE_HELP'] .= gT("Please choose *only one* of the following:");
                         $question['ANSWER'] = "\n<ul>\n\t<li>\n\t\t" . self::_input_type_image('radio', gT('Yes')) . "\n\t\t" . gT('Yes') . self::_addsgqacode(" (Y)") . "\n\t</li>\n";
                         $question['ANSWER'] .= "\n\t<li>\n\t\t" . self::_input_type_image('radio', gT('No')) . "\n\t\t" . gT('No') . self::_addsgqacode(" (N)") . "\n\t</li>\n</ul>\n";
                         break;
                         // ==================================================================
                     // ==================================================================
                     case "A":
                         //ARRAY (5 POINT CHOICE)
                         $condition = "parent_qid = '{$deqrow['qid']}'  AND language= '{$sLanguageCode}'";
                         $question['QUESTION_TYPE_HELP'] .= gT("Please choose the appropriate response for each item:");
                         $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $sLanguageCode, $surveyid);
                         $question['ANSWER'] = "\n            <table>\n                <thead>\n                    <tr>\n                        <td>&nbsp;</td>\n                        <th style='font-family:Arial,helvetica,sans-serif;font-weight:normal;'>1&nbsp;&nbsp;&nbsp;&nbsp;" . self::_addsgqacode(" (1)") . "</th>\n                        <th style='font-family:Arial,helvetica,sans-serif;font-weight:normal;'>2&nbsp;&nbsp;&nbsp;&nbsp;" . self::_addsgqacode(" (2)") . "</th>\n                        <th style='font-family:Arial,helvetica,sans-serif;font-weight:normal;'>3&nbsp;&nbsp;&nbsp;&nbsp;" . self::_addsgqacode(" (3)") . "</th>\n                        <th style='font-family:Arial,helvetica,sans-serif;font-weight:normal;'>4&nbsp;&nbsp;&nbsp;&nbsp;" . self::_addsgqacode(" (4)") . "</th>\n                        <th style='font-family:Arial,helvetica,sans-serif;font-weight:normal;'>5" . self::_addsgqacode(" (5)") . "</th>\n                    </tr>\n                </thead>\n                <tbody>";
                         $j = 0;
                         $rowclass = 'array1';
                         $mearesult = Question::model()->getAllRecords($condition, array('question_order'));
                         foreach ($mearesult->readAll() as $mearow) {
                             $question['ANSWER'] .= "\t\t<tr class=\"{$rowclass}\">\n";
                             $rowclass = alternation($rowclass, 'row');
                             //semantic differential question type?
                             if (strpos($mearow['question'], '|')) {
                                 $answertext = substr($mearow['question'], 0, strpos($mearow['question'], '|')) . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . ")") . " ";
                             } else {
                                 $answertext = $mearow['question'] . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . ")");
                             }
                             $question['ANSWER'] .= "\t\t\t<th class=\"answertext\">{$answertext}</th>\n";
                             for ($i = 1; $i <= 5; $i++) {
                                 $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio', $i) . "</td>\n";
                             }
                             $answertext .= $mearow['question'];
                             //semantic differential question type?
                             if (strpos($mearow['question'], '|')) {
                                 $answertext2 = substr($mearow['question'], strpos($mearow['question'], '|') + 1);
                                 $question['ANSWER'] .= "\t\t\t<th class=\"answertextright\">{$answertext2}</td>\n";
                             }
                             $question['ANSWER'] .= "\t\t</tr>\n";
                             $j++;
                         }
                         $question['ANSWER'] .= "\t</tbody>\n</table>\n";
                         break;
                         // ==================================================================
                     // ==================================================================
                     case "B":
                         //ARRAY (10 POINT CHOICE)
                         $question['QUESTION_TYPE_HELP'] .= gT("Please choose the appropriate response for each item:");
                         $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $sLanguageCode, $surveyid);
                         $question['ANSWER'] .= "\n<table>\n\t<thead>\n\t\t<tr>\n\t\t\t<td>&nbsp;</td>\n";
                         for ($i = 1; $i <= 10; $i++) {
                             $question['ANSWER'] .= "\t\t\t<th>{$i}" . self::_addsgqacode(" ({$i})") . "</th>\n";
                         }
                         $question['ANSWER'] .= "\t</thead>\n\n\t<tbody>\n";
                         $j = 0;
                         $rowclass = 'array1';
                         $mearesult = Question::model()->getAllRecords(" parent_qid='{$deqrow['qid']}' AND language='{$sLanguageCode}' ", array('question_order'));
                         foreach ($mearesult->readAll() as $mearow) {
                             $question['ANSWER'] .= "\t\t<tr class=\"{$rowclass}\">\n\t\t\t<th class=\"answertext\">{$mearow['question']}" . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . ")") . "</th>\n";
                             $rowclass = alternation($rowclass, 'row');
                             for ($i = 1; $i <= 10; $i++) {
                                 $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio', $i) . "</td>\n";
                             }
                             $question['ANSWER'] .= "\t\t</tr>\n";
                             $j++;
                         }
                         $question['ANSWER'] .= "\t</tbody>\n</table>\n";
                         break;
                         // ==================================================================
                     // ==================================================================
                     case "C":
                         //ARRAY (YES/UNCERTAIN/NO)
                         $question['QUESTION_TYPE_HELP'] .= gT("Please choose the appropriate response for each item:");
                         $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $sLanguageCode, $surveyid);
                         $question['ANSWER'] = '
         <table>
             <thead>
                 <tr>
                     <td>&nbsp;</td>
                     <th>' . gT("Yes") . self::_addsgqacode(" (Y)") . '</th>
                     <th>' . gT("Uncertain") . self::_addsgqacode(" (U)") . '</th>
                     <th>' . gT("No") . self::_addsgqacode(" (N)") . '</th>
                 </tr>
             </thead>
             <tbody>
         ';
                         $j = 0;
                         $rowclass = 'array1';
                         $mearesult = Question::model()->getAllRecords(" parent_qid='{$deqrow['qid']}'  AND language='{$sLanguageCode}' ", array('question_order'));
                         foreach ($mearesult->readAll() as $mearow) {
                             $question['ANSWER'] .= "\t\t<tr class=\"{$rowclass}\">\n";
                             $question['ANSWER'] .= "\t\t\t<th class=\"answertext\">{$mearow['question']}" . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . ")") . "</th>\n";
                             $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio', gT("Yes")) . "</td>\n";
                             $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio', gT("Uncertain")) . "</td>\n";
                             $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio', gT("No")) . "</td>\n";
                             $question['ANSWER'] .= "\t\t</tr>\n";
                             $j++;
                             $rowclass = alternation($rowclass, 'row');
                         }
                         $question['ANSWER'] .= "\t</tbody>\n</table>\n";
                         break;
                     case "E":
                         //ARRAY (Increase/Same/Decrease)
                         $question['QUESTION_TYPE_HELP'] .= gT("Please choose the appropriate response for each item:");
                         $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $sLanguageCode, $surveyid);
                         $question['ANSWER'] = '
         <table>
             <thead>
                 <tr>
                     <td>&nbsp;</td>
                     <th>' . gT("Increase") . self::_addsgqacode(" (I)") . '</th>
                     <th>' . gT("Same") . self::_addsgqacode(" (S)") . '</th>
                     <th>' . gT("Decrease") . self::_addsgqacode(" (D)") . '</th>
                 </tr>
             </thead>
             <tbody>
         ';
                         $j = 0;
                         $rowclass = 'array1';
                         $mearesult = Question::model()->getAllRecords(" parent_qid='{$deqrow['qid']}'  AND language='{$sLanguageCode}' ", array('question_order'));
                         foreach ($mearesult->readAll() as $mearow) {
                             $question['ANSWER'] .= "\t\t<tr class=\"{$rowclass}\">\n";
                             $question['ANSWER'] .= "\t\t\t<th class=\"answertext\">{$mearow['question']}" . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . ")") . "</th>\n";
                             $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio', gT("Increase")) . "</td>\n";
                             $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio', gT("Same")) . "</td>\n";
                             $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio', gT("Decrease")) . "</td>\n";
                             $question['ANSWER'] .= "\t\t</tr>\n";
                             $j++;
                             $rowclass = alternation($rowclass, 'row');
                         }
                         $question['ANSWER'] .= "\t</tbody>\n</table>\n";
                         break;
                         // ==================================================================
                     // ==================================================================
                     case ":":
                         //ARRAY (Multi Flexible) (Numbers)
                         $headstyle = "style='padding-left: 20px; padding-right: 7px'";
                         if (trim($qidattributes['multiflexible_max']) != '' && trim($qidattributes['multiflexible_min']) == '') {
                             $maxvalue = $qidattributes['multiflexible_max'];
                             $minvalue = 1;
                         }
                         if (trim($qidattributes['multiflexible_min']) != '' && trim($qidattributes['multiflexible_max']) == '') {
                             $minvalue = $qidattributes['multiflexible_min'];
                             $maxvalue = $qidattributes['multiflexible_min'] + 10;
                         }
                         if (trim($qidattributes['multiflexible_min']) == '' && trim($qidattributes['multiflexible_max']) == '') {
                             $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']) != '') {
                             $stepvalue = $qidattributes['multiflexible_step'];
                         } else {
                             $stepvalue = 1;
                         }
                         if ($qidattributes['multiflexible_checkbox'] != 0) {
                             $checkboxlayout = true;
                         } else {
                             $checkboxlayout = false;
                         }
                         $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $sLanguageCode, $surveyid);
                         $question['ANSWER'] .= "\n<table>\n\t<thead>\n\t\t<tr>\n\t\t\t<td>&nbsp;</td>\n";
                         $fresult = Question::model()->getAllRecords(" parent_qid='{$deqrow['qid']}' and scale_id=1 AND language='{$sLanguageCode}' ", array('question_order'));
                         $fresult = $fresult->readAll();
                         $fcount = count($fresult);
                         $fwidth = "120";
                         $i = 0;
                         //array to temporary store X axis question codes
                         $xaxisarray = array();
                         foreach ($fresult as $frow) {
                             $question['ANSWER'] .= "\t\t\t<th>{$frow['question']}</th>\n";
                             $i++;
                             //add current question code
                             $xaxisarray[$i] = $frow['title'];
                         }
                         $question['ANSWER'] .= "\t\t</tr>\n\t</thead>\n\n\t<tbody>\n";
                         $a = 1;
                         //Counter for pdfoutput
                         $rowclass = 'array1';
                         $mearesult = Question::model()->getAllRecords(" parent_qid='{$deqrow['qid']}' and scale_id=0 AND language='{$sLanguageCode}' ", array('question_order'));
                         $result = $mearesult->readAll();
                         foreach ($result as $frow) {
                             $question['ANSWER'] .= "\t<tr class=\"{$rowclass}\">\n";
                             $rowclass = alternation($rowclass, 'row');
                             $answertext = $frow['question'];
                             if (strpos($answertext, '|')) {
                                 $answertext = substr($answertext, 0, strpos($answertext, '|'));
                             }
                             $question['ANSWER'] .= "\t\t\t\t\t<th class=\"answertext\">{$answertext}</th>\n";
                             //$printablesurveyoutput .="\t\t\t\t\t<td>";
                             for ($i = 1; $i <= $fcount; $i++) {
                                 $question['ANSWER'] .= "\t\t\t<td>\n";
                                 if ($checkboxlayout === false) {
                                     $question['ANSWER'] .= "\t\t\t\t" . self::_input_type_image('text', '', 4) . self::_addsgqacode(" (" . $fieldname . $frow['title'] . "_" . $xaxisarray[$i] . ") ") . "\n";
                                 } else {
                                     $question['ANSWER'] .= "\t\t\t\t" . self::_input_type_image('checkbox') . self::_addsgqacode(" (" . $fieldname . $frow['title'] . "_" . $xaxisarray[$i] . ") ") . "\n";
                                 }
                                 $question['ANSWER'] .= "\t\t\t</td>\n";
                             }
                             $answertext = $frow['question'];
                             if (strpos($answertext, '|')) {
                                 $answertext = substr($answertext, strpos($answertext, '|') + 1);
                                 $question['ANSWER'] .= "\t\t\t<th class=\"answertextright\">{$answertext}</th>\n";
                             }
                             $question['ANSWER'] .= "\t\t</tr>\n";
                             $a++;
                         }
                         $question['ANSWER'] .= "\t</tbody>\n</table>\n";
                         break;
                         // ==================================================================
                     // ==================================================================
                     case ";":
                         //ARRAY (Multi Flexible) (text)
                         $headstyle = "style='padding-left: 20px; padding-right: 7px'";
                         $mearesult = Question::model()->getAllRecords(" parent_qid='{$deqrow['qid']}' AND scale_id=0 AND language='{$sLanguageCode}' ", array('question_order'));
                         $mearesult = $mearesult->readAll();
                         $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $sLanguageCode, $surveyid);
                         $question['ANSWER'] .= "\n<table>\n\t<thead>\n\t\t<tr>\n\t\t\t<td>&nbsp;</td>\n";
                         $fresult = Question::model()->getAllRecords(" parent_qid='{$deqrow['qid']}'  AND scale_id=1 AND language='{$sLanguageCode}' ", array('question_order'));
                         $fresult = $fresult->readAll();
                         $fcount = count($fresult);
                         $fwidth = "120";
                         $i = 0;
                         //array to temporary store X axis question codes
                         $xaxisarray = array();
                         foreach ($fresult as $frow) {
                             $question['ANSWER'] .= "\t\t\t<th>{$frow['question']}</th>\n";
                             $i++;
                             //add current question code
                             $xaxisarray[$i] = $frow['title'];
                         }
                         $question['ANSWER'] .= "\t\t</tr>\n\t</thead>\n\n<tbody>\n";
                         $a = 1;
                         $rowclass = 'array1';
                         foreach ($mearesult as $mearow) {
                             $question['ANSWER'] .= "\t\t<tr class=\"{$rowclass}\">\n";
                             $rowclass = alternation($rowclass, 'row');
                             $answertext = $mearow['question'];
                             if (strpos($answertext, '|')) {
                                 $answertext = substr($answertext, 0, strpos($answertext, '|'));
                             }
                             $question['ANSWER'] .= "\t\t\t<th class=\"answertext\">{$answertext}</th>\n";
                             for ($i = 1; $i <= $fcount; $i++) {
                                 $question['ANSWER'] .= "\t\t\t<td>\n";
                                 $question['ANSWER'] .= "\t\t\t\t" . self::_input_type_image('text', '', 23) . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . "_" . $xaxisarray[$i] . ") ") . "\n";
                                 $question['ANSWER'] .= "\t\t\t</td>\n";
                             }
                             $answertext = $mearow['question'];
                             if (strpos($answertext, '|')) {
                                 $answertext = substr($answertext, strpos($answertext, '|') + 1);
                                 $question['ANSWER'] .= "\t\t\t\t<th class=\"answertextright\">{$answertext}</th>\n";
                             }
                             $question['ANSWER'] .= "\t\t</tr>\n";
                             $a++;
                         }
                         $question['ANSWER'] .= "\t</tbody>\n</table>\n";
                         break;
                         // ==================================================================
                     // ==================================================================
                     case "F":
                         //ARRAY (Flexible Labels)
                         $question['QUESTION_TYPE_HELP'] .= gT("Please choose the appropriate response for each item:");
                         $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $sLanguageCode, $surveyid);
                         $fresult = Answer::model()->getAllRecords(" scale_id=0 AND qid='{$deqrow['qid']}'  AND language='{$sLanguageCode}'", array('sortorder', 'code'));
                         $fresult = $fresult->readAll();
                         $fcount = count($fresult);
                         $fwidth = "120";
                         $i = 1;
                         $column_headings = array();
                         foreach ($fresult as $frow) {
                             $column_headings[] = $frow['answer'] . self::_addsgqacode(" (" . $frow['code'] . ")");
                         }
                         if (trim($qidattributes['answer_width']) != '') {
                             $iAnswerWidth = 100 - $qidattributes['answer_width'];
                         } else {
                             $iAnswerWidth = 80;
                         }
                         if (count($column_headings) > 0) {
                             $col_width = round($iAnswerWidth / count($column_headings));
                         } else {
                             $heading = '';
                         }
                         $question['ANSWER'] .= "\n<table>\n\t<thead>\n\t\t<tr>\n";
                         $question['ANSWER'] .= "\t\t\t<td>&nbsp;</td>\n";
                         foreach ($column_headings as $heading) {
                             $question['ANSWER'] .= "\t\t\t<th style=\"width:{$col_width}%;\">{$heading}</th>\n";
                         }
                         $i++;
                         $question['ANSWER'] .= "\t\t</tr>\n\t</thead>\n\n\t<tbody>\n";
                         $counter = 1;
                         $rowclass = 'array1';
                         $mearesult = Question::model()->getAllRecords(" parent_qid='{$deqrow['qid']}'  AND language='{$sLanguageCode}' ", array('question_order'));
                         foreach ($mearesult->readAll() as $mearow) {
                             $question['ANSWER'] .= "\t\t<tr class=\"{$rowclass}\">\n";
                             $rowclass = alternation($rowclass, 'row');
                             if (trim($answertext) == '') {
                                 $answertext = '&nbsp;';
                             }
                             //semantic differential question type?
                             if (strpos($mearow['question'], '|')) {
                                 $answertext = substr($mearow['question'], 0, strpos($mearow['question'], '|')) . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . ")") . " ";
                             } else {
                                 $answertext = $mearow['question'] . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . ")");
                             }
                             if (trim($qidattributes['answer_width']) != '') {
                                 $sInsertStyle = ' style="width:' . $qidattributes['answer_width'] . '%" ';
                             } else {
                                 $sInsertStyle = '';
                             }
                             $question['ANSWER'] .= "\t\t\t<th {$sInsertStyle} class=\"answertext\">{$answertext}</th>\n";
                             for ($i = 1; $i <= $fcount; $i++) {
                                 $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio') . "</td>\n";
                             }
                             $counter++;
                             $answertext = $mearow['question'];
                             //semantic differential question type?
                             if (strpos($mearow['question'], '|')) {
                                 $answertext2 = substr($mearow['question'], strpos($mearow['question'], '|') + 1);
                                 $question['ANSWER'] .= "\t\t\t<th class=\"answertextright\">{$answertext2}</th>\n";
                             }
                             $question['ANSWER'] .= "\t\t</tr>\n";
                         }
                         $question['ANSWER'] .= "\t</tbody>\n</table>\n";
                         break;
                         // ==================================================================
                     // ==================================================================
                     case "1":
                         //ARRAY (Flexible Labels) multi scale
                         $leftheader = $qidattributes['dualscale_headerA'][$sLanguageCode];
                         $rightheader = $qidattributes['dualscale_headerB'][$sLanguageCode];
                         $headstyle = 'style="padding-left: 20px; padding-right: 7px"';
                         $question['QUESTION_TYPE_HELP'] .= gT("Please choose the appropriate response for each item:");
                         $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $sLanguageCode, $surveyid);
                         $question['ANSWER'] .= "\n<table>\n\t<thead>\n";
                         $condition = "qid= '{$deqrow['qid']}'  AND language= '{$sLanguageCode}' AND scale_id=0";
                         $fresult = Answer::model()->getAllRecords($condition, array('sortorder', 'code'));
                         $fresult = $fresult->readAll();
                         $fcount = count($fresult);
                         $fwidth = "120";
                         $l1 = 0;
                         $printablesurveyoutput2 = "\t\t\t<td>&nbsp;</td>\n";
                         $myheader2 = '';
                         foreach ($fresult as $frow) {
                             $printablesurveyoutput2 .= "\t\t\t<th>{$frow['answer']}" . self::_addsgqacode(" (" . $frow['code'] . ")") . "</th>\n";
                             $myheader2 .= "<td></td>";
                             $l1++;
                         }
                         // second scale
                         $printablesurveyoutput2 .= "\t\t\t<td>&nbsp;</td>\n";
                         //$fquery1 = "SELECT * FROM {{answers}} WHERE qid='{$deqrow['qid']}'  AND language='{$sLanguageCode}' AND scale_id=1 ORDER BY sortorder, code";
                         // $fresult1 = Yii::app()->db->createCommand($fquery1)->query();
                         $fresult1 = Answer::model()->getAllRecords(" qid='{$deqrow['qid']}'  AND language='{$sLanguageCode}' AND scale_id=1 ", array('sortorder', 'code'));
                         $fresult1 = $fresult1->readAll();
                         $fcount1 = count($fresult1);
                         $fwidth = "120";
                         $l2 = 0;
                         //array to temporary store second scale question codes
                         $scale2array = array();
                         foreach ($fresult1 as $frow1) {
                             $printablesurveyoutput2 .= "\t\t\t<th>{$frow1['answer']}" . self::_addsgqacode(" (" . $frow1['code'] . ")") . "</th>\n";
                             //add current question code
                             $scale2array[$l2] = $frow1['code'];
                             $l2++;
                         }
                         // build header if needed
                         if ($leftheader != '' || $rightheader != '') {
                             $myheader = "\t\t\t<td>&nbsp;</td>";
                             $myheader .= "\t\t\t<th colspan=\"" . $l1 . "\">{$leftheader}</th>\n";
                             if ($rightheader != '') {
                                 // $myheader .= "\t\t\t\t\t" .$myheader2;
                                 $myheader .= "\t\t\t<td>&nbsp;</td>";
                                 $myheader .= "\t\t\t<th colspan=\"" . $l2 . "\">{$rightheader}</td>\n";
                             }
                             $myheader .= "\t\t\t\t</tr>\n";
                         } else {
                             $myheader = '';
                         }
                         $question['ANSWER'] .= $myheader . "\t\t</tr>\n\n\t\t<tr>\n";
                         $question['ANSWER'] .= $printablesurveyoutput2;
                         $question['ANSWER'] .= "\t\t</tr>\n\t</thead>\n\n\t<tbody>\n";
                         $rowclass = 'array1';
                         //counter for each subquestion
                         $sqcounter = 0;
                         $mearesult = Question::model()->getAllRecords(" parent_qid={$deqrow['qid']}  AND language='{$sLanguageCode}' ", array('question_order'));
                         foreach ($mearesult->readAll() as $mearow) {
                             $question['ANSWER'] .= "\t\t<tr class=\"{$rowclass}\">\n";
                             $rowclass = alternation($rowclass, 'row');
                             $answertext = $mearow['question'] . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . "#0) / (" . $fieldname . $mearow['title'] . "#1)");
                             if (strpos($answertext, '|')) {
                                 $answertext = substr($answertext, 0, strpos($answertext, '|'));
                             }
                             $question['ANSWER'] .= "\t\t\t<th class=\"answertext\">{$answertext}</th>\n";
                             for ($i = 1; $i <= $fcount; $i++) {
                                 $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio') . "</td>\n";
                             }
                             $question['ANSWER'] .= "\t\t\t<td>&nbsp;</td>\n";
                             for ($i = 1; $i <= $fcount1; $i++) {
                                 $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio') . "</td>\n";
                             }
                             $answertext = $mearow['question'];
                             if (strpos($answertext, '|')) {
                                 $answertext = substr($answertext, strpos($answertext, '|') + 1);
                                 $question['ANSWER'] .= "\t\t\t<th class=\"answertextright\">{$answertext}</th>\n";
                             }
                             $question['ANSWER'] .= "\t\t</tr>\n";
                             //increase subquestion counter
                             $sqcounter++;
                         }
                         $question['ANSWER'] .= "\t</tbody>\n</table>\n";
                         break;
                         // ==================================================================
                     // ==================================================================
                     case "H":
                         //ARRAY (Flexible Labels) by Column
                         //$headstyle="style='border-left-style: solid; border-left-width: 1px; border-left-color: #AAAAAA'";
                         $headstyle = "style='padding-left: 20px; padding-right: 7px'";
                         $condition = "parent_qid= '{$deqrow['qid']}'  AND language= '{$sLanguageCode}'";
                         $fresult = Question::model()->getAllRecords($condition, array('question_order', 'title'));
                         $fresult = $fresult->readAll();
                         $question['QUESTION_TYPE_HELP'] .= gT("Please choose the appropriate response for each item:");
                         $question['ANSWER'] .= "\n<table>\n\t<thead>\n\t\t<tr>\n\t\t\t<td>&nbsp;</td>\n";
                         $fcount = count($fresult);
                         $fwidth = "120";
                         $i = 0;
                         foreach ($fresult as $frow) {
                             $question['ANSWER'] .= "\t\t\t<th>{$frow['question']}" . self::_addsgqacode(" (" . $fieldname . $frow['title'] . ")") . "</th>\n";
                             $i++;
                         }
                         $question['ANSWER'] .= "\t\t</tr>\n\t</thead>\n\n\t<tbody>\n";
                         $a = 1;
                         $rowclass = 'array1';
                         $mearesult = Answer::model()->getAllRecords(" qid='{$deqrow['qid']}' AND scale_id=0 AND language='{$sLanguageCode}' ", array('sortorder', 'code'));
                         foreach ($mearesult->readAll() as $mearow) {
                             //$_POST['type']=$type;
                             $question['ANSWER'] .= "\t\t<tr class=\"{$rowclass}\">\n";
                             $rowclass = alternation($rowclass, 'row');
                             $question['ANSWER'] .= "\t\t\t<th class=\"answertext\">{$mearow['answer']}" . self::_addsgqacode(" (" . $mearow['code'] . ")") . "</th>\n";
                             //$printablesurveyoutput .="\t\t\t\t\t<td>";
                             for ($i = 1; $i <= $fcount; $i++) {
                                 $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio') . "</td>\n";
                             }
                             //$printablesurveyoutput .="\t\t\t\t\t</tr></table></td>\n";
                             $question['ANSWER'] .= "\t\t</tr>\n";
                             $a++;
                         }
                         $question['ANSWER'] .= "\t</tbody>\n</table>\n";
                         break;
                     case "|":
                         // File Upload
                         $question['QUESTION_TYPE_HELP'] .= "Kindly attach the aforementioned documents along with the survey";
                         break;
                         // === END SWITCH ===================================================
                 }
                 $question['QUESTION_TYPE_HELP'] = self::_star_replace($question['QUESTION_TYPE_HELP']);
                 $group['QUESTIONS'] .= self::_populate_template('question', $question);
             }
             if ($bGroupHasVisibleQuestions) {
                 $survey_output['GROUPS'] .= self::_populate_template('group', $group);
             }
         }
         $survey_output['THEREAREXQUESTIONS'] = str_replace('{NUMBEROFQUESTIONS}', $total_questions, gT('There are {NUMBEROFQUESTIONS} questions in this survey'));
         // START recursive tag stripping.
         // PHP 5.1.0 introduced the count parameter for preg_replace() and thus allows this procedure to run with only one regular expression.
         // Previous version of PHP needs two regular expressions to do the same thing and thus will run a bit slower.
         $server_is_newer = version_compare(PHP_VERSION, '5.1.0', '>');
         $rounds = 0;
         while ($rounds < 1) {
             $replace_count = 0;
             if ($server_is_newer) {
                 $survey_output['GROUPS'] = preg_replace(array('/<td>(?:&nbsp;|&#160;| )?<\\/td>/isU', '/<th[^>]*>(?:&nbsp;|&#160;| )?<\\/th>/isU', '/<([^ >]+)[^>]*>(?:&nbsp;|&#160;|\\r\\n|\\n\\r|\\n|\\r|\\t| )*<\\/\\1>/isU'), array('[[EMPTY-TABLE-CELL]]', '[[EMPTY-TABLE-CELL-HEADER]]', ''), $survey_output['GROUPS'], -1, $replace_count);
             } else {
                 $survey_output['GROUPS'] = preg_replace(array('/<td>(?:&nbsp;|&#160;| )?<\\/td>/isU', '/<th[^>]*>(?:&nbsp;|&#160;| )?<\\/th>/isU', '/<([^ >]+)[^>]*>(?:&nbsp;|&#160;|\\r\\n|\\n\\r|\\n|\\r|\\t| )*<\\/\\1>/isU'), array('[[EMPTY-TABLE-CELL]]', '[[EMPTY-TABLE-CELL-HEADER]]', ''), $survey_output['GROUPS']);
                 $replace_count = preg_match('/<([^ >]+)[^>]*>(?:&nbsp;|&#160;|\\r\\n|\\n\\r|\\n|\\r|\\t| )*<\\/\\1>/isU', $survey_output['GROUPS']);
             }
             if ($replace_count == 0) {
                 ++$rounds;
                 $survey_output['GROUPS'] = preg_replace(array('/\\[\\[EMPTY-TABLE-CELL\\]\\]/', '/\\[\\[EMPTY-TABLE-CELL-HEADER\\]\\]/', '/\\n(?:\\t*\\n)+/'), array('<td>&nbsp;</td>', '<th>&nbsp;</th>', "\n"), $survey_output['GROUPS']);
             }
         }
         $survey_output['GROUPS'] = preg_replace('/(<div[^>]*>){NOTEMPTY}(<\\/div>)/', '\\1&nbsp;\\2', $survey_output['GROUPS']);
         // END recursive empty tag stripping.
         echo self::_populate_template('survey', $survey_output);
     }
     // End print
 }
Ejemplo n.º 7
0
 'template'=>array(
     'type'=>'select',
     'label'=>gT("Template"),
     'options'=>$aTemplateOptions,
     'current'=>$esrow['template'],
     'selectOptions'=>array(
         'minimumResultsForSearch'=>15,
     ),
     'events'=>array(
         'change'=>'js: function(event) {  templatechange(event.val) } ',
     ),
 ),
 'preview'=>array(
     'type'=>'info',
     'label'=>gT("Template preview"),
     'content'=>CHtml::image(getTemplateURL($esrow['template']).'/preview.png',gT("Template preview image"),array('id'=>'preview','class'=>'img-thumbnail')),
 ),
 'showwelcome'=>array(
     'type'=>'select',
     'label'=>gT("Show welcome screen?"),
     'options'=>array(
         "Y"=>gT("Yes",'unescaped'),
         "N"=>gT("No",'unescaped'),
     ),
     'current'=>$esrow['showwelcome'],
 ),
 'navigationdelay'=>array(
     'type'=>'int',
     'label'=>gT("Navigation delay (seconds)"),
     'htmlOptions'=>array(
         'style'=>'width:12em',
Ejemplo n.º 8
0
}
if (!empty($futureSurveys)) {
    $list .= "</ul><div class=\"survey-list-heading\">" . gT("Following survey(s) are not yet active but you can register for them.") . "</div><ul>";
    foreach ($futureSurveys as $survey) {
        $list .= CHtml::openTag('li');
        $list .= CHtml::link(stripJavaScript($survey->localizedTitle), array('survey/index', 'sid' => $survey->sid, 'lang' => App()->lang->langcode), array('class' => 'surveytitle'));
        $list .= CHtml::closeTag('li');
        $list .= CHtml::tag('div', array('data-regformsurvey' => $survey->sid));
    }
}
if (empty($list)) {
    $list = CHtml::openTag('li', array('class' => 'surveytitle')) . gT("No available surveys") . CHtml::closeTag('li');
}
$data['surveylist'] = array("nosid" => "", "contact" => sprintf(App()->lang->gT("Please contact %s ( %s ) for further assistance."), Yii::app()->getConfig("siteadminname"), encodeEmail(Yii::app()->getConfig("siteadminemail"))), "listheading" => App()->lang->gT("The following surveys are available:"), "list" => $list);
$data['templatedir'] = getTemplatePath(Yii::app()->getConfig("defaulttemplate"));
$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']);
                        <?php 
    }
}
?>
            </select>
        </li>

        <li><label for='preview'><?php 
$clang->eT("Template Preview:");
?>
</label>
            <img alt='<?php 
$clang->eT("Template preview image");
?>
' name='preview' id='preview' src='<?php 
echo getTemplateURL($esrow['template']);
?>
/preview.png' />
        </li>


        <li><label for='showwelcome'><?php 
$clang->eT("Show welcome screen?");
?>
</label>
            <select id='showwelcome' name='showwelcome'>
                <option value='Y'
                    <?php 
if (!$esrow['showwelcome'] || $esrow['showwelcome'] == "Y") {
    ?>
                        selected='selected'
Ejemplo n.º 10
0
    function action()
    {
        global $surveyid;
        global $thissurvey, $thisstep;
        global $clienttoken, $tokensexist, $token;
        global $clang;
        $clang = Yii::app()->lang;
        @ini_set('session.gc_maxlifetime', Yii::app()->getConfig('iSessionExpirationTime'));
        $this->_loadRequiredHelpersAndLibraries();
        $param = $this->_getParameters(func_get_args(), $_POST);
        $surveyid = $param['sid'];
        Yii::app()->setConfig('surveyID', $surveyid);
        $thisstep = $param['thisstep'];
        $move = $param['move'];
        $clienttoken = $param['token'];
        $standardtemplaterootdir = Yii::app()->getConfig('standardtemplaterootdir');
        // unused vars in this method (used in methods using compacted method vars)
        @($loadname = $param['loadname']);
        @($loadpass = $param['loadpass']);
        $sitename = Yii::app()->getConfig('sitename');
        if (isset($param['newtest']) && $param['newtest'] == "Y") {
            killSurveySession($surveyid);
        }
        list($surveyExists, $isSurveyActive) = $this->_surveyExistsAndIsActive($surveyid);
        // collect all data in this method to pass on later
        $redata = compact(array_keys(get_defined_vars()));
        $clang = $this->_loadLimesurveyLang($surveyid);
        if ($this->_isClientTokenDifferentFromSessionToken($clienttoken, $surveyid)) {
            $asMessage = array($clang->gT('Token mismatch'), $clang->gT('The token you provided doesn\'t match the one in your session.'), $clang->gT('Please wait to begin with a new session.'));
            $this->_createNewUserSessionAndRedirect($surveyid, $redata, __LINE__, $asMessage);
        }
        if ($this->_isSurveyFinished($surveyid)) {
            $asMessage = array($clang->gT('Previous session is set to be finished.'), $clang->gT('Your browser reports that it was used previously to answer this survey. We are resetting the session so that you can start from the beginning.'), $clang->gT('Please wait to begin with a new session.'));
            $this->_createNewUserSessionAndRedirect($surveyid, $redata, __LINE__, $asMessage);
        }
        if ($this->_isPreviewAction($param) && !$this->_canUserPreviewSurvey($surveyid)) {
            $asMessage = array($clang->gT('Error'), $clang->gT('We are sorry but you don\'t have permissions to do this.'));
            $this->_niceExit($redata, __LINE__, null, $asMessage);
        }
        if ($this->_surveyCantBeViewedWithCurrentPreviewAccess($surveyid, $isSurveyActive, $surveyExists)) {
            $bPreviewRight = $this->_userHasPreviewAccessSession($surveyid);
            if ($bPreviewRight === false) {
                $asMessage = array($clang->gT("Error"), $clang->gT("We are sorry but you don't have permissions to do this."), sprintf($clang->gT("Please contact %s ( %s ) for further assistance."), $thissurvey['adminname'], $thissurvey['adminemail']));
                $this->_niceExit($redata, __LINE__, null, $asMessage);
            }
        }
        // TODO can this be moved to the top?
        // (Used to be global, used in ExpressionManager, merged into amVars. If not filled in === '')
        // can this be added in the first computation of $redata?
        if (isset($_SESSION['survey_' . $surveyid]['srid'])) {
            $saved_id = $_SESSION['survey_' . $surveyid]['srid'];
        }
        // recompute $redata since $saved_id used to be a global
        $redata = compact(array_keys(get_defined_vars()));
        /*if ( $this->_didSessionTimeOut() )
          {
          // @TODO is this still required ?
          $asMessage = array(
          $clang->gT("Error"),
          $clang->gT("We are sorry but your session has expired."),
          $clang->gT("Either you have been inactive for too long, you have cookies disabled for your browser, or there were problems with your connection."),
          sprintf($clang->gT("Please contact %s ( %s ) for further assistance."),$thissurvey['adminname'],$thissurvey['adminemail'])
          );
          $this->_niceExit($redata, __LINE__, null, $asMessage);
          };*/
        // Set the language of the survey, either from POST, GET parameter of session var
        if (!empty($_REQUEST['lang'])) {
            $sTempLanguage = sanitize_languagecode($_REQUEST['lang']);
        } elseif (!empty($param['lang'])) {
            $sTempLanguage = sanitize_languagecode($param['lang']);
        } elseif (isset($_SESSION['survey_' . $surveyid]['s_lang'])) {
            $sTempLanguage = $_SESSION['survey_' . $surveyid]['s_lang'];
        } else {
            $sTempLanguage = '';
        }
        //CHECK FOR REQUIRED INFORMATION (sid)
        if ($surveyid && $surveyExists) {
            LimeExpressionManager::SetSurveyId($surveyid);
            // must be called early - it clears internal cache if a new survey is being used
            $clang = SetSurveyLanguage($surveyid, $sTempLanguage);
            UpdateSessionGroupList($surveyid, $sTempLanguage);
            // to refresh the language strings in the group list session variable
            UpdateFieldArray();
            // to refresh question titles and question text
        } else {
            if (!is_null($param['lang'])) {
                $sDisplayLanguage = $param['lang'];
            } else {
                $sDisplayLanguage = Yii::app()->getConfig('defaultlang');
            }
            $clang = $this->_loadLimesurveyLang($sDisplayLanguage);
            $languagechanger = makeLanguageChanger($sDisplayLanguage);
            //Find out if there are any publicly available surveys
            $query = "SELECT sid, surveyls_title, publicstatistics, language\n            FROM {{surveys}}\n            INNER JOIN {{surveys_languagesettings}}\n            ON ( surveyls_survey_id = sid  )\n            AND (surveyls_language=language)\n            WHERE\n            active='Y'\n            AND listpublic='Y'\n            AND ((expires >= '" . date("Y-m-d H:i") . "') OR (expires is null))\n            AND ((startdate <= '" . date("Y-m-d H:i") . "') OR (startdate is null))\n            ORDER BY surveyls_title";
            $result = dbExecuteAssoc($query, false, true) or safeDie("Could not connect to database. If you try to install LimeSurvey please refer to the <a href='http://docs.limesurvey.org'>installation docs</a> and/or contact the system administrator of this webpage.");
            //Checked
            $list = array();
            foreach ($result->readAll() as $rows) {
                $querylang = "SELECT surveyls_title\n                FROM {{surveys_languagesettings}}\n                WHERE surveyls_survey_id={$rows['sid']}\n                AND surveyls_language='{$sDisplayLanguage}'";
                $resultlang = Yii::app()->db->createCommand($querylang)->queryRow();
                if ($resultlang['surveyls_title']) {
                    $rows['surveyls_title'] = $resultlang['surveyls_title'];
                    $langtag = "";
                } else {
                    $langtag = "lang=\"{$rows['language']}\"";
                }
                $link = "<li><a href='" . $this->getController()->createUrl('/survey/index/sid/' . $rows['sid']);
                if (isset($param['lang']) && $langtag == "") {
                    $link .= "/lang-" . sanitize_languagecode($param['lang']);
                }
                $link .= "' {$langtag} class='surveytitle'>" . $rows['surveyls_title'] . "</a>\n";
                if ($rows['publicstatistics'] == 'Y') {
                    $link .= "<a href='" . $this->getController()->createUrl("/statistics_user/action/surveyid/" . $rows['sid']) . "/language/" . $sDisplayLanguage . "'>(" . $clang->gT('View statistics') . ")</a>";
                }
                $link .= "</li>\n";
                $list[] = $link;
            }
            //Check for inactive surveys which allow public registration.
            // TODO add a new template replace {SURVEYREGISTERLIST} ?
            $squery = "SELECT sid, surveyls_title, publicstatistics, language\n            FROM {{surveys}}\n            INNER JOIN {{surveys_languagesettings}}\n            ON (surveyls_survey_id = sid)\n            AND (surveyls_language=language)\n            WHERE allowregister='Y'\n            AND active='Y'\n            AND listpublic='Y'\n            AND ((expires >= '" . date("Y-m-d H:i") . "') OR (expires is null))\n            AND (startdate >= '" . date("Y-m-d H:i") . "')\n            ORDER BY surveyls_title";
            $sresult = dbExecuteAssoc($squery) or safeDie("Couldn't execute {$squery}");
            $aRows = $sresult->readAll();
            if (count($aRows) > 0) {
                $list[] = "</ul>" . " <div class=\"survey-list-heading\">" . $clang->gT("Following survey(s) are not yet active but you can register for them.") . "</div>" . " <ul>";
                // TODO give it to template
                foreach ($aRows as $rows) {
                    $querylang = "SELECT surveyls_title\n                    FROM {{surveys_languagesettings}}\n                    WHERE surveyls_survey_id={$rows['sid']}\n                    AND surveyls_language='{$sDisplayLanguage}'";
                    $resultlang = Yii::app()->db->createCommand($querylang)->queryRow();
                    if ($resultlang['surveyls_title']) {
                        $rows['surveyls_title'] = $resultlang['surveyls_title'];
                        $langtag = "";
                    } else {
                        $langtag = "lang=\"{$rows['language']}\"";
                    }
                    $link = "<li><a href=\"#\" id='inactivesurvey' onclick = 'sendreq(" . $rows['sid'] . ");' ";
                    //$link = "<li><a href=\"#\" id='inactivesurvey' onclick = 'convertGETtoPOST(".$this->getController()->createUrl('survey/send/')."?sid={$rows['sid']}&amp;)sendreq(".$rows['sid'].",".$rows['startdate'].",".$rows['expires'].");' ";
                    $link .= " {$langtag} class='surveytitle'>" . $rows['surveyls_title'] . "</a>\n";
                    $link .= "</li><div id='regform'></div>\n";
                    $list[] = $link;
                }
            }
            if (count($list) < 1) {
                $list[] = "<li class='surveytitle'>" . $clang->gT("No available surveys") . "</li>";
            }
            if (!$surveyid) {
                $thissurvey['name'] = Yii::app()->getConfig("sitename");
                $nosid = $clang->gT("You have not provided a survey identification number");
            } else {
                $thissurvey['name'] = $clang->gT("The survey identification number is invalid");
                $nosid = $clang->gT("The survey identification number is invalid");
            }
            $surveylist = array("nosid" => $nosid, "contact" => sprintf($clang->gT("Please contact %s ( %s ) for further assistance."), Yii::app()->getConfig("siteadminname"), encodeEmail(Yii::app()->getConfig("siteadminemail"))), "listheading" => $clang->gT("The following surveys are available:"), "list" => implode("\n", $list));
            $data['thissurvey'] = $thissurvey;
            //$data['privacy'] = $privacy;
            $data['surveylist'] = $surveylist;
            $data['surveyid'] = $surveyid;
            $data['templatedir'] = getTemplatePath(Yii::app()->getConfig("defaulttemplate"));
            $data['templateurl'] = getTemplateURL(Yii::app()->getConfig("defaulttemplate")) . "/";
            $data['templatename'] = Yii::app()->getConfig("defaulttemplate");
            $data['sitename'] = Yii::app()->getConfig("sitename");
            $data['languagechanger'] = $languagechanger;
            //A nice exit
            sendCacheHeaders();
            doHeader();
            $this->_printTemplateContent(getTemplatePath(Yii::app()->getConfig("defaulttemplate")) . "/startpage.pstpl", $data, __LINE__);
            $this->_printTemplateContent(getTemplatePath(Yii::app()->getConfig("defaulttemplate")) . "/surveylist.pstpl", $data, __LINE__);
            echo '<script type="text/javascript" >
            function sendreq(surveyid)
            {

            $.ajax({
            type: "GET",
            url: "' . $this->getController()->createUrl("/register/ajaxregisterform/surveyid") . '/" + surveyid,
            }).done(function(msg) {
            document.getElementById("regform").innerHTML = msg;
            });
            }
            </script>';
            $this->_printTemplateContent(getTemplatePath(Yii::app()->getConfig("defaulttemplate")) . "/endpage.pstpl", $data, __LINE__);
            doFooter();
            exit;
        }
        // Get token
        if (!isset($token)) {
            $token = $clienttoken;
        }
        //GET BASIC INFORMATION ABOUT THIS SURVEY
        $thissurvey = getSurveyInfo($surveyid, $_SESSION['survey_' . $surveyid]['s_lang']);
        //SEE IF SURVEY USES TOKENS
        if ($surveyExists == 1 && tableExists('{{tokens_' . $thissurvey['sid'] . '}}')) {
            $tokensexist = 1;
        } else {
            $tokensexist = 0;
            unset($_POST['token']);
            unset($param['token']);
            unset($token);
            unset($clienttoken);
        }
        //SET THE TEMPLATE DIRECTORY
        $thistpl = getTemplatePath($thissurvey['templatedir']);
        $timeadjust = Yii::app()->getConfig("timeadjust");
        //MAKE SURE SURVEY HASN'T EXPIRED
        if ($thissurvey['expiry'] != '' and dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust) > $thissurvey['expiry'] && $thissurvey['active'] != 'N') {
            $redata = compact(array_keys(get_defined_vars()));
            $asMessage = array($clang->gT("Error"), $clang->gT("This survey is no longer available."), sprintf($clang->gT("Please contact %s ( %s ) for further assistance."), $thissurvey['adminname'], $thissurvey['adminemail']));
            $this->_niceExit($redata, __LINE__, $thistpl, $asMessage);
        }
        //MAKE SURE SURVEY IS ALREADY VALID
        if ($thissurvey['startdate'] != '' and dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust) < $thissurvey['startdate'] && $thissurvey['active'] != 'N') {
            $redata = compact(array_keys(get_defined_vars()));
            $asMessage = array($clang->gT("Error"), $clang->gT("This survey is not yet started."), sprintf($clang->gT("Please contact %s ( %s ) for further assistance."), $thissurvey['adminname'], $thissurvey['adminemail']));
            $this->_niceExit($redata, __LINE__, $thistpl, $asMessage);
        }
        //CHECK FOR PREVIOUSLY COMPLETED COOKIE
        //If cookies are being used, and this survey has been completed, a cookie called "PHPSID[sid]STATUS" will exist (ie: SID6STATUS) and will have a value of "COMPLETE"
        $sCookieName = "LS_" . $surveyid . "_STATUS";
        if (isset($_COOKIE[$sCookieName]) && $_COOKIE[$sCookieName] == "COMPLETE" && $thissurvey['usecookie'] == "Y" && $tokensexist != 1 && (!isset($param['newtest']) || $param['newtest'] != "Y")) {
            $redata = compact(array_keys(get_defined_vars()));
            $asMessage = array($clang->gT("Error"), $clang->gT("You have already completed this survey."), sprintf($clang->gT("Please contact %s ( %s ) for further assistance."), $thissurvey['adminname'], $thissurvey['adminemail']));
            $this->_niceExit($redata, __LINE__, $thistpl, $asMessage);
        }
        if (isset($_GET['loadall']) && $_GET['loadall'] == "reload") {
            if (returnGlobal('loadname') && returnGlobal('loadpass')) {
                $_POST['loadall'] = "reload";
            }
        }
        //LOAD SAVED SURVEY
        if (isset($_POST['loadall']) && $_POST['loadall'] == "reload") {
            $errormsg = "";
            if (!isset($param['loadname']) || $param['loadname'] == null) {
                $errormsg .= $clang->gT("You did not provide a name") . "<br />\n";
            }
            if (!isset($param['loadpass']) || $param['loadpass'] == null) {
                $errormsg .= $clang->gT("You did not provide a password") . "<br />\n";
            }
            // if security question answer is incorrect
            // Not called if scid is set in GET params (when using email save/reload reminder URL)
            if (function_exists("ImageCreate") && isCaptchaEnabled('saveandloadscreen', $thissurvey['usecaptcha'])) {
                if ((!isset($_POST['loadsecurity']) || !isset($_SESSION['survey_' . $surveyid]['secanswer']) || $_POST['loadsecurity'] != $_SESSION['survey_' . $surveyid]['secanswer']) && !isset($_GET['scid'])) {
                    $errormsg .= $clang->gT("The answer to the security question is incorrect.") . "<br />\n";
                }
            }
            // Load session before loading the values from the saved data
            if (isset($_GET['loadall'])) {
                buildsurveysession($surveyid);
            }
            $_SESSION['survey_' . $surveyid]['holdname'] = $param['loadname'];
            //Session variable used to load answers every page.
            $_SESSION['survey_' . $surveyid]['holdpass'] = $param['loadpass'];
            //Session variable used to load answers every page.
            if ($errormsg == "") {
                loadanswers();
            }
            $move = "movenext";
            if ($errormsg) {
                $_POST['loadall'] = $clang->gT("Load unfinished survey");
            }
        }
        //Allow loading of saved survey
        if (isset($_POST['loadall']) && $_POST['loadall'] == $clang->gT("Load unfinished survey")) {
            $redata = compact(array_keys(get_defined_vars()));
            Yii::import("application.libraries.Load_answers");
            $tmp = new Load_answers();
            $tmp->run($redata);
        }
        //Check if TOKEN is used for EVERY PAGE
        //This function fixes a bug where users able to submit two surveys/votes
        //by checking that the token has not been used at each page displayed.
        // bypass only this check at first page (Step=0) because
        // this check is done in buildsurveysession and error message
        // could be more interresting there (takes into accound captcha if used)
        if ($tokensexist == 1 && isset($token) && $token && isset($_SESSION['survey_' . $surveyid]['step']) && $_SESSION['survey_' . $surveyid]['step'] > 0 && tableExists("tokens_{$surveyid}}}")) {
            //check if tokens actually haven't been already used
            $areTokensUsed = usedTokens(trim(strip_tags(returnGlobal('token'))), $surveyid);
            // check if token actually does exist
            // check also if it is allowed to change survey after completion
            if ($thissurvey['alloweditaftercompletion'] == 'Y') {
                $sQuery = "SELECT * FROM {{tokens_" . $surveyid . "}} WHERE token='" . $token . "'";
            } else {
                $sQuery = "SELECT * FROM {{tokens_" . $surveyid . "}} WHERE token='" . $token . "' AND (completed = 'N' or completed='')";
            }
            $aRow = Yii::app()->db->createCommand($sQuery)->queryRow();
            $tokendata = $aRow;
            if (!$aRow || $areTokensUsed && $thissurvey['alloweditaftercompletion'] != 'Y') {
                sendCacheHeaders();
                doHeader();
                //TOKEN DOESN'T EXIST OR HAS ALREADY BEEN USED. EXPLAIN PROBLEM AND EXIT
                $redata = compact(array_keys(get_defined_vars()));
                $this->_printTemplateContent($thistpl . '/startpage.pstpl', $redata, __LINE__);
                $this->_printTemplateContent($thistpl . '/survey.pstpl', $redata, __LINE__);
                $asMessage = array(null, $clang->gT("This is a controlled survey. You need a valid token to participate."), sprintf($clang->gT("For further information please contact %s"), $thissurvey['adminname'] . " (<a href='mailto:{$thissurvey['adminemail']}'>" . "{$thissurvey['adminemail']}</a>)"));
                $this->_niceExit($redata, __LINE__, $thistpl, $asMessage, true);
            }
        }
        if ($tokensexist == 1 && isset($token) && $token && tableExists("{{tokens_" . $surveyid . "}}")) {
            // check also if it is allowed to change survey after completion
            if ($thissurvey['alloweditaftercompletion'] == 'Y') {
                $tkquery = "SELECT * FROM {{tokens_" . $surveyid . "}} WHERE token='" . $token . "'";
            } else {
                $tkquery = "SELECT * FROM {{tokens_" . $surveyid . "}} WHERE token='" . $token . "' AND (completed = 'N' or completed='')";
            }
            $tkresult = dbExecuteAssoc($tkquery);
            //Checked
            $tokendata = $tkresult->read();
            if (isset($tokendata['validfrom']) && (trim($tokendata['validfrom']) != '' && $tokendata['validfrom'] > dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust)) || isset($tokendata['validuntil']) && (trim($tokendata['validuntil']) != '' && $tokendata['validuntil'] < dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust))) {
                sendCacheHeaders();
                doHeader();
                //TOKEN DOESN'T EXIST OR HAS ALREADY BEEN USED. EXPLAIN PROBLEM AND EXIT
                $redata = compact(array_keys(get_defined_vars()));
                $this->_printTemplateContent($thistpl . '/startpage.pstpl', $redata, __LINE__);
                $this->_printTemplateContent($thistpl . '/survey.pstpl', $redata, __LINE__);
                $asMessage = array(null, $clang->gT("We are sorry but you are not allowed to enter this survey."), $clang->gT("Your token seems to be valid but can be used only during a certain time period."), sprintf($clang->gT("For further information please contact %s"), $thissurvey['adminname'] . " (<a href='mailto:{$thissurvey['adminemail']}'>" . "{$thissurvey['adminemail']}</a>)"));
                $this->_niceExit($redata, __LINE__, $thistpl, $asMessage, true);
            }
        }
        //Clear session and remove the incomplete response if requested.
        if (isset($move) && $move == "clearall") {
            // delete the response but only if not already completed
            $s_lang = $_SESSION['survey_' . $surveyid]['s_lang'];
            if (isset($_SESSION['survey_' . $surveyid]['srid']) && !Survey_dynamic::model($surveyid)->isCompleted($_SESSION['survey_' . $surveyid]['srid'])) {
                // delete the response but only if not already completed
                $result = dbExecuteAssoc('DELETE FROM {{survey_' . $surveyid . '}} WHERE id=' . $_SESSION['survey_' . $surveyid]['srid'] . " AND submitdate IS NULL");
                if ($result->count() > 0) {
                    // Using count() here *should* be okay for MSSQL because it is a delete statement
                    // find out if there are any fuqt questions - checked
                    $fieldmap = createFieldMap($surveyid, 'short', false, false, $s_lang);
                    foreach ($fieldmap as $field) {
                        if ($field['type'] == "|" && !strpos($field['fieldname'], "_filecount")) {
                            if (!isset($qid)) {
                                $qid = array();
                            }
                            $qid[] = $field['fieldname'];
                        }
                    }
                    // if yes, extract the response json to those questions
                    if (isset($qid)) {
                        $query = "SELECT * FROM {{survey_" . $surveyid . "}} WHERE id=" . $_SESSION['survey_' . $surveyid]['srid'];
                        $result = dbExecuteAssoc($query);
                        foreach ($result->readAll() as $row) {
                            foreach ($qid as $question) {
                                $json = $row[$question];
                                if ($json == "" || $json == NULL) {
                                    continue;
                                }
                                // decode them
                                $phparray = json_decode($json);
                                foreach ($phparray as $metadata) {
                                    $target = Yii::app()->getConfig("uploaddir") . "/surveys/" . $surveyid . "/files/";
                                    // delete those files
                                    unlink($target . $metadata->filename);
                                }
                            }
                        }
                    }
                    // done deleting uploaded files
                }
                // also delete a record from saved_control when there is one
                dbExecuteAssoc('DELETE FROM {{saved_control}} WHERE srid=' . $_SESSION['survey_' . $surveyid]['srid'] . ' AND sid=' . $surveyid);
            }
            killSurveySession($surveyid);
            sendCacheHeaders();
            doHeader();
            $redata = compact(array_keys(get_defined_vars()));
            $this->_printTemplateContent($thistpl . '/startpage.pstpl', $redata, __LINE__);
            echo "\n\n<!-- JAVASCRIPT FOR CONDITIONAL QUESTIONS -->\n" . "\t<script type='text/javascript'>\n" . "\t<!--\n" . "function checkconditions(value, name, type, evt_type)\n" . "\t{\n" . "\t}\n" . "\t//-->\n" . "\t</script>\n\n";
            //Present the clear all page using clearall.pstpl template
            $this->_printTemplateContent($thistpl . '/clearall.pstpl', $redata, __LINE__);
            $this->_printTemplateContent($thistpl . '/endpage.pstpl', $redata, __LINE__);
            doFooter();
            exit;
        }
        //Check to see if a refering URL has been captured.
        if (!isset($_SESSION['survey_' . $surveyid]['refurl'])) {
            $_SESSION['survey_' . $surveyid]['refurl'] = GetReferringUrl();
            // do not overwrite refurl
        }
        // Let's do this only if
        //  - a saved answer record hasn't been loaded through the saved feature
        //  - the survey is not anonymous
        //  - the survey is active
        //  - a token information has been provided
        //  - the survey is setup to allow token-response-persistence
        if (!isset($_SESSION['survey_' . $surveyid]['srid']) && $thissurvey['anonymized'] == "N" && $thissurvey['active'] == "Y" && isset($token) && $token != '') {
            // load previous answers if any (dataentry with nosubmit)
            $sQuery = "SELECT id,submitdate,lastpage FROM {$thissurvey['tablename']} WHERE {$thissurvey['tablename']}.token='{$token}' order by id desc";
            $aRow = Yii::app()->db->createCommand($sQuery)->queryRow();
            if ($aRow) {
                if ($aRow['submitdate'] == '' && $thissurvey['tokenanswerspersistence'] == 'Y' || $aRow['submitdate'] != '' && $thissurvey['alloweditaftercompletion'] == 'Y') {
                    $_SESSION['survey_' . $surveyid]['srid'] = $aRow['id'];
                    if (!is_null($aRow['lastpage']) && $aRow['submitdate'] == '') {
                        $_SESSION['survey_' . $surveyid]['LEMtokenResume'] = true;
                        $_SESSION['survey_' . $surveyid]['step'] = $aRow['lastpage'];
                    }
                }
                buildsurveysession($surveyid);
                loadanswers();
            }
        }
        //        // SAVE POSTED ANSWERS TO DATABASE IF MOVE (NEXT,PREV,LAST, or SUBMIT) or RETURNING FROM SAVE FORM
        //        if (isset($move) || isset($_POST['saveprompt']))
        //        {
        //            $redata = compact(array_keys(get_defined_vars()));
        //            //save.php
        //            Yii::import("application.libraries.Save");
        //            $tmp = new Save();
        //            $tmp->run($redata);
        //
        //            // RELOAD THE ANSWERS INCASE SOMEONE ELSE CHANGED THEM
        //            if ($thissurvey['active'] == "Y" &&
        //            ( $thissurvey['allowsave'] == "Y" || $thissurvey['tokenanswerspersistence'] == "Y") )
        //            {
        //                loadanswers();
        //            }
        //        }
        if (isset($param['action']) && $param['action'] == 'previewgroup') {
            $thissurvey['format'] = 'G';
            buildsurveysession($surveyid, true);
        }
        if (isset($param['action']) && $param['action'] == 'previewquestion') {
            $thissurvey['format'] = 'S';
            buildsurveysession($surveyid, true);
        }
        sendCacheHeaders();
        //Send local variables to the appropriate survey type
        unset($redata);
        $redata = compact(array_keys(get_defined_vars()));
        Yii::import('application.helpers.SurveyRuntimeHelper');
        $tmp = new SurveyRuntimeHelper();
        $tmp->run($surveyid, $redata);
        if (isset($_POST['saveall']) || isset($flashmessage)) {
            echo "<script type='text/javascript'> \$(document).ready( function() { alert('" . $clang->gT("Your responses were successfully saved.", "js") . "');}) </script>";
        }
    }
    function run($actionID)
    {
        $surveyid = Yii::app()->session['LEMsid'];
        $oSurvey = Survey::model()->findByPk($surveyid);
        if (!$oSurvey) {
            throw new CHttpException(400);
        }
        // See for debug > 1
        $sLanguage = isset(Yii::app()->session['survey_' . $surveyid]['s_lang']) ? Yii::app()->session['survey_' . $surveyid]['s_lang'] : "";
        $uploaddir = Yii::app()->getConfig("uploaddir");
        $tempdir = Yii::app()->getConfig("tempdir");
        Yii::app()->loadHelper("database");
        // Fill needed var
        $sFileGetContent = Yii::app()->request->getParam('filegetcontents', '');
        // The file to view fu_ or fu_tmp
        $bDelete = Yii::app()->request->getParam('delete');
        $sFieldName = Yii::app()->request->getParam('fieldname');
        $sFileName = Yii::app()->request->getParam('filename', '');
        // The file to delete fu_ or fu_tmp
        $sOriginalFileName = Yii::app()->request->getParam('name', '');
        // Used for javascript return only
        $sMode = Yii::app()->request->getParam('mode');
        $sPreview = Yii::app()->request->getParam('preview', 0);
        // Validate and filter and throw error if problems
        // Using 'futmp_'.randomChars(15).'_'.$pathinfo['extension'] for filename, then remove all other characters
        $sFileGetContentFiltered = preg_replace('/[^a-zA-Z0-9_]/', '', $sFileGetContent);
        $sFileNameFiltered = preg_replace('/[^a-zA-Z0-9_]/', '', $sFileName);
        $sFieldNameFiltered = preg_replace('/[^X0-9]/', '', $sFieldName);
        if ($sFileGetContent != $sFileGetContentFiltered || $sFileName != $sFileNameFiltered || $sFieldName != $sFieldNameFiltered) {
            // If one seems to be a hack: Bad request
            throw new CHttpException(400);
            // See for debug > 1
        }
        if ($sFileGetContent) {
            if (substr($sFileGetContent, 0, 6) == 'futmp_') {
                $sFileDir = $tempdir . '/upload/';
            } elseif (substr($sFileGetContent, 0, 3) == 'fu_') {
                // Need to validate $_SESSION['srid'], and this file is from this srid !
                $sFileDir = "{$uploaddir}/surveys/{$surveyid}/files/";
            } else {
                throw new CHttpException(400);
                // See for debug > 1
            }
            if (is_file($sFileDir . $sFileGetContent)) {
                header('Content-Type: ' . CFileHelper::getMimeType($sFileDir . $sFileGetContent));
                readfile($sFileDir . $sFileGetContent);
                Yii::app()->end();
            } else {
                Yii::app()->end();
            }
        } elseif ($bDelete) {
            if (substr($sFileName, 0, 6) == 'futmp_') {
                $sFileDir = $tempdir . '/upload/';
            } elseif (substr($sFileName, 0, 3) == 'fu_') {
                // Need to validate $_SESSION['srid'], and this file is from this srid !
                $sFileDir = "{$uploaddir}/surveys/{$surveyid}/files/";
            } else {
                throw new CHttpException(400);
                // See for debug > 1
            }
            if (isset($_SESSION[$sFieldName])) {
                // We already have $sFieldName ?
                $sJSON = $_SESSION[$sFieldName];
                $aFiles = json_decode(stripslashes($sJSON), true);
                if (substr($sFileName, 0, 3) == 'fu_') {
                    $iFileIndex = 0;
                    $found = false;
                    foreach ($aFiles as $aFile) {
                        if ($aFile['filename'] == $sFileName) {
                            $found = true;
                            break;
                        }
                        $iFileIndex++;
                    }
                    if ($found == true) {
                        unset($aFiles[$iFileIndex]);
                    }
                    $_SESSION[$sFieldName] = ls_json_encode($aFiles);
                }
            }
            //var_dump($sFileDir.$sFilename);
            // Return some json to do a beautiful text
            if (@unlink($sFileDir . $sFileName)) {
                echo sprintf(gT('File %s deleted'), $sOriginalFileName);
            } else {
                echo gT('Oops, There was an error deleting the file');
            }
            Yii::app()->end();
        }
        if ($sMode == "upload") {
            $sTempUploadDir = $tempdir . '/upload/';
            // Check if exists and is writable
            if (!file_exists($sTempUploadDir)) {
                // Try to create
                mkdir($sTempUploadDir);
            }
            $filename = $_FILES['uploadfile']['name'];
            // Do we filter file name ? It's used on displaying only , but not save like that.
            //$filename = sanitize_filename($_FILES['uploadfile']['name']);// This remove all non alpha numeric characters and replaced by _ . Leave only one dot .
            $size = 0.001 * $_FILES['uploadfile']['size'];
            $preview = Yii::app()->session['preview'];
            $aFieldMap = createFieldMap($surveyid, 'short', false, false, $sLanguage);
            if (!isset($aFieldMap[$sFieldName])) {
                throw new CHttpException(400);
                // See for debug > 1
            }
            $aAttributes = getQuestionAttributeValues($aFieldMap[$sFieldName]['qid']);
            $maxfilesize = (int) $aAttributes['max_filesize'];
            $valid_extensions_array = explode(",", $aAttributes['allowed_filetypes']);
            $valid_extensions_array = array_map('trim', $valid_extensions_array);
            $pathinfo = pathinfo($_FILES['uploadfile']['name']);
            $ext = strtolower($pathinfo['extension']);
            $randfilename = 'futmp_' . randomChars(15) . '_' . $pathinfo['extension'];
            $randfileloc = $sTempUploadDir . $randfilename;
            // check to see that this file type is allowed
            // it is also  checked at the client side, but jst double checking
            if (!in_array($ext, $valid_extensions_array)) {
                $return = array("success" => false, "msg" => sprintf(gT("Sorry, this file extension (%s) is not allowed!"), $ext));
                //header('Content-Type: application/json');
                echo ls_json_encode($return);
                Yii::app()->end();
            }
            // If this is just a preview, don't save the file
            if ($preview) {
                if ($size > $maxfilesize) {
                    $return = array("success" => false, "msg" => sprintf(gT("Sorry, this file is too large. Only files upto %s KB are allowed."), $maxfilesize));
                    //header('Content-Type: application/json');
                    echo ls_json_encode($return);
                    Yii::app()->end();
                } else {
                    if (move_uploaded_file($_FILES['uploadfile']['tmp_name'], $randfileloc)) {
                        $return = array("success" => true, "file_index" => $filecount, "size" => $size, "name" => rawurlencode(basename($filename)), "ext" => $ext, "filename" => $randfilename, "msg" => gT("The file has been successfuly uploaded."));
                        // TODO : unlink this file since this is just a preview. But we can do it only if it's not needed, and still needed to have the file content
                        // Maybe use a javascript 'onunload' on preview question/group
                        // unlink($randfileloc)
                        //header('Content-Type: application/json');
                        echo ls_json_encode($return);
                        Yii::app()->end();
                    }
                }
            } else {
                // if everything went fine and the file was uploaded successfuly,
                // send the file related info back to the client
                $iFileUploadTotalSpaceMB = Yii::app()->getConfig("iFileUploadTotalSpaceMB");
                if ($size > $maxfilesize) {
                    $return = array("success" => false, "msg" => sprintf(gT("Sorry, this file is too large. Only files up to %s KB are allowed.", 'unescaped'), $maxfilesize));
                    //header('Content-Type: application/json');
                    echo ls_json_encode($return);
                    Yii::app()->end();
                } elseif ($iFileUploadTotalSpaceMB > 0 && calculateTotalFileUploadUsage() + $size / 1024 / 1024 > $iFileUploadTotalSpaceMB) {
                    $return = array("success" => false, "msg" => gT("We are sorry but there was a system error and your file was not saved. An email has been dispatched to notify the survey administrator.", 'unescaped'));
                    //header('Content-Type: application/json');
                    echo ls_json_encode($return);
                    Yii::app()->end();
                } elseif (move_uploaded_file($_FILES['uploadfile']['tmp_name'], $randfileloc)) {
                    $return = array("success" => true, "size" => $size, "name" => rawurlencode(basename($filename)), "ext" => $ext, "filename" => $randfilename, "msg" => gT("The file has been successfuly uploaded."));
                    //header('Content-Type: application/json');
                    echo ls_json_encode($return);
                    Yii::app()->end();
                } else {
                    // check for upload error
                    if ($_FILES['uploadfile']['error'] > 2) {
                        $return = array("success" => false, "msg" => gT("Sorry, there was an error uploading your file"));
                        //header('Content-Type: application/json');
                        echo ls_json_encode($return);
                        Yii::app()->end();
                    } else {
                        if ($_FILES['uploadfile']['error'] == 1 || $_FILES['uploadfile']['error'] == 2 || $size > $maxfilesize) {
                            $return = array("success" => false, "msg" => sprintf(gT("Sorry, this file is too large. Only files upto %s KB are allowed."), $maxfilesize));
                            //header('Content-Type: application/json');
                            echo ls_json_encode($return);
                            Yii::app()->end();
                        } else {
                            $return = array("success" => false, "msg" => gT("Unknown error"));
                            //header('Content-Type: application/json');
                            echo ls_json_encode($return);
                            Yii::app()->end();
                        }
                    }
                }
            }
            return;
        }
        $meta = '';
        App()->getClientScript()->registerPackage('jqueryui');
        App()->getClientScript()->registerPackage('jquery-superfish');
        $sNeededScriptVar = '
            var uploadurl = "' . $this->createUrl('/uploader/index/mode/upload/') . '";
            var imageurl = "' . Yii::app()->getConfig('imageurl') . '/";
            var surveyid = "' . $surveyid . '";
            var fieldname = "' . $sFieldName . '";
            var questgrppreview  = ' . $sPreview . ';
            csrfToken = ' . ls_json_encode(Yii::app()->request->csrfToken) . ';
            showpopups="' . Yii::app()->getConfig("showpopups") . '";
        ';
        $sLangScriptVar = "\n                uploadLang = {\n                     titleFld: '" . gT('Title', 'js') . "',\n                     commentFld: '" . gT('Comment', 'js') . "',\n                     errorNoMoreFiles: '" . gT('Sorry, no more files can be uploaded!', 'js') . "',\n                     errorOnlyAllowed: '" . gT('Sorry, only %s files can be uploaded for this question!', 'js') . "',\n                     uploading: '" . gT('Uploading', 'js') . "',\n                     selectfile: '" . gT('Select file', 'js') . "',\n                     errorNeedMore: '" . gT('Please upload %s more file(s).', 'js') . "',\n                     errorMoreAllowed: '" . gT('If you wish, you may upload %s more file(s); else you may return back to survey.', 'js') . "',\n                     errorMaxReached: '" . gT('The maximum number of files has been uploaded. You may return back to survey.', 'js') . "',\n                     errorTooMuch: '" . gT('The maximum number of files has been uploaded. You may return back to survey.', 'js') . "',\n                     errorNeedMoreConfirm: '" . gT("You need to upload %s more files for this question.\nAre you sure you want to exit?", 'js') . "',\n                     deleteFile : '" . gt('Delete', 'js') . "',\n                     editFile : '" . gt('Edit', 'js') . "',\n                    };\n        ";
        $aSurveyInfo = getSurveyInfo($surveyid, $sLanguage);
        $oEvent = new PluginEvent('beforeSurveyPage');
        $oEvent->set('surveyId', $surveyid);
        App()->getPluginManager()->dispatchEvent($oEvent);
        if (!is_null($oEvent->get('template'))) {
            $aSurveyInfo['templatedir'] = $event->get('template');
        }
        $sTemplateDir = getTemplatePath($aSurveyInfo['template']);
        $sTemplateUrl = getTemplateURL($aSurveyInfo['template']) . "/";
        App()->clientScript->registerScript('sNeededScriptVar', $sNeededScriptVar, CClientScript::POS_HEAD);
        App()->clientScript->registerScript('sLangScriptVar', $sLangScriptVar, CClientScript::POS_HEAD);
        App()->getClientScript()->registerScriptFile(Yii::app()->getConfig("generalscripts") . 'ajaxupload.js');
        App()->getClientScript()->registerScriptFile(Yii::app()->getConfig("generalscripts") . 'uploader.js');
        App()->getClientScript()->registerScriptFile("{$sTemplateUrl}template.js");
        App()->clientScript->registerCssFile(Yii::app()->getConfig("publicstyleurl") . "uploader.css");
        App()->getClientScript()->registerCssFile(Yii::app()->getConfig('publicstyleurl') . "uploader-files.css");
        if (file_exists($sTemplateDir . DIRECTORY_SEPARATOR . 'jquery-ui-custom.css')) {
            Yii::app()->getClientScript()->registerCssFile("{$sTemplateUrl}jquery-ui-custom.css");
        } elseif (file_exists($sTemplateDir . DIRECTORY_SEPARATOR . 'jquery-ui.css')) {
            Yii::app()->getClientScript()->registerCssFile("{$sTemplateUrl}jquery-ui.css");
        } else {
            Yii::app()->getClientScript()->registerCssFile(Yii::app()->getConfig('publicstyleurl') . "jquery-ui.css");
        }
        App()->clientScript->registerCssFile("{$sTemplateUrl}template.css");
        $header = getHeader($meta);
        echo $header;
        $fn = $sFieldName;
        $qid = (int) Yii::app()->request->getParam('qid');
        $minfiles = (int) Yii::app()->request->getParam('minfiles');
        $maxfiles = (int) Yii::app()->request->getParam('maxfiles');
        $qidattributes = getQuestionAttributeValues($qid);
        $qidattributes['max_filesize'] = floor(min($qidattributes['max_filesize'] * 1024, getMaximumFileUploadSize()) / 1024);
        $body = '</head><body class="uploader">
                <div id="notice"></div>
                <input type="hidden" id="ia"                value="' . $fn . '" />
                <input type="hidden" id="' . $fn . '_minfiles"          value="' . $minfiles . '" />
                <input type="hidden" id="' . $fn . '_maxfiles"          value="' . $maxfiles . '" />
                <input type="hidden" id="' . $fn . '_maxfilesize"       value="' . $qidattributes['max_filesize'] . '" />
                <input type="hidden" id="' . $fn . '_allowed_filetypes" value="' . $qidattributes['allowed_filetypes'] . '" />
                <input type="hidden" id="preview"                   value="' . Yii::app()->session['preview'] . '" />
                <input type="hidden" id="' . $fn . '_show_comment"      value="' . $qidattributes['show_comment'] . '" />
                <input type="hidden" id="' . $fn . '_show_title"        value="' . $qidattributes['show_title'] . '" />
                <input type="hidden" id="' . $fn . '_licount"           value="0" />
                <input type="hidden" id="' . $fn . '_filecount"         value="0" />

                <!-- The upload button -->
                <div class="upload-div">
                    <button id="button1" class="button upload-button" type="button" >' . gT("Select file") . '</button>
                </div>

                <p class="uploadmsg">' . sprintf(gT("You can upload %s under %s KB each."), $qidattributes['allowed_filetypes'], $qidattributes['max_filesize']) . '</p>
                <div class="uploadstatus" id="uploadstatus"></div>

                <!-- The list of uploaded files -->

            </body>
        </html>';
        App()->getClientScript()->render($body);
        echo $body;
    }
Ejemplo n.º 12
0
 /**
  * Function that initialises all data and call other functions to load default view.
  *
  * @access protected
  * @param string $templatename
  * @param string $screenname
  * @param string $editfile
  * @param bool $showsummary
  * @return
  */
 protected function _initialise($templatename, $screenname, $editfile, $showsummary = true, $useindex = false)
 {
     // LimeSurvey style
     global $oEditedTemplate;
     $oEditedTemplate = Template::model()->getTemplateConfiguration($templatename);
     // In survey mode, bootstrap is loaded via the app init.
     // From template editor, we just add the bootstrap files to the js/css to load for template_helper::templatereplace()
     if ($oEditedTemplate->cssFramework == 'bootstrap') {
         // Core templates (are published only if exists)
         $oEditedTemplate->config->files->css->filename[] = "../../styles-public/bootstrap-for-template-editor.css";
         $oEditedTemplate->config->files->js->filename[] = "../../scripts/bootstrap-for-template-editor.js";
         // User templates (are published only if exists)
         $oEditedTemplate->config->files->css->filename[] = "../../../styles-public/bootstrap-for-template-editor.css";
         $oEditedTemplate->config->files->js->filename[] = "../../../scripts/bootstrap-for-template-editor.js";
     }
     //App()->getClientScript()->reset();
     Yii::app()->loadHelper('surveytranslator');
     Yii::app()->loadHelper('admin/template');
     $files = $this->_initfiles($templatename);
     $cssfiles = $this->_initcssfiles($oEditedTemplate);
     // Standard Support Files
     // These files may be edited or saved
     $supportfiles[] = array('name' => 'print_img_radio.png');
     $supportfiles[] = array('name' => 'print_img_checkbox.png');
     // Standard screens
     // Only these may be viewed
     $screens[] = array('name' => gT('Survey List Page'), 'id' => 'surveylist');
     $screens[] = array('name' => gT('Welcome Page'), 'id' => 'welcome');
     $screens[] = array('name' => gT('Question Page'), 'id' => 'question');
     $screens[] = array('name' => gT('Completed Page'), 'id' => 'completed');
     $screens[] = array('name' => gT('Clear All Page'), 'id' => 'clearall');
     $screens[] = array('name' => gT('Register Page'), 'id' => 'register');
     $screens[] = array('name' => gT('Load Page'), 'id' => 'load');
     $screens[] = array('name' => gT('Save Page'), 'id' => 'save');
     $screens[] = array('name' => gT('Print answers page'), 'id' => 'printanswers');
     $screens[] = array('name' => gT('Printable survey page'), 'id' => 'printablesurvey');
     // Page display blocks
     $SurveyList = array('startpage.pstpl', 'surveylist.pstpl', 'endpage.pstpl');
     $Welcome = array('startpage.pstpl', 'welcome.pstpl', 'privacy.pstpl', 'navigator.pstpl', 'endpage.pstpl');
     $Question = array('startpage.pstpl', 'survey.pstpl', 'startgroup.pstpl', 'groupdescription.pstpl', 'question.pstpl', 'endgroup.pstpl', 'navigator.pstpl', 'endpage.pstpl');
     $CompletedTemplate = array('startpage.pstpl', 'assessment.pstpl', 'completed.pstpl', 'endpage.pstpl');
     $Clearall = array('startpage.pstpl', 'clearall.pstpl', 'endpage.pstpl');
     $Register = array('startpage.pstpl', 'survey.pstpl', 'register.pstpl', 'endpage.pstpl');
     $Save = array('startpage.pstpl', 'save.pstpl', 'endpage.pstpl');
     $Load = array('startpage.pstpl', 'load.pstpl', 'endpage.pstpl');
     $printtemplate = array('startpage.pstpl', 'printanswers.pstpl', 'endpage.pstpl');
     $printablesurveytemplate = array('print_survey.pstpl', 'print_group.pstpl', 'print_question.pstpl');
     $file_version = "LimeSurvey template editor " . Yii::app()->getConfig('versionnumber');
     Yii::app()->session['s_lang'] = Yii::app()->session['adminlang'];
     $templatename = sanitize_dirname($templatename);
     $screenname = autoUnescape($screenname);
     // Checks if screen name is in the list of allowed screen names
     if (multiarray_search($screens, 'id', $screenname) === false) {
         Yii::app()->user->setFlash('error', gT('Invalid screen name'));
         $this->getController()->redirect(array("admin/templates/sa/upload"));
     }
     if (!isset($action)) {
         $action = sanitize_paranoid_string(returnGlobal('action'));
     }
     if (!isset($subaction)) {
         $subaction = sanitize_paranoid_string(returnGlobal('subaction'));
     }
     if (!isset($newname)) {
         $newname = sanitize_dirname(returnGlobal('newname'));
     }
     if (!isset($copydir)) {
         $copydir = sanitize_dirname(returnGlobal('copydir'));
     }
     if (is_file(Yii::app()->getConfig('usertemplaterootdir') . '/' . $templatename . '/question_start.pstpl')) {
         $files[] = array('name' => 'question_start.pstpl');
         $Question[] = 'question_start.pstpl';
     }
     $editfile = sanitize_filename($editfile);
     // Fixed with editable file after, but put in aData before fix
     $availableeditorlanguages = array('bg', 'cs', 'de', 'dk', 'en', 'eo', 'es', 'fi', 'fr', 'hr', 'it', 'ja', 'mk', 'nl', 'pl', 'pt', 'ru', 'sk', 'zh');
     // 2.06 way of doing.
     if (!$useindex) {
         $extension = substr(strrchr($editfile, "."), 1);
     } else {
         // The extension is now set as a prefix separated by a _
         $file_datas = explode("_", $editfile);
         $extension = $file_datas[0];
         // The file name is now based on the index of the oTemplate files
         $file_index = $file_datas[1];
         switch ($extension) {
             case 'css':
                 $aTemplateFiles = (array) $oEditedTemplate->config->files_editable->css->filename;
                 break;
             case 'js':
                 $aTemplateFiles = (array) $oEditedTemplate->config->files_editable->js->filename;
                 break;
             default:
                 $aTemplateFiles = (array) $oEditedTemplate->config->files_editable->css->filename;
                 break;
         }
         $editfile = $aTemplateFiles[$file_index];
     }
     if ($extension == 'css' || $extension == 'js') {
         $highlighter = $extension;
     } else {
         $highlighter = 'html';
     }
     if (in_array(Yii::app()->session['adminlang'], $availableeditorlanguages)) {
         $codelanguage = Yii::app()->session['adminlang'];
     } else {
         $codelanguage = 'en';
     }
     $templates = getTemplateList();
     if (!isset($templates[$templatename])) {
         $templatename = Yii::app()->getConfig('defaulttemplate');
     }
     $normalfiles = array("DUMMYENTRY", ".", "..", "preview.png");
     foreach ($files as $fl) {
         $normalfiles[] = $fl["name"];
     }
     foreach ($cssfiles as $fl) {
         $normalfiles[] = $fl["name"];
     }
     // Some global data
     $aData['sitename'] = Yii::app()->getConfig('sitename');
     $siteadminname = Yii::app()->getConfig('siteadminname');
     $siteadminemail = Yii::app()->getConfig('siteadminemail');
     // Set this so common.php doesn't throw notices about undefined variables
     $thissurvey['active'] = 'N';
     // FAKE DATA FOR TEMPLATES
     $thissurvey['name'] = gT("Template Sample");
     $thissurvey['description'] = "<p>" . gT('This is a sample survey description. It could be quite long.') . "</p>" . "<p>" . gT("But this one isn't.") . "<p>";
     $thissurvey['welcome'] = "<p>" . gT('Welcome to this sample survey') . "<p>" . "<p>" . gT('You should have a great time doing this') . "<p>";
     $thissurvey['allowsave'] = "Y";
     $thissurvey['active'] = "Y";
     $thissurvey['tokenanswerspersistence'] = "Y";
     $thissurvey['templatedir'] = $templatename;
     $thissurvey['format'] = "G";
     $thissurvey['surveyls_url'] = "http://www.limesurvey.org/";
     $thissurvey['surveyls_urldescription'] = gT("Some URL description");
     $thissurvey['usecaptcha'] = "A";
     $percentcomplete = makegraph(6, 10);
     $groupname = gT("Group 1: The first lot of questions");
     $groupdescription = gT("This group description is fairly vacuous, but quite important.");
     $navigator = $this->getController()->render('/admin/templates/templateeditor_navigator_view', array('screenname' => $screenname), true);
     $completed = $this->getController()->render('/admin/templates/templateeditor_completed_view', array(), true);
     $assessments = $this->getController()->render('/admin/templates/templateeditor_assessments_view', array(), true);
     $printoutput = $this->getController()->render('/admin/templates/templateeditor_printoutput_view', array(), true);
     $totalquestions = '10';
     $surveyformat = 'Format';
     $notanswered = '5';
     $privacy = '';
     $surveyid = '1295';
     $token = 1234567;
     $templatedir = $oEditedTemplate->viewPath;
     $templateurl = getTemplateURL($templatename);
     // Save these variables in an array
     $aData['thissurvey'] = $thissurvey;
     $aData['percentcomplete'] = $percentcomplete;
     $aData['groupname'] = $groupname;
     $aData['groupdescription'] = $groupdescription;
     $aData['navigator'] = $navigator;
     $aData['help'] = gT("This is some help text.");
     $aData['surveyformat'] = $surveyformat;
     $aData['totalquestions'] = $totalquestions;
     $aData['completed'] = $completed;
     $aData['notanswered'] = $notanswered;
     $aData['privacy'] = $privacy;
     $aData['surveyid'] = $surveyid;
     $aData['sid'] = $surveyid;
     $aData['token'] = $token;
     $aData['assessments'] = $assessments;
     $aData['printoutput'] = $printoutput;
     $aData['templatedir'] = $templatedir;
     $aData['templateurl'] = $templateurl;
     $aData['templatename'] = $templatename;
     $aData['screenname'] = $screenname;
     $aData['editfile'] = $editfile;
     $myoutput[] = "";
     switch ($screenname) {
         case 'surveylist':
             unset($files);
             $surveylist = array("nosid" => gT("You have not provided a survey identification number"), "contact" => sprintf(gT("Please contact %s ( %s ) for further assistance."), Yii::app()->getConfig("siteadminname"), Yii::app()->getConfig("siteadminemail")), "listheading" => gT("The following surveys are available:"), "list" => $this->getController()->render('/admin/templates/templateeditor_surveylist_view', array(), true));
             $aData['surveylist'] = $surveylist;
             $myoutput[] = "";
             //$myoutput[] = templatereplace(file_get_contents("$templatedir/startpage.pstpl"), array(), $aData, 'Unspecified', false, NULL, array(), false, $oEditedTemplate);
             foreach ($SurveyList as $qs) {
                 $files[] = array("name" => $qs);
                 $myoutput = array_merge($myoutput, doreplacement($oEditedTemplate->viewPath . "/{$qs}", $aData, $oEditedTemplate));
             }
             break;
         case 'question':
             unset($files);
             foreach ($Question as $qs) {
                 $files[] = array("name" => $qs);
             }
             $myoutput[] = $this->getController()->render('/admin/templates/templateeditor_question_meta_view', array(), true);
             $aData['aReplacements'] = array('SAVE_LINKS' => '<li><a href="#" id="saveallbtnlink">Resume later</a></li>', 'CLEARALL_LINKS' => '<li><a href="#" id="clearallbtnlink">' . gT("Exit and clear survey") . '</a></li>');
             $myoutput = array_merge($myoutput, doreplacement($oEditedTemplate->viewPath . "/startpage.pstpl", $aData, $oEditedTemplate));
             $myoutput = array_merge($myoutput, doreplacement($oEditedTemplate->viewPath . "/survey.pstpl", $aData, $oEditedTemplate));
             $myoutput = array_merge($myoutput, doreplacement($oEditedTemplate->viewPath . "/startgroup.pstpl", $aData, $oEditedTemplate));
             $myoutput = array_merge($myoutput, doreplacement($oEditedTemplate->viewPath . "/groupdescription.pstpl", $aData, $oEditedTemplate));
             $aReplacements = array('QUESTION_TEXT' => gT("How many roads must a man walk down?"), 'QUESTION_CODE' => '1a', 'QUESTIONHELP' => 'helpful text', 'QUESTION_MANDATORY' => gT("*"), 'QUESTION_MAN_CLASS' => ' mandatory', 'QUESTION_ESSENTIALS' => 'id="question1"', 'QUESTION_CLASS' => 'list-radio', 'QUESTION_NUMBER' => '1');
             $aReplacements['ANSWER'] = $this->getController()->render('/admin/templates/templateeditor_question_answer_view', array(), true);
             $aData['aReplacements'] = $aReplacements;
             $myoutput = array_merge($myoutput, doreplacement($oEditedTemplate->viewPath . "/question.pstpl", $aData, $oEditedTemplate));
             $aReplacements = array('QUESTION_TEXT' => gT('Please explain something in detail:'), 'QUESTION_CODE' => '2a', 'QUESTION_ESSENTIALS' => 'id="question2"', 'QUESTION_CLASS' => 'text-long', 'QUESTION_NUMBER' => '2');
             $aReplacements['ANSWER'] = $this->getController()->render('/admin/templates/templateeditor_question_answer_view', array('alt' => true), true);
             $aData['aReplacements'] = $aReplacements;
             $myoutput = array_merge($myoutput, doreplacement($oEditedTemplate->viewPath . "/question.pstpl", $aData, $oEditedTemplate));
             $myoutput = array_merge($myoutput, doreplacement($oEditedTemplate->viewPath . "/endgroup.pstpl", $aData, $oEditedTemplate));
             $aData['aReplacements'] = array('MOVEPREVBUTTON' => '<button type="submit" id="moveprevbtn" value="moveprev" name="moveprev" accesskey="p" class="submit button btn btn-default btn-lg ">Previous</button>', 'MOVENEXTBUTTON' => '<button type="submit" id="movenextbtn" value="movenext" name="movenext" accesskey="n" class="submit button btn btn-default btn-lg ">Next</button>');
             $myoutput = array_merge($myoutput, doreplacement($oEditedTemplate->viewPath . "/navigator.pstpl", $aData, $oEditedTemplate));
             $myoutput = array_merge($myoutput, doreplacement($oEditedTemplate->viewPath . "/endpage.pstpl", $aData, $oEditedTemplate));
             break;
         case 'welcome':
             unset($files);
             foreach ($Welcome as $qs) {
                 $files[] = array("name" => $qs);
                 $myoutput = array_merge($myoutput, doreplacement($oEditedTemplate->viewPath . "/{$qs}", $aData, $oEditedTemplate));
             }
             /*
             $myoutput = array_merge($myoutput, doreplacement($oEditedTemplate->viewPath  . "/startpage.pstpl", $aData, $oEditedTemplate));
             $myoutput = array_merge($myoutput, doreplacement($oEditedTemplate->viewPath  . "/welcome.pstpl", $aData, $oEditedTemplate));
             $myoutput = array_merge($myoutput, doreplacement($oEditedTemplate->viewPath  . "/privacy.pstpl", $aData, $oEditedTemplate));
             */
             $aData['aReplacements'] = array('MOVENEXTBUTTON' => '<button type="submit" id="movenextbtn" value="movenext" name="movenext" accesskey="n" class="submit button btn btn-default btn-lg">Next</button>');
             $myoutput = array_merge($myoutput, doreplacement($oEditedTemplate->viewPath . "/navigator.pstpl", $aData, $oEditedTemplate));
             $myoutput = array_merge($myoutput, doreplacement($oEditedTemplate->viewPath . "/endpage.pstpl", $aData, $oEditedTemplate));
             break;
         case 'register':
             unset($files);
             foreach ($Register as $qs) {
                 $files[] = array("name" => $qs);
             }
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/startpage.pstpl"), array(), $aData, 'Unspecified', false, NULL, array(), false, $oEditedTemplate);
             $aData = array('aReplacements' => array('SURVEYNAME' => 'Survey name'));
             $myoutput = array_merge($myoutput, doreplacement($oEditedTemplate->viewPath . "/survey.pstpl", $aData, $oEditedTemplate));
             $aData['aReplacements'] = array('REGISTERERROR' => 'Example error message', 'REGISTERMESSAGE1' => 'Register message 1', 'REGISTERMESSAGE2' => 'Register message 2', 'REGISTERFORM' => $this->getController()->render('/admin/templates/templateeditor_register_view', array('alt' => true), true));
             $myoutput = array_merge($myoutput, doreplacement($oEditedTemplate->viewPath . "/register.pstpl", $aData, $oEditedTemplate));
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/endpage.pstpl"), array(), $aData, 'Unspecified', false, NULL, array(), false, $oEditedTemplate);
             $myoutput[] = "\n";
             break;
         case 'save':
             unset($files);
             foreach ($Save as $qs) {
                 $files[] = array("name" => $qs);
             }
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/startpage.pstpl"), array(), $aData, 'Unspecified', false, NULL, array(), false, $oEditedTemplate);
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/save.pstpl"), array(), $aData, 'Unspecified', false, NULL, array(), false, $oEditedTemplate);
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/endpage.pstpl"), array(), $aData, 'Unspecified', false, NULL, array(), false, $oEditedTemplate);
             $myoutput[] = "\n";
             break;
         case 'load':
             unset($files);
             foreach ($Load as $qs) {
                 $files[] = array("name" => $qs);
             }
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/startpage.pstpl"), array(), $aData, 'Unspecified', false, NULL, array(), false, $oEditedTemplate);
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/load.pstpl"), array(), $aData, 'Unspecified', false, NULL, array(), false, $oEditedTemplate);
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/endpage.pstpl"), array(), $aData, 'Unspecified', false, NULL, array(), false, $oEditedTemplate);
             $myoutput[] = "\n";
             break;
         case 'clearall':
             unset($files);
             foreach ($Clearall as $qs) {
                 $files[] = array("name" => $qs);
             }
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/startpage.pstpl"), array(), $aData, 'Unspecified', false, NULL, array(), false, $oEditedTemplate);
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/clearall.pstpl"), array(), $aData, 'Unspecified', false, NULL, array(), false, $oEditedTemplate);
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/endpage.pstpl"), array(), $aData, 'Unspecified', false, NULL, array(), false, $oEditedTemplate);
             $myoutput[] = "\n";
             break;
         case 'completed':
             unset($files);
             $myoutput[] = "";
             foreach ($CompletedTemplate as $qs) {
                 $files[] = array("name" => $qs);
                 $myoutput = array_merge($myoutput, doreplacement($oEditedTemplate->viewPath . "/{$qs}", $aData, $oEditedTemplate));
             }
             break;
         case 'printablesurvey':
             unset($files);
             foreach ($printablesurveytemplate as $qs) {
                 $files[] = array("name" => $qs);
             }
             $questionoutput = array();
             foreach (file("{$templatedir}/print_question.pstpl") as $op) {
                 $questionoutput[] = templatereplace($op, array('QUESTION_NUMBER' => '1', 'QUESTION_CODE' => 'Q1', 'QUESTION_MANDATORY' => gT('*'), 'QUESTION_SCENARIO' => 'Only answer this if certain conditions are met.', 'QUESTION_CLASS' => ' mandatory list-radio', 'QUESTION_TYPE_HELP' => gT('Please choose *only one* of the following:'), 'QUESTION_MAN_MESSAGE' => '', 'QUESTION_VALID_MESSAGE' => '', 'QUESTION_FILE_VALID_MESSAGE' => '', 'QUESTION_TEXT' => gT('This is a sample question text. The user was asked to pick an entry.'), 'QUESTIONHELP' => gT('This is some help text for this question.'), 'ANSWER' => $this->getController()->render('/admin/templates/templateeditor_printablesurvey_quesanswer_view', array('templateurl' => $templateurl), true)), $aData, 'Unspecified', false, NULL, array(), false, $oEditedTemplate);
             }
             $groupoutput = array();
             $groupoutput[] = templatereplace(file_get_contents("{$templatedir}/print_group.pstpl"), array('QUESTIONS' => implode(' ', $questionoutput)), $aData, 'Unspecified', false, NULL, array(), false, $oEditedTemplate);
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/print_survey.pstpl"), array('GROUPS' => implode(' ', $groupoutput), 'FAX_TO' => gT("Please fax your completed survey to:") . " 000-000-000", 'SUBMIT_TEXT' => gT("Submit your survey."), 'HEADELEMENTS' => getPrintableHeader(), 'SUBMIT_BY' => sprintf(gT("Please submit by %s"), date('d.m.y')), 'THANKS' => gT('Thank you for completing this survey.'), 'END' => gT('This is the survey end message.')), $aData, 'Unspecified', false, NULL, array(), false, $oEditedTemplate);
             break;
         case 'printanswers':
             unset($files);
             foreach ($printtemplate as $qs) {
                 $files[] = array("name" => $qs);
             }
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/startpage.pstpl"), array(), $aData, 'Unspecified', false, NULL, array(), false, $oEditedTemplate);
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/printanswers.pstpl"), array('ANSWERTABLE' => $printoutput), $aData, 'Unspecified', false, NULL, array(), false, $oEditedTemplate);
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/endpage.pstpl"), array(), $aData, 'Unspecified', false, NULL, array(), false, $oEditedTemplate);
             $myoutput[] = "\n";
             break;
     }
     $myoutput[] = "</html>";
     $jsfiles = $this->_getEditableJsFiles($oEditedTemplate);
     if (is_array($files)) {
         $match = 0;
         foreach ($files as $f) {
             if ($editfile == $f["name"]) {
                 $match = 1;
             }
         }
         $aCssAndJsfiles = array_merge($cssfiles, $jsfiles);
         foreach ($aCssAndJsfiles as $f) {
             if ($editfile == $f["name"]) {
                 $match = 1;
             }
         }
         if ($match == 0) {
             if (count($files) > 0) {
                 $editfile = $files[0]["name"];
             } else {
                 $editfile = "";
             }
         }
     }
     // Get list of 'otherfiles'
     // We can't use $oTemplate->otherFiles, because of retrocompatibility with 2.06 template and the big mess of it mixing files
     $filesdir = $oEditedTemplate->filesPath != '' ? $oEditedTemplate->filesPath : $templatedir . '../files';
     $otherfiles = array();
     if (file_exists($filesdir) && ($handle = opendir($filesdir))) {
         while (false !== ($file = readdir($handle))) {
             if (!array_search($file, $normalfiles)) {
                 if (!is_dir($templatedir . DIRECTORY_SEPARATOR . $file)) {
                     $otherfiles[] = array("name" => $file);
                 }
             }
         }
         closedir($handle);
     }
     $aData['codelanguage'] = $codelanguage;
     $aData['highlighter'] = $highlighter;
     $aData['screens'] = $screens;
     $aData['templatename'] = $templatename;
     $aData['templates'] = $templates;
     $aData['editfile'] = $editfile;
     $aData['screenname'] = $screenname;
     $aData['tempdir'] = Yii::app()->getConfig('tempdir');
     $aData['usertemplaterootdir'] = Yii::app()->getConfig('usertemplaterootdir');
     $aViewUrls['templateeditorbar_view'][] = $aData;
     if ($showsummary) {
         //$aCssfileseditable = (array) $oEditedTemplate->config->files_editable->css->filename;
         $aViewUrls = array_merge($aViewUrls, $this->_templatesummary($templatename, $screenname, $editfile, $templates, $files, $cssfiles, $jsfiles, $otherfiles, $myoutput));
     }
     App()->getClientScript()->registerScriptFile(App()->getAssetManager()->publish(ADMIN_SCRIPT_PATH . 'admin_core.js'));
     return $aViewUrls;
 }
            <select id='template'class="form-control"  name='template'>
                <?php foreach (array_keys(getTemplateList()) as $tname) {

                        if (Permission::model()->hasGlobalPermission('superadmin','read') || Permission::model()->hasGlobalPermission('templates','read') || hasTemplateManageRights(Yii::app()->session["loginID"], $tname) == 1 || $esrow['template']==htmlspecialchars($tname) ) { ?>
                        <option value='<?php echo $tname; ?>'
                            <?php if ($esrow['template'] && htmlspecialchars($tname) == $esrow['template']) { ?>
                                selected='selected'
                                <?php   } elseif (!$esrow['template'] && $tname == Yii::app()->getConfig('defaulttemplate')) { ?>
                                selected='selected'
                                <?php } ?>
                            ><?php echo $tname; ?></option>
                        <?php }
                } ?>
            </select>
            <div class="col-sm-8 col-sm-offset-2 template-img">
                <img class="img-responsive" alt='<?php  eT("Template preview image"); ?>' name='preview' id='preview' src='<?php echo getTemplateURL($esrow['template']); ?>/preview.png' />
            </div>
        </div>
    </div>

    <!-- welcome screen -->
    <div class="form-group">
        <label class="col-sm-4 control-label" for='showwelcome'><?php  eT("Show welcome screen:") ; ?></label>
        <div class="col-sm-8">
            <select id='showwelcome' name='showwelcome' class="form-control">
                <option value='Y'
                    <?php if (!$esrow['showwelcome'] || $esrow['showwelcome'] == "Y") { ?>
                        selected='selected'
                        <?php } ?>
                    ><?php  eT("Yes") ; ?>
                </option>
Ejemplo n.º 14
0
        if (!in_array($sValShowqnumcode, array("B", "N", "C", "X"))) {
            $sValShowqnumcode = "X";
        }
        break;
}
/* shownoanswer */
$sValShownoanswer = $esrow['shownoanswer'];
$shownoanswer = !is_null(Yii::app()->getConfig('shownoanswer')) ? Yii::app()->getConfig('shownoanswer') : 1;
switch ($shownoanswer) {
    case '1':
        $aShownoanswerOptions = array("Y" => gT('Yes (Forced by the system administrator)', 'unescaped'));
        $bDisableShownoanswer = true;
        $sValShownoanswer = "Y";
        break;
    case '0':
        $aShownoanswerOptions = array("N" => gT('No (Forced by the system administrator)', 'unescaped'));
        $bDisableShownoanswer = true;
        $sValShownoanswer = "N";
        break;
    case '2':
    default:
        $aShownoanswerOptions = array("Y" => gT("Yes", 'unescaped'), "N" => gT("No", 'unescaped'));
        $bDisableShownoanswer = false;
        break;
}
/* Need some javascript var */
$sTemplateUrlScriptVar = "standardtemplaterooturl='" . Yii::app()->getConfig('standardtemplaterooturl') . "'\n" . "templaterooturl='" . Yii::app()->getConfig('usertemplaterooturl') . "'\n";
Yii::app()->getClientScript()->registerScript("sTemplateUrlScriptVar", $sTemplateUrlScriptVar, CClientScript::POS_BEGIN);
/* Presentation & navigation settings */
$this->widget('ext.SettingsWidget.SettingsWidget', array('id' => 'presentation', 'title' => gT("Presentation & navigation"), 'form' => false, 'formHtmlOptions' => array('class' => 'form-core'), 'settings' => array('format' => array('type' => 'select', 'label' => gT("Format"), 'options' => array("S" => gT("Question by Question", 'unescaped'), "G" => gT("Group by Group", 'unescaped'), "A" => gT("All in one", 'unescaped')), 'current' => $esrow['format']), 'template' => array('type' => 'select', 'label' => gT("Template"), 'options' => $aTemplateOptions, 'current' => $esrow['template'], 'selectOptions' => array('minimumResultsForSearch' => 15), 'events' => array('change' => 'js: function(event) {  templatechange(event.val) } ')), 'preview' => array('type' => 'info', 'label' => gT("Template preview"), 'content' => CHtml::image(getTemplateURL($esrow['template']) . '/preview.png', gT("Template preview image"), array('id' => 'preview', 'class' => 'img-thumbnail'))), 'showwelcome' => array('type' => 'select', 'label' => gT("Show welcome screen?"), 'options' => array("Y" => gT("Yes", 'unescaped'), "N" => gT("No", 'unescaped')), 'current' => $esrow['showwelcome']), 'navigationdelay' => array('type' => 'int', 'label' => gT("Navigation delay (seconds)"), 'htmlOptions' => array('style' => 'width:12em'), 'current' => $esrow['navigationdelay']), 'allowprev' => array('type' => 'select', 'label' => gT("Show [Previous] button"), 'options' => array("Y" => gT("Yes", 'unescaped'), "N" => gT("No", 'unescaped')), 'current' => $esrow['allowprev']), 'questionindex' => array('type' => 'select', 'label' => gT("Show question index / allow jumping"), 'options' => array(0 => gT('Disabled', 'unescaped'), 1 => gT('Incremental', 'unescaped'), 2 => gT('Full', 'unescaped')), 'current' => $esrow['questionindex']), 'nokeyboard' => array('type' => 'select', 'label' => gT("Keyboard-less operation"), 'options' => array("Y" => gT("Yes", 'unescaped'), "N" => gT("No", 'unescaped')), 'current' => $esrow['nokeyboard'] ? $esrow['nokeyboard'] : "N"), 'showprogress' => array('type' => 'select', 'label' => gT("Show progress bar"), 'options' => array("Y" => gT("Yes", 'unescaped'), "N" => gT("No", 'unescaped')), 'current' => $esrow['showprogress']), 'printanswers' => array('type' => 'select', 'label' => gT("Participants may print answers?"), 'options' => array("Y" => gT("Yes", 'unescaped'), "N" => gT("No", 'unescaped')), 'current' => $esrow['printanswers']), 'publicstatistics' => array('type' => 'select', 'label' => gT("Public statistics?"), 'options' => array("Y" => gT("Yes", 'unescaped'), "N" => gT("No", 'unescaped')), 'current' => $esrow['publicstatistics']), 'publicgraphs' => array('type' => 'select', 'label' => gT("Show graphs in public statistics?"), 'options' => array("Y" => gT("Yes", 'unescaped'), "N" => gT("No", 'unescaped')), 'current' => $esrow['publicgraphs']), 'autoredirect' => array('type' => 'select', 'label' => gT("Automatically load URL when survey complete?"), 'options' => array("Y" => gT("Yes", 'unescaped'), "N" => gT("No", 'unescaped')), 'current' => $esrow['autoredirect']), 'showxquestions' => array('type' => 'select', 'label' => gT('Show "There are X questions in this survey"'), 'options' => $aShowxquestionsOptions, 'current' => $sValShowxquestions, 'htmlOptions' => array('readonly' => $bDisableShowxquestions)), 'showgroupinfo' => array('type' => 'select', 'label' => gT('Show group name and/or group description'), 'options' => $aShowgroupinfoOptions, 'current' => $sValShowgroupinfo, 'htmlOptions' => array('readonly' => $bDisableShowgroupinfo)), 'showqnumcode' => array('type' => 'select', 'label' => gT('Show question number and/or code'), 'options' => $aShowqnumcodeOptions, 'current' => $sValShowqnumcode, 'htmlOptions' => array('readonly' => $bDisableShowqnumcode)), 'shownoanswer' => array('type' => 'select', 'label' => gT('Show "No answer"'), 'options' => $aShownoanswerOptions, 'current' => $sValShownoanswer, 'htmlOptions' => array('readonly' => $bDisableShownoanswer)))));
 /**
  * @param int $surveyid
  * @param string $language
  */
 public function actionAction($surveyid, $language = null)
 {
     $sLanguage = $language;
     $this->sLanguage = $language;
     ob_start(function ($buffer) {
         App()->getClientScript()->render($buffer);
         App()->getClientScript()->reset();
         return $buffer;
     });
     ob_implicit_flush(false);
     $iSurveyID = (int) $surveyid;
     $this->iSurveyID = (int) $surveyid;
     //$postlang = returnglobal('lang');
     Yii::import('application.libraries.admin.progressbar', true);
     Yii::app()->loadHelper("userstatistics");
     Yii::app()->loadHelper('database');
     Yii::app()->loadHelper('surveytranslator');
     App()->getClientScript()->registerPackage('jqueryui');
     App()->getClientScript()->registerPackage('jquery-touch-punch');
     App()->getClientScript()->registerScriptFile(Yii::app()->getConfig('generalscripts') . "survey_runtime.js");
     $data = array();
     if (!isset($iSurveyID)) {
         $iSurveyID = returnGlobal('sid');
     } else {
         $iSurveyID = (int) $iSurveyID;
     }
     if (!$iSurveyID) {
         //This next line ensures that the $iSurveyID value is never anything but a number.
         safeDie('You have to provide a valid survey ID.');
     }
     $actresult = Survey::model()->findAll('sid = :sid AND active = :active', array(':sid' => $iSurveyID, ':active' => 'Y'));
     //Checked
     if (count($actresult) == 0) {
         safeDie('You have to provide a valid survey ID.');
     } else {
         $surveyinfo = getSurveyInfo($iSurveyID);
         // CHANGE JSW_NZ - let's get the survey title for display
         $thisSurveyTitle = $surveyinfo["name"];
         // CHANGE JSW_NZ - let's get css from individual template.css - so define path
         $thisSurveyCssPath = getTemplateURL($surveyinfo["template"]);
         if ($surveyinfo['publicstatistics'] != 'Y') {
             safeDie('The public statistics for this survey are deactivated.');
         }
         //check if graphs should be shown for this survey
         if ($surveyinfo['publicgraphs'] == 'Y') {
             $publicgraphs = 1;
         } else {
             $publicgraphs = 0;
         }
     }
     //we collect all the output within this variable
     $statisticsoutput = '';
     //for creating graphs we need some more scripts which are included here
     //True -> include
     //False -> forget about charts
     if (isset($publicgraphs) && $publicgraphs == 1) {
         require_once APPPATH . 'third_party/pchart/pchart/pChart.class';
         require_once APPPATH . 'third_party/pchart/pchart/pData.class';
         require_once APPPATH . 'third_party/pchart/pchart/pCache.class';
         $MyCache = new pCache(Yii::app()->getConfig("tempdir") . DIRECTORY_SEPARATOR);
         //$currentuser is created as prefix for pchart files
         if (isset($_SERVER['REDIRECT_REMOTE_USER'])) {
             $currentuser = $_SERVER['REDIRECT_REMOTE_USER'];
         } else {
             if (session_id()) {
                 $currentuser = substr(session_id(), 0, 15);
             } else {
                 $currentuser = "******";
             }
         }
     }
     // Set language for questions and labels to base language of this survey
     if ($sLanguage == null || !in_array($sLanguage, Survey::model()->findByPk($iSurveyID)->getAllLanguages())) {
         $sLanguage = Survey::model()->findByPk($iSurveyID)->language;
     } else {
         $sLanguage = sanitize_languagecode($sLanguage);
     }
     //set survey language for translations
     SetSurveyLanguage($iSurveyID, $sLanguage);
     //Create header
     sendCacheHeaders();
     $condition = false;
     $sitename = Yii::app()->getConfig("sitename");
     $data['surveylanguage'] = $sLanguage;
     $data['sitename'] = $sitename;
     $data['condition'] = $condition;
     $data['thisSurveyCssPath'] = $thisSurveyCssPath;
     /*
      * only show questions where question attribute "public_statistics" is set to "1"
      */
     $query = "SELECT q.* , group_name, group_order FROM {{questions}} q, {{groups}} g, {{question_attributes}} qa\n                    WHERE g.gid = q.gid AND g.language = :lang1 AND q.language = :lang2 AND q.sid = :surveyid AND q.qid = qa.qid AND q.parent_qid = 0 AND qa.attribute = 'public_statistics'";
     $databasetype = Yii::app()->db->getDriverName();
     if ($databasetype == 'mssql' || $databasetype == "sqlsrv" || $databasetype == "dblib") {
         $query .= " AND CAST(CAST(qa.value as varchar) as int)='1'\n";
     } else {
         $query .= " AND qa.value='1'\n";
     }
     //execute query
     $result = Yii::app()->db->createCommand($query)->bindParam(":lang1", $sLanguage, PDO::PARAM_STR)->bindParam(":lang2", $sLanguage, PDO::PARAM_STR)->bindParam(":surveyid", $iSurveyID, PDO::PARAM_INT)->queryAll();
     //store all the data in $rows
     $rows = $result;
     //SORT IN NATURAL ORDER!
     usort($rows, 'groupOrderThenQuestionOrder');
     //put the question information into the filter array
     $filters = array();
     foreach ($rows as $row) {
         //store some column names in $filters array
         $filters[] = array($row['qid'], $row['gid'], $row['type'], $row['title'], $row['group_name'], flattenText($row['question']));
     }
     //number of records for this survey
     $totalrecords = 0;
     //count number of answers
     $query = "SELECT count(*) FROM {{survey_" . intval($iSurveyID) . "}}";
     //if incompleted answers should be filtert submitdate has to be not null
     //this setting is taken from config-defaults.php
     if (Yii::app()->getConfig("filterout_incomplete_answers") == true) {
         $query .= " WHERE {{survey_" . intval($iSurveyID) . "}}.submitdate is not null";
     }
     $result = Yii::app()->db->createCommand($query)->queryAll();
     //$totalrecords = total number of answers
     foreach ($result as $row) {
         $totalrecords = reset($row);
     }
     //...while this is the array from copy/paste which we don't want to replace because this is a nasty source of error
     $allfields = array();
     //---------- CREATE SGQA OF ALL QUESTIONS WHICH USE "PUBLIC_STATISTICS" ----------
     /*
              * let's go through the filter array which contains
              *     ['qid'],
              ['gid'],
              ['type'],
              ['title'],
              ['group_name'],
              ['question'];
     */
     $currentgroup = '';
     // use to check if there are any question with public statistics
     if (isset($filters)) {
         $allfields = $this->createSGQA($filters);
     }
     // end if -> for removing the error message in case there are no filters
     $summary = $allfields;
     // Get the survey inforamtion
     $thissurvey = getSurveyInfo($surveyid, $sLanguage);
     //SET THE TEMPLATE DIRECTORY
     $data['sTemplatePath'] = $surveyinfo['template'];
     // surveyinfo=getSurveyInfo and if survey don't exist : stop before.
     //---------- CREATE STATISTICS ----------
     $redata = compact(array_keys(get_defined_vars()));
     doHeader();
     /// $oTemplate is a global variable defined in controller/survey/index
     $oTemplate = Template::model()->getInstance(null, $surveyid);
     echo templatereplace(file_get_contents($oTemplate->viewPath . "startpage.pstpl"), array(), $redata);
     //some progress bar stuff
     // Create progress bar which is shown while creating the results
     $prb = new ProgressBar();
     $prb->pedding = 2;
     // Bar Pedding
     $prb->brd_color = "#404040 #dfdfdf #dfdfdf #404040";
     // Bar Border Color
     $prb->setFrame();
     // set ProgressBar Frame
     $prb->frame['left'] = 50;
     // Frame position from left
     $prb->frame['top'] = 80;
     // Frame position from top
     $prb->addLabel('text', 'txt1', gT("Please wait ..."));
     // add Text as Label 'txt1' and value 'Please wait'
     $prb->addLabel('percent', 'pct1');
     // add Percent as Label 'pct1'
     $prb->addButton('btn1', gT('Go back'), '?action=statistics&amp;sid=' . $iSurveyID);
     // add Button as Label 'btn1' and action '?restart=1'
     $prb->show();
     // show the ProgressBar
     // 1: Get list of questions with answers chosen
     //"Getting Questions and Answer ..." is shown above the bar
     $prb->setLabelValue('txt1', gT('Getting questions and answers ...'));
     $prb->moveStep(5);
     // creates array of post variable names
     $postvars = array();
     for (reset($_POST); $key = key($_POST); next($_POST)) {
         $postvars[] = $key;
     }
     $data['thisSurveyTitle'] = $thisSurveyTitle;
     $data['totalrecords'] = $totalrecords;
     $data['summary'] = $summary;
     //show some main data at the beginnung
     // CHANGE JSW_NZ - let's allow html formatted questions to show
     //push progress bar from 35 to 40
     $process_status = 40;
     //Show Summary results
     if (isset($summary) && !empty($summary)) {
         //"Generating Summaries ..." is shown above the progress bar
         $prb->setLabelValue('txt1', gT('Generating summaries ...'));
         $prb->moveStep($process_status);
         //let's run through the survey // Fixed bug 3053 with array_unique
         $runthrough = array_unique($summary);
         //loop through all selected questions
         foreach ($runthrough as $rt) {
             //update progress bar
             if ($process_status < 100) {
                 $process_status++;
             }
             $prb->moveStep($process_status);
         }
         // end foreach -> loop through all questions
         $helper = new userstatistics_helper();
         $statisticsoutput .= $helper->generate_statistics($iSurveyID, $summary, $summary, $publicgraphs, 'html', null, $sLanguage, false);
     }
     //end if -> show summary results
     $data['statisticsoutput'] = $statisticsoutput;
     //done! set progress bar to 100%
     if (isset($prb)) {
         $prb->setLabelValue('txt1', gT('Completed'));
         $prb->moveStep(100);
         $prb->hide();
     }
     $redata = compact(array_keys(get_defined_vars()));
     $data['redata'] = $redata;
     Yii::app()->getClientScript()->registerScriptFile(Yii::app()->getConfig('generalscripts') . 'statistics_user.js');
     $this->renderPartial('/statistics_user_view', $data);
     //output footer
     echo getFooter();
     //Delete all Session Data
     Yii::app()->session['finished'] = true;
 }
Ejemplo n.º 16
0
<?php

echo '<link rel="stylesheet" type="text/css" href="' . getTemplateURL(Yii::app()->getConfig('defaulttemplate')) . '/print_template.css" />';
echo $surveydesc . "<br />";
echo $welcome . "<br /><br />";
echo $numques;
while (list($key, $val) = each($survey_output)) {
    if ($key == "GROUPS") {
        echo "{$val}<br>";
    }
}
echo $survey_output['END'] . "<br />";
echo $survey_output['SUBMIT_BY'] . "<br /><br />";
echo $survey_output['SUBMIT_TEXT'];
echo "<br />";
echo $survey_output['THANKS'];