Example #1
0
 public function formatLanguageList($value)
 {
     $langArr = explode(' ', trim($value));
     $expandedArr = array();
     foreach ($langArr as $lang) {
         array_push($expandedArr, getLanguageNameFromCode($lang, false));
     }
     sort($expandedArr);
     return implode(', ', $expandedArr);
 }
Example #2
0
function browsemenubar($title = '')
{
    global $surveyid, $scriptname, $imagefiles, $homeurl, $clang, $sumrows5, $surrows;
    $thissurvey = getSurveyInfo($surveyid);
    //BROWSE MENU BAR
    $browsemenubar = "<div class='menubar'>\n" . "<div class='menubar-title'>\n" . "<strong>{$title}</strong>: ({$thissurvey['name']})" . "</div>" . "<div class='menubar-main'>\n" . "<div class='menubar-left'>\n" . "<a href='{$scriptname}?sid={$surveyid}' title=\"" . $clang->gTview("Return to survey administration") . "\" >" . "<img name='Administration' src='{$imagefiles}/home.png' title='' alt='" . $clang->gT("Return to survey administration") . "' /></a>\n" . "<img src='{$imagefiles}/blank.gif' alt='' width='11' />\n" . "<img src='{$imagefiles}/seperator.gif' alt='' />\n" . "<a href='{$scriptname}?action=browse&amp;sid={$surveyid}' title=\"" . $clang->gTview("Show summary information") . "\" >" . "<img name='SurveySummary' src='{$imagefiles}/summary.png' title='' alt='" . $clang->gT("Show summary information") . "' /></a>\n";
    //Display responses
    if (count(GetAdditionalLanguagesFromSurveyID($surveyid)) == 0) {
        $browsemenubar .= "<a href='{$scriptname}?action=browse&amp;sid={$surveyid}&amp;subaction=all' title=\"" . $clang->gTview("Display Responses") . "\" >" . "<img name='ViewAll' src='{$imagefiles}/document.png' title='' alt='" . $clang->gT("Display Responses") . "' /></a>\n";
    } else {
        $browsemenubar .= "<a href=\"#\" accesskey='b' id='browseresponses'" . "title=\"" . $clang->gTview("Display Responses") . "\" >" . "<img src='{$imagefiles}/document.png' alt='" . $clang->gT("Display Responses") . "' name='ViewAll' /></a>";
        $tmp_survlangs = GetAdditionalLanguagesFromSurveyID($surveyid);
        $baselang = GetBaseLanguageFromSurveyID($surveyid);
        $tmp_survlangs[] = $baselang;
        rsort($tmp_survlangs);
        $browsemenubar .= "<div class=\"langpopup\" id=\"browselangpopup\">" . $clang->gT("Please select a language:") . "<ul>";
        foreach ($tmp_survlangs as $tmp_lang) {
            $browsemenubar .= "<li><a href=\"{$scriptname}?action=browse&amp;sid={$surveyid}&amp;subaction=all&amp;browselang={$tmp_lang}\" accesskey='b'>" . getLanguageNameFromCode($tmp_lang, false) . "</a></li>";
        }
        $browsemenubar .= "</ul></div>";
    }
    // Display last 50 responses
    $browsemenubar .= "<a href='{$scriptname}?action=browse&amp;sid={$surveyid}&amp;subaction=all&amp;limit=50&amp;order=desc'" . " title=\"" . $clang->gTview("Display Last 50 Responses") . "\" >" . "<img name='ViewLast' src='{$imagefiles}/viewlast.png' alt='" . $clang->gT("Display Last 50 Responses") . "' /></a>\n";
    // Data entry
    $browsemenubar .= "<a href='{$scriptname}?action=dataentry&amp;sid={$surveyid}'" . " title=\"" . $clang->gTview("Dataentry Screen for Survey") . "\" >" . "<img name='DataEntry' src='{$imagefiles}/dataentry.png' alt='" . $clang->gT("Dataentry Screen for Survey") . "' /></a>\n";
    // Statistics
    $browsemenubar .= "<a href='{$scriptname}?action=statistics&amp;sid={$surveyid}' " . "title=\"" . $clang->gTview("Get statistics from these responses") . "\" >" . "<img name='Statistics' src='{$imagefiles}/statistics.png' alt='" . $clang->gT("Get statistics from these responses") . "' /></a>\n";
    $browsemenubar .= "<img src='{$imagefiles}/seperator.gif' alt='' />\n";
    if (bHasRight($surveyid, 'export')) {
        // Export to application
        $browsemenubar .= "<a href='{$scriptname}?action=exportresults&amp;sid={$surveyid}' title=\"" . $clang->gTview("Export Results to Application") . "\" >" . "<img name='Export' src='{$imagefiles}/export.png' " . "alt='" . $clang->gT("Export Results to Application") . "' /></a>\n" . "<a href='{$scriptname}?action=exportspss&amp;sid={$surveyid}' title=\"" . $clang->gTview("Export results to a SPSS/PASW command file") . "\" >" . "<img src='{$imagefiles}/exportspss.png' " . "alt='" . $clang->gT("Export results to a SPSS/PASW command file") . "' /></a>\n" . "<a href='{$scriptname}?action=exportr&amp;sid={$surveyid}' title=\"" . $clang->gTview("Export results to a R data file") . "\" >" . "<img src='{$imagefiles}/exportr.png' " . "alt='" . $clang->gT("Export results to a R data file") . "' /></a>\n";
    }
    //Import old response table
    $browsemenubar .= "<a href='{$scriptname}?action=importoldresponses&amp;sid={$surveyid}' title=\"" . $clang->gTview("Import answers from a deactivated survey table") . "\" >" . "<img name='ImportOldResponses' src='{$imagefiles}/importold.png' alt='" . $clang->gT("Import answers from a deactivated survey table") . "' /></a>\n";
    $browsemenubar .= "<img src='{$imagefiles}/seperator.gif' alt='' />\n";
    //browse saved responses
    $browsemenubar .= "<a href='{$scriptname}?action=saved&amp;sid={$surveyid}' title=\"" . $clang->gTview("View Saved but not submitted Responses") . "\" >" . "<img src='{$imagefiles}/saved.png' title='' alt='" . $clang->gT("View Saved but not submitted Responses") . "' name='BrowseSaved' /></a>\n" . "<a href='{$scriptname}?action=vvimport&amp;sid={$surveyid}' title=\"" . $clang->gTview("Import a VV survey file") . "\" >" . "<img src='{$imagefiles}/importvv.png' alt='" . $clang->gT("Import a VV survey file") . "' /></a>\n";
    //Export VV
    if (bHasRight($surveyid, 'export')) {
        $browsemenubar .= "<a href='{$scriptname}?action=vvexport&amp;sid={$surveyid}' title=\"" . $clang->gTview("Export a VV survey file") . "\" >" . "<img src='{$imagefiles}/exportvv.png' title='' alt='" . $clang->gT("Export a VV survey file") . "' /></a>\n";
    }
    //Iterate survey
    if (($surrows['browse_response'] && $surrows['activate_survey'] || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1) && ($thissurvey['private'] == 'N' && $thissurvey['tokenanswerspersistence'] == 'Y')) {
        $browsemenubar .= "<a href='{$scriptname}?action=iteratesurvey&amp;sid={$surveyid}' title=\"" . $clang->gTview("Iterate survey") . "\" >" . "<img src='{$imagefiles}/iterate.png' title='' alt='" . $clang->gT("Iterate survey") . "' /></a>\n";
    }
    $browsemenubar .= "</div>\n" . "\t</div>\n" . "</div>\n";
    return $browsemenubar;
}
<div class='header ui-widget-header'>
    <?php $clang->eT("Edit subquestions"); ?>
</div>
<?php echo CHtml::form(array("admin/database"), 'post', array('id'=>'editsubquestionsform', 'name'=>'editsubquestionsform')); ?>

    <input type='hidden' name='sid' value='<?php echo $surveyid; ?>' />
    <input type='hidden' name='gid' value='<?php echo $gid; ?>' />
    <input type='hidden' name='qid' value='<?php echo $qid; ?>' />
    <input type='hidden' id='action' name='action' value='updatesubquestions' />
    <input type='hidden' id='sortorder' name='sortorder' value='' />
    <input type='hidden' id='deletedqids' name='deletedqids' value='' />
    <div id='tabs'>
        <ul>
            <?php foreach ($anslangs as $anslang)
                { ?>
                <li><a href='#tabpage_<?php echo $anslang; ?>'><?php echo getLanguageNameFromCode($anslang, false); ?>
                        <?php if ($anslang==Survey::model()->findByPk($surveyid)->language) { ?> (<?php echo $clang->gT("Base language"); ?>) <?php } ?></a>
                </li>
                <?php } ?>
        </ul>
        <?php
            $first=true;
            $sortorderids='';
            $codeids='';
        ?>

        <?php foreach ($anslangs as $anslang)
            { ?>
            <div id='tabpage_<?php echo $anslang; ?>' class='tab-page'>
                <?php for ($scale_id = 0; $scale_id < $scalecount; $scale_id++)
                    {
        ?>
                           <option value='<?php 
        echo $lang;
        ?>
' selected='selected'><?php 
        echo getLanguageNameFromCode($lang, false);
        ?>
</option>
                        <?php 
    } else {
        ?>
                            <option value='<?php 
        echo $lang;
        ?>
'><?php 
        echo getLanguageNameFromCode($lang, false);
        ?>
</option>
                            <?php 
    }
}
?>
                    </select>
                </li>
                
                 <li><label for='queXMLStyle'><?php 
eT("Style:");
?>
</label>
            
            <textarea rows="10" cols="80" id='queXMLStyle' name='queXMLStyle'><?php 
