Example #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 string $line Text to search in
 * @param array $replacements Array of replacements:  Array( <stringtosearch>=><stringtoreplacewith>, where <stringtosearch> is NOT surrounded with curly braces
 * @param boolean $anonymized Determines if token data is being used or just replaced with blanks
 * @return string  Text with replaced strings
 */
function templatereplace($line, $replacements = array(), $anonymized = false, $questionNum = NULL)
{
    global $surveylist, $sitename, $clienttoken, $rooturl;
    global $thissurvey, $imageurl, $defaulttemplate;
    global $percentcomplete, $move;
    global $groupname, $groupdescription;
    global $question;
    global $showxquestions, $showgroupinfo, $showqnumcode;
    global $answer, $navigator;
    global $help, $surveyformat;
    global $completed, $register_errormsg;
    global $privacy, $surveyid;
    global $publicurl, $templatedir, $token;
    global $assessments, $s_lang;
    global $errormsg, $clang;
    global $saved_id;
    global $totalBoilerplatequestions, $relativeurl;
    global $languagechanger;
    global $captchapath, $loadname;
    // lets sanitize the survey template
    if (isset($thissurvey['templatedir'])) {
        $_templatename = $thissurvey['templatedir'];
    } else {
        $_templatename = $defaulttemplate;
    }
    #    $_templatename = validate_templatedir($_templatename); // Not needed: sGetTemplateURL and sgetTemplatePath do validation
    // create absolute template URL and template dir vars
    $_templateurl = sGetTemplateURL($_templatename) . '/';
    $templatedir = sgetTemplatePath($_templatename);
    $interviewer = returnglobal('interviewer');
    if (!empty($interviewer) || isset($_SESSION['interviewer']) && $_SESSION['interviewer'] == true) {
        $interviewer = true;
        $_SESSION['interviewer'] = true;
    } else {
        $interviewer = false;
    }
    if (stripos($line, "</head>")) {
        //queXS Addition
        $textfocus = "";
        if ($interviewer) {
            $textfocus = '<script type="text/javascript">
		$(document).ready(function()
		{
	        	$(".text").focus();
		        $(".textarea").focus();
		});
		</script>';
        }
        $line = str_ireplace("</head>", "<script type=\"text/javascript\" src=\"{$rooturl}/scripts/survey_runtime.js\"></script>\n" . "{$textfocus}\n" . use_firebug() . "\t</head>", $line);
    }
    // Get some vars : move elsewhere ?
    // surveyformat
    if (isset($thissurvey['format'])) {
        $surveyformat = str_replace(array("A", "S", "G"), array("allinone", "questionbyquestion", "groupbygroup"), $thissurvey['format']);
    } else {
        $surveyformat = "";
    }
    /*if (isset($thissurvey['allowjumps']) && $thissurvey['allowjumps']=="Y" && $surveyformat!="allinone" && (isset($_SESSION['step']) && $_SESSION['step']>0)){
          $surveyformat .= " withindex";
      }*/
    if (isset($thissurvey['showprogress']) && $thissurvey['showprogress'] == "Y") {
        $surveyformat .= " showprogress";
    }
    if (isset($thissurvey['showqnumcode'])) {
        $surveyformat .= " showqnumcode-" . $thissurvey['showqnumcode'];
    }
    // real survey contact
    if (isset($surveylist['contact'])) {
        $_surveycontact = $surveylist['contact'];
    } elseif (isset($thissurvey['admin']) && $thissurvey['admin'] != "") {
        $_surveycontact = sprintf($clang->gT("Please contact %s ( %s ) for further assistance."), $thissurvey['admin'], $thissurvey['adminemail']);
    } else {
        $_surveycontact = "";
    }
    // If there are non-bracketed replacements to be made do so above this line.
    // Only continue in this routine if there are bracketed items to replace {}
    if (strpos($line, "{") === false) {
        return LimeExpressionManager::ProcessString($line, $questionNum, NULL, false, 1, 1, true);
    }
    if ($showgroupinfo == 'both' || $showgroupinfo == 'name' || $showgroupinfo == 'choose' && !isset($thissurvey['showgroupinfo']) || $showgroupinfo == 'choose' && $thissurvey['showgroupinfo'] == 'B' || $showgroupinfo == 'choose' && $thissurvey['showgroupinfo'] == 'N') {
        $_groupname = $groupname;
    } else {
        $_groupname = '';
    }
    if ($showgroupinfo == 'both' || $showgroupinfo == 'description' || $showgroupinfo == 'choose' && !isset($thissurvey['showgroupinfo']) || $showgroupinfo == 'choose' && $thissurvey['showgroupinfo'] == 'B' || $showgroupinfo == 'choose' && $thissurvey['showgroupinfo'] == 'D') {
        $_groupdescription = $groupdescription;
    } else {
        $_groupdescription = '';
    }
    if (is_array($question)) {
        $_question = $question['all'];
        $_question_text = $question['text'];
        $_question_help = $question['help'];
        $_question_mandatory = $question['mandatory'];
        $_question_man_message = $question['man_message'];
        $_question_valid_message = $question['valid_message'];
        $_question_file_valid_message = $question['file_valid_message'];
        if (isset($question['sgq'])) {
            $_question_sgq = $question['sgq'];
            $_parts = explode('X', $_question_sgq);
            $_question_gid = $_parts[1];
        } else {
            $_question_sgq = '';
            $_question_gid = '';
        }
        $_question_essentials = $question['essentials'];
        $_question_class = $question['class'];
        $_question_man_class = $question['man_class'];
        $_question_input_error_class = $question['input_error_class'];
        $_aid = isset($question['aid']) ? $question['aid'] : '';
        $_sqid = isset($question['sqid']) ? $question['sqid'] : '';
        $_question_type = isset($question['type']) ? $question['type'] : '';
    } else {
        $_question = $question;
        $_question_text = '';
        $_question_help = '';
        $_question_mandatory = '';
        $_question_man_message = '';
        $_question_valid_message = '';
        $_question_file_valid_message = '';
        $_question_gid = '';
        $_question_sgq = '';
        $_question_essentials = '';
        $_question_class = '';
        $_question_man_class = '';
        $_question_input_error_class = '';
        $_aid = '';
        $_sqid = '';
        $_question_type = '';
    }
    global $answer_id;
    if ($_question_type == '*') {
        $_question_text = '<div class="em_equation">' . $_question_text . '</div>';
    }
    if ($showqnumcode == 'both' || $showqnumcode == 'number' || $showqnumcode == 'choose' && !isset($thissurvey['showqnumcode']) || $showqnumcode == 'choose' && $thissurvey['showqnumcode'] == 'B' || $showqnumcode == 'choose' && $thissurvey['showqnumcode'] == 'N') {
        $_question_number = $question['number'];
    } else {
        $_question_number = '';
    }
    if ($showqnumcode == 'both' || $showqnumcode == 'code' || $showqnumcode == 'choose' && !isset($thissurvey['showqnumcode']) || $showqnumcode == 'choose' && $thissurvey['showqnumcode'] == 'B' || $showqnumcode == 'choose' && $thissurvey['showqnumcode'] == 'C') {
        $_question_code = $question['code'];
    } else {
        $_question_code = '';
    }
    if (isset($_SESSION['therearexquestions'])) {
        $_totalquestionsAsked = $_SESSION['therearexquestions'] - $totalBoilerplatequestions;
    } else {
        $_totalquestionsAsked = 0;
    }
    if ($showxquestions == 'show' || $showxquestions == 'choose' && !isset($thissurvey['showxquestions']) || $showxquestions == 'choose' && $thissurvey['showxquestions'] == 'Y') {
        if ($_totalquestionsAsked < 1) {
            $_therearexquestions = $clang->gT("There are no questions in this survey");
            // Singular
        } elseif ($_totalquestionsAsked == 1) {
            $_therearexquestions = $clang->gT("There is 1 question in this survey");
            //Singular
        } else {
            $_therearexquestions = $clang->gT("There are {NUMBEROFQUESTIONS} questions in this survey.");
            //Note this line MUST be before {NUMBEROFQUESTIONS}
        }
    } else {
        $_therearexquestions = '';
    }
    if (isset($token)) {
        $_token = $token;
    } elseif (isset($clienttoken)) {
        $_token = htmlentities($clienttoken, ENT_QUOTES, 'UTF-8');
    } else {
        $_token = '';
    }
    if (isset($thissurvey['surveyls_dateformat'])) {
        $dateformatdetails = getDateFormatData($thissurvey['surveyls_dateformat']);
    } else {
        $dateformatdetails = getDateFormatData();
    }
    if (isset($thissurvey['expiry'])) {
        $_datetimeobj = new Date_Time_Converter($thissurvey['expiry'], "Y-m-d");
        $_dateoutput = $_datetimeobj->convert($dateformatdetails['phpdate']);
    } else {
        $_dateoutput = '-';
    }
    $_submitbutton = "<input class='submit' type='submit' value=' " . $clang->gT("Submit") . " ' name='move2' onclick=\"javascript:document.limesurvey.move.value = 'movesubmit';\" />";
    if (isset($thissurvey['surveyls_url']) and $thissurvey['surveyls_url'] != "") {
        if (trim($thissurvey['surveyls_urldescription']) != '') {
            $_linkreplace = "<a href='{$thissurvey['surveyls_url']}'>{$thissurvey['surveyls_urldescription']}</a>";
        } else {
            $_linkreplace = "<a href='{$thissurvey['surveyls_url']}'>{$thissurvey['surveyls_url']}</a>";
        }
    } else {
        $_linkreplace = '';
    }
    if (isset($clienttoken)) {
        $token = $clienttoken;
    } else {
        $token = '';
    }
    if (!isset($_SESSION['s_lang'])) {
        $_s_lang = 'en';
    } else {
        $_s_lang = $_SESSION['s_lang'];
    }
    // CLEARALL
    if ($surveyid && !isCompleted($surveyid, $saved_id)) {
        $_clearall = "<input type='button' name='clearallbtn' value='" . $clang->gT("Exit and Clear Survey") . "' class='clearall' " . "onclick=\"if (confirm('" . $clang->gT("Are you sure you want to clear all your responses?", 'js') . "')) {\nwindow.open('{$publicurl}/index.php?sid={$surveyid}&amp;move=clearall&amp;lang=" . $_s_lang;
        if (returnglobal('token')) {
            $_clearall .= "&amp;token={$_token}";
        }
        $_clearall .= "', '_self')}\" />";
    } else {
        $_clearall = "";
        // This survey are already completed or surveyid not set, then don't have access to clearallbtn
    }
    if (isset($_SESSION['datestamp'])) {
        $_datestamp = $_SESSION['datestamp'];
    } else {
        $_datestamp = '-';
    }
    //Set up save/load feature
    if (isset($thissurvey['allowsave']) and $thissurvey['allowsave'] == "Y") {
        // Find out if the user has any saved data
        if ($thissurvey['format'] == 'A') {
            if ($thissurvey['tokenanswerspersistence'] != 'Y' || !tableExists('tokens_' . $surveyid)) {
                $_saveall = "\t\t\t<input type='button' name='loadall' value='" . $clang->gT("Load Unfinished Survey") . "' class='saveall' onclick=\"javascript:addHiddenField(document.getElementById('limesurvey'),'loadall',this.value);document.getElementById('limesurvey').submit();\" " . ($thissurvey['active'] != "Y" ? "disabled='disabled'" : "") . "/>" . "\n\t\t\t<input type='button' name='saveallbtn' value='" . $clang->gT("Resume Later") . "' class='saveall' onclick=\"javascript:document.limesurvey.move.value = this.value;addHiddenField(document.getElementById('limesurvey'),'saveall',this.value);document.getElementById('limesurvey').submit();\" " . ($thissurvey['active'] != "Y" ? "disabled='disabled'" : "") . "/>";
                // Show Save So Far button
            } else {
                $_saveall = "\t\t\t<input type='button' name='saveallbtn' value='" . $clang->gT("Resume Later") . "' class='saveall' onclick=\"javascript:document.limesurvey.move.value = this.value;addHiddenField(document.getElementById('limesurvey'),'saveall',this.value);document.getElementById('limesurvey').submit();\" " . ($thissurvey['active'] != "Y" ? "disabled='disabled'" : "") . "/>";
                // Show Save So Far button
            }
        } elseif (!isset($_SESSION['step']) || !$_SESSION['step']) {
            //First page, show LOAD
            if ($thissurvey['tokenanswerspersistence'] != 'Y' || !tableExists('tokens_' . $surveyid)) {
                $_saveall = "\t\t\t<input type='button' name='loadall' value='" . $clang->gT("Load Unfinished Survey") . "' class='saveall' onclick=\"javascript:addHiddenField(document.getElementById('limesurvey'),'loadall',this.value);document.getElementById('limesurvey').submit();\" " . ($thissurvey['active'] != "Y" ? "disabled='disabled'" : "") . "/>";
            } else {
                $_saveall = '';
            }
        } elseif (isset($_SESSION['scid']) && (isset($move) && $move == "movelast")) {
            //Already saved and on Submit Page, dont show Save So Far button
            $_saveall = '';
        } else {
            $_saveall = "<input type='button' name='saveallbtn' value='" . $clang->gT("Resume Later") . "' class='saveall' onclick=\"javascript:document.limesurvey.move.value = this.value;addHiddenField(document.getElementById('limesurvey'),'saveall',this.value);document.getElementById('limesurvey').submit();\" " . ($thissurvey['active'] != "Y" ? "disabled='disabled'" : "") . "/>";
            // Show Save So Far button
        }
    } else {
        $_saveall = "";
    }
    $_templatecss = "<link rel='stylesheet' type='text/css' href='{$_templateurl}template.css' />\n";
    if (getLanguageRTL($clang->langcode)) {
        $_templatecss .= "<link rel='stylesheet' type='text/css' href='{$_templateurl}template-rtl.css' />\n";
    }
    if (FlattenText($help, true) != '') {
        if (!isset($helpicon)) {
            if (file_exists($templatedir . '/help.gif')) {
                $helpicon = $_templateurl . 'help.gif';
            } elseif (file_exists($templatedir . '/help.png')) {
                $helpicon = $_templateurl . 'help.png';
            } else {
                $helpicon = $imageurl . "/help.gif";
            }
        }
        $_questionhelp = "<img src='{$helpicon}' alt='Help' align='left' />" . $help;
    } else {
        $_questionhelp = $help;
    }
    if (isset($thissurvey['allowprev']) && $thissurvey['allowprev'] == "N") {
        $_strreview = "";
    } else {
        $_strreview = $clang->gT("If you want to check any of the answers you have made, and/or change them, you can do that now by clicking on the [<< prev] button and browsing through your responses.");
    }
    if (isset($thissurvey['active']) and $thissurvey['active'] == "N") {
        $_restart = "<a href='{$publicurl}/index.php?sid={$surveyid}&amp;newtest=Y";
        if (isset($s_lang) && $s_lang != '') {
            $_restart .= "&amp;lang=" . $s_lang;
        }
        $_restart .= "'>" . $clang->gT("Restart this Survey") . "</a>";
    } else {
        $restart_extra = "";
        $restart_token = returnglobal('token');
        if (!empty($restart_token)) {
            $restart_extra .= "&amp;token=" . urlencode($restart_token);
        } else {
            $restart_extra = "&amp;newtest=Y";
        }
        if (!empty($_GET['lang'])) {
            $restart_extra .= "&amp;lang=" . returnglobal('lang');
        }
        $_restart = "<a href='{$publicurl}/index.php?sid={$surveyid}" . $restart_extra . "'>" . $clang->gT("Restart this Survey") . "</a>";
    }
    if (isset($thissurvey['anonymized']) && $thissurvey['anonymized'] == 'Y') {
        $_savealert = $clang->gT("To remain anonymous please use a pseudonym as your username, also an email address is not required.");
    } else {
        $_savealert = "";
    }
    $_return_to_survey = "<a href='{$relativeurl}/index.php?sid={$surveyid}";
    if (returnglobal('token')) {
        $_return_to_survey .= "&amp;token=" . urlencode(trim(sanitize_xss_string(strip_tags(returnglobal('token')))));
    }
    $_return_to_survey .= "'>" . $clang->gT("Return To Survey") . "</a>";
    $_saveform = "<table><tr><td align='right'>" . $clang->gT("Name") . ":</td><td><input type='text' name='savename' value='";
    if (isset($_POST['savename'])) {
        $_saveform .= html_escape(auto_unescape($_POST['savename']));
    }
    $_saveform .= "' /></td></tr>\n" . "<tr><td align='right'>" . $clang->gT("Password") . ":</td><td><input type='password' name='savepass' value='";
    if (isset($_POST['savepass'])) {
        $_saveform .= html_escape(auto_unescape($_POST['savepass']));
    }
    $_saveform .= "' /></td></tr>\n" . "<tr><td align='right'>" . $clang->gT("Repeat Password") . ":</td><td><input type='password' name='savepass2' value='";
    if (isset($_POST['savepass2'])) {
        $_saveform .= html_escape(auto_unescape($_POST['savepass2']));
    }
    $_saveform .= "' /></td></tr>\n" . "<tr><td align='right'>" . $clang->gT("Your Email") . ":</td><td><input type='text' name='saveemail' value='";
    if (isset($_POST['saveemail'])) {
        $_saveform .= html_escape(auto_unescape($_POST['saveemail']));
    }
    $_saveform .= "' /></td></tr>\n";
    if (isset($thissurvey['usecaptcha']) && function_exists("ImageCreate") && captcha_enabled('saveandloadscreen', $thissurvey['usecaptcha'])) {
        $_saveform .= "<tr><td align='right'>" . $clang->gT("Security Question") . ":</td><td><table><tr><td valign='middle'><img src='{$captchapath}verification.php?sid={$surveyid}' alt='' /></td><td valign='middle' style='text-align:left'><input type='text' size='5' maxlength='3' name='loadsecurity' value='' /></td></tr></table></td></tr>\n";
    }
    $_saveform .= "<tr><td align='right'></td><td></td></tr>\n" . "<tr><td></td><td><input type='submit'  id='savebutton' name='savesubmit' value='" . $clang->gT("Save Now") . "' /></td></tr>\n" . "</table>";
    $_loadform = "<table><tr><td align='right'>" . $clang->gT("Saved name") . ":</td><td><input type='text' name='loadname' value='";
    if ($loadname) {
        $_loadform .= html_escape(auto_unescape($loadname));
    }
    $_loadform .= "' /></td></tr>\n" . "<tr><td align='right'>" . $clang->gT("Password") . ":</td><td><input type='password' name='loadpass' value='";
    if (isset($loadpass)) {
        $_loadform .= html_escape(auto_unescape($loadpass));
    }
    $_loadform .= "' /></td></tr>\n";
    if (isset($thissurvey['usecaptcha']) && function_exists("ImageCreate") && captcha_enabled('saveandloadscreen', $thissurvey['usecaptcha'])) {
        $_loadform .= "<tr><td align='right'>" . $clang->gT("Security Question") . ":</td><td><table><tr><td valign='middle'><img src='{$captchapath}verification.php?sid={$surveyid}' alt='' /></td><td valign='middle'><input type='text' size='5' maxlength='3' name='loadsecurity' value='' alt=''/></td></tr></table></td></tr>\n";
    }
    $_loadform .= "<tr><td align='right'></td><td></td></tr>\n" . "<tr><td></td><td><input type='submit' id='loadbutton' value='" . $clang->gT("Load Now") . "' /></td></tr></table>\n";
    $_registerform = "<form method='post' action='{$publicurl}/register.php'>\n";
    if (!isset($_REQUEST['lang'])) {
        $_reglang = GetBaseLanguageFromSurveyID($surveyid);
    } else {
        $_reglang = returnglobal('lang');
    }
    $_registerform .= "<input type='hidden' name='lang' value='" . $_reglang . "' />\n";
    $_registerform .= "<input type='hidden' name='sid' value='{$surveyid}' id='sid' />\n";
    $_registerform .= "<table class='register' summary='Registrationform'>\n" . "<tr><td align='right'>" . $clang->gT("First name") . ":</td>" . "<td align='left'><input class='text' type='text' name='register_firstname'";
    if (isset($_POST['register_firstname'])) {
        $_registerform .= " value='" . htmlentities(returnglobal('register_firstname'), ENT_QUOTES, 'UTF-8') . "'";
    }
    $_registerform .= " /></td></tr>" . "<tr><td align='right'>" . $clang->gT("Last name") . ":</td>\n" . "<td align='left'><input class='text' type='text' name='register_lastname'";
    if (isset($_POST['register_lastname'])) {
        $_registerform .= " value='" . htmlentities(returnglobal('register_lastname'), ENT_QUOTES, 'UTF-8') . "'";
    }
    $_registerform .= " /></td></tr>\n" . "<tr><td align='right'>" . $clang->gT("Email address") . ":</td>\n" . "<td align='left'><input class='text' type='text' name='register_email'";
    if (isset($_POST['register_email'])) {
        $_registerform .= " value='" . htmlentities(returnglobal('register_email'), ENT_QUOTES, 'UTF-8') . "'";
    }
    $_registerform .= " /></td></tr>\n";
    if (isset($thissurvey['usecaptcha']) && function_exists("ImageCreate") && captcha_enabled('registrationscreen', $thissurvey['usecaptcha'])) {
        $_registerform .= "<tr><td align='right'>" . $clang->gT("Security Question") . ":</td><td><table><tr><td valign='middle'><img src='{$captchapath}verification.php?sid={$surveyid}' alt='' /></td><td valign='middle'><input type='text' size='5' maxlength='3' name='loadsecurity' value='' /></td></tr></table></td></tr>\n";
    }
    /*      if(isset($thissurvey['attribute1']) && $thissurvey['attribute1'])
             {
             $_registerform .= "<tr><td align='right'>".$thissurvey['attribute1'].":</td>\n"
             ."<td align='left'><input class='text' type='text' name='register_attribute1'";
             if (isset($_POST['register_attribute1']))
             {
             $_registerform .= " value='".htmlentities(returnglobal('register_attribute1'),ENT_QUOTES,'UTF-8')."'";
             }
             $_registerform .= " /></td></tr>\n";
             }
             if(isset($thissurvey['attribute2']) && $thissurvey['attribute2'])
             {
             $_registerform .= "<tr><td align='right'>".$thissurvey['attribute2'].":</td>\n"
             ."<td align='left'><input class='text' type='text' name='register_attribute2'";
             if (isset($_POST['register_attribute2']))
             {
             $_registerform .= " value='".htmlentities(returnglobal('register_attribute2'),ENT_QUOTES,'UTF-8')."'";
             }
             $_registerform .= " /></td></tr>\n";
          } */
    $_registerform .= "<tr><td></td><td><input id='registercontinue' class='submit' type='submit' value='" . $clang->gT("Continue") . "' />" . "</td></tr>\n" . "</table>\n" . "</form>\n";
    if (!is_null($surveyid) && function_exists('doAssessment')) {
        $assessmentdata = doAssessment($surveyid, true);
        $_assessment_current_total = $assessmentdata['total'];
    } else {
        $_assessment_current_total = '';
    }
    if (isset($thissurvey['googleanalyticsapikey']) && trim($thissurvey['googleanalyticsapikey']) != '') {
        $_googleAnalyticsAPIKey = trim($thissurvey['googleanalyticsapikey']);
    } else {
        $_googleAnalyticsAPIKey = trim(getGlobalSetting('googleanalyticsapikey'));
    }
    $_googleAnalyticsStyle = isset($thissurvey['googleanalyticsstyle']) ? $thissurvey['googleanalyticsstyle'] : '0';
    $_googleAnalyticsJavaScript = '';
    if ($_googleAnalyticsStyle != '' && $_googleAnalyticsStyle != 0 && $_googleAnalyticsAPIKey != '') {
        switch ($_googleAnalyticsStyle) {
            case '1':
                // Default Google Tracking
                $_googleAnalyticsJavaScript = <<<EOD
<script type="text/javascript">
  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', '{$_googleAnalyticsAPIKey}']);
  _gaq.push(['_trackPageview']);

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

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

    $fieldmap=createFieldMap($surveyid, "full");

    if (is_null($statlangcode))
    {
        $statlang=$clang;
    }
    else
    {
        $statlang = new limesurvey_lang($statlangcode);
    }

    /*
     * this variable is used in the function shortencode() which cuts off a question/answer title
     * after $maxchars and shows the rest as tooltip (in html mode)
     */
    $maxchars = 13;
    //we collect all the html-output within this variable
    $statisticsoutput ='';
    /**
     * $outputType: html || pdf ||
     */
    /**
     * get/set Survey Details
     */

    //no survey ID? -> come and get one
    if (!isset($surveyid)) {$surveyid=returnglobal('sid');}

    //Get an array of codes of all available languages in this survey
    $surveylanguagecodes = GetAdditionalLanguagesFromSurveyID($surveyid);
    $surveylanguagecodes[] = GetBaseLanguageFromSurveyID($surveyid);

    // Set language for questions and answers to base language of this survey
    $language=$statlangcode;

    if ($usegraph==1)
    {
        //for creating graphs we need some more scripts which are included here
        require_once(dirname(__FILE__).'/../classes/pchart/pchart/pChart.class');
        require_once(dirname(__FILE__).'/../classes/pchart/pchart/pData.class');
        require_once(dirname(__FILE__).'/../classes/pchart/pchart/pCache.class');
        $MyCache = new pCache($tempdir.'/');

        //pick the best font file if font setting is 'auto'
        if ($chartfontfile=='auto')
        {
            $chartfontfile='vera.ttf';
            if ( $language=='ar')
            {
                $chartfontfile='KacstOffice.ttf';
            }
            elseif  ($language=='fa' )
            {
                $chartfontfile='KacstFarsi.ttf';
            }

        }
    }

    if($q2show=='all' )
    {
        $summarySql=" SELECT gid, parent_qid, qid, type "
        ." FROM {$dbprefix}questions WHERE parent_qid=0"
        ." AND sid=$surveyid ";

        $summaryRs = db_execute_assoc($summarySql);

        foreach($summaryRs as $field)
        {
            $myField = $surveyid."X".$field['gid']."X".$field['qid'];

            // Multiple choice get special treatment
            if ($field['type'] == "M") {$myField = "M$myField";}
            if ($field['type'] == "P") {$myField = "P$myField";}
            //numerical input will get special treatment (arihtmetic mean, standard derivation, ...)
            if ($field['type'] == "N") {$myField = "N$myField";}

            if ($field['type'] == "|") {$myField = "|$myField";}

            if ($field['type'] == "Q") {$myField = "Q$myField";}
            // textfields get special treatment
            if ($field['type'] == "S" || $field['type'] == "T" || $field['type'] == "U"){$myField = "T$myField";}
            //statistics for Date questions are not implemented yet.
            if ($field['type'] == "D") {$myField = "D$myField";}
            if ($field['type'] == "F" || $field['type'] == "H")
            {
                //Get answers. We always use the answer code because the label might be too long elsewise
                $query = "SELECT code, answer FROM ".db_table_name("answers")." WHERE qid='".$field['qid']."' AND scale_id=0 AND language='{$language}' ORDER BY sortorder, answer";
                $result = db_execute_num($query) or safe_die ("Couldn't get answers!<br />$query<br />".$connect->ErrorMsg());
                $counter2=0;

                //check all the answers
                while ($row=$result->FetchRow())
                {
                    $myField = "$myField{$row[0]}";
                }
                //$myField = "{$surveyid}X{$flt[1]}X{$flt[0]}{$row[0]}[]";


            }
            if($q2show=='all')
            $summary[]=$myField;

            //$allfields[]=$myField;
        }
    }
    else
    {
        // This gets all the 'to be shown questions' from the POST and puts these into an array
        if (!is_array($q2show))
        $summary=returnglobal('summary');
        else
            $summary = $q2show;

        //print_r($_POST);
        //if $summary isn't an array we create one
        if (isset($summary) && !is_array($summary))
        {
            $summary = explode("+", $summary);
        }
    }

	/* Some variable depend on output type, actually : only line feed */
    switch($outputType)
        {
            case 'xls':
                $linefeed = "\n";
                break;
            case 'pdf':
                $linefeed = "\n";
                break;
            case 'html':
                $linefeed = "<br />\n";
                break;
            default:

            break;
        }

    /**
     * pdf Config
     */
    if($outputType=='pdf')
    {
        require_once('classes/tcpdf/config/lang/eng.php');
        global $l;
        $l['w_page'] = $statlang->gT("Page",'unescaped');
        require_once('classes/tcpdf/mypdf.php');

        // create new PDF document
        $pdf = new MyPDF();
        $pdf->SetFont($pdfdefaultfont,'',$pdffontsize);

        $surveyInfo = getSurveyInfo($surveyid,$language);

        // set document information
        $pdf->SetCreator(PDF_CREATOR);
        $pdf->SetAuthor('LimeSurvey');
        $pdf->SetTitle('Statistic survey '.$surveyid);
        $pdf->SetSubject($surveyInfo['surveyls_title']);
        $pdf->SetKeywords('LimeSurvey, Statistics, Survey '.$surveyid.'');
        $pdf->SetDisplayMode('fullpage', 'two');

        // set header and footer fonts
        $pdf->setHeaderFont(Array($pdfdefaultfont, '', PDF_FONT_SIZE_MAIN));
        $pdf->setFooterFont(Array($pdfdefaultfont, '', PDF_FONT_SIZE_DATA));

        // set default header data
        // the path looks awkward - did not find a better solution to set the image path?
        $pdf->SetHeaderData("statistics.png", 10, $statlang->gT("Quick statistics",'unescaped') , $statlang->gT("Survey")." ".$surveyid." '".FlattenText($surveyInfo['surveyls_title'],true,'UTF-8')."'");


        // set default monospaced font
        $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

        //set margins
        $pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
        $pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
        $pdf->SetFooterMargin(PDF_MARGIN_FOOTER);

        //set auto page breaks
        $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

        //set image scale factor
        $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

        //set some language-dependent strings
        $pdf->setLanguageArray($l);
    }
    if($outputType=='xls')
    {
        /**
         * Initiate the Spreadsheet_Excel_Writer
         */
        include_once(dirname(__FILE__)."/classes/pear/Spreadsheet/Excel/Writer.php");
        if($pdfOutput=='F')
        $workbook = new Spreadsheet_Excel_Writer($tempdir.'/statistic-survey'.$surveyid.'.xls');
        else
        $workbook = new Spreadsheet_Excel_Writer();

        $workbook->setVersion(8);
        // Inform the module that our data will arrive as UTF-8.
        // Set the temporary directory to avoid PHP error messages due to open_basedir restrictions and calls to tempnam("", ...)
        if (!empty($tempdir)) {
            $workbook->setTempDir($tempdir);
        }
        if ($pdfOutput!='F')
        $workbook->send('statistic-survey'.$surveyid.'.xls');

        // Creating the first worksheet
        $sheet =& $workbook->addWorksheet(utf8_decode('results-survey'.$surveyid));
        $sheet->setInputEncoding('utf-8');
        $sheet->setColumn(0,20,20);
        $separator="~|";
    }
    /**
     * Start generating
     */

    // creates array of post variable names
    for (reset($_POST); $key=key($_POST); next($_POST)) { $postvars[]=$key;}

    $aQuestionMap=array();
    foreach ($fieldmap as $field)
    {
        if(isset($field['qid']) && $field['qid']!='')
        $aQuestionMap[]=$field['sid'].'X'.$field['gid'].'X'.$field['qid'];
    }

    /*
     * Iterate through postvars to create "nice" data for SQL later.
     *
     * Remember there might be some filters applied which have to be put into an SQL statement
     */
    if(isset($postvars))

    foreach ($postvars as $pv)
    {
        //Only do this if there is actually a value for the $pv
        if (in_array($pv, $allfields) || in_array(substr($pv,1),$aQuestionMap) || in_array($pv,$aQuestionMap) || (($pv[0]=='D' || $pv[0]=='N' || $pv[0]=='K') && in_array(substr($pv,1,strlen($pv)-2),$aQuestionMap)))
        {
            $firstletter=substr($pv,0,1);
            /*
             * these question types WON'T be handled here:
             * M = Multiple choice
             * T - Long Free Text
             * Q - Multiple Short Text
             * D - Date
             * N - Numerical Input
             * | - File Upload
             * K - Multiple Numerical Input
             */
            if ($pv != "sid" && $pv != "display" && $firstletter != "M" && $firstletter != "P" && $firstletter != "T" &&
            $firstletter != "Q" && $firstletter != "D" && $firstletter != "N" && $firstletter != "K" && $firstletter != "|" &&
            $pv != "summary" && substr($pv, 0, 2) != "id" && substr($pv, 0, 9) != "datestamp") //pull out just the fieldnames
            {
                //put together some SQL here
                $thisquestion = db_quote_id($pv)." IN (";

                foreach ($_POST[$pv] as $condition)
                {
                    $thisquestion .= "'$condition', ";
                }

                $thisquestion = substr($thisquestion, 0, -2)
                . ")";

                //we collect all the to be selected data in this array
                $selects[]=$thisquestion;
            }

            //M - Multiple choice
            //P - Multiple choice with comments
            elseif ($firstletter == "M"  || $firstletter == "P")
            {
                $mselects=array();
                //create a list out of the $pv array
                list($lsid, $lgid, $lqid) = explode("X", $pv);

                $aquery="SELECT title FROM ".db_table_name("questions")." WHERE parent_qid=$lqid AND language='{$language}' and scale_id=0 ORDER BY question_order";
                $aresult=db_execute_num($aquery) or safe_die ("Couldn't get subquestions<br />$aquery<br />".$connect->ErrorMsg());

                // go through every possible answer
                while ($arow=$aresult->FetchRow())
                {
                    // only add condition if answer has been chosen
                    if (in_array($arow[0], $_POST[$pv]))
                    {
                        $mselects[]=db_quote_id(substr($pv, 1, strlen($pv)).$arow[0])." = 'Y'";
                    }
                }
                if ($mselects)
                {
                    $thismulti=implode(" OR ", $mselects);
                    $selects[]="($thismulti)";
                    $mselects = "";
                }
            }


            //N - Numerical Input
            //K - Multiple Numerical Input
            elseif ($firstletter == "N" || $firstletter == "K")
            {
                //value greater than
                if (substr($pv, strlen($pv)-1, 1) == "G" && $_POST[$pv] != "")
                {
                    $selects[]=db_quote_id(substr($pv, 1, -1))." > ".sanitize_int($_POST[$pv]);
                }

                //value less than
                if (substr($pv, strlen($pv)-1, 1) == "L" && $_POST[$pv] != "")
                {
                    $selects[]=db_quote_id(substr($pv, 1, -1))." < ".sanitize_int($_POST[$pv]);
                }
            }

            //| - File Upload Question Type
            else if ($firstletter == "|")
            {
                // no. of files greater than
                if (substr($pv, strlen($pv)-1, 1) == "G" && $_POST[$pv] != "")
                    $selects[]=db_quote_id(substr($pv, 1, -1)."_filecount")." > ".sanitize_int($_POST[$pv]);

                // no. of files less than
                if (substr($pv, strlen($pv)-1, 1) == "L" && $_POST[$pv] != "")
                    $selects[]=db_quote_id(substr($pv, 1, -1)."_filecount")." < ".sanitize_int($_POST[$pv]);
            }

            //"id" is a built in field, the unique database id key of each response row
            elseif (substr($pv, 0, 2) == "id")
            {
                if (substr($pv, strlen($pv)-1, 1) == "G" && $_POST[$pv] != "")
                {
                    $selects[]=db_quote_id(substr($pv, 0, -1))." > '".$_POST[$pv]."'";
                }
                if (substr($pv, strlen($pv)-1, 1) == "L" && $_POST[$pv] != "")
                {
                    $selects[]=db_quote_id(substr($pv, 0, -1))." < '".$_POST[$pv]."'";
                }
            }

            //T - Long Free Text
            //Q - Multiple Short Text
            elseif (($firstletter == "T" || $firstletter == "Q" ) && $_POST[$pv] != "")
            {
                $selectSubs = array();
                //We intepret and * and % as wildcard matches, and use ' OR ' and , as the seperators
                $pvParts = explode(",",str_replace('*','%', str_replace(' OR ',',',$_POST[$pv])));
                if(is_array($pvParts) AND count($pvParts)){
                    foreach($pvParts AS $pvPart){
                        $selectSubs[]=db_quote_id(substr($pv, 1, strlen($pv)))." LIKE '".trim($pvPart)."'";
                    }
                    if(count($selectSubs)){
                        $selects[] = ' ('.implode(' OR ',$selectSubs).') ';
                    }
                }
            }

            //D - Date
            elseif ($firstletter == "D" && $_POST[$pv] != "")
            {
                //Date equals
                if (substr($pv, -1, 1) == "=")
                {
                    $selects[]=db_quote_id(substr($pv, 1, strlen($pv)-2))." = '".$_POST[$pv]."'";
                }
                else
                {
                    //date less than
                    if (substr($pv, -1, 1) == "<")
                    {
                        $selects[]= db_quote_id(substr($pv, 1, strlen($pv)-2)) . " >= '".$_POST[$pv]."'";
                    }

                    //date greater than
                    if (substr($pv, -1, 1) == ">")
                    {
                        $selects[]= db_quote_id(substr($pv, 1, strlen($pv)-2)) . " <= '".$_POST[$pv]."'";
                    }
                }
            }

            //check for datestamp of given answer
            elseif (substr($pv, 0, 9) == "datestamp")
            {
                //timestamp equals
                $formatdata=getDateFormatData($_SESSION['dateformat']);
                if (substr($pv, -1, 1) == "E" && !empty($_POST[$pv]))
                {
                    $datetimeobj = new Date_Time_Converter($_POST[$pv], $formatdata['phpdate'].' H:i');
                    $_POST[$pv]=$datetimeobj->convert("Y-m-d");

                    $selects[] = db_quote_id('datestamp')." >= '".$_POST[$pv]." 00:00:00' and ".db_quote_id('datestamp')." <= '".$_POST[$pv]." 23:59:59'";
                }
                else
                {
                    //timestamp less than
                    if (substr($pv, -1, 1) == "L" && !empty($_POST[$pv]))
                    {
                        $datetimeobj = new Date_Time_Converter($_POST[$pv], $formatdata['phpdate'].' H:i');
                        $_POST[$pv]=$datetimeobj->convert("Y-m-d H:i:s");
                        $selects[]= db_quote_id('datestamp')." < '".$_POST[$pv]."'";
                    }

                    //timestamp greater than
                    if (substr($pv, -1, 1) == "G" && !empty($_POST[$pv]))
                    {
                        $datetimeobj = new Date_Time_Converter($_POST[$pv], $formatdata['phpdate'].' H:i');
                        $_POST[$pv]=$datetimeobj->convert("Y-m-d H:i:s");
                        $selects[]= db_quote_id('datestamp')." > '".$_POST[$pv]."'";
                    }
                }
            }
        }
        else
        {
            $statisticsoutput .= "<!-- $pv DOES NOT EXIST IN ARRAY -->";
        }

    }	//end foreach -> loop through filter options to create SQL

    //count number of answers
    $query = "SELECT count(*) FROM ".db_table_name("survey_$surveyid");

    //if incompleted answers should be filtert submitdate has to be not null
    if (incompleteAnsFilterstate() == "inc") {$query .= " WHERE submitdate is null";}
    elseif (incompleteAnsFilterstate() == "filter") {$query .= " WHERE submitdate is not null";}
    $result = db_execute_num($query) or safe_die ("Couldn't get total<br />$query<br />".$connect->ErrorMsg());

    //$total = total number of answers
    while ($row=$result->FetchRow()) {$total=$row[0];}

    //are there any filters that have to be taken care of?
    if (isset($selects) && $selects)
    {
        //filter incomplete answers?
        if (incompleteAnsFilterstate() == "filter" || incompleteAnsFilterstate() == "inc") {$query .= " AND ";}

        else {$query .= " WHERE ";}

        //add filter criteria to SQL
        $query .= implode(" AND ", $selects);
    }

    //$_POST['sql'] is a post field that is sent from the statistics script to the export script in order
    // to export just those results filtered by this statistics script. It can also be passed to the statistics
    // script to filter from external scripts.
    elseif (!empty($_POST['sql']) && !isset($_POST['id=']))
    {
        $newsql=substr($_POST['sql'], strpos($_POST['sql'], "WHERE")+5, strlen($_POST['sql']));

        //for debugging only
        //$query = $_POST['sql'];

        //filter incomplete answers?
        if (incompleteAnsFilterstate() == "inc") {$query .= " AND ".$newsql;}
        elseif (incompleteAnsFilterstate() == "filter") {$query .= " AND ".$newsql;}

        else {$query .= " WHERE ".$newsql;}
    }

    //get me some data Scotty
    $result=db_execute_num($query) or safe_die("Couldn't get results<br />$query<br />".$connect->ErrorMsg());

    //put all results into $results
    while ($row=$result->FetchRow()) {$results=$row[0];}

    if ($total)
    {
        $percent=sprintf("%01.2f", ($results/$total)*100);

    }
    switch($outputType)
    {
        case "xls":
            $xlsRow = 0;
            $sheet->write($xlsRow,0,$statlang->gT("Number of records in this query:"));
            $sheet->write($xlsRow,1,$results);
            ++$xlsRow;
            $sheet->write($xlsRow,0,$statlang->gT("Total records in survey:"));
            $sheet->write($xlsRow,1,$total);

            if($total)
            {
                ++$xlsRow;
                $sheet->write($xlsRow,0,$statlang->gT("Percentage of total:"));
                $sheet->write($xlsRow,1,$percent."%");
            }

            break;
        case 'pdf':

            // add summary to pdf
            $array = array();
            //$array[] = array($statlang->gT("Results"),"");
            $array[] = array($statlang->gT("Number of records in this query:"), $results);
            $array[] = array($statlang->gT("Total records in survey:"), $total);

            if($total)
            $array[] = array($statlang->gT("Percentage of total:"), $percent."%");

            $pdf->addPage('P','A4');

            $pdf->Bookmark($pdf->delete_html($statlang->gT("Results")), 0, 0);
            $pdf->titleintopdf($statlang->gT("Results"),$statlang->gT("Survey")." ".$surveyid);
            $pdf->tableintopdf($array);

            $pdf->addPage('P','A4');

            break;
        case 'html':

            $statisticsoutput .= "<br />\n<table class='statisticssummary' >\n"
            ."\t<thead><tr><th colspan='2'>".$statlang->gT("Results")."</th></tr></thead>\n"
            ."\t<tr><th >".$statlang->gT("Number of records in this query:").'</th>'
            ."<td>$results</td></tr>\n"
            ."\t<tr><th>".$statlang->gT("Total records in survey:").'</th>'
            ."<td>$total</td></tr>\n";

            //only calculate percentage if $total is set
            if ($total)
            {
                $percent=sprintf("%01.2f", ($results/$total)*100);
                $statisticsoutput .= "\t<tr><th align='right'>".$statlang->gT("Percentage of total:").'</th>'
                ."<td>$percent%</td></tr>\n";
            }
            $statisticsoutput .="</table>\n";

            break;
        default:


            break;
    }

    //put everything from $selects array into a string connected by AND
    if (isset ($selects) && $selects) {$sql=implode(" AND ", $selects);}

    elseif (!empty($newsql)) {$sql = $newsql;}

    if (!isset($sql) || !$sql) {$sql="NULL";}

    //only continue if we have something to output
    if ($results > 0)
    {
        if($outputType=='html' && $browse === true)
        {
            //add a buttons to browse results
            $statisticsoutput .= "<form action='$scriptname?action=browse' method='post' target='_blank'>\n"
            ."\t\t<p>"
            ."\t\t\t<input type='submit' value='".$statlang->gT("Browse")."'  />\n"
            ."\t\t\t<input type='hidden' name='sid' value='$surveyid' />\n"
            ."\t\t\t<input type='hidden' name='sql' value=\"$sql\" />\n"
            ."\t\t\t<input type='hidden' name='subaction' value='all' />\n"
            ."\t\t</p>"
            ."\t\t</form>\n";
        }
    }	//end if (results > 0)

    //Show Summary results
    if (isset($summary) && $summary)
    {
        //let's run through the survey
        $runthrough=$summary;

        //START Chop up fieldname and find matching questions

        //GET LIST OF LEGIT QIDs FOR TESTING LATER
        $lq = "SELECT DISTINCT qid FROM ".db_table_name("questions")." WHERE sid=$surveyid and parent_qid=0";
        $lr = db_execute_assoc($lq);

        //loop through the IDs
        while ($lw = $lr->FetchRow())
        {
            //this creates an array of question id's'
            $legitqids[] = $lw['qid'];
        }

        //loop through all selected questions
        foreach ($runthrough as $rt)
        {

            $firstletter = substr($rt, 0, 1);
            // 1. Get answers for question ##############################################################

            //M - Multiple choice, therefore multiple fields
            if ($firstletter == "M" || $firstletter == "P")
            {
                //get SGQ data
                list($qsid, $qgid, $qqid) = explode("X", substr($rt, 1, strlen($rt)), 3);

                //select details for this question
                $nquery = "SELECT title, type, question, parent_qid, other FROM ".db_table_name("questions")." WHERE language='{$language}' AND parent_qid=0 AND qid='$qqid'";
                $nresult = db_execute_num($nquery) or safe_die ("Couldn't get question<br />$nquery<br />".$connect->ErrorMsg());

                //loop through question data
                while ($nrow=$nresult->FetchRow())
                {
                    $qtitle=$nrow[0];
                    $qtype=$nrow[1];
                    $qquestion=FlattenText($nrow[2]);
                    $qlid=$nrow[3];
                    $qother=$nrow[4];
                }

                //1. Get list of answers
                $query="SELECT title, question FROM ".db_table_name("questions")." WHERE parent_qid='$qqid' AND language='{$language}' and scale_id=0 ORDER BY question_order";
                $result=db_execute_num($query) or safe_die("Couldn't get list of subquestions for multitype<br />$query<br />".$connect->ErrorMsg());

                //loop through multiple answers
                while ($row=$result->FetchRow())
                {
                    $mfield=substr($rt, 1, strlen($rt))."$row[0]";

                    //create an array containing answer code, answer and fieldname(??)
                    $alist[]=array("$row[0]", FlattenText($row[1]), $mfield);
                }

                //check "other" field. is it set?
                if ($qother == "Y")
                {
                    $mfield=substr($rt, 1, strlen($rt))."other";

                    //create an array containing answer code, answer and fieldname(??)
                    $alist[]=array($statlang->gT("Other"), $statlang->gT("Other"), $mfield);
                }
            }


            //S - Short Free Text
            //T - Long Free Text
            elseif ($firstletter == "T" || $firstletter == "S") //Short and long text
            {

                //search for key
                $fld = substr($rt, 1, strlen($rt));
                $fielddata=$fieldmap[$fld];

                //get SGQA IDs
                $qsid=$fielddata['sid'];
                $qgid=$fielddata['gid'];
                $qqid=$fielddata['qid'];


                list($qanswer, $qlid)=!empty($fielddata['aid']) ? explode("_", $fielddata['aid']) : array("", "");
                //get SGQ data
                //list($qsid, $qgid, $qqid) = explode("X", substr($rt, 1, strlen($rt)), 3);


                //get question data
                $nquery = "SELECT title, type, question, other, parent_qid FROM ".db_table_name("questions")." WHERE parent_qid=0 AND qid='$qqid' AND language='{$language}'";
                $nresult = db_execute_num($nquery) or safe_die("Couldn't get text question<br />$nquery<br />".$connect->ErrorMsg());

                //loop through question data
                while ($nrow=$nresult->FetchRow())
                {
                    $qtitle=FlattenText($nrow[0]);
                    $qtype=$nrow[1];
                    $qquestion=FlattenText($nrow[2]);
                    $nlid=$nrow[4];
                }

                $mfield=substr($rt, 1, strlen($rt));

                //Text questions either have an answer, or they don't. There's no other way of quantising the results.
                // So, instead of building an array of predefined answers like we do with lists & other types,
                // we instead create two "types" of possible answer - either there is a response.. or there isn't.
                // This question type then can provide a % of the question answered in the summary.
                $alist[]=array("Answers", $statlang->gT("Answer"), $mfield);
                $alist[]=array("NoAnswer", $statlang->gT("No answer"), $mfield);
            }


            //Multiple short text
            elseif ($firstletter == "Q")
            {
                //get SGQ data
                list($qsid, $qgid, $qqid) = explode("X", substr($rt, 1, strlen($rt)), 3);

                //separating another ID
                $tmpqid=substr($qqid, 0, strlen($qqid)-1);

                //check if we have legid QIDs. if not create them by substringing
                while (!in_array ($tmpqid,$legitqids)) $tmpqid=substr($tmpqid, 0, strlen($tmpqid)-1);

                //length of QID
                $qidlength=strlen($tmpqid);

                //we somehow get the answer code (see SQL later) from the $qqid
                $qaid=substr($qqid, $qidlength, strlen($qqid)-$qidlength);

                //get some question data
                $nquery = "SELECT title, type, question, other FROM ".db_table_name("questions")." WHERE qid='".substr($qqid, 0, $qidlength)."' AND parent_qid=0 AND language='{$language}'";
                $nresult = db_execute_num($nquery) or safe_die("Couldn't get text question<br />$nquery<br />".$connect->ErrorMsg());

                //more substrings
                $count = substr($qqid, strlen($qqid)-1);

                //loop through question data
                while ($nrow=$nresult->FetchRow())
                {
                    $qtitle=FlattenText($nrow[0]).'-'.$count;
                    $qtype=$nrow[1];
                    $qquestion=FlattenText($nrow[2]);
                }

                //get answers
                $qquery = "SELECT title as code, question as answer FROM ".db_table_name("questions")." WHERE parent_qid='".substr($qqid, 0, $qidlength)."' AND title='$qaid' AND language='{$language}' ORDER BY question_order";
                $qresult=db_execute_num($qquery) or safe_die ("Couldn't get answer details (Array 5p Q)<br />$qquery<br />".$connect->ErrorMsg());

                //loop through answer data
                while ($qrow=$qresult->FetchRow())
                {
                    //store each answer here
                    $atext=FlattenText($qrow[1]);
                }

                //add this to the question title
                $qtitle .= " [$atext]";

                //even more substrings...
                $mfield=substr($rt, 1, strlen($rt));

                //Text questions either have an answer, or they don't. There's no other way of quantising the results.
                // So, instead of building an array of predefined answers like we do with lists & other types,
                // we instead create two "types" of possible answer - either there is a response.. or there isn't.
                // This question type then can provide a % of the question answered in the summary.
                $alist[]=array("Answers", $statlang->gT("Answer"), $mfield);
                $alist[]=array("NoAnswer", $statlang->gT("No answer"), $mfield);
            }


            //RANKING OPTION THEREFORE CONFUSING
            elseif ($firstletter == "R")
            {
                //getting the needed IDs somehow
                $lengthofnumeral=substr($rt, strpos($rt, "-")+1, 1);
                list($qsid, $qgid, $qqid) = explode("X", substr($rt, 1, strpos($rt, "-")-($lengthofnumeral+1)), 3);

                //get question data
                $nquery = "SELECT title, type, question FROM ".db_table_name("questions")." WHERE parent_qid=0 AND qid='$qqid' AND language='{$language}'";
                $nresult = db_execute_num($nquery) or safe_die ("Couldn't get question<br />$nquery<br />".$connect->ErrorMsg());

                //loop through question data
                while ($nrow=$nresult->FetchRow())
                {
                    $qtitle=FlattenText($nrow[0]). " [".substr($rt, strpos($rt, "-")-($lengthofnumeral), $lengthofnumeral)."]";
                    $qtype=$nrow[1];
                    $qquestion=FlattenText($nrow[2]). "[".$statlang->gT("Ranking")." ".substr($rt, strpos($rt, "-")-($lengthofnumeral), $lengthofnumeral)."]";
                }

                //get answers
                $query="SELECT code, answer FROM ".db_table_name("answers")." WHERE qid='$qqid' AND scale_id=0 AND language='{$language}' ORDER BY sortorder, answer";
                $result=db_execute_num($query) or safe_die("Couldn't get list of answers for multitype<br />$query<br />".$connect->ErrorMsg());

                //loop through answers
                while ($row=$result->FetchRow())
                {
                    //create an array containing answer code, answer and fieldname(??)
                    $mfield=substr($rt, 1, strpos($rt, "-")-1);
                    $alist[]=array("$row[0]", FlattenText($row[1]), $mfield);
                }
            }

            else if ($firstletter == "|") // File UPload
            {

                //get SGQ data
                list($qsid, $qgid, $qqid) = explode("X", substr($rt, 1, strlen($rt)), 3);

                //select details for this question
                $nquery = "SELECT title, type, question, parent_qid, other FROM ".db_table_name("questions")." WHERE language='{$language}' AND parent_qid=0 AND qid='$qqid'";
                $nresult = db_execute_num($nquery) or safe_die ("Couldn't get question<br />$nquery<br />".$connect->ErrorMsg());

                //loop through question data
                while ($nrow=$nresult->FetchRow())
                {
                    $qtitle=$nrow[0];
                    $qtype=$nrow[1];
                    $qquestion=FlattenText($nrow[2]);
                    $qlid=$nrow[3];
                    $qother=$nrow[4];
                }

                 /*
                    4)      Average size of file per respondent
                    5)      Average no. of files
                    5)      Summary/count of file types (ie: 37 jpg, 65 gif, 12 png)
                    6)      Total size of all files (useful if you're about to download them all)
                    7)      You could also add things like smallest file size, largest file size, median file size
                    8)      no. of files corresponding to each extension
                    9)      max file size
                    10)     min file size
                 */

                // 1) Total number of files uploaded
                // 2)      Number of respondents who uploaded at least one file (with the inverse being the number of respondents who didn’t upload any)
                $fieldname=substr($rt, 1, strlen($rt));
                $query = "SELECT SUM(".db_quote_id($fieldname.'_filecount').") as sum, AVG(".db_quote_id($fieldname.'_filecount').") as avg FROM ".db_table_name("survey_$surveyid");
                $result=db_execute_assoc($query) or safe_die("Couldn't fetch the records<br />$query<br />".$connect->ErrorMsg());

                $showem = array();

                while ($row = $result->FetchRow())
                {
                    $showem[]=array($statlang->gT("Total number of files"), $row['sum']);
                    $showem[]=array($statlang->gT("Average no. of files per respondent"), $row['avg']);
                }


                $query = "SELECT ". $fieldname ." as json FROM ".db_table_name("survey_$surveyid");
                $result=db_execute_assoc($query) or safe_die("Couldn't fetch the records<br />$query<br />".$connect->ErrorMsg());

                $responsecount = 0;
                $filecount = 0;
                $size = 0;

                while ($row = $result->FetchRow())
                {

                    $json = $row['json'];
                    $phparray = json_decode($json);

                    foreach ($phparray as $metadata)
                    {
                        $size += (int) $metadata->size;
                        $filecount++;
                    }
                    $responsecount++;
                }
                $showem[] = array($statlang->gT("Total size of files"), $size." KB");
                $showem[] = array($statlang->gT("Average file size"), $size/$filecount . " KB");
                $showem[] = array($statlang->gT("Average size per respondent"), $size/$responsecount . " KB");

/*              $query="SELECT title, question FROM ".db_table_name("questions")." WHERE parent_qid='$qqid' AND language='{$language}' ORDER BY question_order";
                $result=db_execute_num($query) or safe_die("Couldn't get list of subquestions for multitype<br />$query<br />".$connect->ErrorMsg());

                //loop through multiple answers
                while ($row=$result->FetchRow())
                {
                    $mfield=substr($rt, 1, strlen($rt))."$row[0]";

                    //create an array containing answer code, answer and fieldname(??)
                    $alist[]=array("$row[0]", FlattenText($row[1]), $mfield);
                }

*/
                //outputting
                switch($outputType)
                {
                    case 'xls':

                        $headXLS = array();
                        $tableXLS = array();
                        $footXLS = array();

                        $xlsTitle = sprintf($statlang->gT("Field summary for %s"),html_entity_decode($qtitle,ENT_QUOTES,'UTF-8'));
                        $xlsDesc = html_entity_decode($qquestion,ENT_QUOTES,'UTF-8');
                        ++$xlsRow;
                        ++$xlsRow;

                        ++$xlsRow;
                        $sheet->setCellValueByColumnAndRow(0,$xlsRow,$xlsTitle);
                        ++$xlsRow;
                        $sheet->setCellValueByColumnAndRow(0,$xlsRow,$xlsDesc);

                        $headXLS[] = array($statlang->gT("Calculation"),$statlang->gT("Result"));
                        ++$xlsRow;
                        $sheet->setCellValueByColumnAndRow(0, $xlsRow,$statlang->gT("Calculation"));
                        $sheet->setCellValueByColumnAndRow(1, $xlsRow,$statlang->gT("Result"));

                        break;
                    case 'pdf':

                        $headPDF = array();
                        $tablePDF = array();
                        $footPDF = array();

                        $pdfTitle = sprintf($statlang->gT("Field summary for %s"),html_entity_decode($qtitle,ENT_QUOTES,'UTF-8'));
                        $titleDesc = html_entity_decode($qquestion,ENT_QUOTES,'UTF-8');

                        $headPDF[] = array($statlang->gT("Calculation"),$statlang->gT("Result"));

                        break;

                    case 'html':

                        $statisticsoutput .= "\n<table class='statisticstable' >\n"
                        ."\t<thead><tr><th colspan='2' align='center'><strong>".sprintf($statlang->gT("Field summary for %s"),$qtitle).":</strong>"
                        ."</th></tr>\n"
                        ."\t<tr><th colspan='2' align='center'><strong>$qquestion</strong></th></tr>\n"
                        ."\t<tr>\n\t\t<th width='50%' align='center' ><strong>"
                        .$statlang->gT("Calculation")."</strong></th>\n"
                        ."\t\t<th width='50%' align='center' ><strong>"
                        .$statlang->gT("Result")."</strong></th>\n"
                        ."\t</tr></thead>\n";

                        foreach ($showem as $res)
                            $statisticsoutput .= "<tr><td>".$res[0]."</td><td>".$res[1]."</td></tr>";
                        break;

                    default:
                        break;
                }
            }

            //N = numerical input
            //K = multiple numerical input
            elseif ($firstletter == "N" || $firstletter == "K") //NUMERICAL TYPE
            {
                //Zero handling
                if (!isset($excludezeros)) //If this hasn't been set, set it to on as default:
                {
                    $excludezeros=1;
                }
                //check last character, greater/less/equals don't need special treatment
                if (substr($rt, -1) == "G" ||  substr($rt, -1) == "L" || substr($rt, -1) == "=")
                {
                    //DO NOTHING
                }
                else
                {
                    //create SGQ identifier
                    list($qsid, $qgid, $qqid) = explode("X", $rt, 3);

                    //multiple numerical input
                    if($firstletter == "K")
                    {
                        // This is a multiple numerical question so we need to strip of the answer id to find the question title
                        $tmpqid=substr($qqid, 0, strlen($qqid)-1);

                        //did we get a valid ID?
                        while (!in_array ($tmpqid,$legitqids))
                        $tmpqid=substr($tmpqid, 0, strlen($tmpqid)-1);

                        //check lenght of ID
                        $qidlength=strlen($tmpqid);

                        //get answer ID from qid
                        $qaid=substr($qqid, $qidlength, strlen($qqid)-$qidlength);

                        //get question details from DB
                        $nquery = "SELECT title, type, question, qid, parent_qid
								   FROM ".db_table_name("questions")."
								   WHERE parent_qid=0 AND qid='".substr($qqid, 0, $qidlength)."'
								   AND language='{$language}'";
                        $nresult = db_execute_num($nquery) or safe_die("Couldn't get text question<br />$nquery<br />".$connect->ErrorMsg());
                    }

                    //probably question type "N" = numerical input
                    else
                    {
                        //we can use the qqid without any editing
                        $nquery = "SELECT title, type, question, qid, parent_qid FROM ".db_table_name("questions")." WHERE parent_qid=0 AND qid='$qqid' AND language='{$language}'";
                        $nresult = db_execute_num($nquery) or safe_die ("Couldn't get question<br />$nquery<br />".$connect->ErrorMsg());
                    }

                    //loop through results
                    while ($nrow=$nresult->FetchRow())
                    {
                        $qtitle=FlattenText($nrow[0]); //clean up title
                        $qtype=$nrow[1];
                        $qquestion=FlattenText($nrow[2]);
                        $qiqid=$nrow[3];
                        $qlid=$nrow[4];
                    }

                    //Get answer texts for multiple numerical
                    if(substr($rt, 0, 1) == "K")
                    {
                        //get answer data
                        $atext=$connect->GetOne("SELECT question FROM ".db_table_name("questions")." WHERE parent_qid='{$qiqid}' AND scale_id=0 AND title='{$qaid}' AND language='{$language}'");
                        //put single items in brackets at output
                        $qtitle .= " [$atext]";
                    }

                    //outputting
                    switch($outputType)
                    {
                        case 'xls':

                            $headXLS = array();
                            $tableXLS = array();
                            $footXLS = array();

                            $xlsTitle = sprintf($statlang->gT("Field summary for %s"),html_entity_decode($qtitle,ENT_QUOTES,'UTF-8'));
                            $xlsDesc = html_entity_decode($qquestion,ENT_QUOTES,'UTF-8');
                            ++$xlsRow;
                            ++$xlsRow;

                            ++$xlsRow;
                            $sheet->write($xlsRow, 0,$xlsTitle);
                            ++$xlsRow;
                            $sheet->write($xlsRow, 0,$xlsDesc);

                            $headXLS[] = array($statlang->gT("Calculation"),$statlang->gT("Result"));
                            ++$xlsRow;
                            $sheet->write($xlsRow, 0,$statlang->gT("Calculation"));
                            $sheet->write($xlsRow, 1,$statlang->gT("Result"));

                            break;
                        case 'pdf':

                            $headPDF = array();
                            $tablePDF = array();
                            $footPDF = array();

                            $pdfTitle = sprintf($statlang->gT("Field summary for %s"),html_entity_decode($qtitle,ENT_QUOTES,'UTF-8'));
                            $titleDesc = html_entity_decode($qquestion,ENT_QUOTES,'UTF-8');

                            $headPDF[] = array($statlang->gT("Calculation"),$statlang->gT("Result"));

                            break;
                        case 'html':

                            $statisticsoutput .= "\n<table class='statisticstable' >\n"
                            ."\t<thead><tr><th colspan='2' align='center'><strong>".sprintf($statlang->gT("Field summary for %s"),$qtitle).":</strong>"
                            ."</th></tr>\n"
                            ."\t<tr><th colspan='2' align='center'><strong>$qquestion</strong></th></tr>\n"
                            ."\t<tr>\n\t\t<th width='50%' align='center' ><strong>"
                            .$statlang->gT("Calculation")."</strong></th>\n"
                            ."\t\t<th width='50%' align='center' ><strong>"
                            .$statlang->gT("Result")."</strong></th>\n"
                            ."\t</tr></thead>\n";

                            break;
                        default:


                            break;
                    }

                    //this field is queried using mathematical functions
                    $fieldname=substr($rt, 1, strlen($rt));

                    //special treatment for MS SQL databases
					if ($connect->databaseType == 'odbc_mssql' || $connect->databaseType == 'odbtp' || $connect->databaseType == 'mssql_n' || $connect->databaseType == 'mssqlnative')
                    {
                        //standard deviation
                        $query = "SELECT STDEVP(".db_quote_id($fieldname)."*1) as stdev";
                    }

                    //other databases (MySQL, Postgres)
                    else
                    {
                        //standard deviation
                        $query = "SELECT STDDEV(".db_quote_id($fieldname).") as stdev";
                    }

                    //sum
                    $query .= ", SUM(".db_quote_id($fieldname)."*1) as sum";

                    //average
                    $query .= ", AVG(".db_quote_id($fieldname)."*1) as average";

                    //min
                    $query .= ", MIN(".db_quote_id($fieldname)."*1) as minimum";

                    //max
                    $query .= ", MAX(".db_quote_id($fieldname)."*1) as maximum";
                    //Only select responses where there is an actual number response, ignore nulls and empties (if these are included, they are treated as zeroes, and distort the deviation/mean calculations)

                    //special treatment for MS SQL databases
					if ($connect->databaseType == 'odbc_mssql' || $connect->databaseType == 'odbtp' || $connect->databaseType == 'mssql_n' || $connect->databaseType == 'mssqlnative')
                    {
                        //no NULL/empty values please
                        $query .= " FROM ".db_table_name("survey_$surveyid")." WHERE ".db_quote_id($fieldname)." IS NOT NULL";
                        if(!$excludezeros)
                        {
                            //NO ZERO VALUES
                            $query .= " AND (".db_quote_id($fieldname)." <> 0)";
                        }
                    }

                    //other databases (MySQL, Postgres)
                    else
                    {
                        //no NULL/empty values please
                        $query .= " FROM ".db_table_name("survey_$surveyid")." WHERE ".db_quote_id($fieldname)." IS NOT NULL";
                        if(!$excludezeros)
                        {
                            //NO ZERO VALUES
                            $query .= " AND (".db_quote_id($fieldname)." != 0)";
                        }
                    }

                    //filter incomplete answers if set
                    if (incompleteAnsFilterstate() == "inc") {$query .= " AND submitdate is null";}
                    elseif (incompleteAnsFilterstate() == "filter") {$query .= " AND submitdate is not null";}

                    //$sql was set somewhere before
                    if ($sql != "NULL") {$query .= " AND $sql";}

                    //execute query
                    $result=db_execute_assoc($query) or safe_die("Couldn't do maths testing<br />$query<br />".$connect->ErrorMsg());

                    //get calculated data
                    while ($row=$result->FetchRow())
                    {
                        //put translation of mean and calculated data into $showem array
                        $showem[]=array($statlang->gT("Sum"), $row['sum']);
                        $showem[]=array($statlang->gT("Standard deviation"), round($row['stdev'],2));
                        $showem[]=array($statlang->gT("Average"), round($row['average'],2));
                        $showem[]=array($statlang->gT("Minimum"), $row['minimum']);

                        //Display the maximum and minimum figures after the quartiles for neatness
                        $maximum=$row['maximum'];
                        $minimum=$row['minimum'];
                    }



                    //CALCULATE QUARTILES

                    //get data
                    $query ="SELECT ".db_quote_id($fieldname)." FROM ".db_table_name("survey_$surveyid")." WHERE ".db_quote_id($fieldname)." IS NOT null";
                    //NO ZEROES
                    if(!$excludezeros)
                    {
                        $query .= " AND ".db_quote_id($fieldname)." != 0";
                    }

                    //filtering enabled?
                    if (incompleteAnsFilterstate() == "inc") {$query .= " AND submitdate is null";}
                    elseif (incompleteAnsFilterstate() == "filter") {$query .= " AND submitdate is not null";}

                    //if $sql values have been passed to the statistics script from another script, incorporate them
                    if ($sql != "NULL") {$query .= " AND $sql";}

                    //execute query
                    $result=$connect->Execute($query) or safe_die("Disaster during median calculation<br />$query<br />".$connect->ErrorMsg());

                    $querystarter="SELECT ".db_quote_id($fieldname)." FROM ".db_table_name("survey_$surveyid")." WHERE ".db_quote_id($fieldname)." IS NOT null";
                    //No Zeroes
                    if(!$excludezeros)
                    {
                        $querystart .= " AND ".db_quote_id($fieldname)." != 0";
                    }
                    //filtering enabled?
                    if (incompleteAnsFilterstate() == "inc") {$querystarter .= " AND submitdate is null";}
                    elseif (incompleteAnsFilterstate() == "filter") {$querystarter .= " AND submitdate is not null";}

                    //if $sql values have been passed to the statistics script from another script, incorporate them
                    if ($sql != "NULL") {$querystarter .= " AND $sql";}

                    //we just count the number of records returned
                    $medcount=$result->RecordCount();

                    //put the total number of records at the beginning of this array
                    array_unshift($showem, array($statlang->gT("Count"), $medcount));


                    //no more comment from Mazi regarding the calculation

                    // Calculating only makes sense with more than one result
                    if ($medcount>1)
                    {
                        //1ST QUARTILE (Q1)
                        $q1=(1/4)*($medcount+1);
                        $q1b=(int)((1/4)*($medcount+1));
                        $q1c=$q1b-1;
                        $q1diff=$q1-$q1b;
                        $total=0;

                        // fix if there are too few values to evaluate.
                        if ($q1c<0) {$q1c=0;}

                        if ($q1 != $q1b)
                        {
                            //ODD NUMBER
                            $query = $querystarter . " ORDER BY ".db_quote_id($fieldname)."*1 ";
                            $result=db_select_limit_assoc($query, 2, $q1c) or safe_die("1st Quartile query failed<br />".$connect->ErrorMsg());

                            while ($row=$result->FetchRow())
                            {
                                if ($total == 0)    {$total=$total-$row[$fieldname];}

                                else                {$total=$total+$row[$fieldname];}

                                $lastnumber=$row[$fieldname];
                            }

                            $q1total=$lastnumber-((1-$q1diff)*$total);

                            if ($q1total < $minimum) {$q1total=$minimum;}

                            $showem[]=array($statlang->gT("1st quartile (Q1)"), $q1total);
                        }
                        else
                        {
                            //EVEN NUMBER
                            $query = $querystarter . " ORDER BY ".db_quote_id($fieldname)."*1 ";
                            $result=db_select_limit_assoc($query,1, $q1c) or safe_die ("1st Quartile query failed<br />".$connect->ErrorMsg());

                            while ($row=$result->FetchRow())
                            {
                                $showem[]=array($statlang->gT("1st quartile (Q1)"), $row[$fieldname]);
                            }
                        }

                        $total=0;


                        //MEDIAN (Q2)
                        $median=(1/2)*($medcount+1);
                        $medianb=(int)((1/2)*($medcount+1));
                        $medianc=$medianb-1;
                        $mediandiff=$median-$medianb;

                        if ($median != $medianb)
                        {
                            //remainder
                            $query = $querystarter . " ORDER BY ".db_quote_id($fieldname)."*1 ";
                            $result=db_select_limit_assoc($query,2, $medianc) or safe_die("What a complete mess with the remainder<br />$query<br />".$connect->ErrorMsg());

                            while
                            (
                            $row=$result->FetchRow()) {$total=$total+$row[$fieldname];
                            }

                            $showem[]=array($statlang->gT("2nd quartile (Median)"), $total/2);
                        }

                        else
                        {
                            //EVEN NUMBER
                            $query = $querystarter . " ORDER BY ".db_quote_id($fieldname)."*1 ";
                            $result=db_select_limit_assoc($query,1, $medianc-1) or safe_die("What a complete mess<br />$query<br />".$connect->ErrorMsg());

                            while ($row=$result->FetchRow())
                            {
                                $showem[]=array($statlang->gT("Median value"), $row[$fieldname]);
                            }
                        }

                        $total=0;


                        //3RD QUARTILE (Q3)
                        $q3=(3/4)*($medcount+1);
                        $q3b=(int)((3/4)*($medcount+1));
                        $q3c=$q3b-1;
                        $q3diff=$q3-$q3b;

                        if ($q3 != $q3b)
                        {
                            $query = $querystarter . " ORDER BY ".db_quote_id($fieldname)."*1 ";
                            $result = db_select_limit_assoc($query,2,$q3c) or safe_die("3rd Quartile query failed<br />".$connect->ErrorMsg());

                            while ($row=$result->FetchRow())
                            {
                                if ($total == 0)    {$total=$total-$row[$fieldname];}

                                else                {$total=$total+$row[$fieldname];}

                                $lastnumber=$row[$fieldname];
                            }
                            $q3total=$lastnumber-((1-$q3diff)*$total);

                            if ($q3total < $maximum) {$q1total=$maximum;}

                            $showem[]=array($statlang->gT("3rd quartile (Q3)"), $q3total);
                        }

                        else
                        {
                            $query = $querystarter . " ORDER BY ".db_quote_id($fieldname)."*1";
                            $result = db_select_limit_assoc($query,1, $q3c) or safe_die("3rd Quartile even query failed<br />".$connect->ErrorMsg());

                            while ($row=$result->FetchRow())
                            {
                                $showem[]=array($statlang->gT("3rd quartile (Q3)"), $row[$fieldname]);
                            }
                        }

                        $total=0;

                        $showem[]=array($statlang->gT("Maximum"), $maximum);

                        //output results
                        foreach ($showem as $shw)
                        {
                            switch($outputType)
                            {
                                case 'xls':

                                    ++$xlsRow;
                                    $sheet->write($xlsRow, 0,html_entity_decode($shw[0],ENT_QUOTES,'UTF-8'));
                                    $sheet->write($xlsRow, 1,html_entity_decode($shw[1],ENT_QUOTES,'UTF-8'));


                                    $tableXLS[] = array($shw[0],$shw[1]);

                                    break;
                                case 'pdf':

                                    $tablePDF[] = array(html_entity_decode($shw[0],ENT_QUOTES,'UTF-8'),html_entity_decode($shw[1],ENT_QUOTES,'UTF-8'));

                                    break;
                                case 'html':

                                    $statisticsoutput .= "\t<tr>\n"
                                    ."\t\t<td align='center' >$shw[0]</td>\n"
                                    ."\t\t<td align='center' >$shw[1]</td>\n"
                                    ."\t</tr>\n";

                                    break;
                                default:


                                    break;
                            }
                        }
                        switch($outputType)
                        {
                            case 'xls':

                                ++$xlsRow;
                                $sheet->write($xlsRow, 0,$statlang->gT("Null values are ignored in calculations"));
                                ++$xlsRow;
                                $sheet->write($xlsRow, 0,sprintf($statlang->gT("Q1 and Q3 calculated using %s"), $statlang->gT("minitab method")));

                                $footXLS[] = array($statlang->gT("Null values are ignored in calculations"));
                                $footXLS[] = array(sprintf($statlang->gT("Q1 and Q3 calculated using %s"), $statlang->gT("minitab method")));

                                break;
                            case 'pdf':

                                $footPDF[] = array($statlang->gT("Null values are ignored in calculations"));
                                $footPDF[] = array(sprintf($statlang->gT("Q1 and Q3 calculated using %s"), "<a href='http://mathforum.org/library/drmath/view/60969.html' target='_blank'>".$statlang->gT("minitab method")."</a>"));
                                $pdf->addPage('P','A4');
                                $pdf->Bookmark($pdf->delete_html($qquestion), 1, 0);
                                $pdf->titleintopdf($pdfTitle,$titleDesc);

                                $pdf->headTable($headPDF, $tablePDF);

                                $pdf->tablehead($footPDF);

                                break;
                            case 'html':

                                //footer of question type "N"
                                $statisticsoutput .= "\t<tr>\n"
                                ."\t\t<td colspan='4' align='center' bgcolor='#EEEEEE'>\n"
                                ."\t\t\t<font size='1'>".$statlang->gT("Null values are ignored in calculations")."<br />\n"
                                ."\t\t\t".sprintf($statlang->gT("Q1 and Q3 calculated using %s"), "<a href='http://mathforum.org/library/drmath/view/60969.html' target='_blank'>".$statlang->gT("minitab method")."</a>")
                                ."</font>\n"
                                ."\t\t</td>\n"
                                ."\t</tr>\n</table>\n";

                                break;
                            default:


                                break;
                        }

                        //clean up
                        unset($showem);

                    }	//end if (enough results?)

                    //not enough (<1) results for calculation
                    else
                    {
                        switch($outputType)
                        {
                            case 'xls':

                                $tableXLS = array();
                                $tableXLS[] = array($statlang->gT("Not enough values for calculation"));

                                ++$xlsRow;
                                $sheet->write($xlsRow, 0, $statlang->gT("Not enough values for calculation"));



                                break;
                            case 'pdf':

                                $tablePDF = array();
                                $tablePDF[] = array($statlang->gT("Not enough values for calculation"));
                                $pdf->addPage('P','A4');
                                $pdf->Bookmark($pdf->delete_html($qquestion), 1, 0);
                                $pdf->titleintopdf($pdfTitle,$titleDesc);

                                $pdf->equalTable($tablePDF);

                                break;
                            case 'html':

                                //output
                                $statisticsoutput .= "\t<tr>\n"
                                ."\t\t<td align='center'  colspan='4'>".$statlang->gT("Not enough values for calculation")."</td>\n"
                                ."\t</tr>\n</table><br />\n";

                                break;
                            default:


                                break;
                        }

                        unset($showem);

                    }

                }	//end else -> check last character, greater/less/equals don't need special treatment

            }	//end else-if -> multiple numerical types

            //is there some "id", "datestamp" or "D" within the type?
            elseif (substr($rt, 0, 2) == "id" || substr($rt, 0, 9) == "datestamp" || ($firstletter == "D"))
            {
                /*
                 * DON'T show anything for date questions
                 * because there aren't any statistics implemented yet!
                 *
                 * See bug report #2539 and
                 * feature request #2620
                 */
            }


            // NICE SIMPLE SINGLE OPTION ANSWERS
            else
            {
                //search for key
                $fielddata=$fieldmap[$rt];
                //print_r($fielddata);
                //get SGQA IDs
                $qsid=$fielddata['sid'];
                $qgid=$fielddata['gid'];
                $qqid=$fielddata['qid'];
                $qanswer=$fielddata['aid'];

                //question type
                $qtype=$fielddata['type'];

                //question string
                $qastring=$fielddata['question'];

                //question ID
                $rqid=$qqid;

                //get question data
                $nquery = "SELECT title, type, question, qid, parent_qid, other FROM ".db_table_name("questions")." WHERE qid='{$rqid}' AND parent_qid=0 and language='{$language}'";
                $nresult = db_execute_num($nquery) or safe_die ("Couldn't get question<br />$nquery<br />".$connect->ErrorMsg());

                //loop though question data
                while ($nrow=$nresult->FetchRow())
                {
                    $qtitle=FlattenText($nrow[0]);
                    $qtype=$nrow[1];
                    $qquestion=FlattenText($nrow[2]);
                    $qiqid=$nrow[3];
                    $qparentqid=$nrow[4];
                    $qother=$nrow[5];
                }

                //check question types
                switch($qtype)
                {
                    //Array of 5 point choices (several items to rank!)
                    case "A":

                        //get data
                        $qquery = "SELECT title, question FROM ".db_table_name("questions")." WHERE parent_qid='$qiqid' AND title='$qanswer' AND language='{$language}' ORDER BY question_order";
                        $qresult=db_execute_num($qquery) or safe_die ("Couldn't get answer details (Array 5p Q)<br />$qquery<br />".$connect->ErrorMsg());

                        //loop through results
                        while ($qrow=$qresult->FetchRow())
                        {
                            //5-point array
                            for ($i=1; $i<=5; $i++)
                            {
                                //add data
                                $alist[]=array("$i", "$i");
                            }
                            //add counter
                            $atext=FlattenText($qrow[1]);
                        }

                        //list IDs and answer codes in brackets
                        $qquestion .= $linefeed."[".$atext."]";
                        $qtitle .= "($qanswer)";
                        break;



                        //Array of 10 point choices
                        //same as above just with 10 items
                    case "B":
                        $qquery = "SELECT title, question FROM ".db_table_name("questions")." WHERE parent_qid='$qiqid' AND title='$qanswer' AND language='{$language}' ORDER BY question_order";
                        $qresult=db_execute_num($qquery) or safe_die ("Couldn't get answer details (Array 10p Q)<br />$qquery<br />".$connect->ErrorMsg());
                        while ($qrow=$qresult->FetchRow())
                        {
                            for ($i=1; $i<=10; $i++)
                            {
                                $alist[]=array("$i", "$i");
                            }
                            $atext=FlattenText($qrow[1]);
                        }

                        $qquestion .= $linefeed."[".$atext."]";
                        $qtitle .= "($qanswer)";
                        break;



                        //Array of Yes/No/$statlang->gT("Uncertain")
                    case "C":
                        $qquery = "SELECT title, question FROM ".db_table_name("questions")." WHERE parent_qid='$qiqid' AND title='$qanswer' AND language='{$language}' ORDER BY question_order";
                        $qresult=db_execute_num($qquery) or safe_die ("Couldn't get answer details<br />$qquery<br />".$connect->ErrorMsg());

                        //loop thorugh results
                        while ($qrow=$qresult->FetchRow())
                        {
                            //add results
                            $alist[]=array("Y", $statlang->gT("Yes"));
                            $alist[]=array("N", $statlang->gT("No"));
                            $alist[]=array("U", $statlang->gT("Uncertain"));
                            $atext=FlattenText($qrow[1]);
                        }
                        //output
                        $qquestion .= $linefeed."[".$atext."]";
                        $qtitle .= "($qanswer)";
                        break;



                        //Array of Yes/No/$statlang->gT("Uncertain")
                        //same as above
                    case "E":
                        $qquery = "SELECT title, question FROM ".db_table_name("questions")." WHERE parent_qid='$qiqid' AND title='$qanswer' AND language='{$language}' ORDER BY question_order";
                        $qresult=db_execute_num($qquery) or safe_die ("Couldn't get answer details<br />$qquery<br />".$connect->ErrorMsg());
                        while ($qrow=$qresult->FetchRow())
                        {
                            $alist[]=array("I", $statlang->gT("Increase"));
                            $alist[]=array("S", $statlang->gT("Same"));
                            $alist[]=array("D", $statlang->gT("Decrease"));
                            $atext=FlattenText($qrow[1]);
                        }
                        $qquestion .= $linefeed."[".$atext."]";
                        $qtitle .= "($qanswer)";
                        break;


                    case ";": //Array (Multi Flexi) (Text)
                        list($qacode, $licode)=explode("_", $qanswer);

                        $qquery = "SELECT title, question FROM ".db_table_name("questions")." WHERE parent_qid='$qiqid' AND title='$qacode' AND language='{$language}' ORDER BY question_order";
                        $qresult=db_execute_num($qquery) or die ("Couldn't get answer details<br />$qquery<br />".$connect->ErrorMsg());

                        while ($qrow=$qresult->FetchRow())
                        {
                            $fquery = "SELECT * FROM ".db_table_name("answers")." WHERE qid='{$qiqid}' AND scale_id=0 AND code = '{$licode}' AND language='{$language}'ORDER BY sortorder, code";
                            $fresult = db_execute_assoc($fquery);
                            while ($frow=$fresult->FetchRow())
                            {
                                $alist[]=array($frow['code'], $frow['answer']);
                                $ltext=$frow['answer'];
                            }
                            $atext=FlattenText($qrow[1]);
                        }

                        $qquestion .= $linefeed."[".$atext."] [".$ltext."]";
                        $qtitle .= "($qanswer)";
                        break;


                    case ":": //Array (Multiple Flexi) (Numbers)
                        $qidattributes=getQuestionAttributes($qiqid);
                        if (trim($qidattributes['multiflexible_max'])!='') {
                            $maxvalue=$qidattributes['multiflexible_max'];
                        }
                        else {
                            $maxvalue=10;
                        }

                        if (trim($qidattributes['multiflexible_min'])!='')
                        {
                            $minvalue=$qidattributes['multiflexible_min'];
                        }
                        else {
                            $minvalue=1;
                        }

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

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

                        for($i=$minvalue; $i<=$maxvalue; $i+=$stepvalue)
                        {
                            $alist[]=array($i, $i);
                        }

                        $qquestion .= $linefeed."[".$fielddata['subquestion1']."] [".$fielddata['subquestion2']."]";
                        list($myans, $mylabel)=explode("_", $qanswer);
                        $qtitle .= "[$myans][$mylabel]";
                        break;

                    case "F": //Array of Flexible
                    case "H": //Array of Flexible by Column
                        $qquery = "SELECT title, question FROM ".db_table_name("questions")." WHERE parent_qid='$qiqid' AND title='$qanswer' AND language='{$language}' ORDER BY question_order";
                        $qresult=db_execute_num($qquery) or safe_die ("Couldn't get answer details<br />$qquery<br />".$connect->ErrorMsg());

                        //loop through answers
                        while ($qrow=$qresult->FetchRow())
                        {
                            //this question type uses its own labels
                            $fquery = "SELECT * FROM ".db_table_name("answers")." WHERE qid='{$qiqid}' AND scale_id=0 AND language='{$language}'ORDER BY sortorder, code";
                            $fresult = db_execute_assoc($fquery);

                            //add code and title to results for outputting them later
                            while ($frow=$fresult->FetchRow())
                            {
                                $alist[]=array($frow['code'], FlattenText($frow['answer']));
                            }

                            //counter
                            $atext=FlattenText($qrow[1]);
                        }

                        //output
                        $qquestion .= $linefeed."[".$atext."]";
                        $qtitle .= "($qanswer)";
                        break;



                    case "G": //Gender
                        $alist[]=array("F", $statlang->gT("Female"));
                        $alist[]=array("M", $statlang->gT("Male"));
                        break;



                    case "Y": //Yes\No
                        $alist[]=array("Y", $statlang->gT("Yes"));
                        $alist[]=array("N", $statlang->gT("No"));
                        break;



                    case "I": //Language
                        // Using previously defined $surveylanguagecodes array of language codes
                        foreach ($surveylanguagecodes as $availlang)
                        {
                            $alist[]=array($availlang, getLanguageNameFromCode($availlang,false));
                        }
                        break;


                    case "5": //5 Point (just 1 item to rank!)
                        for ($i=1; $i<=5; $i++)
                        {
                            $alist[]=array("$i", "$i");
                        }
                        break;


                    case "1":	//array (dual scale)

                        $sSubquestionQuery = "SELECT  question FROM ".db_table_name("questions")." WHERE parent_qid='$qiqid' AND title='$qanswer' AND language='{$language}' ORDER BY question_order";
                        $sSubquestion=FlattenText($connect->GetOne($sSubquestionQuery));

                        //get question attributes
                        $qidattributes=getQuestionAttributes($qqid);

                        //check last character -> label 1
                        if (substr($rt,-1,1) == 0)
                        {
                            //get label 1
                            $fquery = "SELECT * FROM ".db_table_name("answers")." WHERE qid='{$qqid}' AND scale_id=0 AND language='{$language}' ORDER BY sortorder, code";

                            //header available?
                            if (trim($qidattributes['dualscale_headerA'])!='') {
                                //output
                                $labelheader= "[".$qidattributes['dualscale_headerA']."]";
                            }

                            //no header
                            else
                            {
                                $labelheader ='';
                            }

                            //output
                            $labelno = sprintf($clang->gT('Label %s'),'1');
                        }

                        //label 2
                        else
                        {
                            //get label 2
                            $fquery = "SELECT * FROM ".db_table_name("answers")." WHERE qid='{$qqid}' AND scale_id=1 AND language='{$language}' ORDER BY sortorder, code";

                            //header available?
                            if (trim($qidattributes['dualscale_headerB'])!='') {
                                //output
                                $labelheader= "[".$qidattributes['dualscale_headerB']."]";
                            }

                            //no header
                            else
                            {
                                $labelheader ='';
                            }

                            //output
                            $labelno = sprintf($clang->gT('Label %s'),'2');
                        }

                        //get data
                        $fresult = db_execute_assoc($fquery);

                        //put label code and label title into array
                        while ($frow=$fresult->FetchRow())
                        {
                            $alist[]=array($frow['code'], FlattenText($frow['answer']));
                        }

                        //adapt title and question
                        $qtitle = $qtitle." [".$sSubquestion."][".$labelno."]";
                        $qquestion  = $qastring .$labelheader;
                        break;




                    default:	//default handling

                        //get answer code and title
                        $qquery = "SELECT code, answer FROM ".db_table_name("answers")." WHERE qid='$qqid' AND scale_id=0 AND language='{$language}' ORDER BY sortorder, answer";
                        $qresult = db_execute_num($qquery) or safe_die ("Couldn't get answers list<br />$qquery<br />".$connect->ErrorMsg());

                        //put answer code and title into array
                        while ($qrow=$qresult->FetchRow())
                        {
                            $alist[]=array("$qrow[0]", FlattenText($qrow[1]));
                        }

                        //handling for "other" field for list radio or list drowpdown
                        if ((($qtype == "L" || $qtype == "!") && $qother == "Y"))
                        {
                            //add "other"
                            $alist[]=array($statlang->gT("Other"),$statlang->gT("Other"),$fielddata['fieldname'].'other');
                        }
                    	if ( $qtype == "O")
                     	{
                    		//add "comment"
                    		$alist[]=array($statlang->gT("Comments"),$statlang->gT("Comments"),$fielddata['fieldname'].'comment');
                    	}

                }	//end switch question type

                //moved because it's better to have "no answer" at the end of the list instead of the beginning
                //put data into array
                $alist[]=array("", $statlang->gT("No answer"));

            }	//end else -> single option answers

            //foreach ($alist as $al) {$statisticsoutput .= "$al[0] - $al[1]<br />";} //debugging line
            //foreach ($fvalues as $fv) {$statisticsoutput .= "$fv | ";} //debugging line





            //2. Collect and Display results #######################################################################
            if (isset($alist) && $alist) //Make sure there really is an answerlist, and if so:
            {


                // this will count the answers considered completed
                $TotalCompleted = 0;
                switch($outputType)
                {
                    case 'xls':

                        $xlsTitle = sprintf($statlang->gT("Field summary for %s"),html_entity_decode($qtitle,ENT_QUOTES,'UTF-8'));
                        $xlsDesc = html_entity_decode($qquestion,ENT_QUOTES,'UTF-8');

                        ++$xlsRow;
                        ++$xlsRow;

                        ++$xlsRow;
                        $sheet->write($xlsRow, 0,$xlsTitle);
                        ++$xlsRow;
                        $sheet->write($xlsRow, 0,$xlsDesc);

                        $tableXLS = array();
                        $footXLS = array();

                        break;
                    case 'pdf':

                        $sPDFQuestion=FlattenText($qquestion,true);
                        $pdfTitle = $pdf->delete_html(sprintf($statlang->gT("Field summary for %s"),html_entity_decode($qtitle,ENT_QUOTES,'UTF-8')));
                        $titleDesc = $sPDFQuestion;

                        $pdf->addPage('P','A4');
                        $pdf->Bookmark($sPDFQuestion, 1, 0);
                        $pdf->titleintopdf($pdfTitle,$sPDFQuestion);
                        $tablePDF = array();
                        $footPDF = array();

                        break;
                    case 'html':
                        //output
                        $statisticsoutput .= "<table class='statisticstable'>\n"
                        ."\t<thead><tr><th colspan='4' align='center'><strong>"

                        //headline
                        .sprintf($statlang->gT("Field summary for %s"),$qtitle)."</strong>"
                        ."</th></tr>\n"
                        ."\t<tr><th colspan='4' align='center'><strong>"

                        //question title
                        .$qquestion."</strong></th></tr>\n"
                        ."\t<tr>\n\t\t<th width='50%' align='center' >";
                        break;
                    default:


                        break;
                }
                echo '';
                //loop thorugh the array which contains all answer data
                foreach ($alist as $al)
                {
                    //picks out alist that come from the multiple list above
                    if (isset($al[2]) && $al[2])
                    {
                        //handling for "other" option

                        if ($al[0] == $statlang->gT("Other"))
                        {
                            if($qtype=='!' || $qtype=='L')
                            {
                                // It is better for single choice question types to filter on the number of '-oth-' entries, than to
                                // just count the number of 'other' values - that way with failing Javascript the statistics don't get messed up
                                $query = "SELECT count(*) FROM ".db_table_name("survey_$surveyid")." WHERE ".db_quote_id(substr($al[2],0,strlen($al[2])-5))."='-oth-'";
                            }
                            else
                            {
	                            //get data
	                            $query = "SELECT count(*) FROM ".db_table_name("survey_$surveyid")." WHERE ";
	                            $query .= ($connect->databaseType == "mysql")?  db_quote_id($al[2])." != ''" : "NOT (".db_quote_id($al[2])." LIKE '')";
                        	}
                        }

                        /*
                         * text questions:
                         *
                         * U = huge free text
                         * T = long free text
                         * S = short free text
                         * Q = multiple short text
                         */

                        elseif ($qtype == "U" || $qtype == "T" || $qtype == "S" || $qtype == "Q" || $qtype == ";")
                        {
                            //free text answers
                            if($al[0]=="Answers")
                            {
                                $query = "SELECT count(*) FROM ".db_table_name("survey_$surveyid")." WHERE ";
                                $query .= ($connect->databaseType == "mysql")?  db_quote_id($al[2])." != ''" : "NOT (".db_quote_id($al[2])." LIKE '')";
                            }
                            //"no answer" handling
                            elseif($al[0]=="NoAnswer")
                            {
                                $query = "SELECT count(*) FROM ".db_table_name("survey_$surveyid")." WHERE ( ";
                                $query .= ($connect->databaseType == "mysql")?  db_quote_id($al[2])." = '')" : " (".db_quote_id($al[2])." LIKE ''))";
                            }
                        }
                        elseif ($qtype == "O")
                        {
                            $query = "SELECT count(*) FROM ".db_table_name("survey_$surveyid")." WHERE ( ";
                            $query .= ($connect->databaseType == "mysql")?  db_quote_id($al[2])." <> '')" : " (".db_quote_id($al[2])." NOT LIKE ''))";
                            // all other question types
                        }
                        else
                        {
                            $query = "SELECT count(*) FROM ".db_table_name("survey_$surveyid")." WHERE ".db_quote_id($al[2])." =";

                            //ranking question?
                            if (substr($rt, 0, 1) == "R")
                            {
                                $query .= " '$al[0]'";
                            }
                            else
                            {
                                $query .= " 'Y'";
                            }
                        }

                    }	//end if -> alist set

                    else
                    {
                        if ($al[0] != "")
                        {
                            //get more data

							if ($connect->databaseType == 'odbc_mssql' || $connect->databaseType == 'odbtp' || $connect->databaseType == 'mssql_n' || $connect->databaseType == 'mssqlnative')
                            {
                                // mssql cannot compare text blobs so we have to cast here
                                $query = "SELECT count(*) FROM ".db_table_name("survey_$surveyid")." WHERE cast(".db_quote_id($rt)." as varchar)= '$al[0]'";
                            }
                            else
                            $query = "SELECT count(*) FROM ".db_table_name("survey_$surveyid")." WHERE ".db_quote_id($rt)." = '$al[0]'";
                        }
                        else
                        { // This is for the 'NoAnswer' case
                            // We need to take into account several possibilities
                            // * NoAnswer cause the participant clicked the NoAnswer radio
                            //  ==> in this case value is '' or ' '
                            // * NoAnswer in text field
                            //  ==> value is ''
                            // * NoAnswer due to conditions, or a page not displayed
                            //  ==> value is NULL
                            if ($connect->databaseType == 'odbc_mssql' || $connect->databaseType == 'odbtp' || $connect->databaseType == 'mssql_n' || $connect->databaseType == 'mssqlnative')
                            {
                                // mssql cannot compare text blobs so we have to cast here
                                //$query = "SELECT count(*) FROM ".db_table_name("survey_$surveyid")." WHERE (".db_quote_id($rt)." IS NULL "
                                $query = "SELECT count(*) FROM ".db_table_name("survey_$surveyid")." WHERE ( "
                                //                                    . "OR cast(".db_quote_id($rt)." as varchar) = '' "
                                . "cast(".db_quote_id($rt)." as varchar) = '' "
                                . "OR cast(".db_quote_id($rt)." as varchar) = ' ' )";
                            }
                            else
                            //			    $query = "SELECT count(*) FROM ".db_table_name("survey_$surveyid")." WHERE (".db_quote_id($rt)." IS NULL "
                            $query = "SELECT count(*) FROM ".db_table_name("survey_$surveyid")." WHERE ( "
                            //								    . "OR ".db_quote_id($rt)." = '' "
                            . " ".db_quote_id($rt)." = '' "
                            . "OR ".db_quote_id($rt)." = ' ') ";
                        }

                    }

                    //check filter option
                    if (incompleteAnsFilterstate() == "inc") {$query .= " AND submitdate is null";}
                    elseif (incompleteAnsFilterstate() == "filter") {$query .= " AND submitdate is not null";}

                    //check for any "sql" that has been passed from another script
                    if ($sql != "NULL") {$query .= " AND $sql";}

                    //get data
                    $result=db_execute_num($query) or safe_die ("Couldn't do count of values<br />$query<br />".$connect->ErrorMsg());

                    // $statisticsoutput .= "\n<!-- ($sql): $query -->\n\n";

                    // this just extracts the data, after we present
                    while ($row=$result->FetchRow())
                    {
                        //increase counter
                        $TotalCompleted += $row[0];

                        //"no answer" handling
                        if ($al[0] === "")
                        {$fname=$statlang->gT("No answer");}

                        //"other" handling
                        //"Answers" means that we show an option to list answer to "other" text field
                        elseif ($al[0] === $statlang->gT("Other") || $al[0] === "Answers" || ($qtype === "O" && $al[0] === $statlang->gT("Comments")) || $qtype === "P")
                        {
                            if ($qtype == "P" ) $ColumnName_RM = $al[2]."comment";
                            else  $ColumnName_RM = $al[2];
                            if ($qtype=='O') {
                                $TotalCompleted -=$row[0];
                            }
                            $fname="$al[1]";
                            if ($browse===true) $fname .= " <input type='button' value='".$statlang->gT("Browse")."' onclick=\"window.open('admin.php?action=listcolumn&amp;sid=$surveyid&amp;column=$ColumnName_RM&amp;sql=".urlencode($sql)."', 'results', 'width=460, height=500, left=50, top=50, resizable=yes, scrollbars=yes, menubar=no, status=no, location=no, toolbar=no')\" />";
                        }

                        /*
                         * text questions:
                         *
                         * U = huge free text
                         * T = long free text
                         * S = short free text
                         * Q = multiple short text
                         */
                        elseif ($qtype == "S" || $qtype == "U" || $qtype == "T" || $qtype == "Q")
                        {
                            $headPDF = array();
                            $headPDF[] = array($statlang->gT("Answer"),$statlang->gT("Count"),$statlang->gT("Percentage"));

                            //show free text answers
                            if ($al[0] == "Answers")
                            {
                                $fname= "$al[1]";
                                if ($browse===true) $fname .= " <input type='submit' value='"
                                . $statlang->gT("Browse")."' onclick=\"window.open('admin.php?action=listcolumn&sid=$surveyid&amp;column=$al[2]&amp;sql="
                                . urlencode($sql)."', 'results', 'width=460, height=500, left=50, top=50, resizable=yes, scrollbars=yes, menubar=no, status=no, location=no, toolbar=no')\" />";
                            }
                            elseif ($al[0] == "NoAnswer")
                            {
                                $fname= "$al[1]";
                            }

							$statisticsoutput .= "</th>\n"
							."\t\t<th width='25%' align='center' >"
							."<strong>".$statlang->gT("Count")."</strong></th>\n"
							."\t\t<th width='25%' align='center' >"
							."<strong>".$statlang->gT("Percentage")."</strong></th>\n"
							."\t</tr></thead>\n";
                        }


                        //check if aggregated results should be shown
                        elseif (isset($showaggregateddata) && $showaggregateddata == 1)
                        {
                            if(!isset($showheadline) || $showheadline != false)
                            {
                                if($qtype == "5" || $qtype == "A")
                                {
                                    switch($outputType)
                                    {
                                        case 'xls':

                                            $headXLS = array();
                                            $headXLS[] = array($statlang->gT("Answer"),$statlang->gT("Count"),$statlang->gT("Percentage"),$statlang->gT("Sum"));

                                            ++$xlsRow;
                                            $sheet->write($xlsRow,0,$statlang->gT("Answer"));
                                            $sheet->write($xlsRow,1,$statlang->gT("Count"));
                                            $sheet->write($xlsRow,2,$statlang->gT("Percentage"));
                                            $sheet->write($xlsRow,3,$statlang->gT("Sum"));

                                            break;
                                        case 'pdf':

                                            $headPDF = array();
                                            $headPDF[] = array($statlang->gT("Answer"),$statlang->gT("Count"),$statlang->gT("Percentage"),$statlang->gT("Sum"));

                                            break;
                                        case 'html':
                                            //four columns
                                            $statisticsoutput .= "<strong>".$statlang->gT("Answer")."</strong></th>\n"
                                            ."\t\t<th width='15%' align='center' >"
                                            ."<strong>".$statlang->gT("Count")."</strong></th>\n"
                                            ."\t\t<th width='20%' align='center' >"
                                            ."<strong>".$statlang->gT("Percentage")."</strong></th>\n"
                                            ."\t\t<th width='15%' align='center' >"
                                            ."<strong>".$statlang->gT("Sum")."</strong></th>\n"
                                            ."\t</tr></thead>\n";
                                            break;
                                        default:


                                            break;
                                    }


                                    $showheadline = false;
                                }
                                else
                                {
                                    switch($outputType)
                                    {
                                        case 'xls':

                                            $headXLS = array();
                                            $headXLS[] = array($statlang->gT("Answer"),$statlang->gT("Count"),$statlang->gT("Percentage"));

                                            ++$xlsRow;
                                            $sheet->write($xlsRow,0,$statlang->gT("Answer"));
                                            $sheet->write($xlsRow,1,$statlang->gT("Count"));
                                            $sheet->write($xlsRow,2,$statlang->gT("Percentage"));

                                            break;

                                        case 'pdf':

                                            $headPDF = array();
                                            $headPDF[] = array($statlang->gT("Answer"),$statlang->gT("Count"),$statlang->gT("Percentage"));

                                            break;
                                        case 'html':
                                            //three columns
                                            $statisticsoutput .= "<strong>".$statlang->gT("Answer")."</strong></td>\n"
                                            ."\t\t<th width='25%' align='center' >"
                                            ."<strong>".$statlang->gT("Count")."</strong></th>\n"
                                            ."\t\t<th width='25%' align='center' >"
                                            ."<strong>".$statlang->gT("Percentage")."</strong></th>\n"
                                            ."\t</tr></thead>\n";
                                            break;
                                        default:


                                            break;
                                    }

                                    $showheadline = false;
                                }

                            }

                            //text for answer column is always needed
                            $fname="$al[1] ($al[0])";

                            //these question types get special treatment by $showaggregateddata
                            if($qtype == "5" || $qtype == "A")
                            {
                                //put non-edited data in here because $row will be edited later
                                $grawdata[]=$row[0];
                                $showaggregated_indice=count($grawdata) - 1;
                                $showaggregated_indice_table[$showaggregated_indice]="aggregated";
                                $showaggregated_indice=-1;

                                //keep in mind that we already added data (will be checked later)
                                $justadded = true;

                                //we need a counter because we want to sum up certain values
                                //reset counter if 5 items have passed
                                if(!isset($testcounter) || $testcounter >= 4)
                                {
                                    $testcounter = 0;
                                }
                                else
                                {
                                    $testcounter++;
                                }

                                //beside the known percentage value a new aggregated value should be shown
                                //therefore this item is marked in a certain way

                                if($testcounter == 0 )	//add 300 to original value
                                {
                                    //HACK: add three times the total number of results to the value
                                    //This way we get a 300 + X percentage which can be checked later
                                    $row[0] += (3*$results);
                                }

                                //the third value should be shown twice later -> mark it
                                if($testcounter == 2)	//add 400 to original value
                                {
                                    //HACK: add four times the total number of results to the value
                                    //This way there should be a 400 + X percentage which can be checked later
                                    $row[0] += (4*$results);
                                }

                                //the last value aggregates the data of item 4 + item 5 later
                                if($testcounter == 4 )	//add 200 to original value
                                {
                                    //HACK: add two times the total number of results to the value
                                    //This way there should be a 200 + X percentage which can be checked later
                                    $row[0] += (2*$results);
                                }

                            }	//end if -> question type = "5"/"A"

                        }	//end if -> show aggregated data

                        //handling what's left
                        else
                        {
                            if(!isset($showheadline) || $showheadline != false)
                            {
                                switch($outputType)
                                {
                                    case 'xls':

                                        $headXLS = array();
                                        $headXLS[] = array($statlang->gT("Answer"),$statlang->gT("Count"),$statlang->gT("Percentage"));

                                        ++$xlsRow;
                                        $sheet->write($xlsRow,0,$statlang->gT("Answer"));
                                        $sheet->write($xlsRow,1,$statlang->gT("Count"));
                                        $sheet->write($xlsRow,2,$statlang->gT("Percentage"));

                                        break;
                                    case 'pdf':

                                        $headPDF = array();
                                        $headPDF[] = array($statlang->gT("Answer"),$statlang->gT("Count"),$statlang->gT("Percentage"));

                                        break;
                                    case 'html':
                                        //three columns
                                        $statisticsoutput .= "<strong>".$statlang->gT("Answer")."</strong></th>\n"
                                        ."\t\t<th width='25%' align='center' >"
                                        ."<strong>".$statlang->gT("Count")."</strong></th>\n"
                                        ."\t\t<th width='25%' align='center' >"
                                        ."<strong>".$statlang->gT("Percentage")."</strong></th>\n"
                                        ."\t</tr></thead>\n";
                                        break;
                                    default:


                                        break;
                                }

                                $showheadline = false;

                            }
                            //answer text
                            $fname="$al[1] ($al[0])";
                        }

                        //are there some results to play with?
                        if ($results > 0)
                        {
                            //calculate percentage
                            $gdata[] = ($row[0]/$results)*100;
                        }
                        //no results
                        else
                        {
                            //no data!
                            $gdata[] = "N/A";
                        }

                        //only add this if we don't handle question type "5"/"A"
                        if(!isset($justadded))
                        {
                            //put absolute data into array
                            $grawdata[]=$row[0];
                        }
                        else
                        {
                            //unset to handle "no answer" data correctly
                            unset($justadded);
                        }

                        //put question title and code into array
                        $label[]=$fname;

                        //put only the code into the array
                        $justcode[]=$al[0];

                        //edit labels and put them into antoher array
                        $lbl[] = wordwrap(FlattenText("$al[1] ($row[0])"), 25, "\n"); // NMO 2009-03-24
                        $lblrtl[] = utf8_strrev(wordwrap(FlattenText("$al[1] )$row[0]("), 25, "\n")); // NMO 2009-03-24

                    }	//end while -> loop through results

                }	//end foreach -> loop through answer data

                //no filtering of incomplete answers and NO multiple option questions
                //if ((incompleteAnsFilterstate() != "filter") and ($qtype != "M") and ($qtype != "P"))
                //error_log("TIBO ".print_r($showaggregated_indice_table,true));
                if (($qtype != "M") and ($qtype != "P"))
                {
                    //is the checkbox "Don't consider NON completed responses (only works when Filter incomplete answers is Disable)" checked?
                    //if (isset($_POST["noncompleted"]) and ($_POST["noncompleted"] == "on") && (isset($showaggregateddata) && $showaggregateddata == 0))
                    // TIBO: TODO WE MUST SKIP THE FOLLOWING SECTION FOR TYPE A and 5 when
                    // showaggreagated data is set and set to 1
                    if (isset($_POST["noncompleted"]) and ($_POST["noncompleted"] == "on") )
                    {
                        //counter
                        $i=0;

                        while (isset($gdata[$i]))
                        {
                            if (isset($showaggregated_indice_table[$i]) && $showaggregated_indice_table[$i]=="aggregated")
                            { // do nothing, we don't rewrite aggregated results
                                // or at least I don't know how !!! (lemeur)
                            }
                            else
                            {
                                //we want to have some "real" data here
                                if ($gdata[$i] != "N/A")
                                {
                                    //calculate percentage
                                    $gdata[$i] = ($grawdata[$i]/$TotalCompleted)*100;
                                }
                            }

                            //increase counter
                            $i++;

                        }	//end while (data available)

                    }	//end if -> noncompleted checked

                    //noncompleted is NOT checked
                    else
                    {
                        //calculate total number of incompleted records
                        $TotalIncomplete = $results - $TotalCompleted;

                        //output
                        if ((incompleteAnsFilterstate() != "filter"))
                        {
                            $fname=$statlang->gT("Not completed or Not displayed");
                        }
                        else
                        {
                            $fname=$statlang->gT("Not displayed");
                        }

                        //we need some data
                        if ($results > 0)
                        {
                            //calculate percentage
                            $gdata[] = ($TotalIncomplete/$results)*100;
                        }

                        //no data :(
                        else
                        {
                            $gdata[] = "N/A";
                        }

                        //put data of incompleted records into array
                        $grawdata[]=$TotalIncomplete;

                        //put question title ("Not completed") into array
                        $label[]= $fname;

                        //put the code ("Not completed") into the array
                        $justcode[]=$fname;

                        //edit labels and put them into antoher array
                        if ((incompleteAnsFilterstate() != "filter"))
                        {
                            $lbl[] = wordwrap(FlattenText($statlang->gT("Not completed or Not displayed")." ($TotalIncomplete)"), 20, "\n"); // NMO 2009-03-24
                        }
                        else
                        {
                            $lbl[] = wordwrap(FlattenText($statlang->gT("Not displayed")." ($TotalIncomplete)"), 20, "\n"); // NMO 2009-03-24
                        }
                    }	//end else -> noncompleted NOT checked

                }	//end if -> no filtering of incomplete answers and no multiple option questions


                //counter
                $i=0;

                //we need to know which item we are editing
                $itemcounter = 1;

                //array to store items 1 - 5 of question types "5" and "A"
                $stddevarray = array();

                //loop through all available answers
                while (isset($gdata[$i]))
                {
                    //repeat header (answer, count, ...) for each new question
                    unset($showheadline);


                    /*
                     * there are 3 colums:
                     *
                     * 1 (50%) = answer (title and code in brackets)
                     * 2 (25%) = count (absolute)
                     * 3 (25%) = percentage
                     */
                    $statisticsoutput .= "\t<tr>\n\t\t<td align='center' >" . $label[$i] ."\n"
                    ."\t\t</td>\n"

                    //output absolute number of records
                    ."\t\t<td align='center' >" . $grawdata[$i] . "\n</td>";


                    //no data
                    if ($gdata[$i] == "N/A")
                    {
                        switch($outputType)
                        {
                            case 'xls':

                                $label[$i]=FlattenText($label[$i]);
                                $tableXLS[] = array($label[$i],$grawdata[$i],sprintf("%01.2f", $gdata[$i]). "%");

                                ++$xlsRow;
                                $sheet->write($xlsRow,0,$label[$i]);
                                $sheet->write($xlsRow,1,$grawdata[$i]);
                                $sheet->write($xlsRow,2,sprintf("%01.2f", $gdata[$i]). "%");

                                break;
                            case 'pdf':

                                $tablePDF[] = array(FlattenText($label[$i]),$grawdata[$i],sprintf("%01.2f", $gdata[$i]). "%", "");

                                break;
                            case 'html':
                                //output when having no data
                                $statisticsoutput .= "\t\t<td  align='center' >";

                                //percentage = 0
                                $statisticsoutput .= sprintf("%01.2f", $gdata[$i]) . "%";
                                $gdata[$i] = 0;

                                //check if we have to adjust ouput due to $showaggregateddata setting
                                if(isset($showaggregateddata) && $showaggregateddata == 1 && ($qtype == "5" || $qtype == "A"))
                                {
                                    $statisticsoutput .= "\t\t</td>";
                                }
								elseif ($qtype == "S" || $qtype == "U" || $qtype == "T" || $qtype == "Q")
                        		{
                                    $statisticsoutput .= "</td>\n\t</tr>\n";
                                }
                                break;
                            default:


                                break;
                        }

                    }

                    //data available
                    else
                    {
                        //check if data should be aggregated
                        if(isset($showaggregateddata) && $showaggregateddata == 1 && ($qtype == "5" || $qtype == "A"))
                        {
                            //mark that we have done soemthing special here
                            $aggregated = true;

                            //just calculate everything once. the data is there in the array
                            if($itemcounter == 1)
                            {
                                //there are always 5 answers
                                for($x = 0; $x < 5; $x++)
                                {
                                    //put 5 items into array for further calculations
                                    array_push($stddevarray, $grawdata[$x]);
                                }
                            }

                            //"no answer" & items 2 / 4 - nothing special to do here, just adjust output
                            if($gdata[$i] <= 100)
                            {
                                if($itemcounter == 2 && $label[$i+4] == $statlang->gT("No answer"))
                                {
                                    //prevent division by zero
                                    if(($results - $grawdata[$i+4]) > 0)
                                    {
                                        //re-calculate percentage
                                        $percentage = ($grawdata[$i] / ($results - $grawdata[$i+4])) * 100;
                                    }
                                    else
                                    {
                                        $percentage = 0;
                                    }

                                }
                                elseif($itemcounter == 4 && $label[$i+2] == $statlang->gT("No answer"))
                                {
                                    //prevent division by zero
                                    if(($results - $grawdata[$i+2]) > 0)
                                    {
                                        //re-calculate percentage
                                        $percentage = ($grawdata[$i] / ($results - $grawdata[$i+2])) * 100;
                                    }
                                    else
                                    {
                                        $percentage = 0;
                                    }
                                }
                                else
                                {
                                    $percentage = $gdata[$i];
                                }
                                switch($outputType)
                                {
                                    case 'xls':

                                        $label[$i]=FlattenText($label[$i]);
                                        $tableXLS[]= array($label[$i],$grawdata[$i],sprintf("%01.2f", $percentage)."%");

                                        ++$xlsRow;
                                        $sheet->write($xlsRow,0,$label[$i]);
                                        $sheet->write($xlsRow,1,$grawdata[$i]);
                                        $sheet->write($xlsRow,2,sprintf("%01.2f", $percentage)."%");

                                        break;
                                    case 'pdf':
                                        $label[$i]=FlattenText($label[$i]);
                                        $tablePDF[] = array($label[$i],$grawdata[$i],sprintf("%01.2f", $percentage)."%", "");

                                        break;
                                    case 'html':
                                        //output
                                        $statisticsoutput .= "\t\t<td align='center'>";

                                        //output percentage
                                        $statisticsoutput .= sprintf("%01.2f", $percentage) . "%";

                                        //adjust output
                                        $statisticsoutput .= "\t\t</td>";
                                        break;
                                    default:


                                        break;
                                }

                            }

                            //item 3 - just show results twice
                            //old: if($gdata[$i] >= 400)
                            //trying to fix bug #2583:
                            if($gdata[$i] >= 400 && $i != 0)
                            {
                                //remove "400" which was added before
                                $gdata[$i] -= 400;

                                if($itemcounter == 3 && $label[$i+3] == $statlang->gT("No answer"))
                                {
                                    //prevent division by zero
                                    if(($results - $grawdata[$i+3]) > 0)
                                    {
                                        //re-calculate percentage
                                        $percentage = ($grawdata[$i] / ($results - $grawdata[$i+3])) * 100;
                                    }
                                    else
                                    {
                                        $percentage = 0;
                                    }
                                }
                                else
                                {
                                    //get the original percentage
                                    $percentage = $gdata[$i];
                                }
                                switch($outputType)
                                {
                                    case 'xls':

                                        $label[$i]=FlattenText($label[$i]);
                                        $tableXLS[] = array($label[$i],$grawdata[$i],sprintf("%01.2f", $percentage)."%",sprintf("%01.2f", $percentage)."%");

                                        ++$xlsRow;
                                        $sheet->write($xlsRow,0,$label[$i]);
                                        $sheet->write($xlsRow,1,$grawdata[$i]);
                                        $sheet->write($xlsRow,2,sprintf("%01.2f", $percentage)."%");
                                        $sheet->write($xlsRow,3,sprintf("%01.2f", $percentage)."%");

                                        break;
                                    case 'pdf':
                                        $label[$i]=FlattenText($label[$i]);
                                        $tablePDF[] = array($label[$i],$grawdata[$i],sprintf("%01.2f", $percentage)."%",sprintf("%01.2f", $percentage)."%");

                                        break;
                                    case 'html':
                                        //output percentage
                                        $statisticsoutput .= "\t\t<td align='center' >";
                                        $statisticsoutput .= sprintf("%01.2f", $percentage) . "%</td>";

                                        //output again (no real aggregation here)
                                        $statisticsoutput .= "\t\t<td align='center' >";
                                        $statisticsoutput .= sprintf("%01.2f", $percentage)."%";
                                        $statisticsoutput .= "</td>\t\t";
                                        break;
                                    default:


                                        break;
                                }

                            }

                            //FIRST value -> add percentage of item 1 + item 2
                            //old: if($gdata[$i] >= 300 && $gdata[$i] < 400)
                            //trying to fix bug #2583:
                            if(($gdata[$i] >= 300 && $gdata[$i] < 400) || ($i == 0 && $gdata[$i] <= 400))
                            {
                                //remove "300" which was added before
                                $gdata[$i] -= 300;

                                if($itemcounter == 1 && $label[$i+5] == $statlang->gT("No answer"))
                                {
                                    //prevent division by zero
                                    if(($results - $grawdata[$i+5]) > 0)
                                    {
                                        //re-calculate percentage
                                        $percentage = ($grawdata[$i] / ($results - $grawdata[$i+5])) * 100;
                                        $percentage2 = ($grawdata[$i + 1] / ($results - $grawdata[$i+5])) * 100;
                                    }
                                    else
                                    {
                                        $percentage = 0;
                                        $percentage2 = 0;

                                    }
                                }
                                else
                                {
                                    $percentage = $gdata[$i];
                                    $percentage2 = $gdata[$i+1];
                                }
                                //percentage of item 1 + item 2
                                $aggregatedgdata = $percentage + $percentage2;


                                switch($outputType)
                                {
                                    case 'xls':

                                        $label[$i]=FlattenText($label[$i]);
                                        $tableXLS[] = array($label[$i],$grawdata[$i],sprintf("%01.2f", $percentage)."%",sprintf("%01.2f", $aggregatedgdata)."%");

                                        ++$xlsRow;
                                        $sheet->write($xlsRow,0,$label[$i]);
                                        $sheet->write($xlsRow,1,$grawdata[$i]);
                                        $sheet->write($xlsRow,2,sprintf("%01.2f", $percentage)."%");
                                        $sheet->write($xlsRow,3,sprintf("%01.2f", $aggregatedgdata)."%");

                                        break;
                                    case 'pdf':
                                        $label[$i]=FlattenText($label[$i]);
                                        $tablePDF[] = array($label[$i],$grawdata[$i],sprintf("%01.2f", $percentage)."%",sprintf("%01.2f", $aggregatedgdata)."%");

                                        break;
                                    case 'html':
                                        //output percentage
                                        $statisticsoutput .= "\t\t<td align='center' >";
                                        $statisticsoutput .= sprintf("%01.2f", $percentage) . "%</td>";

                                        //output aggregated data
                                        $statisticsoutput .= "\t\t<td align='center' >";
                                        $statisticsoutput .= sprintf("%01.2f", $aggregatedgdata)."%";
                                        $statisticsoutput .= "</td>\t\t";
                                        break;
                                    default:


                                        break;
                                }
                            }

                            //LAST value -> add item 4 + item 5
                            if($gdata[$i] > 100 && $gdata[$i] < 300)
                            {
                                //remove "200" which was added before
                                $gdata[$i] -= 200;

                                if($itemcounter == 5 && $label[$i+1] == $statlang->gT("No answer"))
                                {
                                    //prevent division by zero
                                    if(($results - $grawdata[$i+1]) > 0)
                                    {
                                        //re-calculate percentage
                                        $percentage = ($grawdata[$i] / ($results - $grawdata[$i+1])) * 100;
                                        $percentage2 = ($grawdata[$i - 1] / ($results - $grawdata[$i+1])) * 100;
                                    }
                                    else
                                    {
                                        $percentage = 0;
                                        $percentage2 = 0;
                                    }
                                }
                                else
                                {
                                    $percentage = $gdata[$i];
                                    $percentage2 = $gdata[$i-1];
                                }

                                //item 4 + item 5
                                $aggregatedgdata = $percentage + $percentage2;
                                switch($outputType)
                                {
                                    case 'xls':

                                        $label[$i]=FlattenText($label[$i]);
                                        $tableXLS[] = array($label[$i],$grawdata[$i],sprintf("%01.2f", $percentage)."%",sprintf("%01.2f", $aggregatedgdata)."%");

                                        ++$xlsRow;
                                        $sheet->write($xlsRow,0,$label[$i]);
                                        $sheet->write($xlsRow,1,$grawdata[$i]);
                                        $sheet->write($xlsRow,2,sprintf("%01.2f", $percentage)."%");
                                        $sheet->write($xlsRow,3,sprintf("%01.2f", $aggregatedgdata)."%");

                                        break;
                                    case 'pdf':
                                        $label[$i]=FlattenText($label[$i]);
                                        $tablePDF[] = array($label[$i],$grawdata[$i],sprintf("%01.2f", $percentage)."%",sprintf("%01.2f", $aggregatedgdata)."%");

                                        break;
                                    case 'html':
                                        //output percentage
                                        $statisticsoutput .= "\t\t<td align='center' >";
                                        $statisticsoutput .= sprintf("%01.2f", $percentage) . "%</td>";

                                        //output aggregated data
                                        $statisticsoutput .= "\t\t<td align='center' >";
                                        $statisticsoutput .= sprintf("%01.2f", $aggregatedgdata)."%";
                                        $statisticsoutput .= "</td>\t\t";
                                        break;
                                    default:


                                        break;
                                }

                                // create new row "sum"
                                //calculate sum of items 1-5
                                $sumitems = $grawdata[$i]
                                + $grawdata[$i-1]
                                + $grawdata[$i-2]
                                + $grawdata[$i-3]
                                + $grawdata[$i-4];

                                //special treatment for zero values
                                if($sumitems > 0)
                                {
                                    $sumpercentage = "100.00";
                                }
                                else
                                {
                                    $sumpercentage = "0";
                                }
                                //special treatment for zero values
                                if($TotalCompleted > 0)
                                {
                                    $casepercentage = "100.00";
                                }
                                else
                                {
                                    $casepercentage = "0";
                                }
                                switch($outputType)
                                {
                                    case 'xls':


                                        $footXLS[] = array($statlang->gT("Sum")." (".$statlang->gT("Answers").")",$sumitems,$sumpercentage."%",$sumpercentage."%");
                                        $footXLS[] = array($statlang->gT("Number of cases"),$TotalCompleted,$casepercentage."%","");

                                        ++$xlsRow;
                                        $sheet->write($xlsRow,0,$statlang->gT("Sum")." (".$statlang->gT("Answers").")");
                                        $sheet->write($xlsRow,1,$sumitems);
                                        $sheet->write($xlsRow,2,$sumpercentage."%");
                                        $sheet->write($xlsRow,3,$sumpercentage."%");
                                        ++$xlsRow;
                                        $sheet->write($xlsRow,0,$statlang->gT("Number of cases"));
                                        $sheet->write($xlsRow,1,$TotalCompleted);
                                        $sheet->write($xlsRow,2,$casepercentage."%");

                                        break;
                                    case 'pdf':

                                        $footPDF[] = array($statlang->gT("Sum")." (".$statlang->gT("Answers").")",$sumitems,$sumpercentage."%",$sumpercentage."%");
                                        $footPDF[] = array($statlang->gT("Number of cases"),$TotalCompleted,$casepercentage."%","");

                                        break;
                                    case 'html':
                                        $statisticsoutput .= "\t\t&nbsp;\n\t</tr>\n";
                                        $statisticsoutput .= "<tr><td align='center'><strong>".$statlang->gT("Sum")." (".$statlang->gT("Answers").")</strong></td>";
                                        $statisticsoutput .= "<td align='center' ><strong>".$sumitems."</strong></td>";
                                        $statisticsoutput .= "<td align='center' ><strong>$sumpercentage%</strong></td>";
                                        $statisticsoutput .= "<td align='center' ><strong>$sumpercentage%</strong></td>";
                                        $statisticsoutput .= "\t\t&nbsp;\n\t</tr>\n";

                                        $statisticsoutput .= "<tr><td align='center'>".$statlang->gT("Number of cases")."</td>";	//German: "Fallzahl"
                                        $statisticsoutput .= "<td align='center' >".$TotalCompleted."</td>";
                                        $statisticsoutput .= "<td align='center' >$casepercentage%</td>";
                                        //there has to be a whitespace within the table cell to display correctly
                                        $statisticsoutput .= "<td align='center' >&nbsp;</td></tr>";
                                        break;
                                    default:


                                        break;
                                }

                            }

                        }	//end if -> show aggregated data

                        //don't show aggregated data
                        else
                        {
                            switch($outputType)
                            {
                                case 'xls':
                                    $label[$i]=FlattenText($label[$i]);
                                    $tableXLS[] = array($label[$i],$grawdata[$i],sprintf("%01.2f", $gdata[$i])."%", "");

                                    ++$xlsRow;
                                    $sheet->write($xlsRow,0,$label[$i]);
                                    $sheet->write($xlsRow,1,$grawdata[$i]);
                                    $sheet->write($xlsRow,2,sprintf("%01.2f", $gdata[$i])."%");
                                    //$sheet->write($xlsRow,3,$sumpercentage."%");

                                    break;
                                case 'pdf':
                                    $label[$i]=FlattenText($label[$i]);
                                    $tablePDF[] = array($label[$i],$grawdata[$i],sprintf("%01.2f", $gdata[$i])."%", "");

                                    break;
                                case 'html':
                                    //output percentage
                                    $statisticsoutput .= "\t\t<td align='center' >";
                                    $statisticsoutput .= sprintf("%01.2f", $gdata[$i]) . "%";
                                    $statisticsoutput .= "\t\t";
                                    //end output per line. there has to be a whitespace within the table cell to display correctly
                                    $statisticsoutput .= "\t\t&nbsp;</td>\n\t</tr>\n";
                                    break;
                                default:


                                    break;
                            }

                        }

                    }	//end else -> $gdata[$i] != "N/A"



                    //increase counter
                    $i++;

                    $itemcounter++;

                }	//end while

                //only show additional values when this setting is enabled
                if(isset($showaggregateddata) && $showaggregateddata == 1 )
                {
                    //it's only useful to calculate standard deviation and arithmetic means for question types
                    //5 = 5 Point Scale
                    //A = Array (5 Point Choice)
                    if($qtype == "5" || $qtype == "A")
                    {
                        $stddev = 0;
                        $am = 0;

                        //calculate arithmetic mean
                        if(isset($sumitems) && $sumitems > 0)
                        {


                            //calculate and round results
                            //there are always 5 items
                            for($x = 0; $x < 5; $x++)
                            {
                                //create product of item * value
                                $am += (($x+1) * $stddevarray[$x]);
                            }

                            //prevent division by zero
                            if(isset($stddevarray) && array_sum($stddevarray) > 0)
                            {
                                $am = round($am / array_sum($stddevarray),2);
                            }
                            else
                            {
                                $am = 0;
                            }

                            //calculate standard deviation -> loop through all data
                            /*
                             * four steps to calculate the standard deviation
                             * 1 = calculate difference between item and arithmetic mean and multiply with the number of elements
                             * 2 = create sqaure value of difference
                             * 3 = sum up square values
                             * 4 = multiply result with 1 / (number of items)
                             * 5 = get root
                             */



                            for($j = 0; $j < 5; $j++)
                            {
                                //1 = calculate difference between item and arithmetic mean
                                $diff = (($j+1) - $am);

                                //2 = create square value of difference
                                $squarevalue = square($diff);

                                //3 = sum up square values and multiply them with the occurence
                                //prevent divison by zero
                                if($squarevalue != 0 && $stddevarray[$j] != 0)
                                {
                                    $stddev += $squarevalue * $stddevarray[$j];
                                }

                            }

                            //4 = multiply result with 1 / (number of items (=5))
                            //There are two different formulas to calculate standard derivation
                            //$stddev = $stddev / array_sum($stddevarray);		//formula source: http://de.wikipedia.org/wiki/Standardabweichung

                            //prevent division by zero
                            if((array_sum($stddevarray)-1) != 0 && $stddev != 0)
                            {
                                $stddev = $stddev / (array_sum($stddevarray)-1);	//formula source: http://de.wikipedia.org/wiki/Empirische_Varianz
                            }
                            else
                            {
                                $stddev = 0;
                            }

                            //5 = get root
                            $stddev = sqrt($stddev);
                            $stddev = round($stddev,2);
                        }
                        switch($outputType)
                        {
                            case 'xls':

                                $tableXLS[] = array($statlang->gT("Arithmetic mean"),$am,'','');
                                $tableXLS[] = array($statlang->gT("Standard deviation"),$stddev,'','');

                                ++$xlsRow;
                                $sheet->write($xlsRow,0,$statlang->gT("Arithmetic mean"));
                                $sheet->write($xlsRow,1,$am);

                                ++$xlsRow;
                                $sheet->write($xlsRow,0,$statlang->gT("Standard deviation"));
                                $sheet->write($xlsRow,1,$stddev);

                                break;
                            case 'pdf':

                                $tablePDF[] = array($statlang->gT("Arithmetic mean"),$am,'','');
                                $tablePDF[] = array($statlang->gT("Standard deviation"),$stddev,'','');

                                break;
                            case 'html':
                                //calculate standard deviation
                                $statisticsoutput .= "<tr><td align='center'>".$statlang->gT("Arithmetic mean")."</td>";	//German: "Fallzahl"
                                $statisticsoutput .= "<td>&nbsp;</td><td align='center'> $am</td><td>&nbsp;</td></tr>";
                                $statisticsoutput .= "<tr><td align='center'>".$statlang->gT("Standard deviation")."</td>";    //German: "Fallzahl"
                                $statisticsoutput .= "<td>&nbsp;</td><td align='center'>$stddev</td><td>&nbsp;</td></tr>";

                                break;
                            default:


                                break;
                        }
                    }
                }

                if($outputType=='pdf') //XXX TODO PDF
                {
                    //$tablePDF = array();
                    $tablePDF = array_merge_recursive($tablePDF, $footPDF);
                    $pdf->headTable($headPDF,$tablePDF);
                    //$pdf->tableintopdf($tablePDF);

                    //				if(isset($footPDF))
                    //				foreach($footPDF as $foot)
                    //				{
                    //					$footA = array($foot);
                    //					$pdf->tablehead($footA);
                    //				}
                }




                //-------------------------- PCHART OUTPUT ----------------------------

                //PCHART has to be enabled and we need some data
                if ($usegraph==1 && array_sum($gdata)>0)
                {
                    $graph = "";
                    $p1 = "";
                    //                  $statisticsoutput .= "<pre>";
                    //                  $statisticsoutput .= "GDATA:\n";
                    //                  print_r($gdata);
                    //                  $statisticsoutput .= "GRAWDATA\n";
                    //                  print_r($grawdata);
                    //                  $statisticsoutput .= "LABEL\n";
                    //                  print_r($label);
                    //                  $statisticsoutput .= "JUSTCODE\n";
                    //                  print_r($justcode);
                    //                  $statisticsoutput .= "LBL\n";
                    //                  print_r($lbl);
                    //                  $statisticsoutput .= "</pre>";
                    //First, lets delete any earlier graphs from the tmp directory
                    //$gdata and $lbl are arrays built at the end of the last section
                    //that contain the values, and labels for the data we are about
                    //to send to pchart.

                    $i = 0;
                    foreach ($gdata as $data)
                    {
                        if ($data != 0){$i++;}
                    }
                    $totallines=$i;
                    if ($totallines>15)
                    {
                        $gheight=320+(6.7*($totallines-15));
                        $fontsize=7;
                        $legendtop=0.01;
                        $setcentrey=0.5/(($gheight/320));
                    }
                    else
                    {
                        $gheight=320;
                        $fontsize=8;
                        $legendtop=0.07;
                        $setcentrey=0.5;
                    }

                    // Create bar chart for Multiple choice
                    if ($qtype == "M" || $qtype == "P")
                    {
                        //new bar chart using data from array $grawdata which contains percentage

                        $DataSet = new pData;
                        $counter=0;
                        $maxyvalue=0;
                        foreach ($grawdata as $datapoint)
                        {
                            $DataSet->AddPoint(array($datapoint),"Serie$counter");
                            $DataSet->AddSerie("Serie$counter");

                            $counter++;
                            if ($datapoint>$maxyvalue) $maxyvalue=$datapoint;
                        }

                        if ($maxyvalue<10) {++$maxyvalue;}
                        $counter=0;
                        foreach ($lbl as $label)
                        {
                            $DataSet->SetSerieName($label,"Serie$counter");
                            $counter++;
                        }

                        if ($MyCache->IsInCache("graph".$surveyid,$DataSet->GetData()))
                        {
                            $cachefilename=basename($MyCache->GetFileFromCache("graph".$surveyid,$DataSet->GetData()));
                        }
                        else
                        {
                            $graph = new pChart(1,1);

                            $graph->setFontProperties($rootdir."/fonts/".$chartfontfile, $chartfontsize);
                            $legendsize=$graph->getLegendBoxSize($DataSet->GetDataDescription());

                            if ($legendsize[1]<320) $gheight=420; else $gheight=$legendsize[1]+100;
                            $graph = new pChart(690+$legendsize[0],$gheight);
                            $graph->loadColorPalette($homedir.'/styles/'.$admintheme.'/limesurvey.pal');
                            $graph->setFontProperties($rootdir."/fonts/".$chartfontfile,$chartfontsize);
                            $graph->setGraphArea(50,30,500,$gheight-60);
                            $graph->drawFilledRoundedRectangle(7,7,523+$legendsize[0],$gheight-7,5,254,255,254);
                            $graph->drawRoundedRectangle(5,5,525+$legendsize[0],$gheight-5,5,230,230,230);
                            $graph->drawGraphArea(255,255,255,TRUE);
                            $graph->drawScale($DataSet->GetData(),$DataSet->GetDataDescription(),SCALE_START0,150,150,150,TRUE,90,0,TRUE,5,false);
                            $graph->drawGrid(4,TRUE,230,230,230,50);
                            // Draw the 0 line
                            $graph->setFontProperties($rootdir."/fonts/".$chartfontfile,$chartfontsize);
                            $graph->drawTreshold(0,143,55,72,TRUE,TRUE);

                            // Draw the bar graph
                            $graph->drawBarGraph($DataSet->GetData(),$DataSet->GetDataDescription(),FALSE);
                            //$Test->setLabel($DataSet->GetData(),$DataSet->GetDataDescription(),"Serie4","1","Important point!");
                            // Finish the graph
                            $graph->setFontProperties($rootdir."/fonts/".$chartfontfile, $chartfontsize);
                            $graph->drawLegend(510,30,$DataSet->GetDataDescription(),255,255,255);

                            $MyCache->WriteToCache("graph".$surveyid,$DataSet->GetData(),$graph);
                            $cachefilename=basename($MyCache->GetFileFromCache("graph".$surveyid,$DataSet->GetData()));
                            unset($graph);
                        }
                    }	//end if (bar chart)

                    //Pie Chart
                    else
                    {
                        // this block is to remove the items with value == 0
                        $i = 0;
                        while (isset ($gdata[$i]))
                        {
                            if ($gdata[$i] == 0)
                            {
                                array_splice ($gdata, $i, 1);
                                array_splice ($lbl, $i, 1);
                            }
                            else
                            {$i++;}
                        }

                        $lblout=array();
                        if ($language=='ar')
                        {
                            $lblout=$lbl; //reset text order to original
                            include_once($rootdir.'/classes/core/Arabic.php');
                            $Arabic = new Arabic('ArGlyphs');
                            foreach($lblout as $kkey => $kval){
                                if (preg_match("^[A-Za-z]^", $kval)) { //auto detect if english
                                    //eng
                                    //no reversing
                                }
                                else{
                                    $kval = $Arabic->utf8Glyphs($kval,50,false);
                                    $lblout[$kkey] = $kval;
                                }
                            }
                        }
                        elseif (getLanguageRTL($language))
                        {
                            $lblout=$lblrtl;
                        }
                        else
                        {
                            $lblout=$lbl;
                        }


                        //create new 3D pie chart
                        if ($usegraph==1)
                        {
                            $DataSet = new pData;
                            $DataSet->AddPoint($gdata,"Serie1");
                            $DataSet->AddPoint($lblout,"Serie2");
                            $DataSet->AddAllSeries();
                            $DataSet->SetAbsciseLabelSerie("Serie2");

                            if ($MyCache->IsInCache("graph".$surveyid,$DataSet->GetData()))
                            {
                                $cachefilename=basename($MyCache->GetFileFromCache("graph".$surveyid,$DataSet->GetData()));
                            }
                            else
                            {

                                $gheight=ceil($gheight);
                                $graph = new pChart(690,$gheight);
                                $graph->loadColorPalette($homedir.'/styles/'.$admintheme.'/limesurvey.pal');
                                $graph->drawFilledRoundedRectangle(7,7,687,$gheight-3,5,254,255,254);
                                $graph->drawRoundedRectangle(5,5,689,$gheight-1,5,230,230,230);

                                // Draw the pie chart
                                $graph->setFontProperties($rootdir."/fonts/".$chartfontfile, $chartfontsize);
                                $graph->drawPieGraph($DataSet->GetData(),$DataSet->GetDataDescription(),225,round($gheight/2),170,PIE_PERCENTAGE,TRUE,50,20,5);
                                $graph->setFontProperties($rootdir."/fonts/".$chartfontfile,$chartfontsize);
                                $graph->drawPieLegend(430,12,$DataSet->GetData(),$DataSet->GetDataDescription(),250,250,250);
                                $MyCache->WriteToCache("graph".$surveyid,$DataSet->GetData(),$graph);
                                $cachefilename=basename($MyCache->GetFileFromCache("graph".$surveyid,$DataSet->GetData()));
                                unset($graph);
                            }
                            //print_r($DataSet->GetData()); echo "<br/><br/>";
                        }

                    }	//end else -> pie charts

                    //introduce new counter
                    if (!isset($ci)) {$ci=0;}

                    //increase counter, start value -> 1
                    $ci++;
                    switch($outputType)
                    {
                        case 'xls':

                            /**
                             * No Image for Excel...
                             */

                            break;
                        case 'pdf':

                            $pdf->AddPage('P','A4');

                            $pdf->titleintopdf($pdfTitle,$titleDesc);
                            $pdf->Image($tempdir."/".$cachefilename, 0, 70, 180, 0, '', $homeurl."/admin.php?sid=$surveyid", 'B', true, 150,'C',false,false,0,true);

                            break;
                        case 'html':
                            $statisticsoutput .= "<tr><td colspan='4' style=\"text-align:center\"><img src=\"$tempurl/".$cachefilename."\" border='1' /></td></tr>";

                            break;
                        default:


                            break;
                    }

                }

                //close table/output
                if($outputType=='html')
                $statisticsoutput .= "</table><br /> \n";

            }	//end if -> collect and display results

            //delete data
            unset($gdata);
            unset($grawdata);
            unset($label);
            unset($lbl);
            unset($lblrtl);
            unset($lblout);
            unset($justcode);
            unset ($alist);

        }	// end foreach -> loop through all questions

        //output
        if($outputType=='html')
        $statisticsoutput .= "<br />&nbsp;\n";

    }	//end if -> show summary results

    switch($outputType)
    {
        case 'xls':

            //$workbook->
            $workbook->close();
            if($pdfOutput=='F')
            {
                return $sFileName;
            }
            else
            {
                return;
            }
            break;

        case 'pdf':
            $pdf->lastPage();
            if($pdfOutput=='F')
            { // This is only used by lsrc to send an E-Mail attachment, so it gives back the filename to send and delete afterwards
                $pdf->Output($tempdir."/".$statlang->gT('Survey').'_'.$surveyid."_".$surveyInfo['surveyls_title'].'.pdf', $pdfOutput);
                return $tempdir."/".$statlang->gT('Survey').'_'.$surveyid."_".$surveyInfo['surveyls_title'].'.pdf';
            }
            else
            return $pdf->Output($statlang->gT('Survey').'_'.$surveyid."_".$surveyInfo['surveyls_title'].'.pdf', $pdfOutput);

            break;
        case 'html':
            return $statisticsoutput;

            break;
        default:
            return $statisticsoutput;

            break;
    }

}
Example #5
0
 /**
  * Add dummy tokens form
  */
 function addDummies($iSurveyId, $subaction = '')
 {
     $iSurveyId = sanitize_int($iSurveyId);
     $clang = $this->getController()->lang;
     if (!Permission::model()->hasSurveyPermission($iSurveyId, 'tokens', 'create')) {
         Yii::app()->session['flashmessage'] = $clang->gT("You do not have sufficient rights to access this page.");
         $this->getController()->redirect(array("/admin/survey/sa/view/surveyid/{$iSurveyId}"));
     }
     $bTokenExists = tableExists('{{tokens_' . $iSurveyId . '}}');
     if (!$bTokenExists) {
         self::_newtokentable($iSurveyId);
     }
     $this->getController()->loadHelper("surveytranslator");
     if (!empty($subaction) && $subaction == 'add') {
         $this->getController()->loadLibrary('Date_Time_Converter');
         $dateformatdetails = getDateFormatData(Yii::app()->session['dateformat']);
         //Fix up dates and match to database format
         if (trim(Yii::app()->request->getPost('validfrom')) == '') {
             $_POST['validfrom'] = null;
         } else {
             $datetimeobj = new Date_Time_Converter(trim(Yii::app()->request->getPost('validfrom')), $dateformatdetails['phpdate'] . ' H:i');
             $_POST['validfrom'] = $datetimeobj->convert('Y-m-d H:i:s');
         }
         if (trim(Yii::app()->request->getPost('validuntil')) == '') {
             $_POST['validuntil'] = null;
         } else {
             $datetimeobj = new Date_Time_Converter(trim(Yii::app()->request->getPost('validuntil')), $dateformatdetails['phpdate'] . ' H:i');
             $_POST['validuntil'] = $datetimeobj->convert('Y-m-d H:i:s');
         }
         $santitizedtoken = '';
         $aData = array('firstname' => Yii::app()->request->getPost('firstname'), 'lastname' => Yii::app()->request->getPost('lastname'), 'email' => Yii::app()->request->getPost('email'), 'emailstatus' => 'OK', 'token' => $santitizedtoken, 'language' => sanitize_languagecode(Yii::app()->request->getPost('language')), 'sent' => 'N', 'remindersent' => 'N', 'completed' => 'N', 'usesleft' => Yii::app()->request->getPost('usesleft'), 'validfrom' => Yii::app()->request->getPost('validfrom'), 'validuntil' => Yii::app()->request->getPost('validuntil'));
         // add attributes
         $attrfieldnames = getTokenFieldsAndNames($iSurveyId, true);
         foreach ($attrfieldnames as $attr_name => $desc) {
             $value = Yii::app()->request->getPost($attr_name);
             if ($desc['mandatory'] == 'Y' && trim($value) == '') {
                 $this->getController()->error(sprintf($clang->gT('%s cannot be left empty'), $desc['description']));
             }
             $aData[$attr_name] = Yii::app()->request->getPost($attr_name);
         }
         $amount = sanitize_int(Yii::app()->request->getPost('amount'));
         $tokenlength = sanitize_int(Yii::app()->request->getPost('tokenlen'));
         // Fill an array with all existing tokens
         $existingtokens = array();
         $tokenModel = Token::model($iSurveyId);
         $criteria = $tokenModel->getDbCriteria();
         $criteria->select = 'token';
         $criteria->distinct = true;
         $command = $tokenModel->getCommandBuilder()->createFindCommand($tokenModel->getTableSchema(), $criteria);
         $result = $command->query();
         while ($tokenRow = $result->read()) {
             $existingtokens[$tokenRow['token']] = true;
         }
         $result->close();
         $invalidtokencount = 0;
         $newDummyToken = 0;
         while ($newDummyToken < $amount && $invalidtokencount < 50) {
             $token = Token::create($iSurveyId);
             $token->setAttributes($aData, false);
             $token->firstname = str_replace('{TOKEN_COUNTER}', $newDummyToken, $token->firstname);
             $token->lastname = str_replace('{TOKEN_COUNTER}', $newDummyToken, $token->lastname);
             $token->email = str_replace('{TOKEN_COUNTER}', $newDummyToken, $token->email);
             $attempts = 0;
             do {
                 $token->token = randomChars($tokenlength);
                 $attempts++;
             } while (isset($existingtokens[$token->token]) && $attempts < 50);
             if ($attempts == 50) {
                 throw new Exception('Something is wrong with your random generator.');
             }
             $existingtokens[$token->token] = true;
             $token->save();
             $newDummyToken++;
         }
         $aData['thissurvey'] = getSurveyInfo($iSurveyId);
         $aData['surveyid'] = $iSurveyId;
         if (!$invalidtokencount) {
             $aData['success'] = false;
             $message = array('title' => $clang->gT("Success"), 'message' => $clang->gT("New dummy tokens were added.") . "<br /><br />\n<input type='button' value='" . $clang->gT("Display tokens") . "' onclick=\"window.open('" . $this->getController()->createUrl("admin/tokens/sa/browse/surveyid/{$iSurveyId}") . "', '_top')\" />\n");
         } else {
             $aData['success'] = true;
             $message = array('title' => $clang->gT("Failed"), 'message' => "<p>" . sprintf($clang->gT("Only %s new dummy tokens were added after %s trials."), $newDummyToken, $invalidtokencount) . $clang->gT("Try with a bigger token length.") . "</p>" . "\n<input type='button' value='" . $clang->gT("Display tokens") . "' onclick=\"window.open('" . $this->getController()->createUrl("admin/tokens/sa/browse/surveyid/{$iSurveyId}") . "', '_top')\" />\n");
         }
         $this->_renderWrappedTemplate('token', array('tokenbar', 'message' => $message), $aData);
     } else {
         $tokenlength = !empty(Token::model($iSurveyId)->survey->tokenlength) ? Token::model($iSurveyId)->survey->tokenlength : 15;
         $thissurvey = getSurveyInfo($iSurveyId);
         $aData['thissurvey'] = $thissurvey;
         $aData['surveyid'] = $iSurveyId;
         $aData['tokenlength'] = $tokenlength;
         $aData['dateformatdetails'] = getDateFormatData(Yii::app()->session['dateformat'], $clang->langcode);
         $aData['aAttributeFields'] = GetParticipantAttributes($iSurveyId);
         $this->_renderWrappedTemplate('token', array('tokenbar', 'dummytokenform'), $aData);
     }
 }
Example #6
0
function createinsertquery()
{
    global $thissurvey, $timeadjust, $move, $thisstep;
    global $deletenonvalues, $thistpl;
    global $surveyid, $connect, $clang, $postedfieldnames, $bFinalizeThisAnswer;
    require_once "classes/inputfilter/class.inputfilter_clean.php";
    $myFilter = new InputFilter('', '', 1, 1, 1);
    $fieldmap = createFieldMap($surveyid);
    //Creates a list of the legitimate questions for this survey
    if (isset($_SESSION['insertarray']) && is_array($_SESSION['insertarray'])) {
        $inserts = array_unique($_SESSION['insertarray']);
        $colnames_hidden = array();
        foreach ($inserts as $value) {
            //Work out if the field actually exists in this survey
            $fieldexists = '';
            if (isset($fieldmap[$value])) {
                $fieldexists = $fieldmap[$value];
            }
            //Iterate through possible responses
            if (isset($_SESSION[$value]) && !empty($fieldexists)) {
                //Only create column name and data entry if there is actually data!
                $colnames[] = $value;
                //If deletenonvalues is ON, delete any values that shouldn't exist
                if ($deletenonvalues == 1 && !checkconfield($value)) {
                    $values[] = 'NULL';
                    $colnames_hidden[] = $value;
                } elseif ($_SESSION[$value] == '' && $fieldexists['type'] == 'D' || $_SESSION[$value] == '' && $fieldexists['type'] == 'K' || $_SESSION[$value] == '' && $fieldexists['type'] == 'N') {
                    // most databases do not allow to insert an empty value into a datefield,
                    // therefore if no date was chosen in a date question the insert value has to be NULL
                    $values[] = 'NULL';
                } else {
                    // Empty the 'Other' field if a value other than '-oth-' was set for the main field (prevent invalid other values being saved - for example if Javascript fails to hide the 'Other' input field)
                    if ($fieldexists['type'] == '!' && $fieldmap[$value]['aid'] == 'other' && isset($_POST[substr($value, 0, strlen($value) - 5)]) && $_POST[substr($value, 0, strlen($value) - 5)] != '-oth-') {
                        $_SESSION[$value] = '';
                    } elseif ($fieldexists['type'] == 'N') {
                        $_SESSION[$value] = sanitize_float($_SESSION[$value]);
                    } elseif ($fieldexists['type'] == 'D' && is_array($postedfieldnames) && in_array($value, $postedfieldnames)) {
                        // convert the date to the right DB Format but only if it was posted
                        $dateformatdatat = getDateFormatData($thissurvey['surveyls_dateformat']);
                        $datetimeobj = new Date_Time_Converter($_SESSION[$value], $dateformatdatat['phpdate']);
                        $_SESSION[$value] = $datetimeobj->convert("Y-m-d");
                        $_SESSION[$value] = $connect->BindDate($_SESSION[$value]);
                    }
                    $values[] = $connect->qstr($_SESSION[$value], get_magic_quotes_gpc());
                }
            }
        }
        if ($thissurvey['datestamp'] == "Y") {
            $_SESSION['datestamp'] = date_shift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust);
        }
        // First compute the submitdate
        if ($thissurvey['private'] == "Y" && $thissurvey['datestamp'] == "N") {
            // In case of anonymous answers survey with no datestamp
            // then the the answer submutdate gets a conventional timestamp
            // 1st Jan 1980
            $mysubmitdate = date("Y-m-d H:i:s", mktime(0, 0, 0, 1, 1, 1980));
        } else {
            $mysubmitdate = date_shift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust);
        }
        // CHECK TO SEE IF ROW ALREADY EXISTS
        // srid (=Survey Record ID ) is set when the there were already answers saved for that survey
        if (!isset($_SESSION['srid'])) {
            //Prepare row insertion
            if (!isset($colnames) || !is_array($colnames)) {
                echo submitfailed();
                exit;
            }
            // INSERT NEW ROW
            $query = "INSERT INTO " . db_quote_id($thissurvey['tablename']) . "\n" . "(" . implode(', ', array_map('db_quote_id', $colnames));
            $query .= "," . db_quote_id('lastpage');
            if ($thissurvey['datestamp'] == "Y") {
                $query .= "," . db_quote_id('datestamp');
                $query .= "," . db_quote_id('startdate');
            }
            if ($thissurvey['ipaddr'] == "Y") {
                $query .= "," . db_quote_id('ipaddr');
            }
            $query .= "," . db_quote_id('startlanguage');
            if ($thissurvey['refurl'] == "Y") {
                $query .= "," . db_quote_id('refurl');
            }
            if ($bFinalizeThisAnswer === true && $thissurvey['format'] != "A") {
                $query .= "," . db_quote_id('submitdate');
            }
            $query .= ") ";
            $query .= "VALUES (" . implode(", ", $values);
            $query .= "," . ($thisstep + 1);
            if ($thissurvey['datestamp'] == "Y") {
                $query .= ", '" . $_SESSION['datestamp'] . "'";
                $query .= ", '" . $_SESSION['datestamp'] . "'";
            }
            if ($thissurvey['ipaddr'] == "Y") {
                $query .= ", '" . $_SERVER['REMOTE_ADDR'] . "'";
            }
            $query .= ", '" . $_SESSION['s_lang'] . "'";
            if ($thissurvey['refurl'] == "Y") {
                $query .= ", '" . $_SESSION['refurl'] . "'";
            }
            if ($bFinalizeThisAnswer === true && $thissurvey['format'] != "A") {
                // is if a ALL-IN-ONE survey, we don't set the submit date before the data is validated
                $query .= ", " . $connect->DBDate($mysubmitdate);
            }
            $query .= ")";
        } else {
            // UPDATE EXISTING ROW
            // Updates only the MODIFIED fields posted on current page.
            if (isset($postedfieldnames) && $postedfieldnames) {
                $query = "UPDATE {$thissurvey['tablename']} SET ";
                $query .= " lastpage = '" . $thisstep . "',";
                if ($thissurvey['datestamp'] == "Y") {
                    $query .= " datestamp = '" . $_SESSION['datestamp'] . "',";
                }
                if ($thissurvey['ipaddr'] == "Y") {
                    $query .= " ipaddr = '" . $_SERVER['REMOTE_ADDR'] . "',";
                }
                // is if a ALL-IN-ONE survey, we don't set the submit date before the data is validated
                if ($bFinalizeThisAnswer === true && $thissurvey['format'] != "A") {
                    $query .= " submitdate = " . $connect->DBDate($mysubmitdate) . ", ";
                }
                // Resets fields hidden due to conditions
                if ($deletenonvalues == 1) {
                    $hiddenfields = array_unique(array_values($colnames_hidden));
                    foreach ($hiddenfields as $hiddenfield) {
                        //$fieldinfo = arraySearchByKey($hiddenfield, $fieldmap, "fieldname", 1);
                        //if ($fieldinfo['type']=='D' || $fieldinfo['type']=='N' || $fieldinfo['type']=='K')
                        //{
                        $query .= db_quote_id($hiddenfield) . " = NULL,";
                        //}
                        //else
                        //{
                        //	$query .= db_quote_id($hiddenfield)." = '',";
                        //}
                    }
                } else {
                    $hiddenfields = array();
                }
                $fields = $postedfieldnames;
                $fields = array_unique($fields);
                $fields = array_diff($fields, $hiddenfields);
                // Do not take fields that are hidden
                foreach ($fields as $field) {
                    if (!empty($field)) {
                        $fieldinfo = $fieldmap[$field];
                        if (!isset($_POST[$field])) {
                            $_POST[$field] = '';
                        }
                        //fixed numerical question fields. They have to be NULL instead of '' to avoid database errors
                        if ($_POST[$field] == '' && $fieldinfo['type'] == 'D' || $_POST[$field] == '' && $fieldinfo['type'] == 'N' || $_POST[$field] == '' && $fieldinfo['type'] == 'K') {
                            $query .= db_quote_id($field) . " = NULL,";
                        } else {
                            // Empty the 'Other' field if a value other than '-oth-' was set for the main field (prevent invalid other values being saved - for example if Javascript fails to hide the 'Other' input field)
                            if ($fieldinfo['type'] == '!' && $fieldmap[$field]['aid'] == 'other' && $_POST[substr($field, 0, strlen($field) - 5)] != '-oth-') {
                                $qfield = "''";
                            } elseif ($fieldinfo['type'] == 'N') {
                                $qfield = db_quoteall(sanitize_float($_POST[$field]));
                            } elseif ($fieldinfo['type'] == 'D') {
                                $dateformatdatat = getDateFormatData($thissurvey['surveyls_dateformat']);
                                $datetimeobj = new Date_Time_Converter($_POST[$field], $dateformatdatat['phpdate']);
                                $qfield = db_quoteall($connect->BindDate($datetimeobj->convert("Y-m-d")));
                            } else {
                                $qfield = db_quoteall($_POST[$field], true);
                            }
                            $query .= db_quote_id($field) . " = " . $qfield . ",";
                        }
                    }
                }
                $query .= "WHERE id=" . $_SESSION['srid'];
                $query = str_replace(",WHERE", " WHERE", $query);
                // remove comma before WHERE clause
            } else {
                $query = "";
                if ($bFinalizeThisAnswer === true) {
                    $query = "UPDATE {$thissurvey['tablename']} SET ";
                    $query .= " submitdate = " . $connect->DBDate($mysubmitdate);
                    $query .= " WHERE id=" . $_SESSION['srid'];
                }
            }
        }
        //DEBUG START
        //echo $query;
        //DEBUG END
        return $query;
    } else {
        sendcacheheaders();
        doHeader();
        foreach (file("{$thistpl}/startpage.pstpl") as $op) {
            echo templatereplace($op);
        }
        echo "<br /><center><font face='verdana' size='2'><font color='red'><strong>" . $clang->gT("Error") . "</strong></font><br /><br />\n";
        echo $clang->gT("Cannot submit results - there are none to submit.") . "<br /><br />\n";
        echo "<font size='1'>" . $clang->gT("This error can occur if you have already submitted your responses and pressed 'refresh' on your browser. In this case, your responses have already been saved.") . "<br /><br />" . $clang->gT("If you receive this message in the middle of completing a survey, you should choose '<- BACK' on your browser and then refresh/reload the previous page. While you will lose answers from the last page all your others will still exist. This problem can occur if the webserver is suffering from overload or excessive use. We apologise for this problem.") . "<br />\n";
        echo "</font></center><br /><br />";
        exit;
    }
}
     $hh = htmlspecialchars($hh, ENT_QUOTES);
     //Change & " ' < > to HTML entities to make HTML happy.
     $dataentryoutput .= "\t<img src='{$imageurl}/help.gif' alt='" . $blang->gT("Help about this question") . "' align='right' onclick=\"javascript:alert('Question {$deqrow['title']} Help: {$hh}')\" />\n";
 }
 switch ($deqrow['type']) {
     case "5":
         //5 POINT CHOICE radio-buttons
         $dataentryoutput .= "\t<select name='{$fieldname}'>\n" . "<option value=''>" . $blang->gT("No answer") . "</option>\n";
         for ($x = 1; $x <= 5; $x++) {
             $dataentryoutput .= "<option value='{$x}'>{$x}</option>\n";
         }
         $dataentryoutput .= "\t</select>\n";
         break;
     case "D":
         //DATE
         $datetimeobj = new Date_Time_Converter('', "Y-m-d H:i:s");
         $thisdate = $datetimeobj->convert($dateformatdetails['phpdate']);
         $dataentryoutput .= "\t<input type='text' class='popupdate' size='12' name='{$fieldname}'/>\n";
         break;
     case "G":
         //GENDER drop-down list
         $dataentryoutput .= "\t<select name='{$fieldname}'>\n" . "<option selected='selected' value=''>" . $blang->gT("Please choose") . "..</option>\n" . "<option value='F'>" . $blang->gT("Female") . "</option>\n" . "<option value='M'>" . $blang->gT("Male") . "</option>\n" . "\t</select>\n";
         break;
     case "Q":
         //MULTIPLE SHORT TEXT
     //MULTIPLE SHORT TEXT
     case "K":
         $deaquery = "SELECT question,title FROM " . db_table_name("questions") . " WHERE parent_qid={$deqrow['qid']} AND language='{$sDataEntryLanguage}' ORDER BY question_order";
         $dearesult = db_execute_assoc($deaquery);
         $dataentryoutput .= "\t<table>\n";
         while ($dearow = $dearesult->FetchRow()) {
 /**
  * Cleanse the $_POSTed data and update $_SESSION variables accordingly
  */
 static function ProcessCurrentResponses()
 {
     $LEM =& LimeExpressionManager::singleton();
     if (!isset($LEM->currentQset)) {
         return array();
     }
     $updatedValues = array();
     $radixchange = $LEM->surveyOptions['radix'] == ',' ? true : false;
     foreach ($LEM->currentQset as $qinfo) {
         $relevant = false;
         $qid = $qinfo['info']['qid'];
         $gseq = $qinfo['info']['gseq'];
         $relevant = isset($_POST['relevance' . $qid]) ? $_POST['relevance' . $qid] == 1 : false;
         $grelevant = isset($_POST['relevanceG' . $gseq]) ? $_POST['relevanceG' . $gseq] == 1 : false;
         $_SESSION[$LEM->sessid]['relevanceStatus'][$qid] = $relevant;
         $_SESSION[$LEM->sessid]['relevanceStatus']['G' . $gseq] = $grelevant;
         foreach (explode('|', $qinfo['sgqa']) as $sq) {
             $sqrelevant = true;
             if (isset($LEM->subQrelInfo[$qid][$sq]['rowdivid'])) {
                 $rowdivid = $LEM->subQrelInfo[$qid][$sq]['rowdivid'];
                 if ($rowdivid != '' && isset($_POST['relevance' . $rowdivid])) {
                     $sqrelevant = $_POST['relevance' . $rowdivid] == 1;
                     $_SESSION[$LEM->sessid]['relevanceStatus'][$rowdivid] = $sqrelevant;
                 }
             }
             $type = $qinfo['info']['type'];
             if ($relevant && $grelevant && $sqrelevant) {
                 if ($qinfo['info']['hidden'] && !isset($_POST[$sq])) {
                     $value = isset($_SESSION[$LEM->sessid][$sq]) ? $_SESSION[$LEM->sessid][$sq] : '';
                     // if always hidden, use the default value, if any
                 } else {
                     $value = isset($_POST[$sq]) ? $_POST[$sq] : '';
                 }
                 if ($radixchange && isset($LEM->knownVars[$sq]['onlynum']) && $LEM->knownVars[$sq]['onlynum'] == '1') {
                     // convert from comma back to decimal
                     $value = implode('.', explode(',', $value));
                 }
                 switch ($type) {
                     case 'D':
                         //DATE
                         if (trim($value) == "") {
                             $value = "";
                         } else {
                             $dateformatdatat = getDateFormatData($LEM->surveyOptions['surveyls_dateformat']);
                             $datetimeobj = new Date_Time_Converter($value, $dateformatdatat['phpdate']);
                             $value = $datetimeobj->convert("Y-m-d");
                         }
                         break;
                     case 'N':
                         //NUMERICAL QUESTION TYPE
                     //NUMERICAL QUESTION TYPE
                     case 'K':
                         //MULTIPLE NUMERICAL QUESTION
                         if (trim($value) == "") {
                             $value = "";
                         } else {
                             $value = sanitize_float($value);
                         }
                         break;
                     case '|':
                         //File Upload
                         if (!preg_match('/_filecount$/', $sq)) {
                             $json = $value;
                             $phparray = json_decode(stripslashes($json));
                             // if the files have not been saved already,
                             // move the files from tmp to the files folder
                             $tmp = $LEM->surveyOptions['tempdir'] . 'upload' . DIRECTORY_SEPARATOR;
                             if (!is_null($phparray) && count($phparray) > 0) {
                                 // Move the (unmoved, temp) files from temp to files directory.
                                 // Check all possible file uploads
                                 for ($i = 0; $i < count($phparray); $i++) {
                                     if (file_exists($tmp . $phparray[$i]->filename)) {
                                         $sDestinationFileName = 'fu_' . randomChars(15);
                                         if (!is_dir($LEM->surveyOptions['target'])) {
                                             mkdir($LEM->surveyOptions['target'], 0777, true);
                                         }
                                         if (!rename($tmp . $phparray[$i]->filename, $LEM->surveyOptions['target'] . $sDestinationFileName)) {
                                             echo "Error moving file to target destination";
                                         }
                                         $phparray[$i]->filename = $sDestinationFileName;
                                     }
                                 }
                                 $value = ls_json_encode($phparray);
                                 // so that EM doesn't try to parse it.
                             }
                         }
                         break;
                 }
                 $_SESSION[$LEM->sessid][$sq] = $value;
                 $_update = array('type' => $type, 'value' => $value);
                 $updatedValues[$sq] = $_update;
                 $LEM->updatedValues[$sq] = $_update;
             } else {
                 // irrelevant, so database will be NULLed separately
                 // Must unset the value, rather than setting to '', so that EM can re-use the default value as needed.
                 unset($_SESSION[$LEM->sessid][$sq]);
                 $_update = array('type' => $type, 'value' => NULL);
                 $updatedValues[$sq] = $_update;
                 $LEM->updatedValues[$sq] = $_update;
             }
         }
     }
     if (isset($_POST['timerquestion'])) {
         $_SESSION[$LEM->sessid][$_POST['timerquestion']] = sanitize_float($_POST[$_POST['timerquestion']]);
     }
     return $updatedValues;
 }
/**
 * This is a convenience function for the coversion of datetime values
 *
 * @param mixed $value
 * @param mixed $fromdateformat
 * @param mixed $todateformat
 * @return string
 */
function convertDateTimeFormat($value, $fromdateformat, $todateformat)
{
    $datetimeobj = new Date_Time_Converter($value, $fromdateformat);
    return $datetimeobj->convert($todateformat);
}
Example #10
0
     <label  class="col-sm-2 control-label" for='usesleft'><?php eT("Uses left:"); ?></label>
     <div class="col-sm-10">
         <input type='text' size='20' id='usesleft' name='usesleft' value="1" />
     </div>
 </div>
 
 <!--  Validity -->
 <div class="form-group">
     <label  class="col-sm-2 control-label" for='validfrom'><?php eT("Valid from"); ?>:</label>
     <div class="col-sm-3">
         <input type='text' class='popupdatetime' size='20' id='validfrom' name='validfrom' value="<?php if (isset($validfrom)){$datetimeobj = new Date_Time_Converter($validfrom, "Y-m-d H:i:s");echo $datetimeobj->convert($dateformatdetails['phpdate'] . ' H:i');}?>" /> 
     </div>        
     
     <label  class="col-sm-2 control-label" for='validuntil'><?php eT('until'); ?></label>
     <div class="col-sm-3">
         <input type='text' size='20' id='validuntil' name='validuntil' class='popupdatetime' value="<?php if (isset($validuntil)){$datetimeobj = new Date_Time_Converter($validuntil, "Y-m-d H:i:s");echo $datetimeobj->convert($dateformatdetails['phpdate'] . ' H:i');}?>" /> 
         <span class="help-block"><?php printf(gT('Format: %s'), $dateformatdetails['dateformat'] . ' ' . gT('hh:mm')); ?></span>
     </div>
 </div>
 
 <!-- Attribute fields  -->
 <?php foreach ($aAttributeFields as $attr_name => $attr_description): ?>
     <div class="form-group">
         <label  class="col-sm-2 control-label" for='<?php echo $attr_name; ?>'><?php echo $attr_description['description'] . ($attr_description['mandatory'] == 'Y' ? '*' : '') ?>:</label>
         <div class="col-sm-10">
             <input type='text' size='55' id='<?php echo $attr_name; ?>' name='<?php echo $attr_name; ?>' value='<?php if (isset($$attr_name)){echo htmlspecialchars($$attr_name, ENT_QUOTES, 'UTF-8');}?>' />
         </div>
     </div>
 <?php endforeach; ?>
 
 <!-- Buttons  -->
Example #11
0
function do_date($ia)
{
    global $clang, $js_header_includes, $css_header_includes, $thissurvey;
    $qidattributes=getQuestionAttributes($ia[0],$ia[4]);
    $js_header_includes[] = '/scripts/jquery/jquery-ui.js';
    $js_header_includes[] = '/scripts/jquery/lime-calendar.js';


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

    $dateformatdetails=getDateFormatData($thissurvey['surveyls_dateformat']);
    $numberformatdatat = getRadixPointData($thissurvey['surveyls_numberformat']);

    if (trim($qidattributes['dropdown_dates'])!=0) {
        if (!empty($_SESSION[$ia[1]]))
        {
            list($currentyear, $currentmonth, $currentdate) = explode('-', $_SESSION[$ia[1]]);
        } else {
            $currentdate='';
            $currentmonth='';
            $currentyear='';
        }

        $dateorder = preg_split('/[-\.\/ ]/', $dateformatdetails['phpdate']);
        $answer='<p class="question">';
        foreach($dateorder as $datepart)
        {
            switch($datepart)
            {
                // Show day select box
                case 'j':
                case 'd':   $answer .= ' <select id="day'.$ia[1].'" class="day">
                                                <option value="">'.$clang->gT('Day')."</option>\n";
                for ($i=1; $i<=31; $i++) {
                    if ($i == $currentdate)
                    {
                        $i_date_selected = SELECTED;
                    }
                    else
                    {
                        $i_date_selected = '';
                    }
                    $answer .= '    <option value="'.sprintf('%02d', $i).'"'.$i_date_selected.'>'.sprintf('%02d', $i)."</option>\n";
                }
                $answer .='</select>';
                break;
                // Show month select box
                case 'n':
                case 'm':   $answer .= ' <select id="month'.$ia[1].'" class="month">
                                            <option value="">'.$clang->gT('Month')."</option>\n";
                $montharray=array(
                $clang->gT('Jan'),
                $clang->gT('Feb'),
                $clang->gT('Mar'),
                $clang->gT('Apr'),
                $clang->gT('May'),
                $clang->gT('Jun'),
                $clang->gT('Jul'),
                $clang->gT('Aug'),
                $clang->gT('Sep'),
                $clang->gT('Oct'),
                $clang->gT('Nov'),
                $clang->gT('Dec'));
                for ($i=1; $i<=12; $i++) {
                    if ($i == $currentmonth)
                    {
                        $i_date_selected = SELECTED;
                    }
                    else
                    {
                        $i_date_selected = '';
                    }

                    $answer .= '    <option value="'.sprintf('%02d', $i).'"'.$i_date_selected.'>'.$montharray[$i-1].'</option>';
                }
                $answer .= '    </select>';
                break;
                // Show year select box
                case 'Y':   $answer .= ' <select id="year'.$ia[1].'" class="year">
                                            <option value="">'.$clang->gT('Year').'</option>';

                /*
                 *  New question attributes used only if question attribute
                 * "dropdown_dates" is used (see IF(...) above).
                 *
                 * yearmin = Minimum year value for dropdown list, if not set default is 1900
                 * yearmax = Maximum year value for dropdown list, if not set default is 2020
                 */
                if (trim($qidattributes['dropdown_dates_year_min'])!='')
                {
                    $yearmin = $qidattributes['dropdown_dates_year_min'];
                }
                else
                {
                    $yearmin = 1900;
                }

                if (trim($qidattributes['dropdown_dates_year_max'])!='')
                {
                    $yearmax = $qidattributes['dropdown_dates_year_max'];
                }
                else
                {
                    $yearmax = 2020;
                }

                if ($yearmin > $yearmax)
                {
                    $yearmin = 1900;
                    $yearmax = 2020;
                }

                if ($qidattributes['reverse']==1)
                {
                    $tmp = $yearmin;
                    $yearmin = $yearmax;
                    $yearmax = $tmp;
                    $step = 1;
                    $reverse = true;
                }
                else
                {
                    $step = -1;
                    $reverse = false;
                }

                for ($i=$yearmax; ($reverse? $i<=$yearmin: $i>=$yearmin); $i+=$step) {
                    if ($i == $currentyear)
                    {
                        $i_date_selected = SELECTED;
                    }
                    else
                    {
                        $i_date_selected = '';
                    }
                    $answer .= '  <option value="'.$i.'"'.$i_date_selected.'>'.$i.'</option>';
                }
                $answer .= '</select>';

                break;
            }
        }

        $answer .= '<input class="text" type="text" size="10" name="'.$ia[1].'" style="display: none" id="answer'.$ia[1].'" value="'.$_SESSION[$ia[1]].'" maxlength="10" alt="'.$clang->gT('Answer').'" onchange="'.$checkconditionFunction.'(this.value, this.name, this.type)" />
			</p>';
        $answer .= '<input type="hidden" name="qattribute_answer[]" value="'.$ia[1].'" />
			        <input type="hidden" id="qattribute_answer'.$ia[1].'" name="qattribute_answer'.$ia[1].'" />
                    <input type="hidden" id="dateformat'.$ia[1].'" value="'.$dateformatdetails['jsdate'].'"/>';


    }
    else
    {
        if ($clang->langcode !== 'en')
        {
        $js_header_includes[] = '/scripts/jquery/locale/jquery.ui.datepicker-'.$clang->langcode.'.js';
        }
        $css_header_includes[]= '/scripts/jquery/css/start/jquery-ui.css';

        // Format the date  for output
        if (trim($_SESSION[$ia[1]])!='')
        {
            $datetimeobj = new Date_Time_Converter($_SESSION[$ia[1]] , "Y-m-d");
            $dateoutput=$datetimeobj->convert($dateformatdetails['phpdate']);
        }
        else
        {
            $dateoutput='';
        }

        if (trim($qidattributes['dropdown_dates_year_min'])!='') {
            $minyear=$qidattributes['dropdown_dates_year_min'];
        }
        else
        {
            $minyear='1980';
        }

        if (trim($qidattributes['dropdown_dates_year_max'])!='') {
            $maxyear=$qidattributes['dropdown_dates_year_max'];
        }
        else
        {
            $maxyear='2020';
        }

        $goodchars = str_replace( array("m","d","y"), "", $dateformatdetails['jsdate']);
        $goodchars = "0123456789".$goodchars[0];

        $answer ="<p class=\"question\">
                        <input class='popupdate' type=\"text\" alt=\"".$clang->gT('Date picker')."\" size=\"10\" name=\"{$ia[1]}\" id=\"answer{$ia[1]}\" value=\"$dateoutput\" maxlength=\"10\" onkeypress=\"return goodchars(event,'".$goodchars."')\" onchange=\"$checkconditionFunction(this.value, this.name, this.type)\" />
                        <input  type='hidden' name='dateformat{$ia[1]}' id='dateformat{$ia[1]}' value='{$dateformatdetails['jsdate']}'  />
                        <input  type='hidden' name='datelanguage{$ia[1]}' id='datelanguage{$ia[1]}' value='{$clang->langcode}'  />
                        <input  type='hidden' name='dateyearrange{$ia[1]}' id='dateyearrange{$ia[1]}' value='{$minyear}:{$maxyear}'  />

			         </p>
			         <p class=\"tip\">
				         ".sprintf($clang->gT('Format: %s'),$dateformatdetails['dateformat'])."
			         </p>";
    }
    $inputnames[]=$ia[1];

    return array($answer, $inputnames);
}
Example #12
0
 /**
  * Add dummy tokens form
  */
 function addDummies($iSurveyId, $subaction = '')
 {
     // CHECK TO SEE IF A TOKEN TABLE EXISTS FOR THIS SURVEY
     $bTokenExists = tableExists('{{tokens_' . $iSurveyId . '}}');
     if (!$bTokenExists) {
         self::_newtokentable($iSurveyId);
     }
     $iSurveyId = sanitize_int($iSurveyId);
     $clang = $this->getController()->lang;
     if (!hasSurveyPermission($iSurveyId, 'tokens', 'create')) {
         die("No permissions.");
         // TODO Replace
     }
     $this->getController()->loadHelper("surveytranslator");
     if (!empty($subaction) && $subaction == 'add') {
         $this->getController()->loadLibrary('Date_Time_Converter');
         $dateformatdetails = getDateFormatData(Yii::app()->session['dateformat']);
         //Fix up dates and match to database format
         if (trim(Yii::app()->request->getPost('validfrom')) == '') {
             $_POST['validfrom'] = null;
         } else {
             $datetimeobj = new Date_Time_Converter(trim(Yii::app()->request->getPost('validfrom')), $dateformatdetails['phpdate'] . ' H:i');
             $_POST['validfrom'] = $datetimeobj->convert('Y-m-d H:i:s');
         }
         if (trim(Yii::app()->request->getPost('validuntil')) == '') {
             $_POST['validuntil'] = null;
         } else {
             $datetimeobj = new Date_Time_Converter(trim(Yii::app()->request->getPost('validuntil')), $dateformatdetails['phpdate'] . ' H:i');
             $_POST['validuntil'] = $datetimeobj->convert('Y-m-d H:i:s');
         }
         $santitizedtoken = '';
         $aData = array('firstname' => Yii::app()->request->getPost('firstname'), 'lastname' => Yii::app()->request->getPost('lastname'), 'email' => sanitize_email(Yii::app()->request->getPost('email')), 'emailstatus' => 'OK', 'token' => $santitizedtoken, 'language' => sanitize_languagecode(Yii::app()->request->getPost('language')), 'sent' => 'N', 'remindersent' => 'N', 'completed' => 'N', 'usesleft' => Yii::app()->request->getPost('usesleft'), 'validfrom' => Yii::app()->request->getPost('validfrom'), 'validuntil' => Yii::app()->request->getPost('validuntil'));
         // add attributes
         $attrfieldnames = Survey::model()->findByPk($iSurveyId)->tokenAttributes;
         foreach ($attrfieldnames as $attr_name => $desc) {
             $value = Yii::app()->request->getPost($attr_name);
             if ($desc['mandatory'] == 'Y' && trim($value) == '') {
                 $this->getController()->error(sprintf($clang->gT('%s cannot be empty'), $desc['description']));
             }
             $aData[$attr_name] = Yii::app()->request->getPost($attr_name);
         }
         $amount = sanitize_int(Yii::app()->request->getPost('amount'));
         $tokenlength = sanitize_int(Yii::app()->request->getPost('tokenlen'));
         // Fill an array with all existing tokens
         $criteria = Tokens_dynamic::model($iSurveyId)->getDbCriteria();
         $criteria->select = 'token';
         $ntresult = Tokens_dynamic::model($iSurveyId)->findAllAsArray($criteria);
         //Use AsArray to skip active record creation
         $existingtokens = array();
         foreach ($ntresult as $tkrow) {
             $existingtokens[$tkrow['token']] = true;
         }
         $invalidtokencount = 0;
         $newDummyToken = 0;
         while ($newDummyToken < $amount && $invalidtokencount < 50) {
             $aDataToInsert = $aData;
             $aDataToInsert['firstname'] = str_replace('{TOKEN_COUNTER}', $newDummyToken, $aDataToInsert['firstname']);
             $aDataToInsert['lastname'] = str_replace('{TOKEN_COUNTER}', $newDummyToken, $aDataToInsert['lastname']);
             $aDataToInsert['email'] = str_replace('{TOKEN_COUNTER}', $newDummyToken, $aDataToInsert['email']);
             $isvalidtoken = false;
             while ($isvalidtoken == false && $invalidtokencount < 50) {
                 $newtoken = randomChars($tokenlength);
                 if (!isset($existingtokens[$newtoken])) {
                     $isvalidtoken = true;
                     $existingtokens[$newtoken] = true;
                     $invalidtokencount = 0;
                 } else {
                     $invalidtokencount++;
                 }
             }
             if ($isvalidtoken) {
                 $aDataToInsert['token'] = $newtoken;
                 Tokens_dynamic::model()->insertToken($iSurveyId, $aDataToInsert);
                 $newDummyToken++;
             }
         }
         $aData['thissurvey'] = getSurveyInfo($iSurveyId);
         $aData['surveyid'] = $iSurveyId;
         if (!$invalidtokencount) {
             $aData['success'] = false;
             $message = array('title' => $clang->gT("Success"), 'message' => $clang->gT("New dummy tokens were added.") . "<br /><br />\n<input type='button' value='" . $clang->gT("Display tokens") . "' onclick=\"window.open('" . $this->getController()->createUrl("admin/tokens/browse/surveyid/{$iSurveyId}") . "', '_top')\" />\n");
         } else {
             $aData['success'] = true;
             $message = array('title' => $clang->gT("Failed"), 'message' => "<p>" . sprintf($clang->gT("Only %s new dummy tokens were added after %s trials."), $newDummyToken, $invalidtokencount) . $clang->gT("Try with a bigger token length.") . "</p>" . "\n<input type='button' value='" . $clang->gT("Display tokens") . "' onclick=\"window.open('" . $this->getController()->createUrl("admin/tokens/browse/surveyid/{$iSurveyId}") . "', '_top')\" />\n");
         }
         $this->_renderWrappedTemplate('token', array('tokenbar', 'message' => $message), $aData);
     } else {
         $tkcount = Tokens_dynamic::model($iSurveyId)->count();
         $tokenlength = Yii::app()->db->createCommand()->select('tokenlength')->from('{{surveys}}')->where('sid=:sid')->bindParam(":sid", $iSurveyId, PDO::PARAM_INT)->query()->readColumn(0);
         if (empty($tokenlength)) {
             $tokenlength = 15;
         }
         $thissurvey = getSurveyInfo($iSurveyId);
         $aData['thissurvey'] = $thissurvey;
         $aData['surveyid'] = $iSurveyId;
         $aData['tokenlength'] = $tokenlength;
         $aData['dateformatdetails'] = getDateFormatData(Yii::app()->session['dateformat'], $clang->langcode);
         $this->_renderWrappedTemplate('token', array('tokenbar', 'dummytokenform'), $aData);
     }
 }
Example #13
0
function do_date($ia)
{
    global $thissurvey;
    header_includes(Yii::app()->getConfig("generalscripts") . 'date.js', 'js');
    $clang = Yii::app()->lang;
    $aQuestionAttributes = getQuestionAttributeValues($ia[0], $ia[4]);
    $checkconditionFunction = "checkconditions";
    $dateformatdetails = getDateFormatDataForQID($aQuestionAttributes, $thissurvey);
    $numberformatdatat = getRadixPointData($thissurvey['surveyls_numberformat']);
    if (trim($aQuestionAttributes['dropdown_dates']) == 1) {
        if (!empty($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$ia[1]])) {
            $datetimeobj = getdate(DateTime::createFromFormat("Y-m-d H:i:s", $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$ia[1]])->getTimeStamp());
            $currentyear = $datetimeobj['year'];
            $currentmonth = $datetimeobj['mon'];
            $currentdate = $datetimeobj['mday'];
            $currenthour = $datetimeobj['hours'];
            $currentminute = $datetimeobj['minutes'];
        } else {
            $currentdate = '';
            $currentmonth = '';
            $currentyear = '';
            $currenthour = '';
            $currentminute = '';
        }
        $dateorder = preg_split('/([-\\.\\/ :])/', $dateformatdetails['phpdate'], -1, PREG_SPLIT_DELIM_CAPTURE);
        $answer = '<p class="question answer-item dropdown-item date-item">';
        foreach ($dateorder as $datepart) {
            switch ($datepart) {
                // Show day select box
                case 'j':
                case 'd':
                    $answer .= '<label for="day' . $ia[1] . '" class="hide">' . $clang->gT('Day') . '</label><select id="day' . $ia[1] . '" name="day' . $ia[1] . '" class="day">
                    <option value="">' . $clang->gT('Day') . "</option>\n";
                    for ($i = 1; $i <= 31; $i++) {
                        if ($i == $currentdate) {
                            $i_date_selected = SELECTED;
                        } else {
                            $i_date_selected = '';
                        }
                        $answer .= '<option value="' . sprintf('%02d', $i) . '"' . $i_date_selected . '>' . sprintf('%02d', $i) . "</option>\n";
                    }
                    $answer .= '</select>';
                    break;
                    // Show month select box
                // Show month select box
                case 'n':
                case 'm':
                    $answer .= '<label for="month' . $ia[1] . '" class="hide">' . $clang->gT('Month') . '</label><select id="month' . $ia[1] . '" name="month' . $ia[1] . '" class="month">
                    <option value="">' . $clang->gT('Month') . "</option>\n";
                    $montharray = array($clang->gT('Jan'), $clang->gT('Feb'), $clang->gT('Mar'), $clang->gT('Apr'), $clang->gT('May'), $clang->gT('Jun'), $clang->gT('Jul'), $clang->gT('Aug'), $clang->gT('Sep'), $clang->gT('Oct'), $clang->gT('Nov'), $clang->gT('Dec'));
                    for ($i = 1; $i <= 12; $i++) {
                        if ($i == $currentmonth) {
                            $i_date_selected = SELECTED;
                        } else {
                            $i_date_selected = '';
                        }
                        $answer .= '<option value="' . sprintf('%02d', $i) . '"' . $i_date_selected . '>' . $montharray[$i - 1] . '</option>';
                    }
                    $answer .= '</select>';
                    break;
                    // Show year select box
                // Show year select box
                case 'Y':
                    $answer .= '<label for="year' . $ia[1] . '" class="hide">' . $clang->gT('Year') . '</label><select id="year' . $ia[1] . '" name="year' . $ia[1] . '" class="year">
                    <option value="">' . $clang->gT('Year') . '</option>';
                    /*
                     *  New question attributes used only if question attribute
                     * "dropdown_dates" is used (see IF(...) above).
                     *
                     * yearmin = Minimum year value for dropdown list, if not set default is 1900
                     * yearmax = Maximum year value for dropdown list, if not set default is 2020
                     */
                    if (trim($aQuestionAttributes['dropdown_dates_year_min']) != '') {
                        $yearmin = $aQuestionAttributes['dropdown_dates_year_min'];
                    } else {
                        $yearmin = 1900;
                    }
                    if (trim($aQuestionAttributes['dropdown_dates_year_max']) != '') {
                        $yearmax = $aQuestionAttributes['dropdown_dates_year_max'];
                    } else {
                        $yearmax = 2020;
                    }
                    if ($yearmin > $yearmax) {
                        $yearmin = 1900;
                        $yearmax = 2020;
                    }
                    if ($aQuestionAttributes['reverse'] == 1) {
                        $tmp = $yearmin;
                        $yearmin = $yearmax;
                        $yearmax = $tmp;
                        $step = 1;
                        $reverse = true;
                    } else {
                        $step = -1;
                        $reverse = false;
                    }
                    for ($i = $yearmax; $reverse ? $i <= $yearmin : $i >= $yearmin; $i += $step) {
                        if ($i == $currentyear) {
                            $i_date_selected = SELECTED;
                        } else {
                            $i_date_selected = '';
                        }
                        $answer .= '<option value="' . $i . '"' . $i_date_selected . '>' . $i . '</option>';
                    }
                    $answer .= '</select>';
                    break;
                case 'H':
                case 'h':
                case 'g':
                case 'G':
                    $answer .= '<label for="hour' . $ia[1] . '" class="hide">' . $clang->gT('Hour') . '</label><select id="hour' . $ia[1] . '" name="hour' . $ia[1] . '" class="hour"><option value="">' . $clang->gT('Hour') . '</option>';
                    for ($i = 0; $i < 24; $i++) {
                        if ($i === $currenthour) {
                            $i_date_selected = SELECTED;
                        } else {
                            $i_date_selected = '';
                        }
                        if ($datepart == 'H') {
                            $answer .= '<option value="' . $i . '"' . $i_date_selected . '>' . sprintf('%02d', $i) . '</option>';
                        } else {
                            $answer .= '<option value="' . $i . '"' . $i_date_selected . '>' . $i . '</option>';
                        }
                    }
                    $answer .= '</select>';
                    break;
                case 'i':
                    $answer .= '<label for="minute' . $ia[1] . '" class="hide">' . $clang->gT('Minute') . '</label><select id="minute' . $ia[1] . '" name="minute' . $ia[1] . '" class="minute">
                    <option value="">' . $clang->gT('Minute') . '</option>';
                    for ($i = 0; $i < 60; $i += $aQuestionAttributes['dropdown_dates_minute_step']) {
                        if ($i === $currentminute) {
                            $i_date_selected = SELECTED;
                        } else {
                            $i_date_selected = '';
                        }
                        if ($datepart == 'i') {
                            $answer .= '<option value="' . $i . '"' . $i_date_selected . '>' . sprintf('%02d', $i) . '</option>';
                        } else {
                            $answer .= '<option value="' . $i . '"' . $i_date_selected . '>' . $i . '</option>';
                        }
                    }
                    $answer .= '</select>';
                    break;
                default:
                    $answer .= $datepart;
            }
        }
        $answer .= '<input class="text" type="text" size="10" name="' . $ia[1] . '" style="display: none" id="answer' . $ia[1] . '" value="' . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$ia[1]] . '" maxlength="10" alt="' . $clang->gT('Answer') . '" onchange="' . $checkconditionFunction . '(this.value, this.name, this.type)" />
        </p>';
        $answer .= '<input type="hidden" name="qattribute_answer[]" value="' . $ia[1] . '" />
        <input type="hidden" id="qattribute_answer' . $ia[1] . '" name="qattribute_answer' . $ia[1] . '" />
        <input type="hidden" id="dateformat' . $ia[1] . '" value="' . $dateformatdetails['jsdate'] . '"/>';
    } else {
        header_includes(Yii::app()->getConfig("generalscripts") . 'jquery/lime-calendar.js');
        if ($clang->langcode !== 'en') {
            header_includes(Yii::app()->getConfig("generalscripts") . 'jquery/locale/jquery.ui.datepicker-' . $clang->langcode . '.js');
        }
        // Format the date  for output
        if (trim($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$ia[1]]) != '') {
            $datetimeobj = new Date_Time_Converter($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$ia[1]], "Y-m-d");
            $dateoutput = $datetimeobj->convert($dateformatdetails['phpdate']);
        } else {
            $dateoutput = '';
        }
        if (trim($aQuestionAttributes['dropdown_dates_year_min']) != '') {
            $minyear = $aQuestionAttributes['dropdown_dates_year_min'];
        } else {
            $minyear = '1980';
        }
        if (trim($aQuestionAttributes['dropdown_dates_year_max']) != '') {
            $maxyear = $aQuestionAttributes['dropdown_dates_year_max'];
        } else {
            $maxyear = '2020';
        }
        $goodchars = str_replace(array("m", "d", "y"), "", $dateformatdetails['jsdate']);
        $goodchars = "0123456789" . $goodchars[0];
        $answer = "<p class='question answer-item text-item date-item'><label for='answer{$ia[1]}' class='hide label'>{$clang->gT('Date picker')}</label>\n        <input class='popupdate' type=\"text\" size=\"10\" name=\"{$ia[1]}\" title='" . sprintf($clang->gT('Format: %s'), $dateformatdetails['dateformat']) . "' id=\"answer{$ia[1]}\" value=\"{$dateoutput}\" maxlength=\"10\" onkeypress=\"return goodchars(event,'" . $goodchars . "')\" onchange=\"{$checkconditionFunction}(this.value, this.name, this.type)\" />\n        <input  type='hidden' name='dateformat{$ia[1]}' id='dateformat{$ia[1]}' value='{$dateformatdetails['jsdate']}'  />\n        <input  type='hidden' name='datelanguage{$ia[1]}' id='datelanguage{$ia[1]}' value='{$clang->langcode}'  />\n        <input  type='hidden' name='dateyearrange{$ia[1]}' id='dateyearrange{$ia[1]}' value='{$minyear}:{$maxyear}'  />\n\n        </p>";
        if (trim($aQuestionAttributes['hide_tip']) == 1) {
            $answer .= "<p class=\"tip\">" . sprintf($clang->gT('Format: %s'), $dateformatdetails['dateformat']) . "</p>";
        }
    }
    $inputnames[] = $ia[1];
    return array($answer, $inputnames);
}
 /**
  * Get the date if survey is future
  * @param $iSurveyId
  * @return localized date
  */
 public function getStartDate($iSurveyId)
 {
     $aSurveyInfo = getSurveyInfo($iSurveyId, Yii::app()->language);
     if (empty($aSurveyInfo['startdate']) || dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", Yii::app()->getConfig("timeadjust")) >= $aSurveyInfo['startdate']) {
         return;
     }
     Yii::app()->loadHelper("surveytranslator");
     $aDateFormat = getDateFormatData(getDateFormatForSID($iSurveyId, Yii::app()->language), Yii::app()->language);
     $datetimeobj = new Date_Time_Converter($aSurveyInfo['startdate'], 'Y-m-d H:i:s');
     return $datetimeobj->convert($aDateFormat['phpdate']);
 }
 /**
  * Show survey summary
  * @param int Survey id
  * @param string Action to be performed
  */
 function _surveysummary($iSurveyID, $action = null, $gid = null)
 {
     $clang = $this->getController()->lang;
     $baselang = Survey::model()->findByPk($iSurveyID)->language;
     $condition = array('sid' => $iSurveyID, 'language' => $baselang);
     $sumresult1 = Survey::model()->with(array('languagesettings' => array('condition' => 'surveyls_language=language')))->findByPk($iSurveyID);
     //$sumquery1, 1) ; //Checked
     if (is_null($sumresult1)) {
         Yii::app()->session['flashmessage'] = $clang->gT("Invalid survey ID");
         $this->getController()->redirect($this->getController()->createUrl("admin/index"));
     }
     //  if surveyid is invalid then die to prevent errors at a later time
     $surveyinfo = $sumresult1->attributes;
     $surveyinfo = array_merge($surveyinfo, $sumresult1->languagesettings[0]->attributes);
     $surveyinfo = array_map('flattenText', $surveyinfo);
     //$surveyinfo = array_map('htmlspecialchars', $surveyinfo);
     $activated = $surveyinfo['active'];
     $condition = array('sid' => $iSurveyID, 'parent_qid' => 0, 'language' => $baselang);
     $sumresult3 = Questions::model()->findAllByAttributes($condition);
     //Checked
     $sumcount3 = count($sumresult3);
     $condition = array('sid' => $iSurveyID, 'language' => $baselang);
     //$sumquery2 = "SELECT * FROM ".db_table_name('groups')." WHERE sid={$iSurveyID} AND language='".$baselang."'"; //Getting a count of groups for this survey
     $sumresult2 = Groups::model()->findAllByAttributes($condition);
     //Checked
     $sumcount2 = count($sumresult2);
     //SURVEY SUMMARY
     $aAdditionalLanguages = Survey::model()->findByPk($iSurveyID)->additionalLanguages;
     $surveysummary2 = "";
     if ($surveyinfo['anonymized'] != "N") {
         $surveysummary2 .= $clang->gT("Responses to this survey are anonymized.") . "<br />";
     } else {
         $surveysummary2 .= $clang->gT("Responses to this survey are NOT anonymized.") . "<br />";
     }
     if ($surveyinfo['format'] == "S") {
         $surveysummary2 .= $clang->gT("It is presented question by question.") . "<br />";
     } elseif ($surveyinfo['format'] == "G") {
         $surveysummary2 .= $clang->gT("It is presented group by group.") . "<br />";
     } else {
         $surveysummary2 .= $clang->gT("It is presented on one single page.") . "<br />";
     }
     if ($surveyinfo['allowjumps'] == "Y") {
         if ($surveyinfo['format'] == 'A') {
             $surveysummary2 .= $clang->gT("No question index will be shown with this format.") . "<br />";
         } else {
             $surveysummary2 .= $clang->gT("A question index will be shown; participants will be able to jump between viewed questions.") . "<br />";
         }
     }
     if ($surveyinfo['datestamp'] == "Y") {
         $surveysummary2 .= $clang->gT("Responses will be date stamped.") . "<br />";
     }
     if ($surveyinfo['ipaddr'] == "Y") {
         $surveysummary2 .= $clang->gT("IP Addresses will be logged") . "<br />";
     }
     if ($surveyinfo['refurl'] == "Y") {
         $surveysummary2 .= $clang->gT("Referrer URL will be saved.") . "<br />";
     }
     if ($surveyinfo['usecookie'] == "Y") {
         $surveysummary2 .= $clang->gT("It uses cookies for access control.") . "<br />";
     }
     if ($surveyinfo['allowregister'] == "Y") {
         $surveysummary2 .= $clang->gT("If tokens are used, the public may register for this survey") . "<br />";
     }
     if ($surveyinfo['allowsave'] == "Y" && $surveyinfo['tokenanswerspersistence'] == 'N') {
         $surveysummary2 .= $clang->gT("Participants can save partially finished surveys") . "<br />\n";
     }
     if ($surveyinfo['emailnotificationto'] != '') {
         $surveysummary2 .= $clang->gT("Basic email notification is sent to:") . " {$surveyinfo['emailnotificationto']}<br />\n";
     }
     if ($surveyinfo['emailresponseto'] != '') {
         $surveysummary2 .= $clang->gT("Detailed email notification with response data is sent to:") . " {$surveyinfo['emailresponseto']}<br />\n";
     }
     $dateformatdetails = getDateFormatData(Yii::app()->session['dateformat']);
     if (trim($surveyinfo['startdate']) != '') {
         Yii::import('application.libraries.Date_Time_Converter');
         $datetimeobj = new Date_Time_Converter($surveyinfo['startdate'], 'Y-m-d H:i:s');
         $aData['startdate'] = $datetimeobj->convert($dateformatdetails['phpdate'] . ' H:i');
     } else {
         $aData['startdate'] = "-";
     }
     if (trim($surveyinfo['expires']) != '') {
         //$constructoritems = array($surveyinfo['expires'] , "Y-m-d H:i:s");
         Yii::import('application.libraries.Date_Time_Converter');
         $datetimeobj = new Date_Time_Converter($surveyinfo['expires'], 'Y-m-d H:i:s');
         //$datetimeobj = new Date_Time_Converter($surveyinfo['expires'] , "Y-m-d H:i:s");
         $aData['expdate'] = $datetimeobj->convert($dateformatdetails['phpdate'] . ' H:i');
     } else {
         $aData['expdate'] = "-";
     }
     if (!$surveyinfo['language']) {
         $aData['language'] = getLanguageNameFromCode($currentadminlang, false);
     } else {
         $aData['language'] = getLanguageNameFromCode($surveyinfo['language'], false);
     }
     // get the rowspan of the Additionnal languages row
     // is at least 1 even if no additionnal language is present
     $additionnalLanguagesCount = count($aAdditionalLanguages);
     $first = true;
     $aData['additionnalLanguages'] = "";
     if ($additionnalLanguagesCount == 0) {
         $aData['additionnalLanguages'] .= "<td>-</td>\n";
     } else {
         foreach ($aAdditionalLanguages as $langname) {
             if ($langname) {
                 if (!$first) {
                     $aData['additionnalLanguages'] .= "<tr><td>&nbsp;</td>";
                 }
                 $first = false;
                 $aData['additionnalLanguages'] .= "<td>" . getLanguageNameFromCode($langname, false) . "</td></tr>\n";
             }
         }
     }
     if ($first) {
         $aData['additionnalLanguages'] .= "</tr>";
     }
     if ($surveyinfo['surveyls_urldescription'] == "") {
         $surveyinfo['surveyls_urldescription'] = htmlspecialchars($surveyinfo['surveyls_url']);
     }
     if ($surveyinfo['surveyls_url'] != "") {
         $aData['endurl'] = " <a target='_blank' href=\"" . htmlspecialchars($surveyinfo['surveyls_url']) . "\" title=\"" . htmlspecialchars($surveyinfo['surveyls_url']) . "\">{$surveyinfo['surveyls_urldescription']}</a>";
     } else {
         $aData['endurl'] = "-";
     }
     $aData['sumcount3'] = $sumcount3;
     $aData['sumcount2'] = $sumcount2;
     if ($activated == "N") {
         $aData['activatedlang'] = $clang->gT("No");
     } else {
         $aData['activatedlang'] = $clang->gT("Yes");
     }
     $aData['activated'] = $activated;
     if ($activated == "Y") {
         $aData['surveydb'] = Yii::app()->db->tablePrefix . "survey_" . $iSurveyID;
     }
     $aData['warnings'] = "";
     if ($activated == "N" && $sumcount3 == 0) {
         $aData['warnings'] = $clang->gT("Survey cannot be activated yet.") . "<br />\n";
         if ($sumcount2 == 0 && hasSurveyPermission($iSurveyID, 'surveycontent', 'create')) {
             $aData['warnings'] .= "<span class='statusentryhighlight'>[" . $clang->gT("You need to add question groups") . "]</span><br />";
         }
         if ($sumcount3 == 0 && hasSurveyPermission($iSurveyID, 'surveycontent', 'create')) {
             $aData['warnings'] .= "<span class='statusentryhighlight'>[" . $clang->gT("You need to add questions") . "]</span><br />";
         }
     }
     $aData['hints'] = $surveysummary2;
     //return (array('column'=>array($columns_used,$hard_limit) , 'size' => array($length, $size_limit) ));
     //        $aData['tableusage'] = getDBTableUsage($iSurveyID);
     // ToDo: Table usage is calculated on every menu display which is too slow with bug surveys.
     // Needs to be moved to a database field and only updated if there are question/subquestions added/removed (it's currently also not functional due to the port)
     //
     $aData['tableusage'] = false;
     if ($gid || $action !== true && in_array($action, array('deactivate', 'activate', 'surveysecurity', 'editdefaultvalues', 'editemailtemplates', 'surveyrights', 'addsurveysecurity', 'addusergroupsurveysecurity', 'setsurveysecurity', 'setusergroupsurveysecurity', 'delsurveysecurity', 'editsurveysettings', 'editsurveylocalesettings', 'updatesurveysettingsandeditlocalesettings', 'addgroup', 'importgroup', 'ordergroups', 'deletesurvey', 'resetsurveylogic', 'importsurveyresources', 'translate', 'emailtemplates', 'exportstructure', 'quotas', 'copysurvey', 'viewgroup', 'viewquestion'))) {
         $showstyle = "style='display: none'";
     } else {
         $showstyle = "";
     }
     $aData['showstyle'] = $showstyle;
     $aData['aAdditionalLanguages'] = $aAdditionalLanguages;
     $aData['clang'] = $clang;
     $aData['surveyinfo'] = $surveyinfo;
     $this->getController()->render("/admin/survey/surveySummary_view", $aData);
 }
 /**
  * Saves the new survey after the creation screen is submitted
  *
  * @param $iSurveyID  The survey id to be used for the new survey. If already taken a new random one will be used.
  */
 function insert($iSurveyID = null)
 {
     if (Yii::app()->session['USER_RIGHT_CREATE_SURVEY']) {
         // Check if survey title was set
         if (!$_POST['surveyls_title']) {
             Yii::app()->session['flashmessage'] = $clang->gT("Survey could not be created because it did not have a title");
             redirect($this->getController()->createUrl('admin'));
             return;
         }
         // Check if template may be used
         $sTemplate = $_POST['template'];
         if (!$sTemplate || Yii::app()->session['USER_RIGHT_SUPERADMIN'] != 1 && Yii::app()->session['USER_RIGHT_MANAGE_TEMPLATE'] != 1 && !hasTemplateManageRights(Yii::app()->session['loginID'], $_POST['template'])) {
             $sTemplate = "default";
         }
         Yii::app()->loadHelper("surveytranslator");
         // If start date supplied convert it to the right format
         $aDateFormatData = getDateFormatData(Yii::app()->session['dateformat']);
         $sStartDate = $_POST['startdate'];
         if (trim($sStartDate) != '') {
             Yii::import('application.libraries.Date_Time_Converter');
             $converter = new Date_Time_Converter($sStartDate, $aDateFormatData['phpdate'] . ' H:i:s');
             $sStartDate = $converter->convert("Y-m-d H:i:s");
         }
         // If expiry date supplied convert it to the right format
         $sExpiryDate = $_POST['expires'];
         if (trim($sExpiryDate) != '') {
             Yii::import('application.libraries.Date_Time_Converter');
             $converter = new Date_Time_Converter($sExpiryDate, $aDateFormatData['phpdate'] . ' H:i:s');
             $sExpiryDate = $converter->convert("Y-m-d H:i:s");
         }
         // Insert base settings into surveys table
         $aInsertData = array('expires' => $sExpiryDate, 'startdate' => $sStartDate, 'template' => $sTemplate, 'owner_id' => Yii::app()->session['loginID'], 'admin' => $_POST['admin'], 'active' => 'N', 'adminemail' => $_POST['adminemail'], 'bounce_email' => $_POST['bounce_email'], 'anonymized' => $_POST['anonymized'], 'faxto' => $_POST['faxto'], 'format' => $_POST['format'], 'savetimings' => $_POST['savetimings'], 'language' => $_POST['language'], 'datestamp' => $_POST['datestamp'], 'ipaddr' => $_POST['ipaddr'], 'refurl' => $_POST['refurl'], 'usecookie' => $_POST['usecookie'], 'emailnotificationto' => $_POST['emailnotificationto'], 'allowregister' => $_POST['allowregister'], 'allowsave' => $_POST['allowsave'], 'navigationdelay' => $_POST['navigationdelay'], 'autoredirect' => $_POST['autoredirect'], 'showxquestions' => $_POST['showxquestions'], 'showgroupinfo' => $_POST['showgroupinfo'], 'showqnumcode' => $_POST['showqnumcode'], 'shownoanswer' => $_POST['shownoanswer'], 'showwelcome' => $_POST['showwelcome'], 'allowprev' => $_POST['allowprev'], 'allowjumps' => $_POST['allowjumps'], 'nokeyboard' => $_POST['nokeyboard'], 'showprogress' => $_POST['showprogress'], 'printanswers' => $_POST['printanswers'], 'listpublic' => $_POST['public'], 'htmlemail' => $_POST['htmlemail'], 'sendconfirmation' => $_POST['sendconfirmation'], 'tokenanswerspersistence' => $_POST['tokenanswerspersistence'], 'alloweditaftercompletion' => $_POST['alloweditaftercompletion'], 'usecaptcha' => $_POST['usecaptcha'], 'publicstatistics' => $_POST['publicstatistics'], 'publicgraphs' => $_POST['publicgraphs'], 'assessments' => $_POST['assessments'], 'emailresponseto' => $_POST['emailresponseto'], 'tokenlength' => $_POST['tokenlength']);
         if (!is_null($iSurveyID)) {
             $aInsertData['wishSID'] = $iSurveyID;
         }
         $iNewSurveyid = Survey::model()->insertNewSurvey($aInsertData);
         if (!$iNewSurveyid) {
             die('Survey could not be created.');
         }
         // Prepare locale data for surveys_language_settings table
         $sTitle = $_POST['surveyls_title'];
         $sDescription = $_POST['description'];
         $sWelcome = $_POST['welcome'];
         $sURLDescription = $_POST['urldescrip'];
         if (Yii::app()->getConfig('filterxsshtml')) {
             //$p = new CHtmlPurifier();
             //$p->options = array('URI.AllowedSchemes'=>array('http' => true,  'https' => true));
             //$sTitle=$p->purify($sTitle);
             //$sDescription=$p->purify($sDescription);
             //$sWelcome=$p->purify($sWelcome);
             //$sURLDescription=$p->purify($sURLDescription);
         }
         $sTitle = html_entity_decode($sTitle, ENT_QUOTES, "UTF-8");
         $sDescription = html_entity_decode($sDescription, ENT_QUOTES, "UTF-8");
         $sWelcome = html_entity_decode($sWelcome, ENT_QUOTES, "UTF-8");
         $sURLDescription = html_entity_decode($sURLDescription, ENT_QUOTES, "UTF-8");
         // Fix bug with FCKEditor saving strange BR types
         $sTitle = fixCKeditorText($sTitle);
         $sDescription = fixCKeditorText($sDescription);
         $sWelcome = fixCKeditorText($sWelcome);
         // Insert base language into surveys_language_settings table
         $aInsertData = array('surveyls_survey_id' => $iNewSurveyid, 'surveyls_title' => $sTitle, 'surveyls_description' => $sDescription, 'surveyls_welcometext' => $sWelcome, 'surveyls_language' => $_POST['language'], 'surveyls_urldescription' => $_POST['urldescrip'], 'surveyls_endtext' => $_POST['endtext'], 'surveyls_url' => $_POST['url'], 'surveyls_dateformat' => (int) $_POST['dateformat'], 'surveyls_numberformat' => (int) $_POST['numberformat']);
         $langsettings = new Surveys_languagesettings();
         $langsettings->insertNewSurvey($aInsertData);
         Yii::app()->session['flashmessage'] = $this->getController()->lang->gT("Survey was successfully added.");
         // Update survey permissions
         Survey_permissions::model()->giveAllSurveyPermissions(Yii::app()->session['loginID'], $iNewSurveyid);
         $this->getController()->redirect($this->getController()->createUrl('admin/survey/sa/view/surveyid/' . $iNewSurveyid));
     }
 }
/** Builds the list of addon SQL select statements
*   that builds the query result set
*
*   @param $allfields   An array containing the names of the fields/answers we want to display in the statistics summary
*   @param $fieldmap    The fieldmap for the survey
*   @param $language    The language to use
*
*   @return array $selects array of individual select statements that can be added/appended to
*                          the 'where' portion of a SQL statement to restrict the result set
*                          ie: array("`FIELDNAME`='Y'", "`FIELDNAME2`='Hello'");
*
*/
function buildSelects($allfields, $surveyid, $language)
{
    //Create required variables
    $selects = array();
    $aQuestionMap = array();
    $fieldmap = createFieldMap($surveyid, "full", false, false, $language);
    foreach ($fieldmap as $field) {
        if (isset($field['qid']) && $field['qid'] != '') {
            $aQuestionMap[] = $field['sid'] . 'X' . $field['gid'] . 'X' . $field['qid'];
        }
    }
    // creates array of post variable names
    for (reset($_POST); $key = key($_POST); next($_POST)) {
        $postvars[] = $key;
    }
    /*
     * Iterate through postvars to create "nice" data for SQL later.
     *
     * Remember there might be some filters applied which have to be put into an SQL statement
     *
     * This foreach iterates through the name ($key) of each post value and builds a SELECT
     * statement out of it. It returns an array called $selects[] which will have a select query
     * for each filter chosen. ie: $select[0]="`74X71X428EXP` ='Y'";
     *
     * This array is used later to build the overall query used to limit the number of responses
     *
     */
    if (isset($postvars)) {
        foreach ($postvars as $pv) {
            //Only do this if there is actually a value for the $pv
            if (in_array($pv, $allfields) || in_array(substr($pv, 1), $aQuestionMap) || in_array($pv, $aQuestionMap) || ($pv[0] == 'D' || $pv[0] == 'N' || $pv[0] == 'K') && (in_array(substr($pv, 1, strlen($pv) - 2), $aQuestionMap) || in_array(substr($pv, 1, strlen($pv) - 3), $aQuestionMap) || in_array(substr($pv, 1, strlen($pv) - 5), $aQuestionMap))) {
                $firstletter = substr($pv, 0, 1);
                /*
                 * these question types WON'T be handled here:
                 * M = Multiple choice
                 * T - Long Free Text
                 * Q - Multiple Short Text
                 * D - Date
                 * N - Numerical Input
                 * | - File Upload
                 * K - Multiple Numerical Input
                 */
                if ($pv != "sid" && $pv != "display" && $firstletter != "M" && $firstletter != "P" && $firstletter != "T" && $firstletter != "Q" && $firstletter != "D" && $firstletter != "N" && $firstletter != "K" && $firstletter != "|" && $pv != "summary" && substr($pv, 0, 2) != "id" && substr($pv, 0, 9) != "datestamp") {
                    //put together some SQL here
                    $thisquestion = Yii::app()->db->quoteColumnName($pv) . " IN (";
                    foreach ($_POST[$pv] as $condition) {
                        $thisquestion .= "'{$condition}', ";
                    }
                    $thisquestion = substr($thisquestion, 0, -2) . ")";
                    //we collect all the to be selected data in this array
                    $selects[] = $thisquestion;
                } elseif ($firstletter == "M" || $firstletter == "P") {
                    $mselects = array();
                    //create a list out of the $pv array
                    list($lsid, $lgid, $lqid) = explode("X", $pv);
                    $aresult = Question::model()->findAll(array('order' => 'question_order', 'condition' => 'parent_qid=:parent_qid AND scale_id=0', 'params' => array(":parent_qid" => $lqid)));
                    foreach ($aresult as $arow) {
                        // only add condition if answer has been chosen
                        if (in_array($arow['title'], $_POST[$pv])) {
                            $mselects[] = Yii::app()->db->quoteColumnName(substr($pv, 1, strlen($pv)) . $arow['title']) . " = 'Y'";
                        }
                    }
                    /* If there are mutliple conditions generated from this multiple choice question, join them using the boolean "OR" */
                    if ($mselects) {
                        $thismulti = implode(" OR ", $mselects);
                        $selects[] = "({$thismulti})";
                        unset($mselects);
                    }
                } elseif ($firstletter == "N" || $firstletter == "K") {
                    //value greater than
                    if (substr($pv, strlen($pv) - 1, 1) == "G" && $_POST[$pv] != "") {
                        $selects[] = Yii::app()->db->quoteColumnName(substr($pv, 1, -1)) . " > " . sanitize_int($_POST[$pv]);
                    }
                    //value less than
                    if (substr($pv, strlen($pv) - 1, 1) == "L" && $_POST[$pv] != "") {
                        $selects[] = Yii::app()->db->quoteColumnName(substr($pv, 1, -1)) . " < " . sanitize_int($_POST[$pv]);
                    }
                } else {
                    if ($firstletter == "|") {
                        // no. of files greater than
                        if (substr($pv, strlen($pv) - 1, 1) == "G" && $_POST[$pv] != "") {
                            $selects[] = Yii::app()->db->quoteColumnName(substr($pv, 1, -1) . "_filecount") . " > " . sanitize_int($_POST[$pv]);
                        }
                        // no. of files less than
                        if (substr($pv, strlen($pv) - 1, 1) == "L" && $_POST[$pv] != "") {
                            $selects[] = Yii::app()->db->quoteColumnName(substr($pv, 1, -1) . "_filecount") . " < " . sanitize_int($_POST[$pv]);
                        }
                    } elseif (substr($pv, 0, 2) == "id") {
                        if (substr($pv, strlen($pv) - 1, 1) == "G" && $_POST[$pv] != "") {
                            $selects[] = Yii::app()->db->quoteColumnName(substr($pv, 0, -1)) . " > " . sanitize_int($_POST[$pv]);
                        }
                        if (substr($pv, strlen($pv) - 1, 1) == "L" && $_POST[$pv] != "") {
                            $selects[] = Yii::app()->db->quoteColumnName(substr($pv, 0, -1)) . " < " . sanitize_int($_POST[$pv]);
                        }
                    } elseif (($firstletter == "T" || $firstletter == "Q") && $_POST[$pv] != "") {
                        $selectSubs = array();
                        //We intepret and * and % as wildcard matches, and use ' OR ' and , as the separators
                        $pvParts = explode(",", str_replace('*', '%', str_replace(' OR ', ',', $_POST[$pv])));
                        if (is_array($pvParts) and count($pvParts)) {
                            foreach ($pvParts as $pvPart) {
                                $selectSubs[] = Yii::app()->db->quoteColumnName(substr($pv, 1, strlen($pv))) . " LIKE '" . trim($pvPart) . "'";
                            }
                            if (count($selectSubs)) {
                                $selects[] = ' (' . implode(' OR ', $selectSubs) . ') ';
                            }
                        }
                    } elseif ($firstletter == "D" && $_POST[$pv] != "") {
                        //Date equals
                        if (substr($pv, -2) == "eq") {
                            $selects[] = Yii::app()->db->quoteColumnName(substr($pv, 1, strlen($pv) - 3)) . " = " . dbQuoteAll($_POST[$pv]);
                        } else {
                            //date less than
                            if (substr($pv, -4) == "less") {
                                $selects[] = Yii::app()->db->quoteColumnName(substr($pv, 1, strlen($pv) - 5)) . " >= " . dbQuoteAll($_POST[$pv]);
                            }
                            //date greater than
                            if (substr($pv, -4) == "more") {
                                $selects[] = Yii::app()->db->quoteColumnName(substr($pv, 1, strlen($pv) - 5)) . " <= " . dbQuoteAll($_POST[$pv]);
                            }
                        }
                    } elseif (substr($pv, 0, 9) == "datestamp") {
                        //timestamp equals
                        $formatdata = getDateFormatData(Yii::app()->session['dateformat']);
                        if (substr($pv, -1, 1) == "E" && !empty($_POST[$pv])) {
                            $datetimeobj = new Date_Time_Converter($_POST[$pv], $formatdata['phpdate'] . ' H:i');
                            $sDateValue = $datetimeobj->convert("Y-m-d");
                            $selects[] = Yii::app()->db->quoteColumnName('datestamp') . " >= " . dbQuoteAll($sDateValue . " 00:00:00") . " and " . Yii::app()->db->quoteColumnName('datestamp') . " <= " . dbQuoteAll($sDateValue . " 23:59:59");
                        } else {
                            //timestamp less than
                            if (substr($pv, -1, 1) == "L" && !empty($_POST[$pv])) {
                                $datetimeobj = new Date_Time_Converter($_POST[$pv], $formatdata['phpdate'] . ' H:i');
                                $sDateValue = $datetimeobj->convert("Y-m-d H:i:s");
                                $selects[] = Yii::app()->db->quoteColumnName('datestamp') . " < " . dbQuoteAll($sDateValue);
                            }
                            //timestamp greater than
                            if (substr($pv, -1, 1) == "G" && !empty($_POST[$pv])) {
                                $datetimeobj = new Date_Time_Converter($_POST[$pv], $formatdata['phpdate'] . ' H:i');
                                $sDateValue = $datetimeobj->convert("Y-m-d H:i:s");
                                $selects[] = Yii::app()->db->quoteColumnName('datestamp') . " > " . dbQuoteAll($sDateValue);
                            }
                        }
                    }
                }
            }
        }
    }
    //end foreach -> loop through filter options to create SQL
    return $selects;
}
Example #18
0
/**
 * This function replaces keywords in a text and is mainly intended for templates
 * If you use this functions put your replacement strings into the $replacements variable
 * instead of using global variables
 * NOTE - Don't do any embedded replacements in this function.  Create the array of replacement values and
 * they will be done in batch at the end
 *
 * @param string $line Text to search in
 * @param array $replacements Array of replacements:  Array( <stringtosearch>=><stringtoreplacewith>, where <stringtosearch> is NOT surrounded with curly braces
 * @param boolean $anonymized Determines if token data is being used or just replaced with blanks
 * @return string  Text with replaced strings
 */