Example #5
0
 // KP
 $labelsoutput.= "\t<div class='header ui-widget-header'>".$clang->gT("Labels")."\t</div>\n";
 $labelsoutput.= "<form method='post' action='admin.php' onsubmit=\"return codeCheck('code_',$maxsortorder,'".$clang->gT("Error: You are trying to use duplicate label codes.",'js')."','".$clang->gT("Error: 'other' is a reserved keyword.",'js')."');\">\n"
 ."<input type='hidden' name='sortorder' value='{$row['sortorder']}' />\n"
 ."<input type='hidden' name='lid' value='$lid' />\n"
 ."<input type='hidden' name='action' value='modlabelsetanswers' />\n";
 $first=true;
 $sortorderids=''; $codeids='';
 $i = 0;
 foreach ($lslanguages as $lslanguage)
 {
     $position=0;
     $query = "SELECT * FROM ".db_table_name('labels')." WHERE lid=$lid and language='$lslanguage' ORDER BY sortorder, code";
     $result = db_execute_assoc($query) or safe_die($connect->ErrorMsg());
     $labelcount = $result->RecordCount();
     $tab_title[$i] = getLanguageNameFromCode($lslanguage,false);
     $tab_content[$i] = "<table class='answertable' align='center'>\n"
     ."<thead align='center'>"
     ."<tr>\n"
     ."\t<th align='right' class='settingcaption'>\n"
     .$clang->gT("Code")
     ."\t</th>\n";
     $tab_content[$i].="<th align='right' class='settingcaption'>".$clang->gT("Assessment value").'</th>';
     $tab_content[$i].="\t<th class='settingcaption'>\n"
     .$clang->gT("Title")
     ."\t</th>\n"
     ."\t<th align='center' class='settingcaption'>\n"
     .$clang->gT("Action")
     ."\t</th>\n"
     ."\t<th align='center' class='settingcaption'>\n"
     .$clang->gT("Order")
/**
 * Creates a <select> HTML element for language selection for this survey
 *
 * @param int $surveyid
 * @param string $selected The selected language
 * @return string
 */
function languageDropdownClean($surveyid, $selected)
{
    $slangs = Survey::model()->findByPk($surveyid)->additionalLanguages;
    $baselang = Survey::model()->findByPk($surveyid)->language;
    array_unshift($slangs, $baselang);
    $html = "<select class='form-control listboxquestions' id='language' name='language'>\n";
    foreach ($slangs as $lang) {
        if ($lang == $selected) {
            $html .= "\t<option value='{$lang}' selected='selected'>" . getLanguageNameFromCode($lang, false) . "</option>\n";
        }
        if ($lang != $selected) {
            $html .= "\t<option value='{$lang}'>" . getLanguageNameFromCode($lang, false) . "</option>\n";
        }
    }
    $html .= "</select>";
    return $html;
}
Example #7
0
    /**
     * dataentry::editdata()
     * Edit dataentry.
     * @param mixed $subaction
     * @param mixed $id
     * @param mixed $surveyid
     * @param mixed $language
     * @return
     */
    public function editdata($subaction, $id, $surveyid, $language = '')
    {
        if ($language == '') {
            $language = Survey::model()->findByPk($surveyid)->language;
        }
        $surveyid = sanitize_int($surveyid);
        $id = sanitize_int($id);
        $aViewUrls = array();
        if (!isset($sDataEntryLanguage)) {
            $sDataEntryLanguage = Survey::model()->findByPk($surveyid)->language;
        }
        $surveyinfo = getSurveyInfo($surveyid);
        if (Permission::model()->hasSurveyPermission($surveyid, 'responses', 'update')) {
            $surveytable = "{{survey_" . $surveyid . '}}';
            $aData['display']['menu_bars']['browse'] = gT("Data entry");
            Yii::app()->loadHelper('database');
            //FIRST LETS GET THE NAMES OF THE QUESTIONS AND MATCH THEM TO THE FIELD NAMES FOR THE DATABASE
            $fnquery = "SELECT * FROM {{questions}}, {{groups}} g, {{surveys}} WHERE\n            {{questions}}.gid=g.gid AND\n            {{questions}}.language = '{$sDataEntryLanguage}' AND g.language = '{$sDataEntryLanguage}' AND\n            {{questions}}.sid={{surveys}}.sid AND {{questions}}.sid='{$surveyid}'\n            order by group_order, question_order";
            $fnresult = dbExecuteAssoc($fnquery);
            $fnresult = $fnresult->readAll();
            $fncount = count($fnresult);
            $fnrows = array();
            //Create an empty array in case FetchRow does not return any rows
            foreach ($fnresult as $fnrow) {
                $fnrows[] = $fnrow;
                $private = $fnrow['anonymized'];
                $datestamp = $fnrow['datestamp'];
                $ipaddr = $fnrow['ipaddr'];
            }
            // Get table output into array
            // Perform a case insensitive natural sort on group name then question title of a multidimensional array
            // $fnames = (Field Name in Survey Table, Short Title of Question, Question Type, Field Name, Question Code, Predetermined Answer if exist)
            $fnames['completed'] = array('fieldname' => "completed", 'question' => gT("Completed"), 'type' => 'completed');
            $fnames = array_merge($fnames, createFieldMap($surveyid, 'full', false, false, $sDataEntryLanguage));
            // Fix private if disallowed to view token
            if (!Permission::model()->hasSurveyPermission($surveyid, 'tokens', 'read')) {
                unset($fnames['token']);
            }
            $nfncount = count($fnames) - 1;
            //SHOW INDIVIDUAL RECORD
            if ($subaction == "edit" && Permission::model()->hasSurveyPermission($surveyid, 'responses', 'update')) {
                $idquery = "SELECT * FROM {$surveytable} WHERE id={$id}";
                $idresult = dbExecuteAssoc($idquery) or safeDie("Couldn't get individual record<br />{$idquery}<br />");
                foreach ($idresult->readAll() as $idrow) {
                    $results[] = $idrow;
                }
            } elseif ($subaction == "editsaved" && Permission::model()->hasSurveyPermission($surveyid, 'responses', 'update')) {
                if (isset($_GET['public']) && $_GET['public'] == "true") {
                    $password = md5(Yii::app()->request->getParam('accesscode'));
                } else {
                    $password = Yii::app()->request->getParam('accesscode');
                }
                $svresult = SavedControl::model()->findAllByAttributes(array('sid' => $surveyid, 'identifier' => Yii::app()->request->getParam('identifier'), 'access_code' => $password));
                foreach ($svresult as $svrow) {
                    $saver['email'] = $svrow['email'];
                    $saver['scid'] = $svrow['scid'];
                    $saver['ip'] = $svrow['ip'];
                }
                $svresult = SavedControl::model()->findAllByAttributes(array('scid' => $saver['scid']));
                foreach ($svresult as $svrow) {
                    $responses[$svrow['fieldname']] = $svrow['value'];
                }
                // while
                $fieldmap = createFieldMap($surveyid, 'full', false, false, getBaseLanguageFromSurveyID($surveyid));
                foreach ($fieldmap as $fm) {
                    if (isset($responses[$fm['fieldname']])) {
                        $results1[$fm['fieldname']] = $responses[$fm['fieldname']];
                    } else {
                        $results1[$fm['fieldname']] = "";
                    }
                }
                $results1['id'] = "";
                $results1['datestamp'] = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", Yii::app()->getConfig('timeadjust'));
                $results1['ipaddr'] = $saver['ip'];
                $results[] = $results1;
            }
            $aData = array('id' => $id, 'surveyid' => $surveyid, 'subaction' => $subaction, 'part' => 'header');
            $aViewUrls[] = 'dataentry_header_view';
            $aViewUrls[] = 'edit';
            $highlight = FALSE;
            unset($fnames['lastpage']);
            // unset timings
            foreach ($fnames as $fname) {
                if ($fname['type'] == "interview_time" || $fname['type'] == "page_time" || $fname['type'] == "answer_time") {
                    unset($fnames[$fname['fieldname']]);
                    $nfncount--;
                }
            }
            $aDataentryoutput = '';
            foreach ($results as $idrow) {
                $fname = reset($fnames);
                do {
                    if (isset($idrow[$fname['fieldname']])) {
                        $answer = $idrow[$fname['fieldname']];
                    }
                    $question = $fname['question'];
                    $aDataentryoutput .= "\t<tr";
                    if ($highlight) {
                        $aDataentryoutput .= " class='odd'";
                    } else {
                        $aDataentryoutput .= " class='even'";
                    }
                    $highlight = !$highlight;
                    $aDataentryoutput .= ">\n" . "<td>" . "\n";
                    $aDataentryoutput .= stripJavaScript($question);
                    $aDataentryoutput .= "</td>\n" . "<td>\n";
                    //$aDataentryoutput .= "\t-={$fname[3]}=-"; //Debugging info
                    if (isset($fname['qid']) && isset($fname['type'])) {
                        $qidattributes = getQuestionAttributeValues($fname['qid']);
                    }
                    switch ($fname['type']) {
                        case "completed":
                            // First compute the submitdate
                            if ($private == "Y") {
                                // In case of anonymized responses survey with no datestamp
                                // then the the answer submitdate gets a conventional timestamp
                                // 1st Jan 1980
                                $mysubmitdate = date("Y-m-d H:i", mktime(0, 0, 0, 1, 1, 1980));
                                // Note that the completed field only supports 17 chars (so no seconds!)
                            } else {
                                $mysubmitdate = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i", Yii::app()->getConfig('timeadjust'));
                                // Note that the completed field only supports 17 chars (so no seconds!)
                            }
                            $completedate = empty($idrow['submitdate']) ? $mysubmitdate : $idrow['submitdate'];
                            $selected = empty($idrow['submitdate']) ? 'N' : $completedate;
                            $select_options = array('N' => gT('No', 'unescaped'), $completedate => gT('Yes', 'unescaped'));
                            $aDataentryoutput .= CHtml::dropDownList('completed', $selected, $select_options, array('class' => 'form-control'));
                            break;
                        case "X":
                            //Boilerplate question
                            $aDataentryoutput .= "";
                            break;
                        case "Q":
                        case "K":
                            $aDataentryoutput .= $fname['subquestion'] . '&nbsp;';
                            $aDataentryoutput .= CHtml::textField($fname['fieldname'], $idrow[$fname['fieldname']]);
                            break;
                        case "id":
                            $aDataentryoutput .= CHtml::tag('span', array('style' => 'font-weight: bold;'), '&nbsp;' . $idrow[$fname['fieldname']]);
                            break;
                        case "5":
                            //5 POINT CHOICE radio-buttons
                            for ($i = 1; $i <= 5; $i++) {
                                $checked = FALSE;
                                if ($idrow[$fname['fieldname']] == $i) {
                                    $checked = TRUE;
                                }
                                $aDataentryoutput .= '<span class="five-point">';
                                $aDataentryoutput .= CHtml::radioButton($fname['fieldname'], $checked, array('class' => '', 'value' => $i, 'id' => '5-point-choice-' . $i));
                                $aDataentryoutput .= '<label for="5-point-choice-' . $i . '">' . $i . '</label>';
                                $aDataentryoutput .= '</span>   ';
                            }
                            break;
                        case "D":
                            //DATE
                            $thisdate = '';
                            $dateformatdetails = getDateFormatDataForQID($qidattributes, $surveyid);
                            if ($idrow[$fname['fieldname']] != '') {
                                $datetimeobj = new Date_Time_Converter($idrow[$fname['fieldname']], "Y-m-d H:i:s");
                                $thisdate = $datetimeobj->convert($dateformatdetails['phpdate']);
                            } else {
                                $thisdate = '';
                            }
                            if (canShowDatePicker($dateformatdetails)) {
                                $goodchars = str_replace(array("m", "d", "y", "H", "M"), "", $dateformatdetails['dateformat']);
                                $goodchars = "0123456789" . $goodchars[0];
                                $aDataentryoutput .= CHtml::textField($fname['fieldname'], $thisdate, array('class' => 'popupdate', 'size' => '12', 'onkeypress' => 'return goodchars(event,\'' . $goodchars . '\')'));
                                $aDataentryoutput .= CHtml::hiddenField('dateformat' . $fname['fieldname'], $dateformatdetails['jsdate'], array('id' => "dateformat{$fname['fieldname']}"));
                                // $aDataentryoutput .= "\t<input type='text' class='popupdate' size='12' name='{$fname['fieldname']}' value='{$thisdate}' onkeypress=\"return goodchars(event,'".$goodchars."')\"/>\n";
                                // $aDataentryoutput .= "\t<input type='hidden' name='dateformat{$fname['fieldname']}' id='dateformat{$fname['fieldname']}' value='{$dateformatdetails['jsdate']}'  />\n";
                            } else {
                                $aDataentryoutput .= CHtml::textField($fname['fieldname'], $thisdate);
                            }
                            break;
                        case "G":
                            //GENDER drop-down list
                            $select_options = array('' => gT("Please choose") . '...', 'F' => gT("Female"), 'M' => gT("Male"));
                            $aDataentryoutput .= CHtml::listBox($fname['fieldname'], $idrow[$fname['fieldname']], $select_options);
                            break;
                        case "L":
                            //LIST drop-down
                        //LIST drop-down
                        case "!":
                            //List (Radio)
                            $qidattributes = getQuestionAttributeValues($fname['qid']);
                            if (isset($qidattributes['category_separator']) && trim($qidattributes['category_separator']) != '') {
                                $optCategorySeparator = $qidattributes['category_separator'];
                            } else {
                                unset($optCategorySeparator);
                            }
                            if (substr($fname['fieldname'], -5) == "other") {
                                $aDataentryoutput .= "\t<input type='text' name='{$fname['fieldname']}' value='" . htmlspecialchars($idrow[$fname['fieldname']], ENT_QUOTES) . "' />\n";
                            } else {
                                $lquery = "SELECT * FROM {{answers}} WHERE qid={$fname['qid']} AND language = '{$sDataEntryLanguage}' ORDER BY sortorder, answer";
                                $lresult = dbExecuteAssoc($lquery);
                                $aDataentryoutput .= "\t<select name='{$fname['fieldname']}' class='form-control'>\n" . "<option value=''";
                                if ($idrow[$fname['fieldname']] == "") {
                                    $aDataentryoutput .= " selected='selected'";
                                }
                                $aDataentryoutput .= ">" . gT("Please choose") . "..</option>\n";
                                if (!isset($optCategorySeparator)) {
                                    foreach ($lresult->readAll() as $llrow) {
                                        $aDataentryoutput .= "<option value='{$llrow['code']}'";
                                        if ($idrow[$fname['fieldname']] == $llrow['code']) {
                                            $aDataentryoutput .= " selected='selected'";
                                        }
                                        $aDataentryoutput .= ">{$llrow['answer']}</option>\n";
                                    }
                                } else {
                                    $defaultopts = array();
                                    $optgroups = array();
                                    foreach ($lresult->readAll() as $llrow) {
                                        list($categorytext, $answertext) = explode($optCategorySeparator, $llrow['answer']);
                                        if ($categorytext == '') {
                                            $defaultopts[] = array('code' => $llrow['code'], 'answer' => $answertext);
                                        } else {
                                            $optgroups[$categorytext][] = array('code' => $llrow['code'], 'answer' => $answertext);
                                        }
                                    }
                                    foreach ($optgroups as $categoryname => $optionlistarray) {
                                        $aDataentryoutput .= "<optgroup class=\"dropdowncategory\" label=\"" . $categoryname . "\">\n";
                                        foreach ($optionlistarray as $optionarray) {
                                            $aDataentryoutput .= "\t<option value='{$optionarray['code']}'";
                                            if ($idrow[$fname['fieldname']] == $optionarray['code']) {
                                                $aDataentryoutput .= " selected='selected'";
                                            }
                                            $aDataentryoutput .= ">{$optionarray['answer']}</option>\n";
                                        }
                                        $aDataentryoutput .= "</optgroup>\n";
                                    }
                                    foreach ($defaultopts as $optionarray) {
                                        $aDataentryoutput .= "<option value='{$optionarray['code']}'";
                                        if ($idrow[$fname['fieldname']] == $optionarray['code']) {
                                            $aDataentryoutput .= " selected='selected'";
                                        }
                                        $aDataentryoutput .= ">{$optionarray['answer']}</option>\n";
                                    }
                                }
                                $oquery = "SELECT other FROM {{questions}} WHERE qid={$fname['qid']} AND {{questions}}.language = '{$sDataEntryLanguage}'";
                                $oresult = dbExecuteAssoc($oquery) or safeDie("Couldn't get other for list question<br />" . $oquery . "<br />");
                                foreach ($oresult->readAll() as $orow) {
                                    $fother = $orow['other'];
                                }
                                if ($fother == "Y") {
                                    $aDataentryoutput .= "<option value='-oth-'";
                                    if ($idrow[$fname['fieldname']] == "-oth-") {
                                        $aDataentryoutput .= " selected='selected'";
                                    }
                                    $aDataentryoutput .= ">" . gT("Other") . "</option>\n";
                                }
                                $aDataentryoutput .= "\t</select>\n";
                            }
                            break;
                        case "O":
                            //LIST WITH COMMENT drop-down/radio-button list + textarea
                            $lquery = "SELECT * FROM {{answers}} WHERE qid={$fname['qid']} AND language = '{$sDataEntryLanguage}' ORDER BY sortorder, answer";
                            $lresult = dbExecuteAssoc($lquery);
                            $aDataentryoutput .= "\t<select name='{$fname['fieldname']}' class='form-control'>\n" . "<option value=''";
                            if ($idrow[$fname['fieldname']] == "") {
                                $aDataentryoutput .= " selected='selected'";
                            }
                            $aDataentryoutput .= ">" . gT("Please choose") . "..</option>\n";
                            foreach ($lresult->readAll() as $llrow) {
                                $aDataentryoutput .= "<option value='{$llrow['code']}'";
                                if ($idrow[$fname['fieldname']] == $llrow['code']) {
                                    $aDataentryoutput .= " selected='selected'";
                                }
                                $aDataentryoutput .= ">{$llrow['answer']}</option>\n";
                            }
                            $fname = next($fnames);
                            $aDataentryoutput .= "\t</select>\n" . "\t<br />\n" . "\t<textarea cols='45' rows='5' name='{$fname['fieldname']}'>" . htmlspecialchars($idrow[$fname['fieldname']]) . "</textarea>\n";
                            break;
                        case "R":
                            //RANKING TYPE QUESTION
                            $thisqid = $fname['qid'];
                            $currentvalues = array();
                            $myfname = $fname['sid'] . 'X' . $fname['gid'] . 'X' . $fname['qid'];
                            $aDataentryoutput .= '<div id="question' . $thisqid . '" class="ranking-answers"><ul class="answers-list">';
                            while (isset($fname['type']) && $fname['type'] == "R" && $fname['qid'] == $thisqid) {
                                //Let's get all the existing values into an array
                                if ($idrow[$fname['fieldname']]) {
                                    $currentvalues[] = $idrow[$fname['fieldname']];
                                }
                                $fname = next($fnames);
                            }
                            $ansquery = "SELECT * FROM {{answers}} WHERE language = '{$sDataEntryLanguage}' AND qid={$thisqid} ORDER BY sortorder, answer";
                            $ansresult = Yii::app()->db->createCommand($ansquery)->query()->readAll();
                            //Checked
                            $anscount = count($ansresult);
                            $answers = array();
                            foreach ($ansresult as $ansrow) {
                                $answers[] = $ansrow;
                            }
                            for ($i = 1; $i <= $anscount; $i++) {
                                $aDataentryoutput .= "\n<li class=\"select-item\">";
                                $aDataentryoutput .= "<label for=\"answer{$myfname}{$i}\">";
                                if ($i == 1) {
                                    $aDataentryoutput .= gT('First choice');
                                } else {
                                    $aDataentryoutput .= gT('Next choice');
                                }
                                $aDataentryoutput .= "</label>";
                                $aDataentryoutput .= "<select name=\"{$myfname}{$i}\" id=\"answer{$myfname}{$i}\" class='form-control'>\n";
                                !isset($currentvalues[$i - 1]) ? $selected = " selected=\"selected\"" : ($selected = "");
                                $aDataentryoutput .= "\t<option value=\"\" {$selected}>" . gT('None') . "</option>\n";
                                foreach ($answers as $ansrow) {
                                    isset($currentvalues[$i - 1]) && $currentvalues[$i - 1] == $ansrow['code'] ? $selected = " selected=\"selected\"" : ($selected = "");
                                    $aDataentryoutput .= "\t<option value=\"" . $ansrow['code'] . "\" {$selected}>" . flattenText($ansrow['answer']) . "</option>\n";
                                }
                                $aDataentryoutput .= "</select\n";
                                $aDataentryoutput .= "</li>";
                            }
                            $aDataentryoutput .= '</ul>';
                            $aDataentryoutput .= "<div style='display:none' id='ranking-{$thisqid}-maxans'>{$anscount}</div>" . "<div style='display:none' id='ranking-{$thisqid}-minans'>0</div>" . "<div style='display:none' id='ranking-{$thisqid}-name'>javatbd{$myfname}</div>";
                            $aDataentryoutput .= "<div style=\"display:none\">";
                            foreach ($answers as $ansrow) {
                                $aDataentryoutput .= "<div id=\"htmlblock-{$thisqid}-{$ansrow['code']}\">{$ansrow['answer']}</div>";
                            }
                            $aDataentryoutput .= "</div>";
                            $aDataentryoutput .= '</div>';
                            App()->getClientScript()->registerPackage('jquery-actual');
                            App()->getClientScript()->registerScriptFile(App()->getAssetManager()->publish(SCRIPT_PATH . 'ranking.js'));
                            App()->getClientScript()->registerCssFile(App()->getAssetManager()->publish(dirname(Yii::app()->request->scriptFile) . '/styles-public/ranking.css'));
                            $aDataentryoutput .= "<script type='text/javascript'>\n" . "  <!--\n" . "var aRankingTranslations = {\n                                         choicetitle: '" . gT("Your Choices", 'js') . "',\n                                         ranktitle: '" . gT("Your Ranking", 'js') . "'\n                                        };\n" . "function checkconditions(){};" . "\$(function() {" . " doDragDropRank({$thisqid},0,true,true);\n" . "});\n" . " -->\n" . "</script>\n";
                            unset($answers);
                            $fname = prev($fnames);
                            break;
                        case "M":
                            //Multiple choice checkbox
                            $qidattributes = getQuestionAttributeValues($fname['qid']);
                            if (trim($qidattributes['display_columns']) != '') {
                                $dcols = $qidattributes['display_columns'];
                            } else {
                                $dcols = 0;
                            }
                            //                    while ($fname[3] == "M" && $question != "" && $question == $fname['type'])
                            $thisqid = $fname['qid'];
                            while ($fname['qid'] == $thisqid) {
                                $fieldn = substr($fname['fieldname'], 0, strlen($fname['fieldname']));
                                //$aDataentryoutput .= substr($fname['fieldname'], strlen($fname['fieldname'])-5, 5)."<br />\n";
                                if (substr($fname['fieldname'], -5) == "other") {
                                    $aDataentryoutput .= "\t<input type='text' name='{$fname['fieldname']}' value='" . htmlspecialchars($idrow[$fname['fieldname']], ENT_QUOTES) . "' />\n";
                                } else {
                                    $aDataentryoutput .= "<div class='checkbox'>\t<input type='checkbox' class='checkboxbtn' name='{$fname['fieldname']}' id='{$fname['fieldname']}' value='Y'";
                                    if ($idrow[$fname['fieldname']] == "Y") {
                                        $aDataentryoutput .= " checked";
                                    }
                                    $aDataentryoutput .= " /><label for='{$fname['fieldname']}'>{$fname['subquestion']}</label></div>\n";
                                }
                                $fname = next($fnames);
                            }
                            $fname = prev($fnames);
                            break;
                        case "I":
                            //Language Switch
                            $lquery = "SELECT * FROM {{answers}} WHERE qid={$fname['qid']} AND language = '{$sDataEntryLanguage}' ORDER BY sortorder, answer";
                            $lresult = dbExecuteAssoc($lquery);
                            $slangs = Survey::model()->findByPk($surveyid)->additionalLanguages;
                            $baselang = Survey::model()->findByPk($surveyid)->language;
                            array_unshift($slangs, $baselang);
                            $aDataentryoutput .= "<select name='{$fname['fieldname']}' class='form-control'>\n";
                            $aDataentryoutput .= "<option value=''";
                            if ($idrow[$fname['fieldname']] == "") {
                                $aDataentryoutput .= " selected='selected'";
                            }
                            $aDataentryoutput .= ">" . gT("Please choose") . "..</option>\n";
                            foreach ($slangs as $lang) {
                                $aDataentryoutput .= "<option value='{$lang}'";
                                if ($lang == $idrow[$fname['fieldname']]) {
                                    $aDataentryoutput .= " selected='selected'";
                                }
                                $aDataentryoutput .= ">" . getLanguageNameFromCode($lang, false) . "</option>\n";
                            }
                            $aDataentryoutput .= "</select>";
                            break;
                        case "P":
                            //Multiple choice with comments checkbox + text
                            $aDataentryoutput .= "<table>\n";
                            while (isset($fname) && $fname['type'] == "P") {
                                $thefieldname = $fname['fieldname'];
                                if (substr($thefieldname, -7) == "comment") {
                                    $aDataentryoutput .= "<td><input type='text' name='{$fname['fieldname']}' size='50' value='" . htmlspecialchars($idrow[$fname['fieldname']], ENT_QUOTES) . "' /></td>\n" . "\t</tr>\n";
                                } elseif (substr($fname['fieldname'], -5) == "other") {
                                    $aDataentryoutput .= "\t<tr>\n" . "<td>\n" . "\t<input type='text' name='{$fname['fieldname']}' size='30' value='" . htmlspecialchars($idrow[$fname['fieldname']], ENT_QUOTES) . "' />\n" . "</td>\n" . "<td>\n";
                                    $fname = next($fnames);
                                    $aDataentryoutput .= "\t<input type='text' name='{$fname['fieldname']}' size='50' value='" . htmlspecialchars($idrow[$fname['fieldname']], ENT_QUOTES) . "' />\n" . "</td>\n" . "\t</tr>\n";
                                } else {
                                    $aDataentryoutput .= "\t<tr>\n" . "<td><div class='checkbox'><input type='checkbox' class='checkboxbtn' name=\"{$fname['fieldname']}\" id=\"{$fname['fieldname']}\" value='Y'";
                                    if ($idrow[$fname['fieldname']] == "Y") {
                                        $aDataentryoutput .= " checked";
                                    }
                                    $aDataentryoutput .= " /><label for=\"{$fname['fieldname']}\">{$fname['subquestion']}</label></div></td>\n";
                                }
                                $fname = next($fnames);
                            }
                            $aDataentryoutput .= "</table>\n";
                            $fname = prev($fnames);
                            break;
                        case "|":
                            //FILE UPLOAD
                            $aDataentryoutput .= "<table>\n";
                            if ($fname['aid'] !== 'filecount' && isset($idrow[$fname['fieldname'] . '_filecount']) && $idrow[$fname['fieldname'] . '_filecount'] > 0) {
                                //file metadata
                                $metadata = json_decode($idrow[$fname['fieldname']], true);
                                $qAttributes = getQuestionAttributeValues($fname['qid']);
                                for ($i = 0; $i < $qAttributes['max_num_of_files'] && isset($metadata[$i]); $i++) {
                                    if ($qAttributes['show_title']) {
                                        $aDataentryoutput .= '<tr><td>Title    </td><td><input type="text" class="' . $fname['fieldname'] . '" id="' . $fname['fieldname'] . '_title_' . $i . '" name="title"    size=50 value="' . htmlspecialchars($metadata[$i]["title"]) . '" /></td></tr>';
                                    }
                                    if ($qAttributes['show_comment']) {
                                        $aDataentryoutput .= '<tr><td >Comment  </td><td><input type="text" class="' . $fname['fieldname'] . '" id="' . $fname['fieldname'] . '_comment_' . $i . '" name="comment"  size=50 value="' . htmlspecialchars($metadata[$i]["comment"]) . '" /></td></tr>';
                                    }
                                    $aDataentryoutput .= '<tr><td>        File name</td><td><input   class="' . $fname['fieldname'] . '" id="' . $fname['fieldname'] . '_name_' . $i . '" name="name" size=50 value="' . htmlspecialchars(rawurldecode($metadata[$i]["name"])) . '" /></td></tr>' . '<tr><td></td><td><input type="hidden" class="' . $fname['fieldname'] . '" id="' . $fname['fieldname'] . '_size_' . $i . '" name="size" size=50 value="' . htmlspecialchars($metadata[$i]["size"]) . '" /></td></tr>' . '<tr><td></td><td><input type="hidden" class="' . $fname['fieldname'] . '" id="' . $fname['fieldname'] . '_ext_' . $i . '" name="ext" size=50 value="' . htmlspecialchars($metadata[$i]["ext"]) . '" /></td></tr>' . '<tr><td></td><td><input type="hidden"  class="' . $fname['fieldname'] . '" id="' . $fname['fieldname'] . '_filename_' . $i . '" name="filename" size=50 value="' . htmlspecialchars(rawurldecode($metadata[$i]["filename"])) . '" /></td></tr>';
                                }
                                $aDataentryoutput .= '<tr><td></td><td><input type="hidden" id="' . $fname['fieldname'] . '" name="' . $fname['fieldname'] . '" size=50 value="' . htmlspecialchars($idrow[$fname['fieldname']]) . '" /></td></tr>';
                                $aDataentryoutput .= '</table>';
                                $aDataentryoutput .= '<script type="text/javascript">
                                $(function() {
                                $(".' . $fname['fieldname'] . '").keyup(function() {
                                var filecount = $("#' . $fname['fieldname'] . '_filecount").val();
                                var jsonstr = "[";
                                var i;
                                for (i = 0; i < filecount; i++)
                                {
                                if (i != 0)
                                jsonstr += ",";
                                jsonstr += \'{"title":"\'+$("#' . $fname['fieldname'] . '_title_"+i).val()+\'",\';
                                jsonstr += \'"comment":"\'+$("#' . $fname['fieldname'] . '_comment_"+i).val()+\'",\';
                                jsonstr += \'"size":"\'+$("#' . $fname['fieldname'] . '_size_"+i).val()+\'",\';
                                jsonstr += \'"ext":"\'+$("#' . $fname['fieldname'] . '_ext_"+i).val()+\'",\';
                                jsonstr += \'"filename":"\'+$("#' . $fname['fieldname'] . '_filename_"+i).val()+\'",\';
                                jsonstr += \'"name":"\'+encodeURIComponent($("#' . $fname['fieldname'] . '_name_"+i).val())+\'"}\';
                                }
                                jsonstr += "]";
                                $("#' . $fname['fieldname'] . '").val(jsonstr);

                                });
                                });
                                </script>';
                            } else {
                                //file count
                                $aDataentryoutput .= '<input readonly id="' . $fname['fieldname'] . '" name="' . $fname['fieldname'] . '" value ="' . htmlspecialchars($idrow[$fname['fieldname']]) . '" /></td></table>';
                            }
                            break;
                        case "N":
                            //NUMERICAL TEXT
                            $aDataentryoutput .= "\t<input type='text' name='{$fname['fieldname']}' value='{$idrow[$fname['fieldname']]}' " . "onkeypress=\"return goodchars(event,'0123456789.,')\" />\n";
                            break;
                        case "S":
                            //SHORT FREE TEXT
                            $aDataentryoutput .= "\t<input type='text' name='{$fname['fieldname']}' value='" . htmlspecialchars($idrow[$fname['fieldname']], ENT_QUOTES) . "' />\n";
                            break;
                        case "T":
                            //LONG FREE TEXT
                            $aDataentryoutput .= "\t<textarea rows='5' cols='45' name='{$fname['fieldname']}'>" . htmlspecialchars($idrow[$fname['fieldname']], ENT_QUOTES) . "</textarea>\n";
                            break;
                        case "U":
                            //HUGE FREE TEXT
                            $aDataentryoutput .= "\t<textarea rows='50' cols='70' name='{$fname['fieldname']}'>" . htmlspecialchars($idrow[$fname['fieldname']], ENT_QUOTES) . "</textarea>\n";
                            break;
                        case "Y":
                            //YES/NO radio-buttons
                            $aDataentryoutput .= "\t<select name='{$fname['fieldname']}' class='form-control'>\n" . "<option value=''";
                            if ($idrow[$fname['fieldname']] == "") {
                                $aDataentryoutput .= " selected='selected'";
                            }
                            $aDataentryoutput .= ">" . gT("Please choose") . "..</option>\n" . "<option value='Y'";
                            if ($idrow[$fname['fieldname']] == "Y") {
                                $aDataentryoutput .= " selected='selected'";
                            }
                            $aDataentryoutput .= ">" . gT("Yes") . "</option>\n" . "<option value='N'";
                            if ($idrow[$fname['fieldname']] == "N") {
                                $aDataentryoutput .= " selected='selected'";
                            }
                            $aDataentryoutput .= ">" . gT("No") . "</option>\n" . "\t</select>\n";
                            break;
                        case "A":
                            //ARRAY (5 POINT CHOICE) radio-buttons
                            $aDataentryoutput .= "<table>\n";
                            $thisqid = $fname['qid'];
                            while ($fname['qid'] == $thisqid) {
                                $aDataentryoutput .= "\t<tr>\n" . "<td align='right'>{$fname['subquestion']}</td>\n" . "<td>\n";
                                for ($j = 1; $j <= 5; $j++) {
                                    $aDataentryoutput .= '<span class="five-point">';
                                    $aDataentryoutput .= "\t<input type='radio' class='' name='{$fname['fieldname']}' id='5-point-radio-{$fname['fieldname']}' value='{$j}'";
                                    if ($idrow[$fname['fieldname']] == $j) {
                                        $aDataentryoutput .= " checked";
                                    }
                                    $aDataentryoutput .= " /><label for='5-point-radio-{$fname['fieldname']}'>{$j}</label>&nbsp;\n";
                                    $aDataentryoutput .= '</span>';
                                }
                                $aDataentryoutput .= "</td>\n" . "\t</tr>\n";
                                $fname = next($fnames);
                            }
                            $aDataentryoutput .= "</table>\n";
                            $fname = prev($fnames);
                            break;
                        case "B":
                            //ARRAY (10 POINT CHOICE) radio-buttons
                            $aDataentryoutput .= "<table>\n";
                            $thisqid = $fname['qid'];
                            while ($fname['qid'] == $thisqid) {
                                $fieldn = substr($fname['fieldname'], 0, strlen($fname['fieldname']));
                                $aDataentryoutput .= "\t<tr>\n" . "<td align='right'>{$fname['subquestion']}</td>\n" . "<td>\n";
                                for ($j = 1; $j <= 10; $j++) {
                                    $aDataentryoutput .= '<span class="ten-point">';
                                    $aDataentryoutput .= "\t<input type='radio' class='' name='{$fname['fieldname']}' id='ten-point-{$fname['fieldname']}-{$j}' value='{$j}'";
                                    if ($idrow[$fname['fieldname']] == $j) {
                                        $aDataentryoutput .= " checked";
                                    }
                                    $aDataentryoutput .= " /><label for='ten-point-{$fname['fieldname']}-{$j}'>{$j}</label>&nbsp;\n";
                                    $aDataentryoutput .= '</span>';
                                }
                                $aDataentryoutput .= "</td>\n" . "\t</tr>\n";
                                $fname = next($fnames);
                            }
                            $fname = prev($fnames);
                            $aDataentryoutput .= "</table>\n";
                            break;
                        case "C":
                            //ARRAY (YES/UNCERTAIN/NO) radio-buttons
                            $aDataentryoutput .= "<table>\n";
                            $thisqid = $fname['qid'];
                            while ($fname['qid'] == $thisqid) {
                                $fieldn = substr($fname['fieldname'], 0, strlen($fname['fieldname']));
                                $aDataentryoutput .= "\t<tr>\n" . "<td align='right'>{$fname['subquestion']}</td>\n" . "<td>\n" . "\t<input type='radio' class='' name='{$fname['fieldname']}' value='Y'";
                                if ($idrow[$fname['fieldname']] == "Y") {
                                    $aDataentryoutput .= " checked";
                                }
                                $aDataentryoutput .= " />" . gT("Yes") . "&nbsp;\n" . "\t<input type='radio' class='' name='{$fname['fieldname']}' value='U'";
                                if ($idrow[$fname['fieldname']] == "U") {
                                    $aDataentryoutput .= " checked";
                                }
                                $aDataentryoutput .= " />" . gT("Uncertain") . "&nbsp;\n" . "\t<input type='radio' class='' name='{$fname['fieldname']}' value='N'";
                                if ($idrow[$fname['fieldname']] == "N") {
                                    $aDataentryoutput .= " checked";
                                }
                                $aDataentryoutput .= " />" . gT("No") . "&nbsp;\n" . "</td>\n" . "\t</tr>\n";
                                $fname = next($fnames);
                            }
                            $fname = prev($fnames);
                            $aDataentryoutput .= "</table>\n";
                            break;
                        case "E":
                            //ARRAY (Increase/Same/Decrease) radio-buttons
                            $aDataentryoutput .= "<table>\n";
                            $thisqid = $fname['qid'];
                            while ($fname['qid'] == $thisqid) {
                                $fieldn = substr($fname['fieldname'], 0, strlen($fname['fieldname']));
                                $aDataentryoutput .= "\t<tr>\n" . "<td align='right'>{$fname['subquestion']}</td>\n" . "<td>\n" . "\t<input type='radio' class='' name='{$fname['fieldname']}' value='I'";
                                if ($idrow[$fname['fieldname']] == "I") {
                                    $aDataentryoutput .= " checked";
                                }
                                $aDataentryoutput .= " />Increase&nbsp;\n" . "\t<input type='radio' class='' name='{$fname['fieldname']}' value='S'";
                                if ($idrow[$fname['fieldname']] == "I") {
                                    $aDataentryoutput .= " checked";
                                }
                                $aDataentryoutput .= " />Same&nbsp;\n" . "\t<input type='radio' class='' name='{$fname['fieldname']}' value='D'";
                                if ($idrow[$fname['fieldname']] == "D") {
                                    $aDataentryoutput .= " checked";
                                }
                                $aDataentryoutput .= " />Decrease&nbsp;\n" . "</td>\n" . "\t</tr>\n";
                                $fname = next($fnames);
                            }
                            $fname = prev($fnames);
                            $aDataentryoutput .= "</table>\n";
                            break;
                        case "F":
                            //ARRAY (Flexible Labels)
                        //ARRAY (Flexible Labels)
                        case "H":
                        case "1":
                            $aDataentryoutput .= "<table>\n";
                            $thisqid = $fname['qid'];
                            while (isset($fname['qid']) && $fname['qid'] == $thisqid) {
                                $fieldn = substr($fname['fieldname'], 0, strlen($fname['fieldname']));
                                $aDataentryoutput .= "\t<tr>\n" . "<td>{$fname['subquestion']}";
                                if (isset($fname['scale'])) {
                                    $aDataentryoutput .= " (" . $fname['scale'] . ')';
                                }
                                $aDataentryoutput .= "</td>\n";
                                $scale_id = 0;
                                if (isset($fname['scale_id'])) {
                                    $scale_id = $fname['scale_id'];
                                }
                                $fquery = "SELECT * FROM {{answers}} WHERE qid='{$fname['qid']}' and scale_id={$scale_id} and language='{$sDataEntryLanguage}' order by sortorder, answer";
                                $fresult = dbExecuteAssoc($fquery);
                                $aDataentryoutput .= "<td>\n";
                                foreach ($fresult->readAll() as $frow) {
                                    $aDataentryoutput .= "\t<input type='radio' class='' name='{$fname['fieldname']}' value='{$frow['code']}'";
                                    if ($idrow[$fname['fieldname']] == $frow['code']) {
                                        $aDataentryoutput .= " checked";
                                    }
                                    $aDataentryoutput .= " />" . $frow['answer'] . "&nbsp;\n";
                                }
                                //Add 'No Answer'
                                $aDataentryoutput .= "\t<input type='radio' class='' name='{$fname['fieldname']}' value=''";
                                if ($idrow[$fname['fieldname']] == '') {
                                    $aDataentryoutput .= " checked";
                                }
                                $aDataentryoutput .= " />" . gT("No answer") . "&nbsp;\n";
                                $aDataentryoutput .= "</td>\n" . "\t</tr>\n";
                                $fname = next($fnames);
                            }
                            $fname = prev($fnames);
                            $aDataentryoutput .= "</table>\n";
                            break;
                        case ":":
                            //ARRAY (Multi Flexi) (Numbers)
                            $qidattributes = getQuestionAttributeValues($fname['qid']);
                            if (trim($qidattributes['multiflexible_max']) != '' && trim($qidattributes['multiflexible_min']) == '') {
                                $maxvalue = $qidattributes['multiflexible_max'];
                                $minvalue = 1;
                            }
                            if (trim($qidattributes['multiflexible_min']) != '' && trim($qidattributes['multiflexible_max']) == '') {
                                $minvalue = $qidattributes['multiflexible_min'];
                                $maxvalue = $qidattributes['multiflexible_min'] + 10;
                            }
                            if (trim($qidattributes['multiflexible_min']) == '' && trim($qidattributes['multiflexible_max']) == '') {
                                $minvalue = 1;
                                $maxvalue = 10;
                            }
                            if (trim($qidattributes['multiflexible_min']) != '' && trim($qidattributes['multiflexible_max']) != '') {
                                if ($qidattributes['multiflexible_min'] < $qidattributes['multiflexible_max']) {
                                    $minvalue = $qidattributes['multiflexible_min'];
                                    $maxvalue = $qidattributes['multiflexible_max'];
                                }
                            }
                            if (trim($qidattributes['multiflexible_step']) != '') {
                                $stepvalue = $qidattributes['multiflexible_step'];
                            } else {
                                $stepvalue = 1;
                            }
                            if ($qidattributes['multiflexible_checkbox'] != 0) {
                                $minvalue = 0;
                                $maxvalue = 1;
                                $stepvalue = 1;
                            }
                            $aDataentryoutput .= "<table>\n";
                            $thisqid = $fname['qid'];
                            while (isset($fname['qid']) && $fname['qid'] == $thisqid) {
                                $fieldn = substr($fname['fieldname'], 0, strlen($fname['fieldname']));
                                $aDataentryoutput .= "\t<tr>\n" . "<td>{$fname['subquestion1']}:{$fname['subquestion2']}</td>\n";
                                $aDataentryoutput .= "<td>\n";
                                if ($qidattributes['input_boxes'] != 0) {
                                    $aDataentryoutput .= "\t<input type='text' name='{$fname['fieldname']}' value='";
                                    if (!empty($idrow[$fname['fieldname']])) {
                                        $aDataentryoutput .= $idrow[$fname['fieldname']];
                                    }
                                    $aDataentryoutput .= "' size=4 />";
                                } else {
                                    $aDataentryoutput .= "\t<select name='{$fname['fieldname']}' class='form-control'>\n";
                                    $aDataentryoutput .= "<option value=''>...</option>\n";
                                    for ($ii = $minvalue; $ii <= $maxvalue; $ii += $stepvalue) {
                                        $aDataentryoutput .= "<option value='{$ii}'";
                                        if ($idrow[$fname['fieldname']] == $ii) {
                                            $aDataentryoutput .= " selected";
                                        }
                                        $aDataentryoutput .= ">{$ii}</option>\n";
                                    }
                                }
                                $aDataentryoutput .= "</td>\n" . "\t</tr>\n";
                                $fname = next($fnames);
                            }
                            $fname = prev($fnames);
                            $aDataentryoutput .= "</table>\n";
                            break;
                        case ";":
                            //ARRAY (Multi Flexi)
                            $aDataentryoutput .= "<table>\n";
                            $thisqid = $fname['qid'];
                            while (isset($fname['qid']) && $fname['qid'] == $thisqid) {
                                $fieldn = substr($fname['fieldname'], 0, strlen($fname['fieldname']));
                                $aDataentryoutput .= "\t<tr>\n" . "<td>{$fname['subquestion1']}:{$fname['subquestion2']}</td>\n";
                                $aDataentryoutput .= "<td>\n";
                                $aDataentryoutput .= "\t<input type='text' name='{$fname['fieldname']}' value='";
                                if (!empty($idrow[$fname['fieldname']])) {
                                    $aDataentryoutput .= $idrow[$fname['fieldname']];
                                }
                                $aDataentryoutput .= "' /></td>\n" . "\t</tr>\n";
                                $fname = next($fnames);
                            }
                            $fname = prev($fnames);
                            $aDataentryoutput .= "</table>\n";
                            break;
                        case "token":
                            if (Permission::model()->hasSurveyPermission($surveyid, 'tokens', 'update')) {
                                $aDataentryoutput .= CHtml::textField($fname['fieldname'], $idrow[$fname['fieldname']]);
                            } else {
                                $aDataentryoutput .= CHtml::textField($fname['fieldname'], $idrow[$fname['fieldname']], array('disabled' => 'disabled'));
                            }
                            break;
                        case "submitdate":
                        case "startlanguage":
                        default:
                            $aDataentryoutput .= "\t<input type='text' name='{$fname['fieldname']}' value='" . $idrow[$fname['fieldname']] . "' />\n";
                            break;
                    }
                    $aDataentryoutput .= "        </td>\n                    </tr>\n";
                } while ($fname = next($fnames));
            }
            $aDataentryoutput .= "</table>\n" . "<p>\n";
            $aData['sDataEntryLanguage'] = $sDataEntryLanguage;
            if (!Permission::model()->hasSurveyPermission($surveyid, 'responses', 'update')) {
                // if you are not survey owner or super admin you cannot modify responses
                $aDataentryoutput .= "<p><input type='button' value='" . gT("Save") . "' disabled='disabled'/></p>\n";
            } elseif ($subaction == "edit" && Permission::model()->hasSurveyPermission($surveyid, 'responses', 'update')) {
                $aData['part'] = 'edit';
                $aDataentryoutput .= $this->getController()->renderPartial('/admin/dataentry/edit', $aData, TRUE);
            } elseif ($subaction == "editsaved" && Permission::model()->hasSurveyPermission($surveyid, 'responses', 'update')) {
                $aData['part'] = 'editsaved';
                $aDataentryoutput .= $this->getController()->renderPartial('/admin/dataentry/edit', $aData, TRUE);
            }
            $aDataentryoutput .= "</form>\n";
            $aViewUrls['output'] = $aDataentryoutput;
            $aData['sidemenu']['state'] = false;
            $aData['menu']['edition'] = true;
            $aData['menu']['save'] = true;
            $aData['menu']['close'] = true;
            //$aData['menu']['savebutton'] = 'frmeditgroup';
            $this->_renderWrappedTemplate('dataentry', $aViewUrls, $aData);
        }
    }
        <a href='<?php 
echo $tmp_url;
?>
' target='_blank'><?php 
echo $tmp_url;
?>
</a>
        </td>
    </tr>
        <?php 
foreach ($aAdditionalLanguages as $langname) {
    ?>
        <tr>
            <td>
                <strong><?php 
    echo getLanguageNameFromCode($langname, false) . ":";
    ?>
</strong>
            </td>
            <td>
            <?php 
    $tmp_url = $this->createAbsoluteUrl("/survey/index/sid/{$surveyinfo['sid']}/lang/{$langname}");
    ?>
            <a href='<?php 
    echo $tmp_url;
    ?>
' target='_blank'><?php 
    echo $tmp_url;
    ?>
</a>
            </td>
Example #9
0
 /**
  * Load editing of local settings of a survey screen.
  *
  * @access public
  * @param int $iSurveyID
  * @return void
  */
 public function editlocalsettings($iSurveyID)
 {
     $aData['surveyid'] = $iSurveyID = sanitize_int($iSurveyID);
     $aViewUrls = array();
     if (Permission::model()->hasSurveyPermission($iSurveyID, 'surveylocale', 'read')) {
         if (Permission::model()->hasSurveyPermission($iSurveyID, 'surveylocale', 'update')) {
             Yii::app()->session['FileManagerContext'] = "edit:survey:{$iSurveyID}";
         }
         $grplangs = Survey::model()->findByPk($iSurveyID)->additionalLanguages;
         $baselang = Survey::model()->findByPk($iSurveyID)->language;
         array_unshift($grplangs, $baselang);
         Yii::app()->loadHelper("admin/htmleditor");
         $aViewUrls['output'] = PrepareEditorScript(false, $this->getController());
         foreach ($grplangs as $sLang) {
             // this one is created to get the right default texts fo each language
             Yii::app()->loadHelper('database');
             Yii::app()->loadHelper('surveytranslator');
             $esrow = SurveyLanguageSetting::model()->findByPk(array('surveyls_survey_id' => $iSurveyID, 'surveyls_language' => $sLang))->getAttributes();
             $aTabTitles[$sLang] = getLanguageNameFromCode($esrow['surveyls_language'], false);
             if ($esrow['surveyls_language'] == Survey::model()->findByPk($iSurveyID)->language) {
                 $aTabTitles[$sLang] .= '(' . gT("Base language") . ')';
             }
             $esrow = array_map('htmlspecialchars', $esrow);
             $aData['esrow'] = $esrow;
             $aData['action'] = "editsurveylocalesettings";
             $aTabContents[$sLang] = $this->getController()->renderPartial('/admin/survey/editLocalSettings_view', $aData, true);
         }
         $aData['has_permissions'] = Permission::model()->hasSurveyPermission($iSurveyID, 'surveylocale', 'update');
         $aData['surveyls_language'] = $esrow["surveyls_language"];
         $aData['aTabContents'] = $aTabContents;
         $aData['aTabTitles'] = $aTabTitles;
         $aViewUrls[] = 'editLocalSettings_main_view';
     } else {
         $this->getController()->error('Access denied');
     }
     $this->_renderWrappedTemplate('survey', $aViewUrls, $aData);
 }
Example #10
0
 /**
  * This function prepares the data for label set details
  *
  * @access public
  * @return void
  */
 public function ajaxlabelsetdetails()
 {
     $lid = returnglobal('lid');
     Yii::app()->loadHelper('surveytranslator');
     $labelsetdata = Labelsets::model()->find('lid=:lid', array(':lid' => $lid));
     //$connect->GetArray($query);
     $labelsetlanguages = explode(' ', $labelsetdata->languages);
     foreach ($labelsetlanguages as $language) {
         $criteria = new CDbCriteria();
         $criteria->condition = 'lid=:lid and language=:language';
         $criteria->params = array(':lid' => $lid, ':language' => $language);
         $criteria->order = 'sortorder';
         $labelsdata = Label::model()->findAll($criteria);
         $i = 0;
         foreach ($labelsdata as $labeldata) {
             $data[$i]['lid'] = $labeldata->lid;
             $data[$i]['code'] = $labeldata->code;
             $data[$i]['title'] = $labeldata->title;
             $data[$i]['sortorder'] = $labeldata->sortorder;
             $data[$i]['assessment_value'] = $labeldata->assessment_value;
             $data[$i]['language'] = $labeldata->language;
             $i++;
         }
         $labels = $data;
         //$labels=dbExecuteAssoc($query); //Label::model()->find(array('lid' => $lid, 'language' => $language), array('order' => 'sortorder')); //$connect->GetArray($query);
         $resultdata[] = array($language => array($labels, getLanguageNameFromCode($language, false)));
     }
     echo ls_json_encode($resultdata);
 }
 $dataentryoutput .= "<input type='hidden' name='closedate' value='" . date_shift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust) . "' />\n";
 if ($thissurvey['allowsave'] == "Y") {
     //Show Save Option
     $dataentryoutput .= "\t<tr><td align='left'><input type='checkbox' class='checkboxbtn' name='save' id='save' onclick='saveshow(this.id)' /><label for='save'>" . $clang->gT("Save for further completion by survey user") . "</label>\n";
     $dataentryoutput .= "</td></tr></table>\n";
     $dataentryoutput .= "<div name='saveoptions' id='saveoptions' style='display: none'>\n";
     $dataentryoutput .= "<table align='center' class='outlinetable' cellspacing='0'>\n\t\t\t\t\t  <tr><td align='right'>" . $clang->gT("Identifier:") . "</td>\n\t\t\t\t\t  <td><input type='text' name='save_identifier' /></td></tr>\n\t\t\t\t\t  <tr><td align='right'>" . $clang->gT("Password:"******"</td>\n\t\t\t\t\t  <td><input type='password' name='save_password' /></td></tr>\n\t\t\t\t\t  <tr><td align='right'>" . $clang->gT("Confirm Password:"******"</td>\n\t\t\t\t\t  <td><input type='password' name='save_confirmpassword' /></td></tr>\n\t\t\t\t\t  <tr><td align='right'>" . $clang->gT("Email:") . "</td>\n\t\t\t\t\t  <td><input type='text' name='save_email' /></td></tr>\n\t\t\t\t\t  <tr><td align='right'>" . $clang->gT("Start Language:") . "</td>\n\t\t\t\t\t  <td>";
     $slangs = GetAdditionalLanguagesFromSurveyID($surveyid);
     $sbaselang = GetBaseLanguageFromSurveyID($surveyid);
     array_unshift($slangs, $sbaselang);
     $dataentryoutput .= "<select name='save_language'>\n";
     foreach ($slangs as $lang) {
         if ($lang == $baselang) {
             $dataentryoutput .= "\t<option value='{$lang}' selected='selected'>" . getLanguageNameFromCode($lang, false) . "</option>\n";
         } else {
             $dataentryoutput .= "\t<option value='{$lang}'>" . getLanguageNameFromCode($lang, false) . "</option>\n";
         }
     }
     $dataentryoutput .= "</select>";
     $dataentryoutput .= "</td></tr></table></div>\n";
     $dataentryoutput .= "</td>\n";
     $dataentryoutput .= "\t</tr>\n";
 }
 $dataentryoutput .= "\t<tr>\n";
 $dataentryoutput .= "<td colspan='3' align='center'>\n";
 $dataentryoutput .= "\t<input type='submit' id='submitdata' value='" . $clang->gT("Submit") . "'";
 if (tableExists('tokens_' . $thissurvey['sid'])) {
     $dataentryoutput .= " disabled='disabled'/>\n";
 } else {
     $dataentryoutput .= " />\n";
 }
                    break;



                case "I": // Language
                    $survlangs = Survey::model()->findByPk($surveyid)->additionalLanguages;
                    $survlangs[] = Survey::model()->findByPk($surveyid)->language;
                    foreach ($survlangs  as $availlang)
                    {
                        echo "\t<option value='".$availlang."'";

                        //pre-select values which were marked before
                        if (isset($_POST[$myfield]) && is_array($_POST[$myfield]) && in_array($availlang, $_POST[$myfield]))
                        {echo " selected";}

                        echo ">".getLanguageNameFromCode($availlang,false)."</option>\n";
                    }
                    break;



                    //----------------------- ARRAYS --------------------------

                case "A": // ARRAY OF 5 POINT CHOICE QUESTIONS

                    echo "\t</tr>\n\t<tr>\n";

                    //get answers
                    $result[$key1] = Question::model()->getQuestionsForStatistics('title, question', "parent_qid='$flt[0]' AND language = '{$language}'", 'question_order');
                    $counter2=0;
 </a>            
  
  <?php if(Permission::model()->hasSurveyPermission($surveyid,'surveycontent','update')): ?>
      <?php if (count($languagelist) > 1): ?>
          
          <!-- Preview multilangue -->
          <div class="btn-group">
            <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                <img src="<?php echo $sImageURL; ?>preview.png" />
              <?php eT("Preview this question group"); ?> <span class="caret"></span>
            </button>
            <ul class="dropdown-menu" style="min-width : 252px;">
                <?php foreach ($languagelist as $tmp_lang): ?>
                    <li>
                        <a target="_blank" href="<?php echo $this->createUrl("survey/index/action/previewgroup/sid/{$surveyid}/gid/{$gid}/lang/" . $tmp_lang); ?>" >
                            <?php echo getLanguageNameFromCode($tmp_lang,false); ?>
                        </a>
                    </li>    
                <?php endforeach; ?>
            </ul>
          </div>
      <?php else:?>
          
          <!-- Preview simple langue -->
          <a class="btn btn-default" href="<?php echo $this->createUrl("survey/index/action/previewgroup/sid/$surveyid/gid/$gid/"); ?>" role="button" target="_blank">
              <img src="<?php echo $sImageURL; ?>preview.png" />
              <?php eT("Preview this question group");?>
          </a>
      <?php endif; ?>                    
  <?php endif; ?>        
      
 /**
  * Builds an array containing information about this particular question/answer combination
  *
  * @param string $rt The code passed from the statistics form listing the field/answer (SGQA) combination to be displayed
  * @param mixed $language The language to present output in
  * @param mixed $surveyid The survey id
  * @param string $outputType
  * @param boolean $browse
  *
  * @output array $output An array containing "alist"=>A list of answers to the question in the form of an array ($alist array
  *                       contains an array for every field to be displayed - with the Actual Question Code/Title, The text (flattened)
  *                       of the question, and the fieldname where the data is stored.
  *                       "qtitle"=>The title of the question,
  *                       "qquestion"=>The description of the question,
  *                       "qtype"=>The question type code
  */
 protected function buildOutputList($rt, $language, $surveyid, $outputType, $sql, $oLanguage, $browse = true)
 {
     //Set up required variables
     $alist = array();
     $qtitle = "";
     $qquestion = "";
     $qtype = "";
     $statlang = $oLanguage;
     $firstletter = substr($rt, 0, 1);
     $fieldmap = createFieldMap($surveyid, "full", false, false, $language);
     $sDatabaseType = Yii::app()->db->getDriverName();
     $statisticsoutput = "";
     $qqid = "";
     /* Some variable depend on output type, actually : only line feed */
     switch ($outputType) {
         case 'xls':
         case 'pdf':
             $linefeed = "\n";
             break;
         case 'html':
             $linefeed = "<br />\n";
             break;
         default:
             break;
     }
     //M - Multiple choice, therefore multiple fields - one for each answer
     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
         $nresult = Question::model()->find('language=:language AND parent_qid=0 AND qid=:qid', array(':language' => $language, ':qid' => $qqid));
         $qtitle = $nresult->title;
         $qtype = $nresult->type;
         $qquestion = flattenText($nresult->question);
         $qlid = $nresult->parent_qid;
         $qother = $nresult->other;
         //1. Get list of answers
         $result = Question::model()->findAll(array('order' => 'question_order', 'condition' => 'language=:language AND parent_qid=:qid AND scale_id=0', 'params' => array(':language' => $language, ':qid' => $qqid)));
         foreach ($result as $row) {
             $mfield = substr($rt, 1, strlen($rt)) . $row['title'];
             $alist[] = array($row['title'], flattenText($row['question']), $mfield);
         }
         //Add the "other" answer if it exists
         if ($qother == "Y") {
             $mfield = substr($rt, 1, strlen($rt)) . "other";
             $alist[] = array(gT("Other"), gT("Other"), $mfield);
         }
     } elseif ($firstletter == "T" || $firstletter == "S") {
         //search for key
         $fld = substr($rt, 1, strlen($rt));
         $fielddata = $fieldmap[$fld];
         list($qanswer, $qlid) = !empty($fielddata['aid']) ? explode("_", $fielddata['aid']) : array("", "");
         //get question data
         $nresult = Question::model()->find('language=:language AND parent_qid=0 AND qid=:qid', array(':language' => $language, ':qid' => $fielddata['qid']));
         $qtitle = $nresult->title;
         $qtype = $nresult->type;
         $qquestion = flattenText($nresult->question);
         $qlid = $nresult->parent_qid;
         $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("Answer", gT("Answer"), $mfield);
         $alist[] = array("NoAnswer", gT("No answer"), $mfield);
     } elseif ($firstletter == "Q") {
         //Build an array of legitimate qid's for testing later
         $aQuestionInfo = $fieldmap[substr($rt, 1)];
         $qsid = $aQuestionInfo['sid'];
         $qgid = $aQuestionInfo['gid'];
         $qqid = $aQuestionInfo['qid'];
         $qaid = $aQuestionInfo['aid'];
         //get question data
         $nresult = Question::model()->find('language=:language AND parent_qid=0 AND qid=:qid', array(':language' => $language, ':qid' => $qqid));
         $qtitle = $nresult->title;
         $qtype = $nresult->type;
         $qquestion = flattenText($nresult->question);
         //more substrings
         $count = substr($qqid, strlen($qqid) - 1);
         //get answers / subquestion text
         $nresult = Question::model()->find(array('order' => 'question_order', 'condition' => 'language=:language AND parent_qid=:parent_qid AND title=:title', 'params' => array(':language' => $language, ':parent_qid' => $qqid, ':title' => $qaid)));
         $atext = flattenText($nresult->question);
         //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("Answer", gT("Answer"), $mfield);
         $alist[] = array("NoAnswer", gT("No answer"), $mfield);
     } 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 {{questions}} WHERE parent_qid=0 AND qid='{$qqid}' AND language='{$language}'";
         $nresult = Yii::app()->db->createCommand($nquery)->query();
         //loop through question data
         foreach ($nresult->readAll() as $nrow) {
             $nrow = array_values($nrow);
             $qtitle = flattenText($nrow[0]) . " [" . substr($rt, strpos($rt, "-") - $lengthofnumeral, $lengthofnumeral) . "]";
             $qtype = $nrow[1];
             $qquestion = flattenText($nrow[2]) . "[" . gT("Ranking") . " " . substr($rt, strpos($rt, "-") - $lengthofnumeral, $lengthofnumeral) . "]";
         }
         //get answers
         $query = "SELECT code, answer FROM {{answers}} WHERE qid='{$qqid}' AND scale_id=0 AND language='{$language}' ORDER BY sortorder, answer";
         $result = Yii::app()->db->createCommand($query)->query();
         //loop through answers
         foreach ($result->readAll() as $row) {
             $row = array_values($row);
             //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 == "|") {
             //get SGQ data
             list($qsid, $qgid, $qqid) = explode("X", substr($rt, 1, strlen($rt)), 3);
             //select details for this question
             $nresult = Question::model()->find('language=:language AND parent_qid=0 AND qid=:qid', array(':language' => $language, ':qid' => substr($qqid, 0, $iQuestionIDlength)));
             $qtitle = $nresult->title;
             $qtype = $nresult->type;
             $qquestion = flattenText($nresult->question);
             $qlid = $nresult->parent_qid;
             $qother = $nresult->other;
             /*
             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(" . Yii::app()->db->quoteColumnName($fieldname . '_filecount') . ") as sum, AVG(" . Yii::app()->db->quoteColumnName($fieldname . '_filecount') . ") as avg FROM {{survey_{$surveyid}}}";
             $result = Yii::app()->db->createCommand($query)->query();
             $showem = array();
             foreach ($result->readAll() as $row) {
                 $showem[] = array(gT("Total number of files"), $row['sum']);
                 $showem[] = array(gT("Average no. of files per respondent"), $row['avg']);
             }
             $query = "SELECT " . $fieldname . " as json FROM {{survey_{$surveyid}}}";
             $result = Yii::app()->db->createCommand($query)->query();
             $responsecount = 0;
             $filecount = 0;
             $size = 0;
             foreach ($result->readAll() as $row) {
                 $json = $row['json'];
                 $phparray = json_decode($json);
                 foreach ($phparray as $metadata) {
                     $size += (int) $metadata->size;
                     $filecount++;
                 }
                 $responsecount++;
             }
             $showem[] = array(gT("Total size of files"), $size . " KB");
             $showem[] = array(gT("Average file size"), $size / $filecount . " KB");
             $showem[] = array(gT("Average size per respondent"), $size / $responsecount . " KB");
             /*              $query="SELECT title, question FROM {{questions}} WHERE parent_qid='$qqid' AND language='{$language}' ORDER BY question_order";
                         $result=db_execute_num($query) or safeDie("Couldn't get list of subquestions for multitype<br />$query<br />");
             
                         //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':
                     $xlsTitle = sprintf(gT("Field summary for %s"), html_entity_decode($qtitle, ENT_QUOTES, 'UTF-8'));
                     $xlsDesc = html_entity_decode($qquestion, ENT_QUOTES, 'UTF-8');
                     $this->xlsRow++;
                     $this->xlsRow++;
                     $this->xlsRow++;
                     $this->sheet->write($this->xlsRow, 0, $xlsTitle);
                     $this->xlsRow++;
                     $this->sheet->write($this->xlsRow, 0, $xlsDesc);
                     $this->xlsRow++;
                     $this->sheet->write($this->xlsRow, 0, gT("Calculation"));
                     $this->sheet->write($this->xlsRow, 1, gT("Result"));
                     break;
                 case 'pdf':
                     $headPDF = array();
                     $tablePDF = array();
                     $footPDF = array();
                     $pdfTitle = sprintf(gT("Field summary for %s"), html_entity_decode($qtitle, ENT_QUOTES, 'UTF-8'));
                     $titleDesc = html_entity_decode($qquestion, ENT_QUOTES, 'UTF-8');
                     $headPDF[] = array(gT("Calculation"), gT("Result"));
                     break;
                 case 'html':
                     $statisticsoutput .= "\n<table class='statisticstable' >\n" . "\t<thead><tr><th colspan='2' align='center'><strong>" . sprintf(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>" . gT("Calculation") . "</strong></th>\n" . "\t\t<th width='50%' align='center' ><strong>" . 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;
             }
         } elseif ($firstletter == "N" || $firstletter == "K") {
             //Zero handling
             if (!isset($excludezeros)) {
                 $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 {
                 $showem = array();
                 $fld = substr($rt, 1, strlen($rt));
                 $fielddata = $fieldmap[$fld];
                 $qtitle = flattenText($fielddata['title']);
                 $qtype = $fielddata['type'];
                 $qquestion = $fielddata['question'];
                 //Get answer texts for multiple numerical
                 if (substr($rt, 0, 1) == "K") {
                     //put single items in brackets at output
                     $qtitle .= " [" . $fielddata['subquestion'] . "]";
                 }
                 //outputting
                 switch ($outputType) {
                     case 'xls':
                         $xlsTitle = sprintf(gT("Field summary for %s"), html_entity_decode($qtitle, ENT_QUOTES, 'UTF-8'));
                         $xlsDesc = html_entity_decode($qquestion, ENT_QUOTES, 'UTF-8');
                         $this->xlsRow++;
                         $this->xlsRow++;
                         $this->xlsRow++;
                         $this->sheet->write($this->xlsRow, 0, $xlsTitle);
                         $this->xlsRow++;
                         $this->sheet->write($this->xlsRow, 0, $xlsDesc);
                         $this->xlsRow++;
                         $this->sheet->write($this->xlsRow, 0, gT("Calculation"));
                         $this->sheet->write($this->xlsRow, 1, gT("Result"));
                         break;
                     case 'pdf':
                         $headPDF = array();
                         $tablePDF = array();
                         $footPDF = array();
                         $pdfTitle = sprintf(gT("Field summary for %s"), html_entity_decode($qtitle, ENT_QUOTES, 'UTF-8'));
                         $titleDesc = html_entity_decode($qquestion, ENT_QUOTES, 'UTF-8');
                         $headPDF[] = array(gT("Calculation"), gT("Result"));
                         break;
                     case 'html':
                         $statisticsoutput .= "\n<table class='statisticstable' >\n" . "\t<thead><tr><th colspan='2' align='center'><strong>" . sprintf(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>" . gT("Calculation") . "</strong></th>\n" . "\t\t<th width='50%' align='center' ><strong>" . 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 ($sDatabaseType == 'mssql' || $sDatabaseType == 'sqlsrv' || $sDatabaseType == 'dblib') {
                     //standard deviation
                     $query = "SELECT STDEVP(" . Yii::app()->db->quoteColumnName($fieldname) . "*1) as stdev";
                 } else {
                     //standard deviation
                     $query = "SELECT STDDEV(" . Yii::app()->db->quoteColumnName($fieldname) . ") as stdev";
                 }
                 //sum
                 $query .= ", SUM(" . Yii::app()->db->quoteColumnName($fieldname) . "*1) as sum";
                 //average
                 $query .= ", AVG(" . Yii::app()->db->quoteColumnName($fieldname) . "*1) as average";
                 //min
                 $query .= ", MIN(" . Yii::app()->db->quoteColumnName($fieldname) . "*1) as minimum";
                 //max
                 $query .= ", MAX(" . Yii::app()->db->quoteColumnName($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 ($sDatabaseType == 'mssql' || $sDatabaseType == 'sqlsrv' || $sDatabaseType == 'dblib') {
                     //no NULL/empty values please
                     $query .= " FROM {{survey_{$surveyid}}} WHERE " . Yii::app()->db->quoteColumnName($fieldname) . " IS NOT NULL";
                     if (!$excludezeros) {
                         //NO ZERO VALUES
                         $query .= " AND (" . Yii::app()->db->quoteColumnName($fieldname) . " <> 0)";
                     }
                 } else {
                     //no NULL/empty values please
                     $query .= " FROM {{survey_{$surveyid}}} WHERE " . Yii::app()->db->quoteColumnName($fieldname) . " IS NOT NULL";
                     if (!$excludezeros) {
                         //NO ZERO VALUES
                         $query .= " AND (" . Yii::app()->db->quoteColumnName($fieldname) . " != 0)";
                     }
                 }
                 //filter incomplete answers if set
                 if (incompleteAnsFilterState() == "incomplete") {
                     $query .= " AND submitdate is null";
                 } elseif (incompleteAnsFilterState() == "complete") {
                     $query .= " AND submitdate is not null";
                 }
                 //$sql was set somewhere before
                 if (!empty($sql)) {
                     $query .= " AND {$sql}";
                 }
                 //execute query
                 $result = Yii::app()->db->createCommand($query)->queryAll();
                 //get calculated data
                 foreach ($result as $row) {
                     //put translation of mean and calculated data into $showem array
                     $showem[] = array(gT("Sum"), $row['sum']);
                     $showem[] = array(gT("Standard deviation"), round($row['stdev'], 2));
                     $showem[] = array(gT("Average"), round($row['average'], 2));
                     $showem[] = array(gT("Minimum"), $row['minimum']);
                     //Display the maximum and minimum figures after the quartiles for neatness
                     $maximum = $row['maximum'];
                     $minimum = $row['minimum'];
                 }
                 //CALCULATE QUARTILES
                 $medcount = $this->getQuartile(0, $fieldname, $surveyid, $sql, $excludezeros);
                 // Get the recordcount
                 $quartiles = array();
                 $quartiles[1] = $this->getQuartile(1, $fieldname, $surveyid, $sql, $excludezeros);
                 $quartiles[2] = $this->getQuartile(2, $fieldname, $surveyid, $sql, $excludezeros);
                 $quartiles[3] = $this->getQuartile(3, $fieldname, $surveyid, $sql, $excludezeros);
                 //we just put the total number of records at the beginning of this array
                 array_unshift($showem, array(gT("Count"), $medcount));
                 /* IMPORTANT IMPORTANT IMPORTANT IMPORTANT IMPORTANT IMPORTANT */
                 /* IF YOU DON'T UNDERSTAND WHAT QUARTILES ARE DO NOT MODIFY THIS CODE */
                 /* Quartiles and Median values are NOT related to average, and the sum is irrelevent */
                 if (isset($quartiles[1])) {
                     $showem[] = array(gT("1st quartile (Q1)"), $quartiles[1]);
                 }
                 if (isset($quartiles[2])) {
                     $showem[] = array(gT("2nd quartile (Median)"), $quartiles[2]);
                 }
                 if (isset($quartiles[3])) {
                     $showem[] = array(gT("3rd quartile (Q3)"), $quartiles[3]);
                 }
                 $showem[] = array(gT("Maximum"), $maximum);
                 //output results
                 foreach ($showem as $shw) {
                     switch ($outputType) {
                         case 'xls':
                             $this->xlsRow++;
                             $this->sheet->write($this->xlsRow, 0, html_entity_decode($shw[0], ENT_QUOTES, 'UTF-8'));
                             $this->sheet->write($this->xlsRow, 1, html_entity_decode($shw[1], ENT_QUOTES, 'UTF-8'));
                             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':
                         $this->xlsRow++;
                         $this->sheet->write($this->xlsRow, 0, gT("Null values are ignored in calculations"));
                         $this->xlsRow++;
                         $this->sheet->write($this->xlsRow, 0, sprintf(gT("Q1 and Q3 calculated using %s"), gT("minitab method")));
                         $footXLS[] = array(gT("Null values are ignored in calculations"));
                         $footXLS[] = array(sprintf(gT("Q1 and Q3 calculated using %s"), gT("minitab method")));
                         break;
                     case 'pdf':
                         $footPDF[] = array(gT("Null values are ignored in calculations"));
                         $footPDF[] = array(sprintf(gT("Q1 and Q3 calculated using %s"), "<a href='http://mathforum.org/library/drmath/view/60969.html' target='_blank'>" . gT("minitab method") . "</a>"));
                         $this->pdf->AddPage('P', 'A4');
                         $this->pdf->Bookmark($this->pdf->delete_html($qquestion), 1, 0);
                         $this->pdf->titleintopdf($pdfTitle, $titleDesc);
                         $this->pdf->headTable($headPDF, $tablePDF);
                         $this->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'>" . gT("Null values are ignored in calculations") . "<br />\n" . "\t\t\t" . sprintf(gT("Q1 and Q3 calculated using %s"), "<a href='http://mathforum.org/library/drmath/view/60969.html' target='_blank'>" . gT("minitab method") . "</a>") . "</font>\n" . "\t\t</td>\n" . "\t</tr>\n";
                         if ($browse) {
                             $statisticsoutput .= "\t<tr>\n" . "\t\t<td align='center'  colspan='4'>\n                            <input type='button' class='statisticsbrowsebutton numericalbrowse' value='" . gT("Browse") . "' id='{$fieldname}' /></td>\n</tr>";
                             $statisticsoutput .= "<tr><td class='statisticsbrowsecolumn' colspan='3' style='display: none'>\n                            <div class='statisticsbrowsecolumn' id='columnlist_{$fieldname}'></div></td></tr>";
                         }
                         $statisticsoutput .= "</table>\n";
                         break;
                     default:
                         break;
                 }
                 //clean up
                 unset($showem);
                 //not enough (<1) results for calculation
                 if ($medcount < 1) {
                     switch ($outputType) {
                         case 'xls':
                             $this->xlsRow++;
                             $this->sheet->write($this->xlsRow, 0, gT("Not enough values for calculation"));
                             break;
                         case 'pdf':
                             $tablePDF = array();
                             $tablePDF[] = array(gT("Not enough values for calculation"));
                             $this->pdf->AddPage('P', 'A4');
                             $this->pdf->Bookmark($this->pdf->delete_html($qquestion), 1, 0);
                             $this->pdf->titleintopdf($pdfTitle, $titleDesc);
                             $this->pdf->equalTable($tablePDF);
                             break;
                         case 'html':
                             //output
                             $statisticsoutput .= "\t<tr>\n" . "\t\t<td align='center'  colspan='4'>" . 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
         } 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
              */
         } else {
             //search for key
             $fielddata = $fieldmap[$rt];
             //get SGQA IDs
             $qsid = $fielddata['sid'];
             $qgid = $fielddata['gid'];
             $qqid = $fielddata['qid'];
             $qanswer = $fielddata['aid'];
             $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 {{questions}} WHERE qid='{$rqid}' AND parent_qid=0 and language='{$language}'";
             $nresult = Yii::app()->db->createCommand($nquery)->query();
             //loop though question data
             foreach ($nresult->readAll() as $nrow) {
                 $nrow = array_values($nrow);
                 $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 {{questions}} WHERE parent_qid='{$qiqid}' AND title='{$qanswer}' AND language='{$language}' ORDER BY question_order";
                     $qresult = Yii::app()->db->createCommand($qquery)->query();
                     //loop through results
                     foreach ($qresult->readAll() as $qrow) {
                         $qrow = array_values($qrow);
                         //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
                 //Array of 10 point choices
                 //same as above just with 10 items
                 case "B":
                     $qquery = "SELECT title, question FROM {{questions}} WHERE parent_qid='{$qiqid}' AND title='{$qanswer}' AND language='{$language}' ORDER BY question_order";
                     $qresult = Yii::app()->db->createCommand($qquery)->query();
                     foreach ($qresult->readAll() as $qrow) {
                         $qrow = array_values($qrow);
                         for ($i = 1; $i <= 10; $i++) {
                             $alist[] = array("{$i}", "{$i}");
                         }
                         $atext = flattenText($qrow[1]);
                     }
                     $qquestion .= $linefeed . "[" . $atext . "]";
                     $qtitle .= "({$qanswer})";
                     break;
                     //Array of Yes/No/gT("Uncertain")
                 //Array of Yes/No/gT("Uncertain")
                 case "C":
                     $qquery = "SELECT title, question FROM {{questions}} WHERE parent_qid='{$qiqid}' AND title='{$qanswer}' AND language='{$language}' ORDER BY question_order";
                     $qresult = Yii::app()->db->createCommand($qquery)->query();
                     //loop thorugh results
                     foreach ($qresult->readAll() as $qrow) {
                         $qrow = array_values($qrow);
                         //add results
                         $alist[] = array("Y", gT("Yes"));
                         $alist[] = array("N", gT("No"));
                         $alist[] = array("U", gT("Uncertain"));
                         $atext = flattenText($qrow[1]);
                     }
                     //output
                     $qquestion .= $linefeed . "[" . $atext . "]";
                     $qtitle .= "({$qanswer})";
                     break;
                     //Array of Yes/No/gT("Uncertain")
                     //same as above
                 //Array of Yes/No/gT("Uncertain")
                 //same as above
                 case "E":
                     $qquery = "SELECT title, question FROM {{questions}} WHERE parent_qid='{$qiqid}' AND title='{$qanswer}' AND language='{$language}' ORDER BY question_order";
                     $qresult = Yii::app()->db->createCommand($qquery)->query();
                     foreach ($qresult->readAll() as $qrow) {
                         $qrow = array_values($qrow);
                         $alist[] = array("I", gT("Increase"));
                         $alist[] = array("S", gT("Same"));
                         $alist[] = array("D", 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 {{questions}} WHERE parent_qid='{$qiqid}' AND title='{$qacode}' AND language='{$language}' ORDER BY question_order";
                     $qresult = Yii::app()->db->createCommand($qquery)->query();
                     foreach ($qresult->readAll() as $qrow) {
                         $qrow = array_values($qrow);
                         $fquery = "SELECT * FROM {{answers}} WHERE qid='{$qiqid}' AND scale_id=0 AND code = '{$licode}' AND language='{$language}'ORDER BY sortorder, code";
                         $fresult = Yii::app()->db->createCommand($fquery)->query();
                         foreach ($fresult->readAll() as $frow) {
                             $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)
                     $aQuestionAttributes = getQuestionAttributeValues($qiqid);
                     if (trim($aQuestionAttributes['multiflexible_max']) != '') {
                         $maxvalue = $aQuestionAttributes['multiflexible_max'];
                     } else {
                         $maxvalue = 10;
                     }
                     if (trim($aQuestionAttributes['multiflexible_min']) != '') {
                         $minvalue = $aQuestionAttributes['multiflexible_min'];
                     } else {
                         $minvalue = 1;
                     }
                     if (trim($aQuestionAttributes['multiflexible_step']) != '') {
                         $stepvalue = $aQuestionAttributes['multiflexible_step'];
                     } else {
                         $stepvalue = 1;
                     }
                     if ($aQuestionAttributes['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
                 //Array of Flexible
                 case "H":
                     //Array of Flexible by Column
                     $qquery = "SELECT title, question FROM {{questions}} WHERE parent_qid='{$qiqid}' AND title='{$qanswer}' AND language='{$language}' ORDER BY question_order";
                     $qresult = Yii::app()->db->createCommand($qquery)->query();
                     //loop through answers
                     foreach ($qresult->readAll() as $qrow) {
                         $qrow = array_values($qrow);
                         //this question type uses its own labels
                         $fquery = "SELECT * FROM {{answers}} WHERE qid='{$qiqid}' AND scale_id=0 AND language='{$language}'ORDER BY sortorder, code";
                         $fresult = Yii::app()->db->createCommand($fquery)->query();
                         //add code and title to results for outputting them later
                         foreach ($fresult->readAll() as $frow) {
                             $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", gT("Female"));
                     $alist[] = array("M", gT("Male"));
                     break;
                 case "Y":
                     //Yes\No
                     $alist[] = array("Y", gT("Yes"));
                     $alist[] = array("N", 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 {{questions}} WHERE parent_qid='{$qiqid}' AND title='{$qanswer}' AND language='{$language}' ORDER BY question_order";
                     $questionDesc = Yii::app()->db->createCommand($sSubquestionQuery)->query()->read();
                     $sSubquestion = flattenText($questionDesc['question']);
                     //get question attributes
                     $aQuestionAttributes = getQuestionAttributeValues($qqid);
                     //check last character -> label 1
                     if (substr($rt, -1, 1) == 0) {
                         //get label 1
                         $fquery = "SELECT * FROM {{answers}} WHERE qid='{$qqid}' AND scale_id=0 AND language='{$language}' ORDER BY sortorder, code";
                         //header available?
                         if (trim($aQuestionAttributes['dualscale_headerA'][$language]) != '') {
                             //output
                             $labelheader = "[" . $aQuestionAttributes['dualscale_headerA'][$language] . "]";
                         } else {
                             $labelheader = '';
                         }
                         //output
                         $labelno = sprintf(gT('Label %s'), '1');
                     } else {
                         //get label 2
                         $fquery = "SELECT * FROM {{answers}} WHERE qid='{$qqid}' AND scale_id=1 AND language='{$language}' ORDER BY sortorder, code";
                         //header available?
                         if (trim($aQuestionAttributes['dualscale_headerB'][$language]) != '') {
                             //output
                             $labelheader = "[" . $aQuestionAttributes['dualscale_headerB'][$language] . "]";
                         } else {
                             $labelheader = '';
                         }
                         //output
                         $labelno = sprintf(gT('Label %s'), '2');
                     }
                     //get data
                     $fresult = Yii::app()->db->createCommand($fquery)->query();
                     //put label code and label title into array
                     foreach ($fresult->readAll() as $frow) {
                         $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 {{answers}} WHERE qid='{$qqid}' AND scale_id=0 AND language='{$language}' ORDER BY sortorder, answer";
                     $qresult = Yii::app()->db->createCommand($qquery)->query();
                     //put answer code and title into array
                     foreach ($qresult->readAll() as $qrow) {
                         $qrow = array_values($qrow);
                         $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(gT("Other"), gT("Other"), $fielddata['fieldname'] . 'other');
                     }
                     if ($qtype == "O") {
                         //add "comment"
                         $alist[] = array(gT("Comments"), 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("", gT("No answer"));
         }
     }
     return array("alist" => $alist, "qtitle" => $qtitle, "qquestion" => $qquestion, "qtype" => $qtype, "statisticsoutput" => $statisticsoutput, "parentqid" => $qqid);
 }
    ?>
</h3>

    <div class="row">
        <div class="col-lg-12 content-right">
            <?php 
    echo CHtml::form(array("admin/tokens/sa/updatetokenattributedescriptions/surveyid/{$surveyid}"), 'post');
    ?>
            <div>
                <ul class="nav nav-tabs">
                    <?php 
    $c = true;
    ?>
                    <?php 
    foreach ($languages as $sLanguage) {
        $sTabTitle = getLanguageNameFromCode($sLanguage, false);
        if ($sLanguage == Survey::model()->findByPk($iSurveyID)->language) {
            $sTabTitle .= '(' . gT("Base language") . ')';
        }
        ?>
                        <li <?php 
        if ($c) {
            $c = false;
            echo 'class="active"';
        }
        ?>
 >
                            <a data-toggle="tab" href="#language_<?php 
        echo $sLanguage;
        ?>
"><?php 
 /**
  * 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);
 }
/**
* 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;
    }

}
 /**
  * questiongroup::edit()
  * Load editing of a question group screen.
  *
  * @access public
  * @param int $surveyid
  * @param int $gid
  * @return void
  */
 public function edit($surveyid, $gid)
 {
     $surveyid = sanitize_int($surveyid);
     $gid = sanitize_int($gid);
     $aViewUrls = $aData = array();
     if (Permission::model()->hasSurveyPermission($surveyid, 'surveycontent', 'read')) {
         Yii::app()->session['FileManagerContext'] = "edit:group:{$surveyid}";
         Yii::app()->loadHelper('admin/htmleditor');
         Yii::app()->loadHelper('surveytranslator');
         $aAdditionalLanguages = Survey::model()->findByPk($surveyid)->additionalLanguages;
         $aBaseLanguage = Survey::model()->findByPk($surveyid)->language;
         $aLanguages = array_merge(array($aBaseLanguage), $aAdditionalLanguages);
         $grplangs = array_flip($aLanguages);
         // Check out the intgrity of the language versions of this group
         $egresult = QuestionGroup::model()->findAllByAttributes(array('sid' => $surveyid, 'gid' => $gid));
         foreach ($egresult as $esrow) {
             $esrow = $esrow->attributes;
             // Language Exists, BUT ITS NOT ON THE SURVEY ANYMORE
             if (!in_array($esrow['language'], $aLanguages)) {
                 QuestionGroup::model()->deleteAllByAttributes(array('sid' => $surveyid, 'gid' => $gid, 'language' => $esrow['language']));
             } else {
                 $grplangs[$esrow['language']] = 'exists';
             }
             if ($esrow['language'] == $aBaseLanguage) {
                 $basesettings = $esrow;
             }
         }
         // Create groups in missing languages
         while (list($key, $value) = each($grplangs)) {
             if ($value != 'exists') {
                 $basesettings['language'] = $key;
                 $group = new QuestionGroup();
                 foreach ($basesettings as $k => $v) {
                     $group->{$k} = $v;
                 }
                 switchMSSQLIdentityInsert('groups', true);
                 $group->save();
                 switchMSSQLIdentityInsert('groups', false);
             }
         }
         $first = true;
         foreach ($aLanguages as $sLanguage) {
             $oResult = QuestionGroup::model()->findByAttributes(array('sid' => $surveyid, 'gid' => $gid, 'language' => $sLanguage));
             $aData['aGroupData'][$sLanguage] = $oResult->attributes;
             $aTabTitles[$sLanguage] = getLanguageNameFromCode($sLanguage, false);
             if ($first) {
                 $aTabTitles[$sLanguage] .= ' (' . gT("Base language") . ')';
                 $first = false;
             }
         }
         $aData['action'] = $aData['display']['menu_bars']['gid_action'] = 'editgroup';
         $aData['surveyid'] = $surveyid;
         $aData['gid'] = $gid;
         $aData['tabtitles'] = $aTabTitles;
         $aData['aBaseLanguage'] = $aBaseLanguage;
         $this->_renderWrappedTemplate('survey/QuestionGroups', 'editGroup_view', $aData);
     }
 }
Example #19
0
 /**
  *
  * @param type $iQuestionId
  * @param type $iSurveyId
  * @param type $iQuotaId
  * @return array
  */
 function getQuotaAnswers($iQuestionId, $iSurveyId, $iQuotaId)
 {
     $iQuestionId = sanitize_int($iQuestionId);
     $iSurveyId = sanitize_int($iSurveyId);
     $iQuotaId = sanitize_int($iQuotaId);
     $aData = $this->_getData($iSurveyId);
     $sBaseLang = $aData['sBaseLang'];
     $this->_checkPermissions($iSurveyId, 'read');
     $aQuestion = Question::model()->findByPk(array('qid' => $iQuestionId, 'language' => $sBaseLang));
     $aQuestionType = $aQuestion['type'];
     if ($aQuestionType == 'M') {
         $aResults = Question::model()->findAllByAttributes(array('parent_qid' => $iQuestionId));
         $aAnswerList = array();
         foreach ($aResults as $aDbAnsList) {
             $tmparrayans = array('Title' => $aQuestion['title'], 'Display' => substr($aDbAnsList['question'], 0, 40), 'code' => $aDbAnsList['title']);
             $aAnswerList[$aDbAnsList['title']] = $tmparrayans;
         }
     } elseif ($aQuestionType == 'G') {
         $aAnswerList = array('M' => array('Title' => $aQuestion['title'], 'Display' => gT("Male"), 'code' => 'M'), 'F' => array('Title' => $aQuestion['title'], 'Display' => gT("Female"), 'code' => 'F'));
     } elseif ($aQuestionType == 'L' || $aQuestionType == 'O' || $aQuestionType == '!') {
         $aAnsResults = Answer::model()->findAllByAttributes(array('qid' => $iQuestionId, 'language' => $sBaseLang));
         $aAnswerList = array();
         foreach ($aAnsResults as $aDbAnsList) {
             $aAnswerList[$aDbAnsList['code']] = array('Title' => $aQuestion['title'], 'Display' => substr($aDbAnsList['answer'], 0, 40), 'code' => $aDbAnsList['code']);
         }
     } elseif ($aQuestionType == 'A') {
         $aAnsResults = Question::model()->findAllByAttributes(array('parent_qid' => $iQuestionId));
         $aAnswerList = array();
         foreach ($aAnsResults as $aDbAnsList) {
             for ($x = 1; $x < 6; $x++) {
                 $tmparrayans = array('Title' => $aQuestion['title'], 'Display' => substr($aDbAnsList['question'], 0, 40) . ' [' . $x . ']', 'code' => $aDbAnsList['title']);
                 $aAnswerList[$aDbAnsList['title'] . "-" . $x] = $tmparrayans;
             }
         }
     } elseif ($aQuestionType == 'B') {
         $aAnsResults = Answer::model()->findAllByAttributes(array('qid' => $iQuestionId, 'language' => $sBaseLang));
         $aAnswerList = array();
         foreach ($aAnsResults as $aDbAnsList) {
             for ($x = 1; $x < 11; $x++) {
                 $tmparrayans = array('Title' => $aQuestion['title'], 'Display' => substr($aDbAnsList['answer'], 0, 40) . ' [' . $x . ']', 'code' => $aDbAnsList['code']);
                 $aAnswerList[$aDbAnsList['code'] . "-" . $x] = $tmparrayans;
             }
         }
     } elseif ($aQuestionType == 'Y') {
         $aAnswerList = array('Y' => array('Title' => $aQuestion['title'], 'Display' => gT("Yes"), 'code' => 'Y'), 'N' => array('Title' => $aQuestion['title'], 'Display' => gT("No"), 'code' => 'N'));
     } elseif ($aQuestionType == 'I') {
         $slangs = Survey::model()->findByPk($iSurveyId)->additionalLanguages;
         array_unshift($slangs, $sBaseLang);
         while (list($key, $value) = each($slangs)) {
             $tmparrayans = array('Title' => $aQuestion['title'], 'Display' => getLanguageNameFromCode($value, false), $value);
             $aAnswerList[$value] = $tmparrayans;
         }
     }
     if (empty($aAnswerList)) {
         return array();
     } else {
         // Now we mark answers already used in this quota as such
         $aExistsingAnswers = QuotaMember::model()->findAllByAttributes(array('sid' => $iSurveyId, 'qid' => $iQuestionId, 'quota_id' => $iQuotaId));
         foreach ($aExistsingAnswers as $aAnswerRow) {
             if (array_key_exists($aAnswerRow['code'], $aAnswerList)) {
                 $aAnswerList[$aAnswerRow['code']]['rowexists'] = '1';
             }
         }
         return $aAnswerList;
     }
 }
Example #20
0
        </li>
        <li>
            <label for="quota_action"><?php eT("Quota action");?>:</label>
            <select id="quota_action" name="quota_action" class="form-control">
                <option value ="1"><?php eT("Terminate survey");?></option>
                <option value ="2"><?php eT("Terminate survey with warning");?></option>
            </select>
        </li>
        <li>
            <label for="autoload_url"><?php eT("Autoload URL");?>:</label>
            <input id="autoload_url" name="autoload_url" type="checkbox" value="1" />
        </li>
    </ul>
    <div id="tabs"><ul>
            <?php foreach ($langs as $lang) { ?>
                <li><a href="#tabpage_<?php echo $lang ?>"><?php echo getLanguageNameFromCode($lang,false);
                        if ($lang==$baselang) {echo '('.gT("Base language").')';} ;?></a></li>
                <?php } ?>
        </ul>


        <?php foreach ($langs as $lang) { ?>
            <div id="tabpage_<?php echo $lang ?>">
                <ul>
                    <li>
                        <label for="quotals_message_<?php echo $lang;?>"><?php eT("Quota message");?>:</label>
                        <textarea id="quotals_message_<?php echo $lang;?>" name="quotals_message_<?php echo $lang;?>" cols="60" rows="6"><?php eT("Sorry your responses have exceeded a quota on this survey.");?></textarea>
                    </li>
                    <li>
                        <label for="quotals_url_<?php echo $lang;?>"><?php eT("URL");?>:</label>
                        <input id="quotals_url_<?php echo $lang;?>" name="quotals_url_<?php echo $lang;?>" type="text" size="50" maxlength="255" value="<?php echo $thissurvey['url'];?>" />
<?php echo PrepareEditorScript(true, $this); ?>
<div class='header ui-widget-header'>
    <?php $clang->eT("Send email reminder"); ?></div><br />

<?php if ($thissurvey['active'] != 'Y') { ?>
    <div class='messagebox ui-corner-all'><div class='warningheader'><?php $clang->eT('Warning!'); ?></div><?php $clang->eT("This survey is not yet activated and so your participants won't be able to fill out the survey."); ?></div>
<?php } ?>

<div id='tabs'>
    <ul>
        <?php
        foreach ($surveylangs as $language)
        {
            //GET SURVEY DETAILS
            echo '<li><a href="#tabpage_' . $language . '">' . getLanguageNameFromCode($language, false);
            if ($language == $baselang)
            {
                echo "(" . $clang->gT("Base language") . ")";
            }
            echo "</a></li>";
        }
        ?>
    </ul>

    <?php echo CHtml::form(array("admin/tokens/sa/email/action/remind/surveyid/{$surveyid}"), 'post', array('id'=>'sendreminder', 'class'=>'form30')); ?>
        <?php
        foreach ($surveylangs as $language)
        {
            //GET SURVEY DETAILS
            if (!$thissurvey[$language]['email_remind'])
            {
    <li><label for='maximum'><?php 
    $clang->eT("Maximum");
    ?>
</label><input type='text' id='maximum' name='maximum' class='numbersonly'<?php 
    if (isset($editdata)) {
        echo " value='{$editdata['maximum']}' ";
    }
    ?>
/></li>

	</ul><div id="languagetabs">
    <ul class="ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all">
    <?php 
    foreach ($assessmentlangs as $assessmentlang) {
        $position = 0;
        echo '<li class="ui-state-default ui-corner-top" style="clear: none;"><a href="#tablang' . $assessmentlang . '">' . getLanguageNameFromCode($assessmentlang, false);
        if ($assessmentlang == $baselang) {
            echo ' (' . $clang->gT("Base language") . ')';
        }
        echo '</a></li>';
    }
    ?>
    </ul>
    <?php 
    foreach ($assessmentlangs as $assessmentlang) {
        $heading = '';
        $message = '';
        if ($action == "assessmentedit") {
            $results = Assessment::model()->findAllByAttributes(array('id' => $_POST['id'], 'language' => $assessmentlang));
            foreach ($results as $row) {
                $editdata = $row->attributes;
Example #23
0
    					  <tr><td align='right'><?php $clang->eT("Password:"******"Confirm Password:"******"Email:"); ?></td>
    					  <td><input type='email' name='save_email' /></td></tr>
    					  <tr><td align='right'><?php $clang->eT("Start Language:"); ?></td>
    					  <td>
                    <select name='save_language'>
                    <?php foreach ($slangs as $lang)
                    {
                        if ($lang == $baselang) { ?>
                            <option value='<?php echo $lang; ?>' selected='selected'><?php echo getLanguageNameFromCode($lang,false); ?></option>
                            <?php }
                        else { ?>
                            <option value='<?php echo $lang; ?>'><?php echo getLanguageNameFromCode($lang,false); ?></option>
                            <?php }
                    } ?>
                    </select>


                    </td></tr></table></div>
                    </td>
                    </tr>
                <?php } ?>
                <tr>
                <td colspan='3' align='center'>
                <input type='submit' id='submitdata' value='<?php $clang->eT("Submit"); ?>'

                <?php if (tableExists('tokens_'.$thissurvey['sid']))
                { ?>
Example #24
0
        {
            $tokenoutput .="<div class='messagebox ui-corner-all'><div class='warningheader'>".$clang->gT('Warning!')."</div>".$clang->gT("This survey is not yet activated and so your participants won't be able to fill out the survey.")."</div>";
        }
        //GET SURVEY DETAILS
        $tokenoutput .= "<form method='post' class='form30' id='sendreminder' action='$scriptname?action=tokens'>";
        $surveylangs = GetAdditionalLanguagesFromSurveyID($surveyid);
        $baselang = GetBaseLanguageFromSurveyID($surveyid);
        array_unshift($surveylangs,$baselang);

        $tokenoutput .= "<div class='tab-pane' id='tab-pane-send-$surveyid'>";
        foreach ($surveylangs as $language)
        {
            //GET SURVEY DETAILS
            $thissurvey=getSurveyInfo($surveyid,$language);
            if (!$thissurvey['email_remind']) {$thissurvey['email_remind']=str_replace("\n", "\r\n", $clang->gT("Dear {FIRSTNAME},\n\nRecently we invited you to participate in a survey.\n\nWe note that you have not yet completed the survey, and wish to remind you that the survey is still available should you wish to take part.\n\nThe survey is titled:\n\"{SURVEYNAME}\"\n\n\"{SURVEYDESCRIPTION}\"\n\nTo participate, please click on the link below.\n\nSincerely,\n\n{ADMINNAME} ({ADMINEMAIL})\n\n----------------------------------------------\nClick here to do the survey:\n{SURVEYURL}")."\n\n".$clang->gT("If you do not want to participate in this survey and don't want to receive any more invitations please click the following link:\n{OPTOUTURL}"));}
            $tokenoutput .= '<div class="tab-page"> <h2 class="tab">'.getLanguageNameFromCode($language,false);
            if ($language==$baselang)
            {
                $tokenoutput .= "(".$clang->gT("Base language").")";
            }
            $tokenoutput .= "</h2><ul>\n"
            ."<li><label for='from_$language' >".$clang->gT("From").":</label>\n"
            ."<input type='text' size='50' name='from_$language' id='from_$language' value=\"{$thissurvey['adminname']} <{$thissurvey['adminemail']}>\" /></li>\n"

            ."<li><label for='subject_$language' >".$clang->gT("Subject").":</label>\n";

            $fieldsarray["{ADMINNAME}"]= $thissurvey['adminname'];
            $fieldsarray["{ADMINEMAIL}"]=$thissurvey['adminemail'];
            $fieldsarray["{SURVEYNAME}"]=$thissurvey['name'];
            $fieldsarray["{SURVEYDESCRIPTION}"]=$thissurvey['description'];
            $fieldsarray["{EXPIRY}"]=$thissurvey["expiry"];
Example #25
0
function do_language($ia)
{
    $checkconditionFunction = "checkconditions";
    $answerlangs = Survey::model()->findByPk(Yii::app()->getConfig('surveyID'))->additionalLanguages;
    $answerlangs[] = Survey::model()->findByPk(Yii::app()->getConfig('surveyID'))->language;
    // Get actual answer
    $sLang = $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'];
    if (!in_array($sLang, $answerlangs)) {
        $sLang = Survey::model()->findByPk(Yii::app()->getConfig('surveyID'))->language;
    }
    $answer = "\n\t<p class=\"question answer-item dropdown-item langage-item\">\n" . "<label for='answer{$ia[1]}' class='hide label'>" . gT('Choose your language') . "</label>" . "<select name=\"{$ia['1']}\" id=\"answer{$ia['1']}\" onchange=\"{$checkconditionFunction}(this.value, this.name, this.type);\" class=\"languagesurvey\">\n";
    foreach ($answerlangs as $ansrow) {
        $answer .= "\t<option value=\"{$ansrow}\"";
        if ($sLang == $ansrow) {
            $answer .= SELECTED;
        }
        $aLanguage = getLanguageNameFromCode($ansrow, true);
        $answer .= '>' . $aLanguage[1] . "</option>\n";
    }
    $answer .= "</select>\n";
    $answer .= "<input type=\"hidden\" name=\"java{$ia[1]}\" id=\"java{$ia[1]}\" value=\"{$sLang}\" />\n";
    $inputnames[] = $ia[1];
    $answer .= "<script type='text/javascript'>\n" . "/*<![CDATA[*/\n" . "\$('#answer{$ia[1]}').change(function(){ " . "\$('<input type=\"hidden\">').attr('name','lang').val(\$(this).val()).appendTo(\$('form#limesurvey'));" . " })\n" . " /*]]>*/\n" . "</script>\n";
    return array($answer, $inputnames);
}
Example #26
0
        $separator = "~|";
        break;
    case "csv":
        header("Content-Disposition: attachment; filename=results-survey" . $surveyid . ".csv");
        header("Content-type: text/comma-separated-values; charset=UTF-8");
        $separator = ",";
        break;
    case "pdf":
        $pdf = new PDF($pdforientation, 'mm', 'A4');
        $pdf->SetFont($pdfdefaultfont, '', $pdffontsize);
        $pdf->AddPage();
        $pdf->intopdf("PDF Export " . date("Y.m.d-H:i", time()));
        $query = "SELECT * FROM {$dbprefix}surveys_languagesettings WHERE surveyls_survey_id=" . $surveyid;
        $result = db_execute_assoc($query) or safe_die("Couldn't get privacy data<br />{$query}<br />" . $connect->ErrorMsg());
        while ($row = $result->FetchRow()) {
            $pdf->intopdf($clang->gT("General information in language: ") . getLanguageNameFromCode($row['surveyls_language']), 'B');
            $pdf->ln();
            $pdf->titleintopdf($row['surveyls_title'], $row['surveyls_description']);
            $surveyname = $row['surveyls_title'];
        }
        $pdf->AddPage();
        $separator = "\t";
        break;
    default:
        header("Content-Disposition: attachment; filename=results-survey" . $surveyid . ".csv");
        header("Content-type: text/comma-separated-values; charset=UTF-8");
        $separator = ",";
        break;
}
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Pragma: public");
Example #27
0
    /**
     * dataentry::editdata()
     * Edit dataentry.
     * @param mixed $subaction
     * @param mixed $id
     * @param mixed $surveyid
     * @param mixed $language
     * @return
     */
    public function editdata($subaction, $id, $surveyid, $language = '')
    {
        if ($language == '') {
            $language = Survey::model()->findByPk($surveyid)->language;
        }
        $surveyid = sanitize_int($surveyid);
        $id = sanitize_int($id);
        $aViewUrls = array();
        if (!isset($sDataEntryLanguage)) {
            $sDataEntryLanguage = Survey::model()->findByPk($surveyid)->language;
        }
        $surveyinfo = getSurveyInfo($surveyid);
        if (hasSurveyPermission($surveyid, 'responses', 'update')) {
            $surveytable = "{{survey_" . $surveyid . '}}';
            $aData['clang'] = $clang = $this->getController()->lang;
            $aData['display']['menu_bars']['browse'] = $clang->gT("Data entry");
            Yii::app()->loadHelper('database');
            //FIRST LETS GET THE NAMES OF THE QUESTIONS AND MATCH THEM TO THE FIELD NAMES FOR THE DATABASE
            $fnquery = "SELECT * FROM {{questions}}, {{groups}} g, {{surveys}} WHERE\n            {{questions}}.gid=g.gid AND\n            {{questions}}.language = '{$sDataEntryLanguage}' AND g.language = '{$sDataEntryLanguage}' AND\n            {{questions}}.sid={{surveys}}.sid AND {{questions}}.sid='{$surveyid}'\n            order by group_order, question_order";
            $fnresult = dbExecuteAssoc($fnquery);
            $fnresult = $fnresult->readAll();
            $fncount = count($fnresult);
            $fnrows = array();
            //Create an empty array in case FetchRow does not return any rows
            foreach ($fnresult as $fnrow) {
                $fnrows[] = $fnrow;
                $private = $fnrow['anonymized'];
                $datestamp = $fnrow['datestamp'];
                $ipaddr = $fnrow['ipaddr'];
            }
            // Get table output into array
            // Perform a case insensitive natural sort on group name then question title of a multidimensional array
            // $fnames = (Field Name in Survey Table, Short Title of Question, Question Type, Field Name, Question Code, Predetermined Answers if exist)
            $fnames['completed'] = array('fieldname' => "completed", 'question' => $clang->gT("Completed"), 'type' => 'completed');
            $fnames = array_merge($fnames, createFieldMap($surveyid, 'full', false, false, $sDataEntryLanguage));
            $nfncount = count($fnames) - 1;
            //SHOW INDIVIDUAL RECORD
            if ($subaction == "edit" && hasSurveyPermission($surveyid, 'responses', 'update')) {
                $idquery = "SELECT * FROM {$surveytable} WHERE id={$id}";
                $idresult = dbExecuteAssoc($idquery) or safeDie("Couldn't get individual record<br />{$idquery}<br />");
                foreach ($idresult->readAll() as $idrow) {
                    $results[] = $idrow;
                }
            } elseif ($subaction == "editsaved" && hasSurveyPermission($surveyid, 'responses', 'update')) {
                if (isset($_GET['public']) && $_GET['public'] == "true") {
                    $password = md5(Yii::app()->request->getParam('accesscode'));
                } else {
                    $password = Yii::app()->request->getParam('accesscode');
                }
                $svresult = Saved_control::model()->findAllByAttributes(array('sid' => $surveyid, 'identifier' => Yii::app()->request->getParam('identifier'), 'access_code' => $password));
                foreach ($svresult as $svrow) {
                    $saver['email'] = $svrow['email'];
                    $saver['scid'] = $svrow['scid'];
                    $saver['ip'] = $svrow['ip'];
                }
                $svresult = Saved_control::model()->findAllByAttributes(array('scid' => $saver['scid']));
                foreach ($svresult as $svrow) {
                    $responses[$svrow['fieldname']] = $svrow['value'];
                }
                // while
                $fieldmap = createFieldMap($surveyid, 'full', false, false, getBaseLanguageFromSurveyID($surveyid));
                foreach ($fieldmap as $fm) {
                    if (isset($responses[$fm['fieldname']])) {
                        $results1[$fm['fieldname']] = $responses[$fm['fieldname']];
                    } else {
                        $results1[$fm['fieldname']] = "";
                    }
                }
                $results1['id'] = "";
                $results1['datestamp'] = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", Yii::app()->getConfig('timeadjust'));
                $results1['ipaddr'] = $saver['ip'];
                $results[] = $results1;
            }
            $aData = array('id' => $id, 'surveyid' => $surveyid, 'subaction' => $subaction, 'part' => 'header', 'clang' => $clang);
            $aViewUrls[] = 'dataentry_header_view';
            $aViewUrls[] = 'edit';
            $highlight = FALSE;
            unset($fnames['lastpage']);
            // unset timings
            foreach ($fnames as $fname) {
                if ($fname['type'] == "interview_time" || $fname['type'] == "page_time" || $fname['type'] == "answer_time") {
                    unset($fnames[$fname['fieldname']]);
                    $nfncount--;
                }
            }
            $aDataentryoutput = '';
            foreach ($results as $idrow) {
                $fname = reset($fnames);
                do {
                    if (isset($idrow[$fname['fieldname']])) {
                        $answer = $idrow[$fname['fieldname']];
                    }
                    $question = $fname['question'];
                    $aDataentryoutput .= "\t<tr";
                    if ($highlight) {
                        $aDataentryoutput .= " class='odd'";
                    } else {
                        $aDataentryoutput .= " class='even'";
                    }
                    $highlight = !$highlight;
                    $aDataentryoutput .= ">\n" . "<td>" . "\n";
                    $aDataentryoutput .= stripJavaScript($question);
                    $aDataentryoutput .= "</td>\n" . "<td>\n";
                    //$aDataentryoutput .= "\t-={$fname[3]}=-"; //Debugging info
                    if (isset($fname['qid']) && isset($fname['type'])) {
                        $qidattributes = getQuestionAttributeValues($fname['qid'], $fname['type']);
                    }
                    switch ($fname['type']) {
                        case "completed":
                            // First compute the submitdate
                            if ($private == "Y") {
                                // In case of anonymized responses survey with no datestamp
                                // then the the answer submitdate gets a conventional timestamp
                                // 1st Jan 1980
                                $mysubmitdate = date("Y-m-d H:i:s", mktime(0, 0, 0, 1, 1, 1980));
                            } else {
                                $mysubmitdate = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", Yii::app()->getConfig('timeadjust'));
                            }
                            $completedate = empty($idrow['submitdate']) ? $mysubmitdate : $idrow['submitdate'];
                            $selected = empty($idrow['submitdate']) ? 'N' : $completedate;
                            $select_options = array('N' => $clang->gT('No'), $completedate => $clang->gT('Yes'));
                            $aDataentryoutput .= CHtml::dropDownList('completed', $selected, $select_options);
                            break;
                        case "X":
                            //Boilerplate question
                            $aDataentryoutput .= "";
                            break;
                        case "Q":
                        case "K":
                            $aDataentryoutput .= $fname['subquestion'] . '&nbsp;';
                            $aDataentryoutput .= CHtml::textField($fname['fieldname'], $idrow[$fname['fieldname']]);
                            break;
                        case "id":
                            $aDataentryoutput .= CHtml::tag('span', array('style' => 'font-weight: bold;'), '&nbsp;' . $idrow[$fname['fieldname']]);
                            break;
                        case "5":
                            //5 POINT CHOICE radio-buttons
                            for ($i = 1; $i <= 5; $i++) {
                                $checked = FALSE;
                                if ($idrow[$fname['fieldname']] == $i) {
                                    $checked = TRUE;
                                }
                                $aDataentryoutput .= CHtml::radioButton($fname['fieldname'], $checked, array('class' => 'radiobtn', 'value' => $i));
                                $aDataentryoutput .= $i;
                            }
                            break;
                        case "D":
                            //DATE
                            $thisdate = '';
                            $dateformatdetails = getDateFormatDataForQID($qidattributes, $surveyid);
                            if ($idrow[$fname['fieldname']] != '') {
                                $thisdate = DateTime::createFromFormat("Y-m-d H:i:s", $idrow[$fname['fieldname']])->format($dateformatdetails['phpdate']);
                            } else {
                                $thisdate = '';
                            }
                            if (canShowDatePicker($dateformatdetails)) {
                                $goodchars = str_replace(array("m", "d", "y", "H", "M"), "", $dateformatdetails['dateformat']);
                                $goodchars = "0123456789" . $goodchars[0];
                                $aDataentryoutput .= CHtml::textField($fname['fieldname'], $thisdate, array('class' => 'popupdate', 'size' => '12', 'onkeypress' => 'return goodchars(event,\'' . $goodchars . '\')'));
                                $aDataentryoutput .= CHtml::hiddenField('dateformat' . $fname['fieldname'], $dateformatdetails['jsdate'], array('id' => "dateformat{$fname['fieldname']}"));
                                // $aDataentryoutput .= "\t<input type='text' class='popupdate' size='12' name='{$fname['fieldname']}' value='{$thisdate}' onkeypress=\"return goodchars(event,'".$goodchars."')\"/>\n";
                                // $aDataentryoutput .= "\t<input type='hidden' name='dateformat{$fname['fieldname']}' id='dateformat{$fname['fieldname']}' value='{$dateformatdetails['jsdate']}'  />\n";
                            } else {
                                $aDataentryoutput .= CHtml::textField($fname['fieldname'], $thisdate);
                            }
                            break;
                        case "G":
                            //GENDER drop-down list
                            $select_options = array('' => $clang->gT("Please choose") . '...', 'F' => $clang->gT("Female"), 'G' => $clang->gT("Male"));
                            $aDataentryoutput .= CHtml::listBox($fname['fieldname'], $idrow[$fname['fieldname']], $select_options);
                            break;
                        case "L":
                            //LIST drop-down
                        //LIST drop-down
                        case "!":
                            //List (Radio)
                            $qidattributes = getQuestionAttributeValues($fname['qid']);
                            if (isset($qidattributes['category_separator']) && trim($qidattributes['category_separator']) != '') {
                                $optCategorySeparator = $qidattributes['category_separator'];
                            } else {
                                unset($optCategorySeparator);
                            }
                            if (substr($fname['fieldname'], -5) == "other") {
                                $aDataentryoutput .= "\t<input type='text' name='{$fname['fieldname']}' value='" . htmlspecialchars($idrow[$fname['fieldname']], ENT_QUOTES) . "' />\n";
                            } else {
                                $lquery = "SELECT * FROM {{answers}} WHERE qid={$fname['qid']} AND language = '{$sDataEntryLanguage}' ORDER BY sortorder, answer";
                                $lresult = dbExecuteAssoc($lquery);
                                $aDataentryoutput .= "\t<select name='{$fname['fieldname']}'>\n" . "<option value=''";
                                if ($idrow[$fname['fieldname']] == "") {
                                    $aDataentryoutput .= " selected='selected'";
                                }
                                $aDataentryoutput .= ">" . $clang->gT("Please choose") . "..</option>\n";
                                if (!isset($optCategorySeparator)) {
                                    foreach ($lresult->readAll() as $llrow) {
                                        $aDataentryoutput .= "<option value='{$llrow['code']}'";
                                        if ($idrow[$fname['fieldname']] == $llrow['code']) {
                                            $aDataentryoutput .= " selected='selected'";
                                        }
                                        $aDataentryoutput .= ">{$llrow['answer']}</option>\n";
                                    }
                                } else {
                                    $defaultopts = array();
                                    $optgroups = array();
                                    foreach ($lresult->readAll() as $llrow) {
                                        list($categorytext, $answertext) = explode($optCategorySeparator, $llrow['answer']);
                                        if ($categorytext == '') {
                                            $defaultopts[] = array('code' => $llrow['code'], 'answer' => $answertext);
                                        } else {
                                            $optgroups[$categorytext][] = array('code' => $llrow['code'], 'answer' => $answertext);
                                        }
                                    }
                                    foreach ($optgroups as $categoryname => $optionlistarray) {
                                        $aDataentryoutput .= "<optgroup class=\"dropdowncategory\" label=\"" . $categoryname . "\">\n";
                                        foreach ($optionlistarray as $optionarray) {
                                            $aDataentryoutput .= "\t<option value='{$optionarray['code']}'";
                                            if ($idrow[$fname['fieldname']] == $optionarray['code']) {
                                                $aDataentryoutput .= " selected='selected'";
                                            }
                                            $aDataentryoutput .= ">{$optionarray['answer']}</option>\n";
                                        }
                                        $aDataentryoutput .= "</optgroup>\n";
                                    }
                                    foreach ($defaultopts as $optionarray) {
                                        $aDataentryoutput .= "<option value='{$optionarray['code']}'";
                                        if ($idrow[$fname['fieldname']] == $optionarray['code']) {
                                            $aDataentryoutput .= " selected='selected'";
                                        }
                                        $aDataentryoutput .= ">{$optionarray['answer']}</option>\n";
                                    }
                                }
                                $oquery = "SELECT other FROM {{questions}} WHERE qid={$fname['qid']} AND {{questions}}.language = '{$sDataEntryLanguage}'";
                                $oresult = dbExecuteAssoc($oquery) or safeDie("Couldn't get other for list question<br />" . $oquery . "<br />");
                                foreach ($oresult->readAll() as $orow) {
                                    $fother = $orow['other'];
                                }
                                if ($fother == "Y") {
                                    $aDataentryoutput .= "<option value='-oth-'";
                                    if ($idrow[$fname['fieldname']] == "-oth-") {
                                        $aDataentryoutput .= " selected='selected'";
                                    }
                                    $aDataentryoutput .= ">" . $clang->gT("Other") . "</option>\n";
                                }
                                $aDataentryoutput .= "\t</select>\n";
                            }
                            break;
                        case "O":
                            //LIST WITH COMMENT drop-down/radio-button list + textarea
                            $lquery = "SELECT * FROM {{answers}} WHERE qid={$fname['qid']} AND language = '{$sDataEntryLanguage}' ORDER BY sortorder, answer";
                            $lresult = dbExecuteAssoc($lquery);
                            $aDataentryoutput .= "\t<select name='{$fname['fieldname']}'>\n" . "<option value=''";
                            if ($idrow[$fname['fieldname']] == "") {
                                $aDataentryoutput .= " selected='selected'";
                            }
                            $aDataentryoutput .= ">" . $clang->gT("Please choose") . "..</option>\n";
                            foreach ($lresult->readAll() as $llrow) {
                                $aDataentryoutput .= "<option value='{$llrow['code']}'";
                                if ($idrow[$fname['fieldname']] == $llrow['code']) {
                                    $aDataentryoutput .= " selected='selected'";
                                }
                                $aDataentryoutput .= ">{$llrow['answer']}</option>\n";
                            }
                            $fname = next($fnames);
                            $aDataentryoutput .= "\t</select>\n" . "\t<br />\n" . "\t<textarea cols='45' rows='5' name='{$fname['fieldname']}'>" . htmlspecialchars($idrow[$fname['fieldname']]) . "</textarea>\n";
                            break;
                        case "R":
                            //RANKING TYPE QUESTION
                            $thisqid = $fname['qid'];
                            $currentvalues = array();
                            $myfname = $fname['sid'] . 'X' . $fname['gid'] . 'X' . $fname['qid'];
                            while (isset($fname['type']) && $fname['type'] == "R" && $fname['qid'] == $thisqid) {
                                //Let's get all the existing values into an array
                                if ($idrow[$fname['fieldname']]) {
                                    $currentvalues[] = $idrow[$fname['fieldname']];
                                }
                                $fname = next($fnames);
                            }
                            $ansquery = "SELECT * FROM {{answers}} WHERE language = '{$sDataEntryLanguage}' AND qid={$thisqid} ORDER BY sortorder, answer";
                            $ansresult = dbExecuteAssoc($ansquery);
                            $anscount = 0;
                            $aDataentryoutput .= "\t<script type='text/javascript'>\n" . "\t<!--\n" . "function rankthis_{$thisqid}(\$code, \$value)\n" . "\t{\n" . "\t\$index=document.editresponse.CHOICES_{$thisqid}.selectedIndex;\n" . "\tfor (i=1; i<={$anscount}; i++)\n" . "{\n" . "\$b=i;\n" . "\$b += '';\n" . "\$inputname=\"RANK_{$thisqid}\"+\$b;\n" . "\$hiddenname=\"d{$myfname}\"+\$b;\n" . "\$cutname=\"cut_{$thisqid}\"+i;\n" . "document.getElementById(\$cutname).style.display='none';\n" . "if (!document.getElementById(\$inputname).value)\n" . "\t{\n" . "\tdocument.getElementById(\$inputname).value=\$value;\n" . "\tdocument.getElementById(\$hiddenname).value=\$code;\n" . "\tdocument.getElementById(\$cutname).style.display='';\n" . "\tfor (var b=document.getElementById('CHOICES_{$thisqid}').options.length-1; b>=0; b--)\n" . "{\n" . "if (document.getElementById('CHOICES_{$thisqid}').options[b].value == \$code)\n" . "\t{\n" . "\tdocument.getElementById('CHOICES_{$thisqid}').options[b] = null;\n" . "\t}\n" . "}\n" . "\ti={$anscount};\n" . "\t}\n" . "}\n" . "\tif (document.getElementById('CHOICES_{$thisqid}').options.length == 0)\n" . "{\n" . "document.getElementById('CHOICES_{$thisqid}').disabled=true;\n" . "}\n" . "\tdocument.editresponse.CHOICES_{$thisqid}.selectedIndex=-1;\n" . "\t}\n" . "function deletethis_{$thisqid}(\$text, \$value, \$name, \$thisname)\n" . "\t{\n" . "\tvar qid='{$thisqid}';\n" . "\tvar lngth=qid.length+4;\n" . "\tvar cutindex=\$thisname.substring(lngth, \$thisname.length);\n" . "\tcutindex=parseFloat(cutindex);\n" . "\tdocument.getElementById(\$name).value='';\n" . "\tdocument.getElementById(\$thisname).style.display='none';\n" . "\tif (cutindex > 1)\n" . "{\n" . "\$cut1name=\"cut_{$thisqid}\"+(cutindex-1);\n" . "\$cut2name=\"d{$myfname}\"+(cutindex);\n" . "document.getElementById(\$cut1name).style.display='';\n" . "document.getElementById(\$cut2name).value='';\n" . "}\n" . "\telse\n" . "{\n" . "\$cut2name=\"d{$myfname}\"+(cutindex);\n" . "document.getElementById(\$cut2name).value='';\n" . "}\n" . "\tvar i=document.getElementById('CHOICES_{$thisqid}').options.length;\n" . "\tdocument.getElementById('CHOICES_{$thisqid}').options[i] = new Option(\$text, \$value);\n" . "\tif (document.getElementById('CHOICES_{$thisqid}').options.length > 0)\n" . "{\n" . "document.getElementById('CHOICES_{$thisqid}').disabled=false;\n" . "}\n" . "\t}\n" . "\t//-->\n" . "\t</script>\n";
                            foreach ($ansresult->readAll() as $ansrow) {
                                $answers[] = array($ansrow['code'], $ansrow['answer']);
                                $anscount++;
                            }
                            //now find out how many existing values there are
                            $chosen[] = "";
                            //create array
                            if (!isset($ranklist)) {
                                $ranklist = "";
                            }
                            if (isset($currentvalues)) {
                                $existing = count($currentvalues);
                            } else {
                                $existing = 0;
                            }
                            for ($j = 1; $j <= $anscount; $j++) {
                                $k = $j - 1;
                                if (isset($currentvalues) && isset($currentvalues[$k]) && $currentvalues[$k]) {
                                    foreach ($answers as $ans) {
                                        if ($ans[0] == $currentvalues[$k]) {
                                            $thiscode = $ans[0];
                                            $thistext = $ans[1];
                                        }
                                    }
                                }
                                $ranklist .= "{$j}:&nbsp;<input class='ranklist' id='RANK_{$thisqid}{$j}'";
                                if (isset($currentvalues) && isset($currentvalues[$k]) && $currentvalues[$k]) {
                                    $ranklist .= " value='" . $thistext . "'";
                                }
                                $ranklist .= " onFocus=\"this.blur()\"  />\n" . "<input type='hidden' id='d{$myfname}{$j}' name='{$myfname}{$j}' value='";
                                if (isset($currentvalues) && isset($currentvalues[$k]) && $currentvalues[$k]) {
                                    $ranklist .= $thiscode;
                                    $chosen[] = array($thiscode, $thistext);
                                }
                                $ranklist .= "' />\n" . "<img src='" . Yii::app()->getConfig('imageurl') . "/cut.gif' alt='" . $clang->gT("Remove this item") . "' title='" . $clang->gT("Remove this item") . "' ";
                                if ($j != $existing) {
                                    $ranklist .= "style='display:none'";
                                }
                                $ranklist .= " id='cut_{$thisqid}{$j}' onclick=\"deletethis_{$thisqid}(document.editresponse.RANK_{$thisqid}{$j}.value, document.editresponse.d{$myfname}{$j}.value, document.editresponse.RANK_{$thisqid}{$j}.id, this.id)\" /><br />\n\n";
                            }
                            if (!isset($choicelist)) {
                                $choicelist = "";
                            }
                            $choicelist .= "<select class='choicelist' size='{$anscount}' name='CHOICES' id='CHOICES_{$thisqid}' onclick=\"rankthis_{$thisqid}(this.options[this.selectedIndex].value, this.options[this.selectedIndex].text)\" >\n";
                            foreach ($answers as $ans) {
                                if (!in_array($ans, $chosen)) {
                                    $choicelist .= "\t<option value='{$ans[0]}'>{$ans[1]}</option>\n";
                                }
                            }
                            $choicelist .= "</select>\n";
                            $aDataentryoutput .= "\t<table>\n" . "<tr>\n" . "\t<td>\n" . "<strong>" . $clang->gT("Your Choices") . ":</strong><br />\n" . $choicelist . "\t</td>\n" . "\t<td align='left'>\n" . "<strong>" . $clang->gT("Your Ranking") . ":</strong><br />\n" . $ranklist . "\t</td>\n" . "</tr>\n" . "\t</table>\n" . "\t<input type='hidden' name='multi' value='{$anscount}' />\n" . "\t<input type='hidden' name='lastfield' value='";
                            if (isset($multifields)) {
                                $aDataentryoutput .= $multifields;
                            }
                            $aDataentryoutput .= "' />\n";
                            $choicelist = "";
                            $ranklist = "";
                            unset($answers);
                            $fname = prev($fnames);
                            break;
                        case "M":
                            //Multiple choice checkbox
                            $qidattributes = getQuestionAttributeValues($fname['qid']);
                            if (trim($qidattributes['display_columns']) != '') {
                                $dcols = $qidattributes['display_columns'];
                            } else {
                                $dcols = 0;
                            }
                            //					while ($fname[3] == "M" && $question != "" && $question == $fname['type'])
                            $thisqid = $fname['qid'];
                            while ($fname['qid'] == $thisqid) {
                                $fieldn = substr($fname['fieldname'], 0, strlen($fname['fieldname']));
                                //$aDataentryoutput .= substr($fname['fieldname'], strlen($fname['fieldname'])-5, 5)."<br />\n";
                                if (substr($fname['fieldname'], -5) == "other") {
                                    $aDataentryoutput .= "\t<input type='text' name='{$fname['fieldname']}' value='" . htmlspecialchars($idrow[$fname['fieldname']], ENT_QUOTES) . "' />\n";
                                } else {
                                    $aDataentryoutput .= "\t<input type='checkbox' class='checkboxbtn' name='{$fname['fieldname']}' value='Y'";
                                    if ($idrow[$fname['fieldname']] == "Y") {
                                        $aDataentryoutput .= " checked";
                                    }
                                    $aDataentryoutput .= " />{$fname['subquestion']}<br />\n";
                                }
                                $fname = next($fnames);
                            }
                            $fname = prev($fnames);
                            break;
                        case "I":
                            //Language Switch
                            $lquery = "SELECT * FROM {{answers}} WHERE qid={$fname['qid']} AND language = '{$sDataEntryLanguage}' ORDER BY sortorder, answer";
                            $lresult = dbExecuteAssoc($lquery);
                            $slangs = Survey::model()->findByPk($surveyid)->additionalLanguages;
                            $baselang = Survey::model()->findByPk($surveyid)->language;
                            array_unshift($slangs, $baselang);
                            $aDataentryoutput .= "<select name='{$fname['fieldname']}'>\n";
                            $aDataentryoutput .= "<option value=''";
                            if ($idrow[$fname['fieldname']] == "") {
                                $aDataentryoutput .= " selected='selected'";
                            }
                            $aDataentryoutput .= ">" . $clang->gT("Please choose") . "..</option>\n";
                            foreach ($slangs as $lang) {
                                $aDataentryoutput .= "<option value='{$lang}'";
                                if ($lang == $idrow[$fname['fieldname']]) {
                                    $aDataentryoutput .= " selected='selected'";
                                }
                                $aDataentryoutput .= ">" . getLanguageNameFromCode($lang, false) . "</option>\n";
                            }
                            $aDataentryoutput .= "</select>";
                            break;
                        case "P":
                            //Multiple choice with comments checkbox + text
                            $aDataentryoutput .= "<table>\n";
                            while (isset($fname) && $fname['type'] == "P") {
                                $thefieldname = $fname['fieldname'];
                                if (substr($thefieldname, -7) == "comment") {
                                    $aDataentryoutput .= "<td><input type='text' name='{$fname['fieldname']}' size='50' value='" . htmlspecialchars($idrow[$fname['fieldname']], ENT_QUOTES) . "' /></td>\n" . "\t</tr>\n";
                                } elseif (substr($fname['fieldname'], -5) == "other") {
                                    $aDataentryoutput .= "\t<tr>\n" . "<td>\n" . "\t<input type='text' name='{$fname['fieldname']}' size='30' value='" . htmlspecialchars($idrow[$fname['fieldname']], ENT_QUOTES) . "' />\n" . "</td>\n" . "<td>\n";
                                    $fname = next($fnames);
                                    $aDataentryoutput .= "\t<input type='text' name='{$fname['fieldname']}' size='50' value='" . htmlspecialchars($idrow[$fname['fieldname']], ENT_QUOTES) . "' />\n" . "</td>\n" . "\t</tr>\n";
                                } else {
                                    $aDataentryoutput .= "\t<tr>\n" . "<td><input type='checkbox' class='checkboxbtn' name=\"{$fname['fieldname']}\" value='Y'";
                                    if ($idrow[$fname['fieldname']] == "Y") {
                                        $aDataentryoutput .= " checked";
                                    }
                                    $aDataentryoutput .= " />{$fname['subquestion']}</td>\n";
                                }
                                $fname = next($fnames);
                            }
                            $aDataentryoutput .= "</table>\n";
                            $fname = prev($fnames);
                            break;
                        case "|":
                            //FILE UPLOAD
                            $aDataentryoutput .= "<table>\n";
                            if ($fname['aid'] !== 'filecount' && isset($idrow[$fname['fieldname'] . '_filecount']) && $idrow[$fname['fieldname'] . '_filecount'] > 0) {
                                //file metadata
                                $metadata = json_decode($idrow[$fname['fieldname']], true);
                                $qAttributes = getQuestionAttributeValues($fname['qid']);
                                for ($i = 0; $i < $qAttributes['max_num_of_files'], isset($metadata[$i]); $i++) {
                                    if ($qAttributes['show_title']) {
                                        $aDataentryoutput .= '<tr><td>Title    </td><td><input type="text" class="' . $fname['fieldname'] . '" id="' . $fname['fieldname'] . '_title_' . $i . '" name="title"    size=50 value="' . htmlspecialchars($metadata[$i]["title"]) . '" /></td></tr>';
                                    }
                                    if ($qAttributes['show_comment']) {
                                        $aDataentryoutput .= '<tr><td >Comment  </td><td><input type="text" class="' . $fname['fieldname'] . '" id="' . $fname['fieldname'] . '_comment_' . $i . '" name="comment"  size=50 value="' . htmlspecialchars($metadata[$i]["comment"]) . '" /></td></tr>';
                                    }
                                    $aDataentryoutput .= '<tr><td>        File name</td><td><input   class="' . $fname['fieldname'] . '" id="' . $fname['fieldname'] . '_name_' . $i . '" name="name" size=50 value="' . htmlspecialchars(rawurldecode($metadata[$i]["name"])) . '" /></td></tr>' . '<tr><td></td><td><input type="hidden" class="' . $fname['fieldname'] . '" id="' . $fname['fieldname'] . '_size_' . $i . '" name="size" size=50 value="' . htmlspecialchars($metadata[$i]["size"]) . '" /></td></tr>' . '<tr><td></td><td><input type="hidden" class="' . $fname['fieldname'] . '" id="' . $fname['fieldname'] . '_ext_' . $i . '" name="ext" size=50 value="' . htmlspecialchars($metadata[$i]["ext"]) . '" /></td></tr>' . '<tr><td></td><td><input type="hidden"  class="' . $fname['fieldname'] . '" id="' . $fname['fieldname'] . '_filename_' . $i . '" name="filename" size=50 value="' . htmlspecialchars(rawurldecode($metadata[$i]["filename"])) . '" /></td></tr>';
                                }
                                $aDataentryoutput .= '<tr><td></td><td><input type="hidden" id="' . $fname['fieldname'] . '" name="' . $fname['fieldname'] . '" size=50 value="' . htmlspecialchars($idrow[$fname['fieldname']]) . '" /></td></tr>';
                                $aDataentryoutput .= '</table>';
                                $aDataentryoutput .= '<script type="text/javascript">
                                $(function() {
                                $(".' . $fname['fieldname'] . '").keyup(function() {
                                var filecount = $("#' . $fname['fieldname'] . '_filecount").val();
                                var jsonstr = "[";
                                var i;
                                for (i = 0; i < filecount; i++)
                                {
                                if (i != 0)
                                jsonstr += ",";
                                jsonstr += \'{"title":"\'+$("#' . $fname['fieldname'] . '_title_"+i).val()+\'",\';
                                jsonstr += \'"comment":"\'+$("#' . $fname['fieldname'] . '_comment_"+i).val()+\'",\';
                                jsonstr += \'"size":"\'+$("#' . $fname['fieldname'] . '_size_"+i).val()+\'",\';
                                jsonstr += \'"ext":"\'+$("#' . $fname['fieldname'] . '_ext_"+i).val()+\'",\';
                                jsonstr += \'"filename":"\'+$("#' . $fname['fieldname'] . '_filename_"+i).val()+\'",\';
                                jsonstr += \'"name":"\'+encodeURIComponent($("#' . $fname['fieldname'] . '_name_"+i).val())+\'"}\';
                                }
                                jsonstr += "]";
                                $("#' . $fname['fieldname'] . '").val(jsonstr);

                                });
                                });
                                </script>';
                            } else {
                                //file count
                                $aDataentryoutput .= '<input readonly id="' . $fname['fieldname'] . '" name="' . $fname['fieldname'] . '" value ="' . htmlspecialchars($idrow[$fname['fieldname']]) . '" /></td></table>';
                            }
                            break;
                        case "N":
                            //NUMERICAL TEXT
                            $aDataentryoutput .= "\t<input type='text' name='{$fname['fieldname']}' value='{$idrow[$fname['fieldname']]}' " . "onkeypress=\"return goodchars(event,'0123456789.,')\" />\n";
                            break;
                        case "S":
                            //SHORT FREE TEXT
                            $aDataentryoutput .= "\t<input type='text' name='{$fname['fieldname']}' value='" . htmlspecialchars($idrow[$fname['fieldname']], ENT_QUOTES) . "' />\n";
                            break;
                        case "T":
                            //LONG FREE TEXT
                            $aDataentryoutput .= "\t<textarea rows='5' cols='45' name='{$fname['fieldname']}'>" . htmlspecialchars($idrow[$fname['fieldname']], ENT_QUOTES) . "</textarea>\n";
                            break;
                        case "U":
                            //HUGE FREE TEXT
                            $aDataentryoutput .= "\t<textarea rows='50' cols='70' name='{$fname['fieldname']}'>" . htmlspecialchars($idrow[$fname['fieldname']], ENT_QUOTES) . "</textarea>\n";
                            break;
                        case "Y":
                            //YES/NO radio-buttons
                            $aDataentryoutput .= "\t<select name='{$fname['fieldname']}'>\n" . "<option value=''";
                            if ($idrow[$fname['fieldname']] == "") {
                                $aDataentryoutput .= " selected='selected'";
                            }
                            $aDataentryoutput .= ">" . $clang->gT("Please choose") . "..</option>\n" . "<option value='Y'";
                            if ($idrow[$fname['fieldname']] == "Y") {
                                $aDataentryoutput .= " selected='selected'";
                            }
                            $aDataentryoutput .= ">" . $clang->gT("Yes") . "</option>\n" . "<option value='N'";
                            if ($idrow[$fname['fieldname']] == "N") {
                                $aDataentryoutput .= " selected='selected'";
                            }
                            $aDataentryoutput .= ">" . $clang->gT("No") . "</option>\n" . "\t</select>\n";
                            break;
                        case "A":
                            //ARRAY (5 POINT CHOICE) radio-buttons
                            $aDataentryoutput .= "<table>\n";
                            $thisqid = $fname['qid'];
                            while ($fname['qid'] == $thisqid) {
                                $aDataentryoutput .= "\t<tr>\n" . "<td align='right'>{$fname['subquestion']}</td>\n" . "<td>\n";
                                for ($j = 1; $j <= 5; $j++) {
                                    $aDataentryoutput .= "\t<input type='radio' class='radiobtn' name='{$fname['fieldname']}' value='{$j}'";
                                    if ($idrow[$fname['fieldname']] == $j) {
                                        $aDataentryoutput .= " checked";
                                    }
                                    $aDataentryoutput .= " />{$j}&nbsp;\n";
                                }
                                $aDataentryoutput .= "</td>\n" . "\t</tr>\n";
                                $fname = next($fnames);
                            }
                            $aDataentryoutput .= "</table>\n";
                            $fname = prev($fnames);
                            break;
                        case "B":
                            //ARRAY (10 POINT CHOICE) radio-buttons
                            $aDataentryoutput .= "<table>\n";
                            $thisqid = $fname['qid'];
                            while ($fname['qid'] == $thisqid) {
                                $fieldn = substr($fname['fieldname'], 0, strlen($fname['fieldname']));
                                $aDataentryoutput .= "\t<tr>\n" . "<td align='right'>{$fname['subquestion']}</td>\n" . "<td>\n";
                                for ($j = 1; $j <= 10; $j++) {
                                    $aDataentryoutput .= "\t<input type='radio' class='radiobtn' name='{$fname['fieldname']}' value='{$j}'";
                                    if ($idrow[$fname['fieldname']] == $j) {
                                        $aDataentryoutput .= " checked";
                                    }
                                    $aDataentryoutput .= " />{$j}&nbsp;\n";
                                }
                                $aDataentryoutput .= "</td>\n" . "\t</tr>\n";
                                $fname = next($fnames);
                            }
                            $fname = prev($fnames);
                            $aDataentryoutput .= "</table>\n";
                            break;
                        case "C":
                            //ARRAY (YES/UNCERTAIN/NO) radio-buttons
                            $aDataentryoutput .= "<table>\n";
                            $thisqid = $fname['qid'];
                            while ($fname['qid'] == $thisqid) {
                                $fieldn = substr($fname['fieldname'], 0, strlen($fname['fieldname']));
                                $aDataentryoutput .= "\t<tr>\n" . "<td align='right'>{$fname['subquestion']}</td>\n" . "<td>\n" . "\t<input type='radio' class='radiobtn' name='{$fname['fieldname']}' value='Y'";
                                if ($idrow[$fname['fieldname']] == "Y") {
                                    $aDataentryoutput .= " checked";
                                }
                                $aDataentryoutput .= " />" . $clang->gT("Yes") . "&nbsp;\n" . "\t<input type='radio' class='radiobtn' name='{$fname['fieldname']}' value='U'";
                                if ($idrow[$fname['fieldname']] == "U") {
                                    $aDataentryoutput .= " checked";
                                }
                                $aDataentryoutput .= " />" . $clang->gT("Uncertain") . "&nbsp;\n" . "\t<input type='radio' class='radiobtn' name='{$fname['fieldname']}' value='N'";
                                if ($idrow[$fname['fieldname']] == "N") {
                                    $aDataentryoutput .= " checked";
                                }
                                $aDataentryoutput .= " />" . $clang->gT("No") . "&nbsp;\n" . "</td>\n" . "\t</tr>\n";
                                $fname = next($fnames);
                            }
                            $fname = prev($fnames);
                            $aDataentryoutput .= "</table>\n";
                            break;
                        case "E":
                            //ARRAY (Increase/Same/Decrease) radio-buttons
                            $aDataentryoutput .= "<table>\n";
                            $thisqid = $fname['qid'];
                            while ($fname['qid'] == $thisqid) {
                                $fieldn = substr($fname['fieldname'], 0, strlen($fname['fieldname']));
                                $aDataentryoutput .= "\t<tr>\n" . "<td align='right'>{$fname['subquestion']}</td>\n" . "<td>\n" . "\t<input type='radio' class='radiobtn' name='{$fname['fieldname']}' value='I'";
                                if ($idrow[$fname['fieldname']] == "I") {
                                    $aDataentryoutput .= " checked";
                                }
                                $aDataentryoutput .= " />Increase&nbsp;\n" . "\t<input type='radio' class='radiobtn' name='{$fname['fieldname']}' value='S'";
                                if ($idrow[$fname['fieldname']] == "I") {
                                    $aDataentryoutput .= " checked";
                                }
                                $aDataentryoutput .= " />Same&nbsp;\n" . "\t<input type='radio' class='radiobtn' name='{$fname['fieldname']}' value='D'";
                                if ($idrow[$fname['fieldname']] == "D") {
                                    $aDataentryoutput .= " checked";
                                }
                                $aDataentryoutput .= " />Decrease&nbsp;\n" . "</td>\n" . "\t</tr>\n";
                                $fname = next($fnames);
                            }
                            $fname = prev($fnames);
                            $aDataentryoutput .= "</table>\n";
                            break;
                        case "F":
                            //ARRAY (Flexible Labels)
                        //ARRAY (Flexible Labels)
                        case "H":
                        case "1":
                            $aDataentryoutput .= "<table>\n";
                            $thisqid = $fname['qid'];
                            while (isset($fname['qid']) && $fname['qid'] == $thisqid) {
                                $fieldn = substr($fname['fieldname'], 0, strlen($fname['fieldname']));
                                $aDataentryoutput .= "\t<tr>\n" . "<td>{$fname['subquestion']}";
                                if (isset($fname['scale'])) {
                                    $aDataentryoutput .= " (" . $fname['scale'] . ')';
                                }
                                $aDataentryoutput .= "</td>\n";
                                $scale_id = 0;
                                if (isset($fname['scale_id'])) {
                                    $scale_id = $fname['scale_id'];
                                }
                                $fquery = "SELECT * FROM {{answers}} WHERE qid='{$fname['qid']}' and scale_id={$scale_id} and language='{$sDataEntryLanguage}' order by sortorder, answer";
                                $fresult = dbExecuteAssoc($fquery);
                                $aDataentryoutput .= "<td>\n";
                                foreach ($fresult->readAll() as $frow) {
                                    $aDataentryoutput .= "\t<input type='radio' class='radiobtn' name='{$fname['fieldname']}' value='{$frow['code']}'";
                                    if ($idrow[$fname['fieldname']] == $frow['code']) {
                                        $aDataentryoutput .= " checked";
                                    }
                                    $aDataentryoutput .= " />" . $frow['answer'] . "&nbsp;\n";
                                }
                                //Add 'No Answer'
                                $aDataentryoutput .= "\t<input type='radio' class='radiobtn' name='{$fname['fieldname']}' value=''";
                                if ($idrow[$fname['fieldname']] == '') {
                                    $aDataentryoutput .= " checked";
                                }
                                $aDataentryoutput .= " />" . $clang->gT("No answer") . "&nbsp;\n";
                                $aDataentryoutput .= "</td>\n" . "\t</tr>\n";
                                $fname = next($fnames);
                            }
                            $fname = prev($fnames);
                            $aDataentryoutput .= "</table>\n";
                            break;
                        case ":":
                            //ARRAY (Multi Flexi) (Numbers)
                            $qidattributes = getQuestionAttributeValues($fname['qid']);
                            if (trim($qidattributes['multiflexible_max']) != '' && trim($qidattributes['multiflexible_min']) == '') {
                                $maxvalue = $qidattributes['multiflexible_max'];
                                $minvalue = 1;
                            }
                            if (trim($qidattributes['multiflexible_min']) != '' && trim($qidattributes['multiflexible_max']) == '') {
                                $minvalue = $qidattributes['multiflexible_min'];
                                $maxvalue = $qidattributes['multiflexible_min'] + 10;
                            }
                            if (trim($qidattributes['multiflexible_min']) == '' && trim($qidattributes['multiflexible_max']) == '') {
                                $minvalue = 1;
                                $maxvalue = 10;
                            }
                            if (trim($qidattributes['multiflexible_min']) != '' && trim($qidattributes['multiflexible_max']) != '') {
                                if ($qidattributes['multiflexible_min'] < $qidattributes['multiflexible_max']) {
                                    $minvalue = $qidattributes['multiflexible_min'];
                                    $maxvalue = $qidattributes['multiflexible_max'];
                                }
                            }
                            if (trim($qidattributes['multiflexible_step']) != '') {
                                $stepvalue = $qidattributes['multiflexible_step'];
                            } else {
                                $stepvalue = 1;
                            }
                            if ($qidattributes['multiflexible_checkbox'] != 0) {
                                $minvalue = 0;
                                $maxvalue = 1;
                                $stepvalue = 1;
                            }
                            $aDataentryoutput .= "<table>\n";
                            $thisqid = $fname['qid'];
                            while (isset($fname['qid']) && $fname['qid'] == $thisqid) {
                                $fieldn = substr($fname['fieldname'], 0, strlen($fname['fieldname']));
                                $aDataentryoutput .= "\t<tr>\n" . "<td>{$fname['subquestion1']}:{$fname['subquestion2']}</td>\n";
                                $aDataentryoutput .= "<td>\n";
                                if ($qidattributes['input_boxes'] != 0) {
                                    $aDataentryoutput .= "\t<input type='text' name='{$fname['fieldname']}' value='";
                                    if (!empty($idrow[$fname['fieldname']])) {
                                        $aDataentryoutput .= $idrow[$fname['fieldname']];
                                    }
                                    $aDataentryoutput .= "' size=4 />";
                                } else {
                                    $aDataentryoutput .= "\t<select name='{$fname['fieldname']}'>\n";
                                    $aDataentryoutput .= "<option value=''>...</option>\n";
                                    for ($ii = $minvalue; $ii <= $maxvalue; $ii += $stepvalue) {
                                        $aDataentryoutput .= "<option value='{$ii}'";
                                        if ($idrow[$fname['fieldname']] == $ii) {
                                            $aDataentryoutput .= " selected";
                                        }
                                        $aDataentryoutput .= ">{$ii}</option>\n";
                                    }
                                }
                                $aDataentryoutput .= "</td>\n" . "\t</tr>\n";
                                $fname = next($fnames);
                            }
                            $fname = prev($fnames);
                            $aDataentryoutput .= "</table>\n";
                            break;
                        case ";":
                            //ARRAY (Multi Flexi)
                            $aDataentryoutput .= "<table>\n";
                            $thisqid = $fname['qid'];
                            while (isset($fname['qid']) && $fname['qid'] == $thisqid) {
                                $fieldn = substr($fname['fieldname'], 0, strlen($fname['fieldname']));
                                $aDataentryoutput .= "\t<tr>\n" . "<td>{$fname['subquestion1']}:{$fname['subquestion2']}</td>\n";
                                $aDataentryoutput .= "<td>\n";
                                $aDataentryoutput .= "\t<input type='text' name='{$fname['fieldname']}' value='";
                                if (!empty($idrow[$fname['fieldname']])) {
                                    $aDataentryoutput .= $idrow[$fname['fieldname']];
                                }
                                $aDataentryoutput .= "' /></td>\n" . "\t</tr>\n";
                                $fname = next($fnames);
                            }
                            $fname = prev($fnames);
                            $aDataentryoutput .= "</table>\n";
                            break;
                        default:
                            //This really only applies to tokens for non-private surveys
                            $aDataentryoutput .= "\t<input type='text' name='{$fname['fieldname']}' value='" . $idrow[$fname['fieldname']] . "' />\n";
                            break;
                    }
                    $aDataentryoutput .= "\t\t</td>\n                    </tr>\n";
                } while ($fname = next($fnames));
            }
            $aDataentryoutput .= "</table>\n" . "<p>\n";
            $aData['sDataEntryLanguage'] = $sDataEntryLanguage;
            if (!hasSurveyPermission($surveyid, 'responses', 'update')) {
                // if you are not survey owner or super admin you cannot modify responses
                $aDataentryoutput .= "<p><input type='button' value='" . $clang->gT("Save") . "' disabled='disabled'/></p>\n";
            } elseif ($subaction == "edit" && hasSurveyPermission($surveyid, 'responses', 'update')) {
                $aData['part'] = 'edit';
                $aDataentryoutput .= $this->getController()->render('/admin/dataentry/edit', $aData, TRUE);
            } elseif ($subaction == "editsaved" && hasSurveyPermission($surveyid, 'responses', 'update')) {
                $aData['part'] = 'editsaved';
                $aDataentryoutput .= $this->getController()->render('/admin/dataentry/edit', $aData, TRUE);
            }
            $aDataentryoutput .= "</form>\n";
            $aViewUrls['output'] = $aDataentryoutput;
            $this->_renderWrappedTemplate('dataentry', $aViewUrls, $aData);
        }
    }
 private function _getSurveyButton($iSurveyID, $menuitem_url)
 {
     $survey_button = "";
     $imageurl = Yii::app()->getConfig("adminimageurl");
     $baselang = Survey::model()->findByPk($iSurveyID)->language;
     $langs = Survey::model()->findByPk($iSurveyID)->additionalLanguages;
     $surveyinfo = Survey::model()->with(array('languagesettings' => array('condition' => 'surveyls_language=language')))->findByPk($iSurveyID);
     $surveyinfo = array_merge($surveyinfo->attributes, $surveyinfo->defaultlanguage->attributes);
     $surveyinfo = array_map('flattenText', $surveyinfo);
     $menutext = $surveyinfo['active'] == "N" ? gT("Test this survey") : gT("Execute this survey");
     if (count($langs) == 0) {
         $survey_button .= $this->menuItem($menutext, '', "icon-do text-success", $menuitem_url . $baselang);
     } else {
         $icontext = gT($menutext);
         $survey_button .= CHtml::link('<span class="icon-do text-success"></span>', '#', array('id' => 'dosurvey', 'class' => 'dosurvey', 'accesskey' => 'd'));
         $tmp_survlangs = $langs;
         $tmp_survlangs[] = $baselang;
         rsort($tmp_survlangs);
         // Test Survey Language Selection Popup
         $survey_button .= CHtml::openTag('div', array('class' => 'langpopup', 'id' => 'dosurveylangpopup'));
         $survey_button .= gT("Please select a language:") . CHtml::openTag('ul');
         foreach ($tmp_survlangs as $tmp_lang) {
             $survey_button .= CHtml::tag('li', array(), CHtml::link(getLanguageNameFromCode($tmp_lang, FALSE), $menuitem_url . $tmp_lang, array('target' => '_blank', 'onclick' => "\$('.dosurvey').qtip('hide');", 'accesskey' => 'd')));
         }
         $survey_button .= CHtml::closeTag('ul');
         $survey_button .= CHtml::closeTag('div');
     }
     return $survey_button;
 }
?>
';
        var otherisreserved='<?php 
$clang->eT("Error: 'other' is a reserved keyword.", 'js');
?>
';
    </script>
<div class='header ui-widget-header'><?php 
$clang->eT("Labels");
?>
</div>
<div id='tabs' class='ui-tabs ui-widget ui-widget-content ui-corner-all'>
    <ul class='ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all'>
        <?php 
foreach ($lslanguages as $i => $language) {
    echo "\n                <li><a href='#neweditlblset{$i}'>" . getLanguageNameFromCode($language, false) . "</a></li>";
}
echo "\n            <li><a href='#up_resmgmt'>" . $clang->gT("Uploaded resources management") . "</a></li>";
?>
    </ul>

    <?php 
echo CHtml::form(array("admin/labels/sa/process"), 'post', array('id' => 'mainform'));
?>
        <input type='hidden' name='lid' value='<?php 
echo $lid;
?>
' />
        <input type='hidden' name='action' value='modlabelsetanswers' />
        <?php 
$i = 0;
Example #30
0
        <li><label for='invitationstatus'><?php $clang->eT('Invitation status:'); ?></label><select id='invitationstatus' name='invitationstatus' >
                <option selected='selected' value='0'><?php $clang->eT('All'); ?></option>
                <option value='1'><?php $clang->eT('Invited'); ?></option>
                <option value='2'><?php $clang->eT('Not invited'); ?></option>
            </select></li>
        <li><label for='reminderstatus'><?php $clang->eT('Reminder status:'); ?></label><select id='reminderstatus' name='reminderstatus' >
                <option selected='selected' value='0'><?php $clang->eT('All'); ?></option>
                <option value='1'><?php $clang->eT('Reminder(s) sent'); ?></option>
                <option value='2'><?php $clang->eT('No reminder(s) sent'); ?></option>
            </select></li>
        <li><label for='tokenlanguage' ><?php $clang->eT('Filter by language'); ?></label><select id='tokenlanguage' name='tokenlanguage' >
                <option selected='selected' value=''><?php $clang->eT('All'); ?></option>
<?php
if($resultr){
    foreach ($resultr as $lrow)
    {
        echo "<option value='{$lrow['language']}'>" . getLanguageNameFromCode($lrow['language']) . "</option>";
    }
}
?>
            </select></li>
        <li><label for='filteremail' ><?php $clang->eT('Filter by email address'); ?></label><input type='email' id='filteremail' name='filteremail' /></li>
        <li>&nbsp;</li>
        <li><label for='tokendeleteexported' ><?php $clang->eT('Delete exported tokens'); ?></label><input type='checkbox' id='tokendeleteexported' name='tokendeleteexported' /> </li>
    </ul>
    <p><input type='submit' name='submit' value='<?php $clang->eT('Export tokens'); ?>' />
        <input type='hidden' name='action' id='action' value='tokens' />
        <input type='hidden' name='sid' id='sid' value='<?php echo $surveyid; ?>' />
        <input type='hidden' name='subaction' id='subaction' value='export' />
    </p></form>