function templatereplace($line, $replacements=array(), $anonymized=false)
{
    global $surveylist, $sitename, $clienttoken, $rooturl;
    global $thissurvey, $imageurl, $defaulttemplate;
    global $percentcomplete, $move;
    global $groupname, $groupdescription;
    global $question;
    global $showXquestions, $showgroupinfo, $showqnumcode;
    global $answer, $navigator;
    global $help, $surveyformat;
    global $completed, $register_errormsg;
    global $privacy, $surveyid;
    global $publicurl, $templatedir, $token;
    global $assessments, $s_lang;
    global $errormsg, $clang;
    global $saved_id;
    global $totalBoilerplatequestions, $relativeurl;
    global $languagechanger;
    global $captchapath, $loadname;

    // lets sanitize the survey template
    if (isset($thissurvey['templatedir']))
    {
        $_templatename = $thissurvey['templatedir'];
    }
    else
    {
        $_templatename = $defaulttemplate;
    }
    $_templatename = validate_templatedir($_templatename);

    // create absolute template URL and template dir vars
    $_templateurl = sGetTemplateURL($_templatename) . '/';
    $templatedir = sgetTemplatePath($_templatename);

    if (stripos($line, "</head>"))
    {
        $line = str_ireplace("</head>",
            "<script type=\"text/javascript\" src=\"$rooturl/scripts/survey_runtime.js\"></script>\n"
                        . use_firebug()
                        . "\t</head>", $line);
    }
    // Get some vars : move elsewhere ?
    // surveyformat
    if (isset($thissurvey['format']))
    {
        $surveyformat = str_replace(array("A", "S", "G"), array("allinone", "questionbyquestion", "groupbygroup"), $thissurvey['format']);
    }
    else
    {
        $surveyformat = "";
    }
    // real survey contact
    if (isset($surveylist['contact']))
    {
        $_surveycontact = $surveylist['contact'];
    }
    elseif (isset($thissurvey['admin']) && $thissurvey['admin'] != "")
    {
        $_surveycontact = sprintf($clang->gT("Please contact %s ( %s ) for further assistance."), $thissurvey['admin'], $thissurvey['adminemail']);
    }
    else
    {
        $_surveycontact = "";
    }

    // If there are non-bracketed replacements to be made do so above this line.
    // Only continue in this routine if there are bracketed items to replace {}
    if (strpos($line, "{") === false)
    {
        return $line;
    }

    if (
        $showgroupinfo == 'both' ||
	    $showgroupinfo == 'name' ||
	    ($showgroupinfo == 'choose' && !isset($thissurvey['showgroupinfo'])) ||
	    ($showgroupinfo == 'choose' && $thissurvey['showgroupinfo'] == 'B') ||
	    ($showgroupinfo == 'choose' && $thissurvey['showgroupinfo'] == 'N')
    )
    {
        $_groupname = $groupname;
    }
    else
    {
        $_groupname = '';
    };
    if (
        $showgroupinfo == 'both' ||
	    $showgroupinfo == 'description' ||
	    ($showgroupinfo == 'choose' && !isset($thissurvey['showgroupinfo'])) ||
	    ($showgroupinfo == 'choose' && $thissurvey['showgroupinfo'] == 'B') ||
	    ($showgroupinfo == 'choose' && $thissurvey['showgroupinfo'] == 'D')
    )
    {
        $_groupdescription = $groupdescription;
    }
    else
    {
        $_groupdescription = '';
    };

    if (is_array($question))
    {
        $_question = $question['all'];
        $_question_text = $question['text'];
        $_question_help = $question['help'];
        $_question_mandatory = $question['mandatory'];
        $_question_man_message = $question['man_message'];
        $_question_valid_message = $question['valid_message'];
        $_question_file_valid_message = $question['file_valid_message'];
        $_question_sgq = (isset($question['sgq']) ? $question['sgq'] : '');
        $_question_essentials = $question['essentials'];
        $_question_class = $question['class'];
        $_question_man_class = $question['man_class'];
        $_question_input_error_class = $question['input_error_class'];
        }
        else
        {
        $_question = $question;
        $_question_text = '';
        $_question_help = '';
        $_question_mandatory = '';
        $_question_man_message = '';
        $_question_valid_message = '';
        $_question_file_valid_message = '';
        $_question_sgq = '';
        $_question_essentials = '';
        $_question_class = '';
        $_question_man_class = '';
        $_question_input_error_class = '';
    };

    if (
        $showqnumcode == 'both' ||
	    $showqnumcode == 'number' ||
	    ($showqnumcode == 'choose' && !isset($thissurvey['showqnumcode'])) ||
	    ($showqnumcode == 'choose' && $thissurvey['showqnumcode'] == 'B') ||
	    ($showqnumcode == 'choose' && $thissurvey['showqnumcode'] == 'N')
    )
    {
        $_question_number = $question['number'];
    }
    else
    {
        $_question_number = '';
    };
    if (
        $showqnumcode == 'both' ||
	    $showqnumcode == 'code' ||
	    ($showqnumcode == 'choose' && !isset($thissurvey['showqnumcode'])) ||
	    ($showqnumcode == 'choose' && $thissurvey['showqnumcode'] == 'B') ||
	    ($showqnumcode == 'choose' && $thissurvey['showqnumcode'] == 'C')
    )
    {
        $_question_code = $question['code'];
    }
    else
    {
        $_question_code = '';
    }

    if (isset($_SESSION['therearexquestions']))
    {
        $_totalquestionsAsked = $_SESSION['therearexquestions'] - $totalBoilerplatequestions;
    }
    else {
        $_totalquestionsAsked = 0;
    }
    if (
      $showXquestions == 'show' ||
      ($showXquestions == 'choose' && !isset($thissurvey['showXquestions'])) ||
      ($showXquestions == 'choose' && $thissurvey['showXquestions'] == 'Y')
    )
    {
        if ($_totalquestionsAsked < 1)
        {
            $_therearexquestions = $clang->gT("There are no questions in this survey"); // Singular
        }
        elseif ($_totalquestionsAsked == 1)
        {
            $_therearexquestions = $clang->gT("There is 1 question in this survey"); //Singular
        }
        else
        {
            $_therearexquestions = $clang->gT("There are {NUMBEROFQUESTIONS} questions in this survey.");    //Note this line MUST be before {NUMBEROFQUESTIONS}
	};
    }
    else
    {
        $_therearexquestions = '';
    };

    if (isset($token))
    {
        $_token = $token;
        }
    elseif (isset($clienttoken))
    {
        $_token = htmlentities($clienttoken, ENT_QUOTES, 'UTF-8');
        }
    else
    {
        $_token = '';
    }

    if (isset($thissurvey['surveyls_dateformat']))
    {
        $dateformatdetails = getDateFormatData($thissurvey['surveyls_dateformat']);
    }
    else {
        $dateformatdetails = getDateFormatData();
    }
    if (isset($thissurvey['expiry']))
    {
        $_datetimeobj = new Date_Time_Converter($thissurvey['expiry'], "Y-m-d");
        $_dateoutput = $_datetimeobj->convert($dateformatdetails['phpdate']);
            }
    else
    {
        $_dateoutput = '-';
            }
    $_submitbutton = "<input class='submit' type='submit' value=' " . $clang->gT("Submit") . " ' name='move2' onclick=\"javascript:document.limesurvey.move.value = 'movesubmit';\" />";
    if (isset($thissurvey['surveyls_url']) and $thissurvey['surveyls_url'] != "")
    {
        if (trim($thissurvey['surveyls_urldescription']) != '')
        {
            $_linkreplace = "<a href='{$thissurvey['surveyls_url']}'>{$thissurvey['surveyls_urldescription']}</a>";
        }
        else
        {
            $_linkreplace = "<a href='{$thissurvey['surveyls_url']}'>{$thissurvey['surveyls_url']}</a>";
    }
    }
    else
    {
        $_linkreplace='';
    }

    if (isset($clienttoken))
    {
        $token = $clienttoken;
    }
    else
    {
        $token = '';
    }

    if (!isset($_SESSION['s_lang']))
    {
        $_s_lang = 'en';
    }
    else
    {
        $_s_lang = $_SESSION['s_lang'];
    }

    $_clearall = "<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') . "')) {window.open('{$publicurl}/index.php?sid=$surveyid&amp;move=clearall&amp;lang=" . $_s_lang;
        if (returnglobal('token'))
        {
        $_clearall .= "&amp;token=" . urlencode(trim(sanitize_xss_string(strip_tags(returnglobal('token')))));
        }
        $_clearall .= "', '_self')}\" />";

    if (isset($_SESSION['datestamp']))
    {
        $_datestamp = $_SESSION['datestamp'];
    }
    else
    {
        $_datestamp = '-';
        }
        //Set up save/load feature
    if (isset($thissurvey['allowsave']) and $thissurvey['allowsave'] == "Y")
        {
            // Find out if the user has any saved data

        if ($thissurvey['format'] == 'A')
            {
            if ($thissurvey['tokenanswerspersistence'] != 'Y')
                {
                $_saveall = "\t\t\t<input type='submit' name='loadall' value='" . $clang->gT("Load Unfinished Survey") . "' class='saveall' " . (($thissurvey['active'] != "Y") ? "disabled='disabled'" : "") . "/>"
                        . "\n\t\t\t<input type='button' name='saveallbtn' value='" . $clang->gT("Resume Later") . "' class='saveall' onclick=\"javascript:document.limesurvey.move.value = this.value;addHiddenField(document.getElementById('limesurvey'),'saveall',this.value);document.getElementById('limesurvey').submit();\" " . (($thissurvey['active'] != "Y") ? "disabled='disabled'" : "") . "/>";  // Show Save So Far button
                }
                else
                {
                $_saveall = "\t\t\t<input type='button' name='saveallbtn' value='" . $clang->gT("Resume Later") . "' class='saveall' onclick=\"javascript:document.limesurvey.move.value = this.value;addHiddenField(document.getElementById('limesurvey'),'saveall',this.value);document.getElementById('limesurvey').submit();\" " . (($thissurvey['active'] != "Y") ? "disabled='disabled'" : "") . "/>";  // Show Save So Far button
        	};
            }
        elseif (!isset($_SESSION['step']) || !$_SESSION['step'])
        {  //First page, show LOAD
            if ($thissurvey['tokenanswerspersistence'] != 'Y')
            {
                $_saveall = "\t\t\t<input type='submit' name='loadall' value='" . $clang->gT("Load Unfinished Survey") . "' class='saveall' " . (($thissurvey['active'] != "Y") ? "disabled='disabled'" : "") . "/>";
                }
		else
		{
                    $_saveall = '';
		};
            }
        elseif (isset($_SESSION['scid']) && (isset($move) && $move == "movelast"))
        {  //Already saved and on Submit Page, dont show Save So Far button
            $_saveall = '';
            }
            else
            {
            $_saveall = "<input type='button' name='saveallbtn' value='" . $clang->gT("Resume Later") . "' class='saveall' onclick=\"javascript:document.limesurvey.move.value = this.value;addHiddenField(document.getElementById('limesurvey'),'saveall',this.value);document.getElementById('limesurvey').submit();\" " . (($thissurvey['active'] != "Y") ? "disabled='disabled'" : "") . "/>";  // Show Save So Far button
            }
        }
        else
        {
        $_saveall = "";
        }

    $_templatecss = "<link rel='stylesheet' type='text/css' href='{$_templateurl}template.css' />\n";
        if (getLanguageRTL($clang->langcode))
        {
            $_templatecss.="<link rel='stylesheet' type='text/css' href='{$_templateurl}template-rtl.css' />\n";
        }

    if (FlattenText($help, true) != '')
        {
            If (!isset($helpicon))
            {
            if (file_exists($templatedir . '/help.gif'))
                {

                $helpicon = $_templateurl . 'help.gif';
                }
            elseif (file_exists($templatedir . '/help.png'))
                {

                $helpicon = $_templateurl . 'help.png';
                }
                else
                {
                $helpicon = $imageurl . "/help.gif";
                }
            }
            $_questionhelp =  "<img src='{$helpicon}' alt='Help' align='left' />".$help;
        }
    else
    {
        $_questionhelp = $help;
    }

    if (isset($thissurvey['allowprev']) && $thissurvey['allowprev'] == "N")
    {
            $_strreview = "";
        }
    else
    {
        $_strreview = $clang->gT("If you want to check any of the answers you have made, and/or change them, you can do that now by clicking on the [<< prev] button and browsing through your responses.");
        }

    if (isset($thissurvey['active']) and $thissurvey['active'] == "N")
    {
        $_restart = "<a href='{$publicurl}/index.php?sid=$surveyid&amp;newtest=Y";
        if (isset($s_lang) && $s_lang != '') {
            $_restart.="&amp;lang=" . $s_lang;
        }
        $_restart.="'>" . $clang->gT("Restart this Survey") . "</a>";
    } else
        {
            $restart_extra = "";
            $restart_token = returnglobal('token');
        if (!empty($restart_token))
            $restart_extra .= "&amp;token=" . urlencode($restart_token);
        else
            $restart_extra = "&amp;newtest=Y";
        if (!empty($_GET['lang']))
            $restart_extra .= "&amp;lang=" . returnglobal('lang');
        $_restart = "<a href='{$publicurl}/index.php?sid=$surveyid" . $restart_extra . "'>" . $clang->gT("Restart this Survey") . "</a>";
        }
    if (isset($thissurvey['anonymized']) && $thissurvey['anonymized'] == 'Y')
    {
        $_savealert = $clang->gT("To remain anonymous please use a pseudonym as your username, also an email address is not required.");
        }
        else
        {
        $_savealert = "";
        }

        $_return_to_survey = "<a href='$relativeurl/index.php?sid=$surveyid";
        if (returnglobal('token'))
        {
        $_return_to_survey.= "&amp;token=" . urlencode(trim(sanitize_xss_string(strip_tags(returnglobal('token')))));
        }
    $_return_to_survey .= "'>" . $clang->gT("Return To Survey") . "</a>";

    $_saveform = "<table><tr><td align='right'>" . $clang->gT("Name") . ":</td><td><input type='text' name='savename' value='";
    if (isset($_POST['savename']))
    {
        $_saveform .= html_escape(auto_unescape($_POST['savename']));
    }
        $_saveform .= "' /></td></tr>\n"
            . "<tr><td align='right'>" . $clang->gT("Password") . ":</td><td><input type='password' name='savepass' value='";
    if (isset($_POST['savepass']))
    {
        $_saveform .= html_escape(auto_unescape($_POST['savepass']));
    }
        $_saveform .= "' /></td></tr>\n"
            . "<tr><td align='right'>" . $clang->gT("Repeat Password") . ":</td><td><input type='password' name='savepass2' value='";
    if (isset($_POST['savepass2']))
    {
        $_saveform .= html_escape(auto_unescape($_POST['savepass2']));
    }
        $_saveform .= "' /></td></tr>\n"
            . "<tr><td align='right'>" . $clang->gT("Your Email") . ":</td><td><input type='text' name='saveemail' value='";
    if (isset($_POST['saveemail']))
    {
        $_saveform .= html_escape(auto_unescape($_POST['saveemail']));
    }
        $_saveform .= "' /></td></tr>\n";
    if (isset($thissurvey['usecaptcha']) && function_exists("ImageCreate") && captcha_enabled('saveandloadscreen', $thissurvey['usecaptcha']))
        {
        $_saveform .="<tr><td align='right'>" . $clang->gT("Security Question") . ":</td><td><table><tr><td valign='middle'><img src='{$captchapath}verification.php?sid=$surveyid' alt='' /></td><td valign='middle' style='text-align:left'><input type='text' size='5' maxlength='3' name='loadsecurity' value='' /></td></tr></table></td></tr>\n";
        }
        $_saveform .= "<tr><td align='right'></td><td></td></tr>\n"
            . "<tr><td></td><td><input type='submit'  id='savebutton' name='savesubmit' value='" . $clang->gT("Save Now") . "' /></td></tr>\n"
        . "</table>";

    $_loadform = "<table><tr><td align='right'>" . $clang->gT("Saved name") . ":</td><td><input type='text' name='loadname' value='";
    if ($loadname)
    {
        $_loadform .= html_escape(auto_unescape($loadname));
    }
        $_loadform .= "' /></td></tr>\n"
            . "<tr><td align='right'>" . $clang->gT("Password") . ":</td><td><input type='password' name='loadpass' value='";
    if (isset($loadpass))
    {
        $_loadform .= html_escape(auto_unescape($loadpass));
    }
        $_loadform .= "' /></td></tr>\n";
    if (isset($thissurvey['usecaptcha']) && function_exists("ImageCreate") && captcha_enabled('saveandloadscreen', $thissurvey['usecaptcha']))
        {
        $_loadform .="<tr><td align='right'>" . $clang->gT("Security Question") . ":</td><td><table><tr><td valign='middle'><img src='{$captchapath}verification.php?sid=$surveyid' alt='' /></td><td valign='middle'><input type='text' size='5' maxlength='3' name='loadsecurity' value='' alt=''/></td></tr></table></td></tr>\n";
        }

        $_loadform .="<tr><td align='right'></td><td></td></tr>\n"
            . "<tr><td></td><td><input type='submit' id='loadbutton' value='" . $clang->gT("Load Now") . "' /></td></tr></table>\n";

    $_registerform = "<form method='post' action='{$publicurl}/register.php'>\n";
        if (!isset($_REQUEST['lang']))
        {
            $_reglang = GetBaseLanguageFromSurveyID($surveyid);
        }
        else
        {
            $_reglang = returnglobal('lang');
        }
    $_registerform .= "<input type='hidden' name='lang' value='" . $_reglang . "' />\n";
        $_registerform .= "<input type='hidden' name='sid' value='$surveyid' id='sid' />\n";

        $_registerform.="<table class='register' summary='Registrationform'>\n"
            . "<tr><td align='right'>"
            . $clang->gT("First name") . ":</td>"
            . "<td align='left'><input class='text' type='text' name='register_firstname'";
        if (isset($_POST['register_firstname']))
        {
        $_registerform .= " value='" . htmlentities(returnglobal('register_firstname'), ENT_QUOTES, 'UTF-8') . "'";
        }
        $_registerform .= " /></td></tr>"
            . "<tr><td align='right'>" . $clang->gT("Last name") . ":</td>\n"
            . "<td align='left'><input class='text' type='text' name='register_lastname'";
        if (isset($_POST['register_lastname']))
        {
        $_registerform .= " value='" . htmlentities(returnglobal('register_lastname'), ENT_QUOTES, 'UTF-8') . "'";
        }
        $_registerform .= " /></td></tr>\n"
            . "<tr><td align='right'>" . $clang->gT("Email address") . ":</td>\n"
            . "<td align='left'><input class='text' type='text' name='register_email'";
        if (isset($_POST['register_email']))
        {
        $_registerform .= " value='" . htmlentities(returnglobal('register_email'), ENT_QUOTES, 'UTF-8') . "'";
        }
        $_registerform .= " /></td></tr>\n";


    if (isset($thissurvey['usecaptcha']) && function_exists("ImageCreate") && captcha_enabled('registrationscreen', $thissurvey['usecaptcha']))
        {
        $_registerform .="<tr><td align='right'>" . $clang->gT("Security Question") . ":</td><td><table><tr><td valign='middle'><img src='{$captchapath}verification.php?sid=$surveyid' alt='' /></td><td valign='middle'><input type='text' size='5' maxlength='3' name='loadsecurity' value='' /></td></tr></table></td></tr>\n";
        }


        /*      if(isset($thissurvey['attribute1']) && $thissurvey['attribute1'])
         {
         $_registerform .= "<tr><td align='right'>".$thissurvey['attribute1'].":</td>\n"
         ."<td align='left'><input class='text' type='text' name='register_attribute1'";
         if (isset($_POST['register_attribute1']))
         {
         $_registerform .= " value='".htmlentities(returnglobal('register_attribute1'),ENT_QUOTES,'UTF-8')."'";
         }
         $_registerform .= " /></td></tr>\n";
         }
         if(isset($thissurvey['attribute2']) && $thissurvey['attribute2'])
         {
         $_registerform .= "<tr><td align='right'>".$thissurvey['attribute2'].":</td>\n"
         ."<td align='left'><input class='text' type='text' name='register_attribute2'";
         if (isset($_POST['register_attribute2']))
         {
         $_registerform .= " value='".htmlentities(returnglobal('register_attribute2'),ENT_QUOTES,'UTF-8')."'";
         }
         $_registerform .= " /></td></tr>\n";
      } */
    $_registerform .= "<tr><td></td><td><input id='registercontinue' class='submit' type='submit' value='" . $clang->gT("Continue") . "' />"
            . "</td></tr>\n"
            . "</table>\n"
            . "</form>\n";

    if (!is_null($surveyid) && function_exists('doAssessment'))
    {
        $assessmentdata = doAssessment($surveyid, true);
        $_assessment_current_total = $assessmentdata['total'];
    }
    else
    {
        $_assessment_current_total = '';
    }

    // Set the array of replacement variables here - don't include curly braces
	$corecoreReplacements = array();
	$coreReplacements['ANSWER'] = $answer;  // global
	$coreReplacements['ANSWERSCLEARED'] = $clang->gT("Answers Cleared");
	$coreReplacements['ASSESSMENTS'] = $assessments;    // global
	$coreReplacements['ASSESSMENT_CURRENT_TOTAL'] = $_assessment_current_total;
	$coreReplacements['ASSESSMENT_HEADING'] = $clang->gT("Your Assessment");
	$coreReplacements['CHECKJAVASCRIPT'] = "<noscript><span class='warningjs'>".$clang->gT("Caution: JavaScript execution is disabled in your browser. You may not be able to answer all questions in this survey. Please, verify your browser parameters.")."</span></noscript>";
	$coreReplacements['CLEARALL'] = $_clearall;
	$coreReplacements['CLOSEWINDOW']  =  "<a href='javascript:%20self.close()'>".$clang->gT("Close this window")."</a>";
	$coreReplacements['COMPLETED'] = $completed;    // global
	$coreReplacements['DATESTAMP'] = $_datestamp;
	$coreReplacements['EXPIRY'] = $_dateoutput;
	$coreReplacements['GROUPDESCRIPTION'] = $_groupdescription;
	$coreReplacements['GROUPNAME'] = $_groupname;
	$coreReplacements['LANG'] = $clang->getlangcode();
	$coreReplacements['LANGUAGECHANGER'] = $languagechanger;    // global
	$coreReplacements['LOADERROR'] = $errormsg; // global
	$coreReplacements['LOADFORM'] = $_loadform;
	$coreReplacements['LOADHEADING'] = $clang->gT("Load A Previously Saved Survey");
	$coreReplacements['LOADMESSAGE'] = $clang->gT("You can load a survey that you have previously saved from this screen.")."<br />".$clang->gT("Type in the 'name' you used to save the survey, and the password.")."<br />";
	$coreReplacements['NAVIGATOR'] = $navigator;    // global
	$coreReplacements['NOSURVEYID'] = $surveylist['nosid']; // global
	$coreReplacements['NUMBEROFQUESTIONS'] = $_totalquestionsAsked;
	$coreReplacements['PERCENTCOMPLETE'] = $percentcomplete;    // global
	$coreReplacements['PRIVACY'] = $privacy;    // global
	$coreReplacements['PRIVACYMESSAGE'] = "<span style='font-weight:bold; font-style: italic;'>".$clang->gT("A Note On Privacy")."</span><br />".$clang->gT("This survey is anonymous.")."<br />".$clang->gT("The record kept of your survey responses does not contain any identifying information about you unless a specific question in the survey has asked for this. If you have responded to a survey that used an identifying token to allow you to access the survey, you can rest assured that the identifying token is not kept with your responses. It is managed in a separate database, and will only be updated to indicate that you have (or haven't) completed this survey. There is no way of matching identification tokens with survey responses in this survey.");
	$coreReplacements['QUESTION'] = $_question;
	$coreReplacements['QUESTIONHELP'] = $_questionhelp;
	$coreReplacements['QUESTIONHELPPLAINTEXT'] = strip_tags(addslashes($help)); // global
	$coreReplacements['QUESTION_CLASS'] = $_question_class;
	$coreReplacements['QUESTION_CODE'] = $_question_code;
	$coreReplacements['QUESTION_ESSENTIALS'] = $_question_essentials;
	$coreReplacements['QUESTION_FILE_VALID_MESSAGE'] = $_question_file_valid_message;
	$coreReplacements['QUESTION_HELP'] = $_question_help;
	$coreReplacements['QUESTION_INPUT_ERROR_CLASS'] = $_question_input_error_class;
	$coreReplacements['QUESTION_MANDATORY'] = $_question_mandatory;
	$coreReplacements['QUESTION_MAN_CLASS'] = $_question_man_class;
	$coreReplacements['QUESTION_MAN_MESSAGE'] = $_question_man_message;
	$coreReplacements['QUESTION_NUMBER'] = $_question_number;
	$coreReplacements['QUESTION_TEXT'] = $_question_text;
	$coreReplacements['QUESTION_VALID_MESSAGE'] = $_question_valid_message;
	$coreReplacements['REGISTERERROR'] = $register_errormsg;    // global
	$coreReplacements['REGISTERFORM'] = $_registerform;
	$coreReplacements['REGISTERMESSAGE1'] = $clang->gT("You must be registered to complete this survey");
	$coreReplacements['REGISTERMESSAGE2'] = $clang->gT("You may register for this survey if you wish to take part.")."<br />\n".$clang->gT("Enter your details below, and an email containing the link to participate in this survey will be sent immediately.");
	$coreReplacements['RESTART'] = $_restart;
	$coreReplacements['RETURNTOSURVEY'] = $_return_to_survey;
	$coreReplacements['SAVE'] = $_saveall;
	$coreReplacements['SAVEALERT'] = $_savealert;
	$coreReplacements['SAVEDID'] = $saved_id;   // global
	$coreReplacements['SAVEERROR'] = $errormsg; // global - same as LOADERROR
	$coreReplacements['SAVEFORM'] = $_saveform;
	$coreReplacements['SAVEHEADING'] = $clang->gT("Save Your Unfinished Survey");
	$coreReplacements['SAVEMESSAGE'] = $clang->gT("Enter a name and password for this survey and click save below.")."<br />\n".$clang->gT("Your survey will be saved using that name and password, and can be completed later by logging in with the same name and password.")."<br /><br />\n".$clang->gT("If you give an email address, an email containing the details will be sent to you.")."<br /><br />\n".$clang->gT("After having clicked the save button you can either close this browser window or continue filling out the survey.");
	$coreReplacements['SGQ'] = $_question_sgq;
	$coreReplacements['SID'] = $surveyid;   // global
	$coreReplacements['SITENAME'] = $sitename;  // global
	$coreReplacements['SUBMITBUTTON'] = $_submitbutton;
	$coreReplacements['SUBMITCOMPLETE'] = "<strong>".$clang->gT("Thank you!")."<br /><br />".$clang->gT("You have completed answering the questions in this survey.")."</strong><br /><br />".$clang->gT("Click on 'Submit' now to complete the process and save your answers.");
	$coreReplacements['SUBMITREVIEW'] = $_strreview;
	$coreReplacements['SURVEYCONTACT'] = $_surveycontact;
	$coreReplacements['SURVEYDESCRIPTION'] = (isset($thissurvey['description']) ? $thissurvey['description'] : '');
	$coreReplacements['SURVEYFORMAT'] = $surveyformat;  // global
	$coreReplacements['SURVEYLANGAGE'] = $clang->langcode;
	$coreReplacements['SURVEYLIST'] = $surveylist['list'];  // global
	$coreReplacements['SURVEYLISTHEADING'] =  $surveylist['listheading'];   // global
	$coreReplacements['SURVEYNAME'] = $thissurvey['name'];  // global
	$coreReplacements['TEMPLATECSS'] = $_templatecss;
	$coreReplacements['TEMPLATEURL'] = $_templateurl;
	$coreReplacements['THEREAREXQUESTIONS'] = $_therearexquestions;
	if (!$anonymized) $coreReplacements['TOKEN'] = $_token;
	$coreReplacements['URL'] = $_linkreplace;
	$coreReplacements['WELCOME'] = (isset($thissurvey['welcome']) ? $thissurvey['welcome'] : '');

    $tokenAndAnswerMap = getAnswerAndTokenMappings(false,$anonymized);
    $doTheseReplacements = array_merge($coreReplacements, $tokenAndAnswerMap, $replacements);   // so $replacements overrides core values

    $line = doReplacements($line,$doTheseReplacements);
    // Do replacements twice since some reference others
    $line = doReplacements($line,$doTheseReplacements);

    return $line;
}
Example #19
0
function tokensExport($iSurveyID)
{
    $sEmailFiter = trim(App()->request->getPost('filteremail'));
    $iTokenStatus = App()->request->getPost('tokenstatus');
    $iInvitationStatus = App()->request->getPost('invitationstatus');
    $iReminderStatus = App()->request->getPost('reminderstatus');
    $sTokenLanguage = App()->request->getPost('tokenlanguage');
    $oSurvey = Survey::model()->findByPk($iSurveyID);
    $bIsNotAnonymous = $oSurvey->anonymized == 'N' && $oSurvey->active == 'Y';
    // db table exist (survey_$iSurveyID) ?
    $bquery = "SELECT * FROM {{tokens_{$iSurveyID}}} where 1=1";
    $databasetype = Yii::app()->db->getDriverName();
    if (trim($sEmailFiter) != '') {
        if (in_array($databasetype, array('mssql', 'sqlsrv', 'dblib'))) {
            $bquery .= ' and CAST(email as varchar) like ' . dbQuoteAll('%' . $_POST['filteremail'] . '%', true);
        } else {
            $bquery .= ' and email like ' . dbQuoteAll('%' . $_POST['filteremail'] . '%', true);
        }
    }
    if ($_POST['tokenstatus'] == 1) {
        $bquery .= " and completed<>'N'";
    } elseif ($iTokenStatus == 2) {
        $bquery .= " and completed='N'";
    } elseif ($iTokenStatus == 3 && $bIsNotAnonymous) {
        $bquery .= " and completed='N' and token not in (select token from {{survey_{$iSurveyID}}} group by token)";
    } elseif ($iTokenStatus == 4 && $bIsNotAnonymous) {
        $bquery .= " and completed='N' and token in (select token from {{survey_{$iSurveyID}}} group by token)";
    }
    if ($iInvitationStatus == 1) {
        $bquery .= " and sent<>'N'";
    }
    if ($iInvitationStatus == 2) {
        $bquery .= " and sent='N'";
    }
    if ($iReminderStatus == 1) {
        $bquery .= " and remindersent<>'N'";
    }
    if ($iReminderStatus == 2) {
        $bquery .= " and remindersent='N'";
    }
    if ($sTokenLanguage != '') {
        $bquery .= " and language=" . dbQuoteAll($sTokenLanguage);
    }
    $bquery .= " ORDER BY tid";
    Yii::app()->loadHelper('database');
    $bresult = Yii::app()->db->createCommand($bquery)->query();
    //dbExecuteAssoc($bquery) is faster but deprecated!
    //HEADERS should be after the above query else timeout errors in case there are lots of tokens!
    header("Content-Disposition: attachment; filename=tokens_" . $iSurveyID . ".csv");
    header("Content-type: text/comma-separated-values; charset=UTF-8");
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Pragma: cache");
    // Export UTF8 WITH BOM
    $tokenoutput = chr(hexdec('EF')) . chr(hexdec('BB')) . chr(hexdec('BF'));
    $tokenoutput .= "tid,firstname,lastname,email,emailstatus,token,language,validfrom,validuntil,invited,reminded,remindercount,completed,usesleft";
    $attrfieldnames = getAttributeFieldNames($iSurveyID);
    $attrfielddescr = getTokenFieldsAndNames($iSurveyID, true);
    foreach ($attrfieldnames as $attr_name) {
        $tokenoutput .= ", {$attr_name}";
        if (isset($attrfielddescr[$attr_name])) {
            $tokenoutput .= " <" . str_replace(",", " ", $attrfielddescr[$attr_name]['description']) . ">";
        }
    }
    $tokenoutput .= "\n";
    echo $tokenoutput;
    $tokenoutput = "";
    // Export token line by line and fill $aExportedTokens with token exported
    Yii::import('application.libraries.Date_Time_Converter', true);
    $aExportedTokens = array();
    while ($brow = $bresult->read()) {
        if (trim($brow['validfrom'] != '')) {
            $datetimeobj = new Date_Time_Converter($brow['validfrom'], "Y-m-d H:i:s");
            $brow['validfrom'] = $datetimeobj->convert('Y-m-d H:i');
        }
        if (trim($brow['validuntil'] != '')) {
            $datetimeobj = new Date_Time_Converter($brow['validuntil'], "Y-m-d H:i:s");
            $brow['validuntil'] = $datetimeobj->convert('Y-m-d H:i');
        }
        $tokenoutput .= '"' . trim($brow['tid']) . '",';
        $tokenoutput .= '"' . trim($brow['firstname']) . '",';
        $tokenoutput .= '"' . trim($brow['lastname']) . '",';
        $tokenoutput .= '"' . trim($brow['email']) . '",';
        $tokenoutput .= '"' . trim($brow['emailstatus']) . '",';
        $tokenoutput .= '"' . trim($brow['token']) . '",';
        $tokenoutput .= '"' . trim($brow['language']) . '",';
        $tokenoutput .= '"' . trim($brow['validfrom']) . '",';
        $tokenoutput .= '"' . trim($brow['validuntil']) . '",';
        $tokenoutput .= '"' . trim($brow['sent']) . '",';
        $tokenoutput .= '"' . trim($brow['remindersent']) . '",';
        $tokenoutput .= '"' . trim($brow['remindercount']) . '",';
        $tokenoutput .= '"' . trim($brow['completed']) . '",';
        $tokenoutput .= '"' . trim($brow['usesleft']) . '",';
        foreach ($attrfieldnames as $attr_name) {
            $tokenoutput .= '"' . trim($brow[$attr_name]) . '",';
        }
        $tokenoutput = substr($tokenoutput, 0, -1);
        // remove last comma
        $tokenoutput .= "\n";
        echo $tokenoutput;
        $tokenoutput = '';
        $aExportedTokens[] = $brow['tid'];
    }
    if (Yii::app()->request->getPost('tokendeleteexported') && !empty($aExportedTokens)) {
        Token::model($iSurveyID)->deleteByPk($aExportedTokens);
    }
}
 /**
  * Show survey summary
  * @param int Survey id
  * @param string Action to be performed
  */
 function _surveysummary($aData)
 {
     $iSurveyID = $aData['surveyid'];
     $aSurveyInfo = getSurveyInfo($iSurveyID);
     $oSurvey = $aData['oSurvey'];
     $baselang = $aSurveyInfo['language'];
     $activated = $aSurveyInfo['active'];
     $condition = array('sid' => $iSurveyID, 'parent_qid' => 0, 'language' => $baselang);
     $sumresult3 = Question::model()->findAllByAttributes($condition);
     //Checked
     $sumcount3 = count($sumresult3);
     $condition = array('sid' => $iSurveyID, 'language' => $baselang);
     $sumresult2 = QuestionGroup::model()->findAllByAttributes($condition);
     //Checked
     $sumcount2 = count($sumresult2);
     //SURVEY SUMMARY
     $aAdditionalLanguages = $oSurvey->additionalLanguages;
     $surveysummary2 = "";
     if ($aSurveyInfo['anonymized'] != "N") {
         $surveysummary2 .= gT("Responses to this survey are anonymized.") . "<br />";
     } else {
         $surveysummary2 .= gT("Responses to this survey are NOT anonymized.") . "<br />";
     }
     if ($aSurveyInfo['format'] == "S") {
         $surveysummary2 .= gT("It is presented question by question.") . "<br />";
     } elseif ($aSurveyInfo['format'] == "G") {
         $surveysummary2 .= gT("It is presented group by group.") . "<br />";
     } else {
         $surveysummary2 .= gT("It is presented on one single page.") . "<br />";
     }
     if ($aSurveyInfo['questionindex'] > 0) {
         if ($aSurveyInfo['format'] == 'A') {
             $surveysummary2 .= gT("No question index will be shown with this format.") . "<br />";
         } elseif ($aSurveyInfo['questionindex'] == 1) {
             $surveysummary2 .= gT("A question index will be shown; participants will be able to jump between viewed questions.") . "<br />";
         } elseif ($aSurveyInfo['questionindex'] == 2) {
             $surveysummary2 .= gT("A full question index will be shown; participants will be able to jump between relevant questions.") . "<br />";
         }
     }
     if ($aSurveyInfo['datestamp'] == "Y") {
         $surveysummary2 .= gT("Responses will be date stamped.") . "<br />";
     }
     if ($aSurveyInfo['ipaddr'] == "Y") {
         $surveysummary2 .= gT("IP Addresses will be logged") . "<br />";
     }
     if ($aSurveyInfo['refurl'] == "Y") {
         $surveysummary2 .= gT("Referrer URL will be saved.") . "<br />";
     }
     if ($aSurveyInfo['usecookie'] == "Y") {
         $surveysummary2 .= gT("It uses cookies for access control.") . "<br />";
     }
     if ($aSurveyInfo['allowregister'] == "Y") {
         $surveysummary2 .= gT("If tokens are used, the public may register for this survey") . "<br />";
     }
     if ($aSurveyInfo['allowsave'] == "Y" && $aSurveyInfo['tokenanswerspersistence'] == 'N') {
         $surveysummary2 .= gT("Participants can save partially finished surveys") . "<br />\n";
     }
     if ($aSurveyInfo['emailnotificationto'] != '') {
         $surveysummary2 .= gT("Basic email notification is sent to:") . ' ' . htmlspecialchars($aSurveyInfo['emailnotificationto']) . "<br />\n";
     }
     if ($aSurveyInfo['emailresponseto'] != '') {
         $surveysummary2 .= gT("Detailed email notification with response data is sent to:") . ' ' . htmlspecialchars($aSurveyInfo['emailresponseto']) . "<br />\n";
     }
     $dateformatdetails = getDateFormatData(Yii::app()->session['dateformat']);
     if (trim($aSurveyInfo['startdate']) != '') {
         Yii::import('application.libraries.Date_Time_Converter');
         $datetimeobj = new Date_Time_Converter($aSurveyInfo['startdate'], 'Y-m-d H:i:s');
         $aData['startdate'] = $datetimeobj->convert($dateformatdetails['phpdate'] . ' H:i');
     } else {
         $aData['startdate'] = "-";
     }
     if (trim($aSurveyInfo['expires']) != '') {
         //$constructoritems = array($surveyinfo['expires'] , "Y-m-d H:i:s");
         Yii::import('application.libraries.Date_Time_Converter');
         $datetimeobj = new Date_Time_Converter($aSurveyInfo['expires'], 'Y-m-d H:i:s');
         //$datetimeobj = new Date_Time_Converter($surveyinfo['expires'] , "Y-m-d H:i:s");
         $aData['expdate'] = $datetimeobj->convert($dateformatdetails['phpdate'] . ' H:i');
     } else {
         $aData['expdate'] = "-";
     }
     if (!$aSurveyInfo['language']) {
         $aData['language'] = getLanguageNameFromCode($currentadminlang, false);
     } else {
         $aData['language'] = getLanguageNameFromCode($aSurveyInfo['language'], false);
     }
     // get the rowspan of the Additionnal languages row
     // is at least 1 even if no additionnal language is present
     $additionnalLanguagesCount = count($aAdditionalLanguages);
     $first = true;
     if ($aSurveyInfo['surveyls_urldescription'] == "") {
         $aSurveyInfo['surveyls_urldescription'] = htmlspecialchars($aSurveyInfo['surveyls_url']);
     }
     if ($aSurveyInfo['surveyls_url'] != "") {
         $aData['endurl'] = " <a target='_blank' href=\"" . htmlspecialchars($aSurveyInfo['surveyls_url']) . "\" title=\"" . htmlspecialchars($aSurveyInfo['surveyls_url']) . "\">" . flattenText($aSurveyInfo['surveyls_urldescription']) . "</a>";
     } else {
         $aData['endurl'] = "-";
     }
     $aData['sumcount3'] = $sumcount3;
     $aData['sumcount2'] = $sumcount2;
     if ($activated == "N") {
         $aData['activatedlang'] = gT("No");
     } else {
         $aData['activatedlang'] = gT("Yes");
     }
     $aData['activated'] = $activated;
     if ($activated == "Y") {
         $aData['surveydb'] = Yii::app()->db->tablePrefix . "survey_" . $iSurveyID;
     }
     $aData['warnings'] = "";
     if ($activated == "N" && $sumcount3 == 0) {
         $aData['warnings'] = gT("Survey cannot be activated yet.") . "<br />\n";
         if ($sumcount2 == 0 && Permission::model()->hasSurveyPermission($iSurveyID, 'surveycontent', 'create')) {
             $aData['warnings'] .= "<span class='statusentryhighlight'>[" . gT("You need to add question groups") . "]</span><br />";
         }
         if ($sumcount3 == 0 && Permission::model()->hasSurveyPermission($iSurveyID, 'surveycontent', 'create')) {
             $aData['warnings'] .= "<span class='statusentryhighlight'>[" . gT("You need to add questions") . "]</span><br />";
         }
     }
     $aData['hints'] = $surveysummary2;
     //return (array('column'=>array($columns_used,$hard_limit) , 'size' => array($length, $size_limit) ));
     //        $aData['tableusage'] = getDBTableUsage($iSurveyID);
     // ToDo: Table usage is calculated on every menu display which is too slow with bug surveys.
     // Needs to be moved to a database field and only updated if there are question/subquestions added/removed (it's currently also not functional due to the port)
     //
     $aData['tableusage'] = false;
     $aData['aAdditionalLanguages'] = $aAdditionalLanguages;
     $aData['surveyinfo'] = $aSurveyInfo;
     $aData['groups_count'] = $sumcount2;
     $this->getController()->renderPartial("/admin/survey/surveySummary_view", $aData);
 }
Example #21
0
if ($subaction == "insertdummys" && (bHasSurveyPermission($surveyid, 'tokens','create')))
{
    //Fix up dates and match to database format
    if (trim($_POST['validfrom'])=='') {
        $_POST['validfrom']=null;
    }

    else
    {
        $datetimeobj = new Date_Time_Converter(trim($_POST['validfrom']), $dateformatdetails['phpdate'].' H:i');
        $_POST['validfrom'] =$datetimeobj->convert('Y-m-d H:i:s');
    }
    if (trim($_POST['validuntil'])=='') {$_POST['validuntil']=null;}
    else
    {
        $datetimeobj = new Date_Time_Converter(trim($_POST['validuntil']), $dateformatdetails['phpdate'].' H:i');
        $_POST['validuntil'] =$datetimeobj->convert('Y-m-d H:i:s');
    }

    $santitizedtoken='';

    $tokenoutput .= "\t<div class='header ui-widget-header'>".$clang->gT("Add dummy tokens")."</div>\n"
    ."\t<div class='messagebox ui-corner-all'>\n";
    $data = array('firstname' => $_POST['firstname'],
    'lastname' => $_POST['lastname'],
    'email' => sanitize_email($_POST['email']),
    'emailstatus' => 'OK',
    'token' => $santitizedtoken,
    'language' => sanitize_languagecode($_POST['language']),
        'sent' => 'N',
    'remindersent' => 'N',
Example #22
0
function do_date($ia)
{
    global $thissurvey;
    $aQuestionAttributes = QuestionAttribute::model()->getQuestionAttributes($ia[0]);
    $checkconditionFunction = "checkconditions";
    $dateformatdetails = getDateFormatDataForQID($aQuestionAttributes, $thissurvey);
    $numberformatdatat = getRadixPointData($thissurvey['surveyls_numberformat']);
    $inputnames = array();
    $sDateLangvarJS = " translt = {\n         alertInvalidDate: '" . gT('Date entered is invalid!', 'js') . "',\n        };";
    App()->getClientScript()->registerScript("sDateLangvarJS", $sDateLangvarJS, CClientScript::POS_HEAD);
    App()->getClientScript()->registerScriptFile(Yii::app()->getConfig("generalscripts") . 'date.js');
    App()->getClientScript()->registerPackage('moment');
    // date_min: Determine whether we have an expression, a full date (YYYY-MM-DD) or only a year(YYYY)
    if (trim($aQuestionAttributes['date_min']) != '') {
        $date_min = trim($aQuestionAttributes['date_min']);
        $date_time_em = strtotime(LimeExpressionManager::ProcessString("{" . $date_min . "}", $ia[0]));
        if (ctype_digit($date_min) && strlen($date_min) == 4 && $date_min >= 1900 && $date_min <= 2099) {
            $mindate = $date_min . '-01-01';
            // backward compatibility: if only a year is given, add month and day
        } elseif (preg_match("/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])/", $date_min)) {
            $mindate = $date_min;
        } elseif ($date_time_em) {
            $mindate = date("Y-m-d", $date_time_em);
        } else {
            $mindate = '{' . $aQuestionAttributes['date_min'] . '}';
        }
    } else {
        $mindate = '1900-01-01';
        // Why 1900 ?
    }
    // date_max: Determine whether we have an expression, a full date (YYYY-MM-DD) or only a year(YYYY)
    if (trim($aQuestionAttributes['date_max']) != '') {
        $date_max = trim($aQuestionAttributes['date_max']);
        $date_time_em = strtotime(LimeExpressionManager::ProcessString("{" . $date_max . "}", $ia[0]));
        if (ctype_digit($date_max) && strlen($date_max) == 4 && $date_max >= 1900 && $date_max <= 2099) {
            $maxdate = $date_max . '-12-31';
            // backward compatibility: if only a year is given, add month and day
        } elseif (preg_match("/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])/", $date_max)) {
            $maxdate = $date_max;
        } elseif ($date_time_em) {
            $maxdate = date("Y-m-d", $date_time_em);
        } else {
            $maxdate = '{' . $aQuestionAttributes['date_max'] . '}';
        }
    } else {
        $maxdate = '2037-12-31';
        // Why 2037 ?
    }
    if (trim($aQuestionAttributes['dropdown_dates']) == 1) {
        if (!empty($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$ia[1]]) && $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$ia[1]] != 'INVALID') {
            $datetimeobj = new Date_Time_Converter($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$ia[1]], "Y-m-d H:i:s");
            $currentyear = $datetimeobj->years;
            $currentmonth = $datetimeobj->months;
            $currentdate = $datetimeobj->days;
            $currenthour = $datetimeobj->hours;
            $currentminute = $datetimeobj->minutes;
        } else {
            // If date is invalid get the POSTED value
            $currentdate = App()->request->getPost("day{$ia[1]}", '');
            $currentmonth = App()->request->getPost("month{$ia[1]}", '');
            $currentyear = App()->request->getPost("year{$ia[1]}", '');
            $currenthour = App()->request->getPost("hour{$ia[1]}", '');
            $currentminute = App()->request->getPost("minute{$ia[1]}", '');
        }
        $dateorder = preg_split('/([-\\.\\/ :])/', $dateformatdetails['phpdate'], -1, PREG_SPLIT_DELIM_CAPTURE);
        $sRows = '';
        $montharray = array();
        foreach ($dateorder as $datepart) {
            switch ($datepart) {
                // Show day select box
                case 'j':
                case 'd':
                    $sRows .= doRender('/survey/questions/date/dropdown/rows/day', array('dayId' => $ia[1], 'currentdate' => $currentdate), true);
                    break;
                    // Show month select box
                // Show month select box
                case 'n':
                case 'm':
                    switch ((int) trim($aQuestionAttributes['dropdown_dates_month_style'])) {
                        case 0:
                            $montharray = array(gT('Jan'), gT('Feb'), gT('Mar'), gT('Apr'), gT('May'), gT('Jun'), gT('Jul'), gT('Aug'), gT('Sep'), gT('Oct'), gT('Nov'), gT('Dec'));
                            break;
                        case 1:
                            $montharray = array(gT('January'), gT('February'), gT('March'), gT('April'), gT('May'), gT('June'), gT('July'), gT('August'), gT('September'), gT('October'), gT('November'), gT('December'));
                            break;
                        case 2:
                            $montharray = array('01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12');
                            break;
                    }
                    $sRows .= doRender('/survey/questions/date/dropdown/rows/month', array('monthId' => $ia[1], 'currentmonth' => $currentmonth, 'montharray' => $montharray), true);
                    break;
                    // Show year select box
                // Show year select box
                case 'y':
                case 'Y':
                    /*
                     * yearmin = Minimum year value for dropdown list, if not set default is 1900
                     * yearmax = Maximum year value for dropdown list, if not set default is 2037
                     * if full dates (format: YYYY-MM-DD) are given, only the year is used
                     * expressions are not supported because contents of dropbox cannot be easily updated dynamically
                     */
                    $yearmin = (int) substr($mindate, 0, 4);
                    if (!isset($yearmin) || $yearmin < 1900 || $yearmin > 2037) {
                        $yearmin = 1900;
                    }
                    $yearmax = (int) substr($maxdate, 0, 4);
                    if (!isset($yearmax) || $yearmax < 1900 || $yearmax > 2037) {
                        $yearmax = 2037;
                    }
                    if ($yearmin > $yearmax) {
                        $yearmin = 1900;
                        $yearmax = 2037;
                    }
                    if ($aQuestionAttributes['reverse'] == 1) {
                        $tmp = $yearmin;
                        $yearmin = $yearmax;
                        $yearmax = $tmp;
                        $step = 1;
                        $reverse = true;
                    } else {
                        $step = -1;
                        $reverse = false;
                    }
                    $sRows .= doRender('/survey/questions/date/dropdown/rows/year', array('yearId' => $ia[1], 'currentyear' => $currentyear, 'yearmax' => $yearmax, 'reverse' => $reverse, 'yearmin' => $yearmin, 'step' => $step), true);
                    break;
                case 'H':
                case 'h':
                case 'g':
                case 'G':
                    $sRows .= doRender('/survey/questions/date/dropdown/rows/hour', array('hourId' => $ia[1], 'currenthour' => $currenthour, 'datepart' => $datepart), true);
                    break;
                case 'i':
                    $sRows .= doRender('/survey/questions/date/dropdown/rows/minute', array('minuteId' => $ia[1], 'currentminute' => $currenthour, 'dropdown_dates_minute_step' => $aQuestionAttributes['dropdown_dates_minute_step'], 'datepart' => $datepart), true);
                    break;
                default:
                    $sRows .= doRender('/survey/questions/date/dropdown/rows/datepart', array('datepart' => $datepart), true);
            }
        }
        // Format the date  for output
        $dateoutput = trim($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$ia[1]]);
        if ($dateoutput != '' & $dateoutput != 'INVALID') {
            $datetimeobj = new Date_Time_Converter($dateoutput, "Y-m-d H:i");
            $dateoutput = $datetimeobj->convert($dateformatdetails['phpdate']);
        }
        // ==> answer
        $answer = doRender('/survey/questions/date/dropdown/answer', array('sRows' => $sRows, 'name' => $ia[1], 'dateoutput' => htmlspecialchars($dateoutput, ENT_QUOTES, 'utf-8'), 'checkconditionFunction' => $checkconditionFunction . '(this.value, this.name, this.type)', 'dateformatdetails' => $dateformatdetails['jsdate'], 'dateformat' => $dateformatdetails['jsdate']), true);
        App()->getClientScript()->registerScript("doDropDownDate{$ia[0]}", "doDropDownDate({$ia[0]});", CClientScript::POS_HEAD);
    } else {
        // Format the date  for output
        $dateoutput = trim($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$ia[1]]);
        if ($dateoutput != '' & $dateoutput != 'INVALID') {
            $datetimeobj = new Date_Time_Converter($dateoutput, "Y-m-d H:i");
            $dateoutput = $datetimeobj->convert($dateformatdetails['phpdate']);
        }
        $goodchars = str_replace(array("m", "d", "y"), "", $dateformatdetails['jsdate']);
        $goodchars = "0123456789" . substr($goodchars, 0, 1);
        // Max length of date : Get the date of 1999-12-30 at 32:59:59 to be sure to have space with non leading 0 format
        // "+1" makes room for a trailing space in date/time values
        $iLength = strlen(date($dateformatdetails['phpdate'], mktime(23, 59, 59, 12, 30, 1999))) + 1;
        // Hide calendar (but show hour/minute) if there's no year, month or day in format
        $hideCalendar = strpos($dateformatdetails['jsdate'], 'Y') === false && strpos($dateformatdetails['jsdate'], 'D') === false && strpos($dateformatdetails['jsdate'], 'M') === false;
        // HTML for date question using datepicker
        $answer = doRender('/survey/questions/date/selector/answer', array('name' => $ia[1], 'iLength' => $iLength, 'mindate' => $mindate, 'maxdate' => $maxdate, 'dateformatdetails' => $dateformatdetails['dateformat'], 'dateformatdetailsjs' => $dateformatdetails['jsdate'], 'goodchars' => "", 'checkconditionFunction' => $checkconditionFunction . '(this.value, this.name, this.type)', 'language' => App()->language, 'hidetip' => trim($aQuestionAttributes['hide_tip']) == 0, 'dateoutput' => $dateoutput, 'qid' => $ia[0], 'hideCalendar' => $hideCalendar), true);
    }
    $inputnames[] = $ia[1];
    return array($answer, $inputnames);
}
Example #23
0
 /**
  * Saves the new survey after the creation screen is submitted
  *
  * @param $iSurveyID  The survey id to be used for the new survey. If already taken a new random one will be used.
  */
 function insert($iSurveyID = null)
 {
     if (Permission::model()->hasGlobalPermission('surveys', 'create')) {
         // Check if survey title was set
         if (!$_POST['surveyls_title']) {
             Yii::app()->session['flashmessage'] = gT("Survey could not be created because it did not have a title");
             redirect($this->getController()->createUrl('admin'));
             return;
         }
         Yii::app()->loadHelper("surveytranslator");
         // If start date supplied convert it to the right format
         $aDateFormatData = getDateFormatData(Yii::app()->session['dateformat']);
         $sStartDate = $_POST['startdate'];
         if (trim($sStartDate) != '') {
             Yii::import('application.libraries.Date_Time_Converter');
             $converter = new Date_Time_Converter($sStartDate, $aDateFormatData['phpdate'] . ' H:i:s');
             $sStartDate = $converter->convert("Y-m-d H:i:s");
         }
         // If expiry date supplied convert it to the right format
         $sExpiryDate = $_POST['expires'];
         if (trim($sExpiryDate) != '') {
             Yii::import('application.libraries.Date_Time_Converter');
             $converter = new Date_Time_Converter($sExpiryDate, $aDateFormatData['phpdate'] . ' H:i:s');
             $sExpiryDate = $converter->convert("Y-m-d H:i:s");
         }
         $iTokenLength = $_POST['tokenlength'];
         //token length has to be at least 5, otherwise set it to default (15)
         if ($iTokenLength < 5) {
             $iTokenLength = 15;
         }
         if ($iTokenLength > 36) {
             $iTokenLength = 36;
         }
         // Insert base settings into surveys table
         $aInsertData = array('expires' => $sExpiryDate, 'startdate' => $sStartDate, 'template' => App()->request->getPost('template'), 'owner_id' => Yii::app()->session['loginID'], 'admin' => App()->request->getPost('admin'), 'active' => 'N', 'anonymized' => App()->request->getPost('anonymized'), 'faxto' => App()->request->getPost('faxto'), 'format' => App()->request->getPost('format'), 'savetimings' => App()->request->getPost('savetimings'), 'language' => App()->request->getPost('language'), 'datestamp' => App()->request->getPost('datestamp'), 'ipaddr' => App()->request->getPost('ipaddr'), 'refurl' => App()->request->getPost('refurl'), 'usecookie' => App()->request->getPost('usecookie'), 'emailnotificationto' => App()->request->getPost('emailnotificationto'), 'allowregister' => App()->request->getPost('allowregister'), 'allowsave' => App()->request->getPost('allowsave'), 'navigationdelay' => App()->request->getPost('navigationdelay'), 'autoredirect' => App()->request->getPost('autoredirect'), 'showxquestions' => App()->request->getPost('showxquestions'), 'showgroupinfo' => App()->request->getPost('showgroupinfo'), 'showqnumcode' => App()->request->getPost('showqnumcode'), 'shownoanswer' => App()->request->getPost('shownoanswer'), 'showwelcome' => App()->request->getPost('showwelcome'), 'allowprev' => App()->request->getPost('allowprev'), 'questionindex' => App()->request->getPost('questionindex'), 'nokeyboard' => App()->request->getPost('nokeyboard'), 'showprogress' => App()->request->getPost('showprogress'), 'printanswers' => App()->request->getPost('printanswers'), 'listpublic' => App()->request->getPost('public'), 'htmlemail' => App()->request->getPost('htmlemail'), 'sendconfirmation' => App()->request->getPost('sendconfirmation'), 'tokenanswerspersistence' => App()->request->getPost('tokenanswerspersistence'), 'alloweditaftercompletion' => App()->request->getPost('alloweditaftercompletion'), 'usecaptcha' => App()->request->getPost('usecaptcha'), 'publicstatistics' => App()->request->getPost('publicstatistics'), 'publicgraphs' => App()->request->getPost('publicgraphs'), 'assessments' => App()->request->getPost('assessments'), 'emailresponseto' => App()->request->getPost('emailresponseto'), 'tokenlength' => $iTokenLength);
         $warning = '';
         // make sure we only update emails if they are valid
         if (Yii::app()->request->getPost('adminemail', '') == '' || validateEmailAddress(Yii::app()->request->getPost('adminemail'))) {
             $aInsertData['adminemail'] = Yii::app()->request->getPost('adminemail');
         } else {
             $aInsertData['adminemail'] = '';
             $warning .= gT("Warning! Notification email was not updated because it was not valid.") . '<br/>';
         }
         if (Yii::app()->request->getPost('bounce_email', '') == '' || validateEmailAddress(Yii::app()->request->getPost('bounce_email'))) {
             $aInsertData['bounce_email'] = Yii::app()->request->getPost('bounce_email');
         } else {
             $aInsertData['bounce_email'] = '';
             $warning .= gT("Warning! Bounce email was not updated because it was not valid.") . '<br/>';
         }
         if (!is_null($iSurveyID)) {
             $aInsertData['wishSID'] = $iSurveyID;
         }
         $iNewSurveyid = Survey::model()->insertNewSurvey($aInsertData);
         if (!$iNewSurveyid) {
             die('Survey could not be created.');
         }
         // Prepare locale data for surveys_language_settings table
         $sTitle = $_POST['surveyls_title'];
         $sDescription = $_POST['description'];
         $sWelcome = $_POST['welcome'];
         $sURLDescription = $_POST['urldescrip'];
         $sTitle = html_entity_decode($sTitle, ENT_QUOTES, "UTF-8");
         $sDescription = html_entity_decode($sDescription, ENT_QUOTES, "UTF-8");
         $sWelcome = html_entity_decode($sWelcome, ENT_QUOTES, "UTF-8");
         $sURLDescription = html_entity_decode($sURLDescription, ENT_QUOTES, "UTF-8");
         // Fix bug with FCKEditor saving strange BR types
         $sTitle = fixCKeditorText($sTitle);
         $sDescription = fixCKeditorText($sDescription);
         $sWelcome = fixCKeditorText($sWelcome);
         // Insert base language into surveys_language_settings table
         $aInsertData = array('surveyls_survey_id' => $iNewSurveyid, 'surveyls_title' => $sTitle, 'surveyls_description' => $sDescription, 'surveyls_welcometext' => $sWelcome, 'surveyls_language' => $_POST['language'], 'surveyls_urldescription' => $_POST['urldescrip'], 'surveyls_endtext' => $_POST['endtext'], 'surveyls_url' => $_POST['url'], 'surveyls_dateformat' => (int) $_POST['dateformat'], 'surveyls_numberformat' => (int) $_POST['numberformat']);
         $langsettings = new SurveyLanguageSetting();
         $langsettings->insertNewSurvey($aInsertData);
         Yii::app()->session['flashmessage'] = $warning . gT("Survey was successfully added.");
         // Update survey permissions
         Permission::model()->giveAllSurveyPermissions(Yii::app()->session['loginID'], $iNewSurveyid);
         $this->getController()->redirect(array('admin/survey/sa/view/surveyid/' . $iNewSurveyid));
     }
 }
Example #24
0
 $surveysummary .= "</td></tr>\n" . "<tr >\n" . "<td align='right' valign='top'><strong>" . $clang->gT("Welcome:") . "</strong></td>\n" . "<td align='left'> {$surveyinfo['surveyls_welcometext']}</td></tr>\n" . "<tr ><td align='right' valign='top'><strong>" . $clang->gT("Administrator:") . "</strong></td>\n" . "<td align='left'> {$surveyinfo['admin']} ({$surveyinfo['adminemail']})</td></tr>\n";
 if (trim($surveyinfo['faxto']) != '') {
     $surveysummary .= "<tr><td align='right' valign='top'><strong>" . $clang->gT("Fax to:") . "</strong></td>\n<td align='left'>{$surveyinfo['faxto']}";
     $surveysummary .= "</td></tr>\n";
 }
 $surveysummary .= "<tr><td align='right' valign='top'><strong>" . $clang->gT("Start date/time:") . "</strong></td>\n";
 $dateformatdetails = getDateFormatData($_SESSION['dateformat']);
 if (trim($surveyinfo['startdate']) != '') {
     $datetimeobj = new Date_Time_Converter($surveyinfo['startdate'], "Y-m-d H:i:s");
     $startdate = $datetimeobj->convert($dateformatdetails['phpdate'] . ' H:i');
 } else {
     $startdate = "-";
 }
 $surveysummary .= "<td align='left'>{$startdate}</td></tr>\n" . "<tr><td align='right' valign='top'><strong>" . $clang->gT("Expiry date/time:") . "</strong></td>\n";
 if (trim($surveyinfo['expires']) != '') {
     $datetimeobj = new Date_Time_Converter($surveyinfo['expires'], "Y-m-d H:i:s");
     $expdate = $datetimeobj->convert($dateformatdetails['phpdate'] . ' H:i');
 } else {
     $expdate = "-";
 }
 $surveysummary .= "<td align='left'>{$expdate}</td></tr>\n" . "<tr ><td align='right' valign='top'><strong>" . $clang->gT("Template:") . "</strong></td>\n" . "<td align='left'> {$surveyinfo['template']}</td></tr>\n" . "<tr><td align='right' valign='top'><strong>" . $clang->gT("Base language:") . "</strong></td>\n";
 if (!$surveyinfo['language']) {
     $language = getLanguageNameFromCode($currentadminlang, false);
 } else {
     $language = getLanguageNameFromCode($surveyinfo['language'], false);
 }
 $surveysummary .= "<td align='left'>{$language}</td></tr>\n";
 // get the rowspan of the Additionnal languages row
 // is at least 1 even if no additionnal language is present
 $additionnalLanguagesCount = count($aAdditionalLanguages);
 $surveysummary .= "<tr><td align='right' valign='top'><strong>" . $clang->gT("Additional Languages") . ":</strong></td>\n";
/**
* This is a convenience function for the coversion of datetime values
*
* @param mixed $value
* @param mixed $fromdateformat
* @param mixed $todateformat
* @return string
*/
function convertDateTimeFormat($value, $fromdateformat, $todateformat)
{
    Yii::import('application.libraries.Date_Time_Converter', true);
    $date = new Date_Time_Converter($value, $fromdateformat);
    return $date->convert($todateformat);
}
Example #26
0
     $_POST['urldescrip'] = html_entity_decode($_POST['urldescrip'], ENT_QUOTES, "UTF-8");
 }
 //make sure only numbers are passed within the $_POST variable
 $_POST['dateformat'] = (int) $_POST['dateformat'];
 $_POST['tokenlength'] = (int) $_POST['tokenlength'];
 if (trim($_POST['expires']) == '') {
     $_POST['expires'] = null;
 } else {
     $datetimeobj = new Date_Time_Converter($_POST['expires'], "d.m.Y H:i");
     $browsedatafield = $datetimeobj->convert("Y-m-d H:i:s");
     $_POST['expires'] = $browsedatafield;
 }
 if (trim($_POST['startdate']) == '') {
     $_POST['startdate'] = null;
 } else {
     $datetimeobj = new Date_Time_Converter($_POST['startdate'], "d.m.Y H:i");
     $browsedatafield = $datetimeobj->convert("Y-m-d H:i:s");
     $_POST['startdate'] = $browsedatafield;
 }
 $insertarray = array('sid' => $surveyid, 'owner_id' => $_SESSION['loginID'], 'admin' => $_POST['admin'], 'active' => 'N', 'expires' => $_POST['expires'], 'startdate' => $_POST['startdate'], 'adminemail' => $_POST['adminemail'], 'bounce_email' => $_POST['bounce_email'], 'anonymized' => $_POST['anonymized'], 'faxto' => $_POST['faxto'], 'format' => $_POST['format'], 'savetimings' => $_POST['savetimings'], 'template' => $_POST['template'], 'language' => $_POST['language'], 'datestamp' => $_POST['datestamp'], 'ipaddr' => $_POST['ipaddr'], 'refurl' => $_POST['refurl'], 'usecookie' => $_POST['usecookie'], 'emailnotificationto' => $_POST['emailnotificationto'], 'allowregister' => $_POST['allowregister'], 'allowsave' => $_POST['allowsave'], 'navigationdelay' => $_POST['navigationdelay'], 'autoredirect' => $_POST['autoredirect'], 'showxquestions' => $_POST['showxquestions'], 'showgroupinfo' => $_POST['showgroupinfo'], 'showqnumcode' => $_POST['showqnumcode'], 'shownoanswer' => $_POST['shownoanswer'], 'showwelcome' => $_POST['showwelcome'], 'allowprev' => $_POST['allowprev'], 'allowjumps' => $_POST['allowjumps'], 'nokeyboard' => $_POST['nokeyboard'], 'showprogress' => $_POST['showprogress'], 'printanswers' => $_POST['printanswers'], 'datecreated' => date("Y-m-d"), 'listpublic' => $_POST['public'], 'htmlemail' => $_POST['htmlemail'], 'tokenanswerspersistence' => $_POST['tokenanswerspersistence'], 'alloweditaftercompletion' => $_POST['alloweditaftercompletion'], 'usecaptcha' => $_POST['usecaptcha'], 'publicstatistics' => $_POST['publicstatistics'], 'publicgraphs' => $_POST['publicgraphs'], 'assessments' => $_POST['assessments'], 'emailresponseto' => $_POST['emailresponseto'], 'tokenlength' => $_POST['tokenlength']);
 $dbtablename = db_table_name_nq('surveys');
 $isquery = $connect->GetInsertSQL($dbtablename, $insertarray);
 $isresult = $connect->Execute($isquery) or safe_die($isquery . "<br />" . $connect->ErrorMsg());
 // Checked
 // Fix bug with FCKEditor saving strange BR types
 $_POST['surveyls_title'] = fix_FCKeditor_text($_POST['surveyls_title']);
 $_POST['description'] = fix_FCKeditor_text($_POST['description']);
 $_POST['welcome'] = fix_FCKeditor_text($_POST['welcome']);
 $bplang = new limesurvey_lang($_POST['language']);
 $aDefaultTexts = aTemplateDefaultTexts($bplang, 'unescaped');
 $is_html_email = false;
/**
* 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;
}
 /**
  * Cleanse the $_POSTed data and update $_SESSION variables accordingly
  */
 static function ProcessCurrentResponses()
 {
     $LEM =& LimeExpressionManager::singleton();
     if (!isset($LEM->currentQset)) {
         return array();
     }
     $updatedValues = array();
     $radixchange = $LEM->surveyOptions['radix'] == ',' ? true : false;
     foreach ($LEM->currentQset as $qinfo) {
         $relevant = false;
         $qid = $qinfo['info']['qid'];
         $gseq = $qinfo['info']['gseq'];
         $relevant = isset($_POST['relevance' . $qid]) ? $_POST['relevance' . $qid] == 1 : false;
         $grelevant = isset($_POST['relevanceG' . $gseq]) ? $_POST['relevanceG' . $gseq] == 1 : false;
         $_SESSION[$LEM->sessid]['relevanceStatus'][$qid] = $relevant;
         $_SESSION[$LEM->sessid]['relevanceStatus']['G' . $gseq] = $grelevant;
         foreach (explode('|', $qinfo['sgqa']) as $sq) {
             $sqrelevant = true;
             if (isset($LEM->subQrelInfo[$qid][$sq]['rowdivid'])) {
                 $rowdivid = $LEM->subQrelInfo[$qid][$sq]['rowdivid'];
                 if ($rowdivid != '' && isset($_POST['relevance' . $rowdivid])) {
                     $sqrelevant = $_POST['relevance' . $rowdivid] == 1;
                     $_SESSION[$LEM->sessid]['relevanceStatus'][$rowdivid] = $sqrelevant;
                 }
             }
             $type = $qinfo['info']['type'];
             if ($relevant && $grelevant && $sqrelevant || !$LEM->surveyOptions['deletenonvalues']) {
                 if ($qinfo['info']['hidden'] && !isset($_POST[$sq])) {
                     $value = isset($_SESSION[$LEM->sessid][$sq]) ? $_SESSION[$LEM->sessid][$sq] : '';
                     // if always hidden, use the default value, if any
                 } else {
                     $value = isset($_POST[$sq]) ? $_POST[$sq] : '';
                 }
                 // Check for and adjust ',' and '.' in numbers
                 $isOnlyNum = isset($LEM->knownVars[$sq]['onlynum']) && $LEM->knownVars[$sq]['onlynum'] == '1';
                 if ($radixchange && $isOnlyNum) {
                     // Convert from comma back to decimal
                     // Also make sure to be able to convert numbers like 1.100,10
                     $value = preg_replace('|\\.|', '', $value);
                     $value = preg_replace('|\\,|', '.', $value);
                 } elseif (!$radixchange && $isOnlyNum) {
                     // Still have to remove all ',' introduced by the thousand separator
                     $value = preg_replace('|\\,|', '', $value);
                 }
                 switch ($type) {
                     case 'D':
                         //DATE
                         $value = trim($value);
                         if ($value != "" && $value != "INVALID") {
                             $aAttributes = $LEM->getQuestionAttributesForEM($LEM->sid, $qid, $_SESSION['LEMlang']);
                             if (!isset($aAttributes[$qid])) {
                                 $aAttributes[$qid] = array();
                             }
                             $aDateFormatData = getDateFormatDataForQID($aAttributes[$qid], $LEM->surveyOptions);
                             // We don't really validate date here : if date is invalid : return 1999-12-01 00:00
                             $oDateTimeConverter = new Date_Time_Converter(trim($value), $aDateFormatData['phpdate']);
                             $newValue = $oDateTimeConverter->convert("Y-m-d H:i");
                             $oDateTimeConverter = new Date_Time_Converter($newValue, "Y-m-d H:i");
                             if ($value == $oDateTimeConverter->convert($aDateFormatData['phpdate'])) {
                                 $value = $newValue;
                             } else {
                                 $value = "";
                                 // Or $value="INVALID" ? : dropdown is OK with this not default.
                             }
                         }
                         break;
                         #                            case 'N': //NUMERICAL QUESTION TYPE
                         #                            case 'K': //MULTIPLE NUMERICAL QUESTION
                         #                                if (trim($value)=="") {
                         #                                    $value = "";
                         #                                }
                         #                                else {
                         #                                    $value = sanitize_float($value);
                         #                                }
                         break;
                     case '|':
                         //File Upload
                         if (!preg_match('/_filecount$/', $sq)) {
                             $json = $value;
                             $phparray = json_decode(stripslashes($json));
                             // if the files have not been saved already,
                             // move the files from tmp to the files folder
                             $tmp = $LEM->surveyOptions['tempdir'] . 'upload' . DIRECTORY_SEPARATOR;
                             if (!is_null($phparray) && count($phparray) > 0) {
                                 // Move the (unmoved, temp) files from temp to files directory.
                                 // Check all possible file uploads
                                 for ($i = 0; $i < count($phparray); $i++) {
                                     if (file_exists($tmp . $phparray[$i]->filename)) {
                                         $sDestinationFileName = 'fu_' . randomChars(15);
                                         if (!is_dir($LEM->surveyOptions['target'])) {
                                             mkdir($LEM->surveyOptions['target'], 0777, true);
                                         }
                                         if (!rename($tmp . $phparray[$i]->filename, $LEM->surveyOptions['target'] . $sDestinationFileName)) {
                                             echo "Error moving file to target destination";
                                         }
                                         $phparray[$i]->filename = $sDestinationFileName;
                                     }
                                 }
                                 $value = ls_json_encode($phparray);
                                 // so that EM doesn't try to parse it.
                             }
                         }
                         break;
                 }
                 $_SESSION[$LEM->sessid][$sq] = $value;
                 $_update = array('type' => $type, 'value' => $value);
                 $updatedValues[$sq] = $_update;
                 $LEM->updatedValues[$sq] = $_update;
             } else {
                 // irrelevant, so database will be NULLed separately
                 // Must unset the value, rather than setting to '', so that EM can re-use the default value as needed.
                 unset($_SESSION[$LEM->sessid][$sq]);
                 $_update = array('type' => $type, 'value' => NULL);
                 $updatedValues[$sq] = $_update;
                 $LEM->updatedValues[$sq] = $_update;
             }
         }
     }
     if (isset($_POST['timerquestion'])) {
         $_SESSION[$LEM->sessid][$_POST['timerquestion']] = sanitize_float($_POST[$_POST['timerquestion']]);
     }
     return $updatedValues;
 }
Example #29
0
 /**
  * dataentry::insert()
  * insert new dataentry
  * @return
  */
 public function insert()
 {
     $clang = Yii::app()->lang;
     $subaction = Yii::app()->request->getPost('subaction');
     $surveyid = Yii::app()->request->getPost('sid');
     $lang = isset($_POST['lang']) ? Yii::app()->request->getPost('lang') : NULL;
     $aData = array('surveyid' => $surveyid, 'lang' => $lang, 'clang' => $clang);
     if (hasSurveyPermission($surveyid, 'responses', 'read')) {
         if ($subaction == "insert" && hasSurveyPermission($surveyid, 'responses', 'create')) {
             $surveytable = "{{survey_{$surveyid}}}";
             $thissurvey = getSurveyInfo($surveyid);
             $errormsg = "";
             Yii::app()->loadHelper("database");
             $aViewUrls['display']['menu_bars']['browse'] = $clang->gT("Data entry");
             $aDataentryoutput = '';
             $aDataentrymsgs = array();
             $hiddenfields = '';
             $lastanswfortoken = '';
             // check if a previous answer has been submitted or saved
             $rlanguage = '';
             if (isset($_POST['token'])) {
                 $tokencompleted = "";
                 $tcquery = "SELECT completed from {{tokens_{$surveyid}}} WHERE token='{$_POST['token']}'";
                 //dbQuoteAll($_POST['token'],true);
                 $tcresult = dbExecuteAssoc($tcquery);
                 $tcresult = $tcresult->readAll();
                 $tccount = count($tcresult);
                 foreach ($tcresult as $tcrow) {
                     $tokencompleted = $tcrow['completed'];
                 }
                 if ($tccount < 1) {
                     // token doesn't exist in token table
                     $lastanswfortoken = 'UnknownToken';
                 } elseif ($thissurvey['anonymized'] == "Y") {
                     // token exist but survey is anonymous, check completed state
                     if ($tokencompleted != "" && $tokencompleted != "N") {
                         // token is completed
                         $lastanswfortoken = 'PrivacyProtected';
                     }
                 } else {
                     // token is valid, survey not anonymous, try to get last recorded response id
                     $aquery = "SELECT id,startlanguage FROM {$surveytable} WHERE token='" . $_POST['token'] . "'";
                     //dbQuoteAll($_POST['token'],true);
                     $aresult = dbExecuteAssoc($aquery);
                     foreach ($aresult->readAll() as $arow) {
                         if ($tokencompleted != "N") {
                             $lastanswfortoken = $arow['id'];
                         }
                         $rlanguage = $arow['startlanguage'];
                     }
                 }
             }
             // First Check if the survey uses tokens and if a token has been provided
             if (tableExists('{{tokens_' . $thissurvey['sid'] . '}}') && !$_POST['token']) {
                 $errormsg = CHtml::tag('div', array('class' => 'warningheader'), $clang->gT("Error"));
                 $errormsg .= CHtml::tag('p', array(), $clang->gT("This is a closed-access survey, so you must supply a valid token.  Please contact the administrator for assistance."));
             } elseif (tableExists('{{tokens_' . $thissurvey['sid'] . '}}') && $lastanswfortoken == 'UnknownToken') {
                 $errormsg = CHtml::tag('div', array('class' => 'warningheader'), $clang->gT("Error"));
                 $errormsg .= CHtml::tag('p', array(), $clang->gT("The token you have provided is not valid or has already been used."));
             } elseif (tableExists('{{tokens_' . $thissurvey['sid'] . '}}') && $lastanswfortoken != '') {
                 $errormsg = CHtml::tag('div', array('class' => 'warningheader'), $clang->gT("Error"));
                 $errormsg .= CHtml::tag('p', array(), $clang->gT("There is already a recorded answer for this token"));
                 if ($lastanswfortoken != 'PrivacyProtected') {
                     $errormsg .= "<br /><br />" . $clang->gT("Follow the following link to update it") . ":\n";
                     $errormsg .= CHtml::link("[id:{$lastanswfortoken}]", Yii::app()->baseUrl . ('/admin/dataentry/editdata/subaction/edit/id/' . $lastanswfortoken . '/surveyid/' . $surveyid . '/lang/' . $rlanguage), array('title' => $clang->gT("Edit this entry")));
                 } else {
                     $errormsg .= "<br /><br />" . $clang->gT("This surveys uses anonymized responses, so you can't update your response.") . "\n";
                 }
             } else {
                 $last_db_id = 0;
                 if (isset($_POST['save']) && $_POST['save'] == "on") {
                     $aData['save'] = TRUE;
                     $saver['identifier'] = $_POST['save_identifier'];
                     $saver['language'] = $_POST['save_language'];
                     $saver['password'] = $_POST['save_password'];
                     $saver['passwordconfirm'] = $_POST['save_confirmpassword'];
                     $saver['email'] = $_POST['save_email'];
                     if (!returnGlobal('redo')) {
                         $password = md5($saver['password']);
                     } else {
                         $password = $saver['password'];
                     }
                     $errormsg = "";
                     if (!$saver['identifier']) {
                         $errormsg .= $clang->gT("Error") . ": " . $clang->gT("You must supply a name for this saved session.");
                     }
                     if (!$saver['password']) {
                         $errormsg .= $clang->gT("Error") . ": " . $clang->gT("You must supply a password for this saved session.");
                     }
                     if ($saver['password'] != $saver['passwordconfirm']) {
                         $errormsg .= $clang->gT("Error") . ": " . $clang->gT("Your passwords do not match.");
                     }
                     $aData['errormsg'] = $errormsg;
                     if ($errormsg) {
                         foreach ($_POST as $key => $val) {
                             if (substr($key, 0, 4) != "save" && $key != "action" && $key != "sid" && $key != "datestamp" && $key != "ipaddr") {
                                 $hiddenfields .= CHtml::hiddenField($key, $val);
                                 //$aDataentryoutput .= "<input type='hidden' name='$key' value='$val' />\n";
                             }
                         }
                     }
                 }
                 //BUILD THE SQL TO INSERT RESPONSES
                 $baselang = Survey::model()->findByPk($surveyid)->language;
                 $fieldmap = createFieldMap($surveyid, 'full', false, false, getBaseLanguageFromSurveyID($surveyid));
                 $insert_data = array();
                 $_POST['startlanguage'] = $baselang;
                 if ($thissurvey['datestamp'] == "Y") {
                     $_POST['startdate'] = $_POST['datestamp'];
                 }
                 if (isset($_POST['closerecord'])) {
                     if ($thissurvey['datestamp'] == "Y") {
                         $_POST['submitdate'] = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", Yii::app()->getConfig('timeadjust'));
                     } else {
                         $_POST['submitdate'] = date("Y-m-d H:i:s", mktime(0, 0, 0, 1, 1, 1980));
                     }
                 }
                 foreach ($fieldmap as $irow) {
                     $fieldname = $irow['fieldname'];
                     if (isset($_POST[$fieldname])) {
                         if ($_POST[$fieldname] == "" && ($irow['type'] == 'D' || $irow['type'] == 'N' || $irow['type'] == 'K')) {
                             // can't add '' in Date column
                             // Do nothing
                         } else {
                             if ($irow['type'] == '|') {
                                 if (!strpos($irow['fieldname'], "_filecount")) {
                                     $json = $_POST[$fieldname];
                                     $phparray = json_decode(stripslashes($json));
                                     $filecount = 0;
                                     for ($i = 0; $filecount < count($phparray); $i++) {
                                         if ($_FILES[$fieldname . "_file_" . $i]['error'] != 4) {
                                             $target = Yii::app()->getConfig('uploaddir') . "/surveys/" . $thissurvey['sid'] . "/files/" . randomChars(20);
                                             $size = 0.001 * $_FILES[$fieldname . "_file_" . $i]['size'];
                                             $name = rawurlencode($_FILES[$fieldname . "_file_" . $i]['name']);
                                             if (move_uploaded_file($_FILES[$fieldname . "_file_" . $i]['tmp_name'], $target)) {
                                                 $phparray[$filecount]->filename = basename($target);
                                                 $phparray[$filecount]->name = $name;
                                                 $phparray[$filecount]->size = $size;
                                                 $pathinfo = pathinfo($_FILES[$fieldname . "_file_" . $i]['name']);
                                                 $phparray[$filecount]->ext = $pathinfo['extension'];
                                                 $filecount++;
                                             }
                                         }
                                     }
                                     $insert_data[$fieldname] = ls_json_encode($phparray);
                                 } else {
                                     $insert_data[$fieldname] = count($phparray);
                                 }
                             } elseif ($irow['type'] == 'D') {
                                 Yii::app()->loadLibrary('Date_Time_Converter');
                                 $qidattributes = getQuestionAttributeValues($irow['qid'], $irow['type']);
                                 $dateformatdetails = getDateFormatDataForQID($qidattributes, $thissurvey);
                                 $datetimeobj = new Date_Time_Converter($_POST[$fieldname], $dateformatdetails['phpdate']);
                                 $insert_data[$fieldname] = $datetimeobj->convert("Y-m-d H:i:s");
                             } else {
                                 $insert_data[$fieldname] = $_POST[$fieldname];
                             }
                         }
                     }
                 }
                 Survey_dynamic::sid($surveyid);
                 $new_response = new Survey_dynamic();
                 foreach ($insert_data as $column => $value) {
                     $new_response->{$column} = $value;
                 }
                 $new_response->save();
                 $last_db_id = $new_response->getPrimaryKey();
                 if (isset($_POST['closerecord']) && isset($_POST['token']) && $_POST['token'] != '') {
                     // get submit date
                     if (isset($_POST['closedate'])) {
                         $submitdate = $_POST['closedate'];
                     } else {
                         $submitdate = dateShift(date("Y-m-d H:i:s"), "Y-m-d", $timeadjust);
                     }
                     // check how many uses the token has left
                     $usesquery = "SELECT usesleft FROM {{tokens_}}{$surveyid} WHERE token='" . $_POST['token'] . "'";
                     $usesresult = dbExecuteAssoc($usesquery);
                     $usesrow = $usesresult->readAll();
                     //$usesresult->row_array()
                     if (isset($usesrow)) {
                         $usesleft = $usesrow[0]['usesleft'];
                     }
                     // query for updating tokens
                     $utquery = "UPDATE {{tokens_{$surveyid}}}\n";
                     if (isTokenCompletedDatestamped($thissurvey)) {
                         if (isset($usesleft) && $usesleft <= 1) {
                             $utquery .= "SET usesleft=usesleft-1, completed='{$submitdate}'\n";
                         } else {
                             $utquery .= "SET usesleft=usesleft-1\n";
                         }
                     } else {
                         if (isset($usesleft) && $usesleft <= 1) {
                             $utquery .= "SET usesleft=usesleft-1, completed='Y'\n";
                         } else {
                             $utquery .= "SET usesleft=usesleft-1\n";
                         }
                     }
                     $utquery .= "WHERE token='" . $_POST['token'] . "'";
                     $utresult = dbExecuteAssoc($utquery);
                     //Yii::app()->db->Execute($utquery) or safeDie ("Couldn't update tokens table!<br />\n$utquery<br />\n".Yii::app()->db->ErrorMsg());
                     // save submitdate into survey table
                     $srid = Yii::app()->db->getLastInsertID();
                     // Yii::app()->db->getLastInsertID();
                     $sdquery = "UPDATE {{survey_{$surveyid}}} SET submitdate='" . $submitdate . "' WHERE id={$srid}\n";
                     $sdresult = dbExecuteAssoc($sdquery) or safeDie("Couldn't set submitdate response in survey table!<br />\n{$sdquery}<br />\n");
                     $last_db_id = Yii::app()->db->getLastInsertID();
                 }
                 if (isset($_POST['save']) && $_POST['save'] == "on") {
                     $srid = Yii::app()->db->getLastInsertID();
                     //Yii::app()->db->getLastInsertID();
                     $aUserData = Yii::app()->session;
                     //CREATE ENTRY INTO "saved_control"
                     $saved_control_table = '{{saved_control}}';
                     $columns = array("sid", "srid", "identifier", "access_code", "email", "ip", "refurl", 'saved_thisstep', "status", "saved_date");
                     $values = array("'" . $surveyid . "'", "'" . $srid . "'", "'" . $saver['identifier'] . "'", "'" . $password . "'", "'" . $saver['email'] . "'", "'" . $aUserData['ip_address'] . "'", "'" . getenv("HTTP_REFERER") . "'", 0, "'" . "S" . "'", "'" . dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", "'" . Yii::app()->getConfig('timeadjust')) . "'");
                     $SQL = "INSERT INTO {$saved_control_table}\n                        (" . implode(',', $columns) . ")\n                        VALUES\n                        (" . implode(',', $values) . ")";
                     /*$scdata = array("sid"=>$surveyid,
                       "srid"=>$srid,
                       "identifier"=>$saver['identifier'],
                       "access_code"=>$password,
                       "email"=>$saver['email'],
                       "ip"=>$aUserData['ip_address'],
                       "refurl"=>getenv("HTTP_REFERER"),
                       'saved_thisstep' => 0,
                       "status"=>"S",
                       "saved_date"=>dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", Yii::app()->getConfig('timeadjust')));
                       $this->load->model('saved_control_model');*/
                     if (dbExecuteAssoc($SQL)) {
                         $scid = Yii::app()->db->getLastInsertID();
                         // Yii::app()->db->getLastInsertID("{{saved_control}}","scid");
                         $aDataentrymsgs[] = CHtml::tag('font', array('class' => 'successtitle'), $clang->gT("Your survey responses have been saved successfully.  You will be sent a confirmation e-mail. Please make sure to save your password, since we will not be able to retrieve it for you."));
                         //$aDataentryoutput .= "<font class='successtitle'></font><br />\n";
                         $tokens_table = "{{tokens_{$surveyid}}}";
                         $last_db_id = Yii::app()->db->getLastInsertID();
                         if (tableExists($tokens_table)) {
                             $tkquery = "SELECT * FROM {$tokens_table}";
                             $tkresult = dbExecuteAssoc($tkquery);
                             /*$tokendata = array (
                               "firstname"=> $saver['identifier'],
                               "lastname"=> $saver['identifier'],
                               "email"=>$saver['email'],
                               "token"=>randomChars(15),
                               "language"=>$saver['language'],
                               "sent"=>dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i", $timeadjust),
                               "completed"=>"N");*/
                             $columns = array("firstname", "lastname", "email", "token", "language", "sent", "completed");
                             $values = array("'" . $saver['identifier'] . "'", "'" . $saver['identifier'] . "'", "'" . $saver['email'] . "'", "'" . $password . "'", "'" . randomChars(15) . "'", "'" . $saver['language'] . "'", "'" . "N" . "'");
                             $SQL = "INSERT INTO {$token_table}\n                                (" . implode(',', $columns) . ")\n                                VALUES\n                                (" . implode(',', $values) . ")";
                             //$this->tokens_dynamic_model->insertToken($surveyid,$tokendata);
                             dbExecuteAssoc($SQL);
                             //Yii::app()->db->AutoExecute(db_table_name("tokens_".$surveyid), $tokendata,'INSERT');
                             $aDataentrymsgs[] = CHtml::tag('font', array('class' => 'successtitle'), $clang->gT("A token entry for the saved survey has been created too."));
                             //$aDataentryoutput .= "<font class='successtitle'></font><br />\n";
                             $last_db_id = Yii::app()->db->getLastInsertID();
                         }
                         if ($saver['email']) {
                             //Send email
                             if (validateEmailAddress($saver['email']) && !returnGlobal('redo')) {
                                 $subject = $clang->gT("Saved Survey Details");
                                 $message = $clang->gT("Thank you for saving your survey in progress.  The following details can be used to return to this survey and continue where you left off.  Please keep this e-mail for your reference - we cannot retrieve the password for you.");
                                 $message .= "\n\n" . $thissurvey['name'] . "\n\n";
                                 $message .= $clang->gT("Name") . ": " . $saver['identifier'] . "\n";
                                 $message .= $clang->gT("Password") . ": " . $saver['password'] . "\n\n";
                                 $message .= $clang->gT("Reload your survey by clicking on the following link (or pasting it into your browser):") . ":\n";
                                 $message .= Yii::app()->getConfig('publicurl') . "/index.php?sid={$surveyid}&loadall=reload&scid=" . $scid . "&lang=" . urlencode($saver['language']) . "&loadname=" . urlencode($saver['identifier']) . "&loadpass="******"&token=" . $tokendata['token'];
                                 }
                                 $from = $thissurvey['adminemail'];
                                 if (SendEmailMessage($message, $subject, $saver['email'], $from, $sitename, false, getBounceEmail($surveyid))) {
                                     $emailsent = "Y";
                                     $aDataentrymsgs[] = CHtml::tag('font', array('class' => 'successtitle'), $clang->gT("An email has been sent with details about your saved survey"));
                                 }
                             }
                         }
                     } else {
                         safeDie("Unable to insert record into saved_control table.<br /><br />");
                     }
                 }
                 $aData['thisid'] = $last_db_id;
             }
             $aData['errormsg'] = $errormsg;
             $aData['dataentrymsgs'] = $aDataentrymsgs;
             $this->_renderWrappedTemplate('dataentry', 'insert', $aData);
         }
     }
 }
Example #30
0
                    <label class="col-sm-2 control-label"  for='usesleft'><?php eT("Uses left:"); ?></label>
                    <div class="col-sm-10">
                        <input type='text' size='20' id='usesleft' name='usesleft' value="<?php if (isset($usesleft)){echo $usesleft;}else{echo "1";}?>" />
                    </div>
                </div>

                <!-- Valid from to  -->                    
                <div class="form-group">
                    <label class="col-sm-2 control-label"  for='validfrom'><?php eT("Valid from"); ?>:</label>
                    <div class="col-sm-2">
                        <input type='text' class='popupdatetime' size='20' id='validfrom' name='validfrom' value="<?php if (isset($validfrom)){Yii::import('application.libraries.Date_Time_Converter', true);$datetimeobj = new Date_Time_Converter($validfrom, "Y-m-d H:i:s"); echo $datetimeobj->convert($dateformatdetails['phpdate'] . ' H:i');} ?>" /> 
                    </div>
    
                    <label class="col-sm-2 control-label"  for='validuntil'><?php eT('until'); ?></label>
                    <div class="col-sm-5">
                        <input type='text' size='20' id='validuntil' name='validuntil' class='popupdatetime' value="<?php if (isset($validuntil)){$datetimeobj = new Date_Time_Converter($validuntil, "Y-m-d H:i:s");echo $datetimeobj->convert($dateformatdetails['phpdate'] . ' H:i');}?>" /> <span class='annotation'><?php echo sprintf(gT('Format: %s'), $dateformatdetails['dateformat'] . ' ' . gT('hh:mm')); ?></span>
                    </div>
                </div>
                    
                <!-- Attributes -->                    
                <?php foreach ($attrfieldnames as $attr_name => $attr_description): ?>
                    <div class="form-group">
                        <label class="col-sm-2 control-label"  for='<?php echo $attr_name; ?>'><?php echo $attr_description['description'] . ($attr_description['mandatory'] == 'Y' ? '*' : '') ?>:</label>
                        <div class="col-sm-10">
                            <input type='text' size='55' id='<?php echo $attr_name; ?>' name='<?php echo $attr_name; ?>' value='<?php if (isset($$attr_name)){echo htmlspecialchars($$attr_name, ENT_QUOTES, 'UTF-8');}?>' />
                        </div>
                    </div>
                <?php endforeach; ?>

                <!-- Buttons -->                
                <p>